blob: d6e8e0a01a8697feaed01162a078046cf2c738bd [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"
Benjamin Kramer699128e2011-09-21 01:13:19 +000020#include "llvm/DebugInfo/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"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000039#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/MemoryBuffer.h"
41#include "llvm/Support/TargetRegistry.h"
42#include "llvm/Support/TargetSelect.h"
43#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000044#include <algorithm>
45#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000046#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000047
48#if HAVE_CXXABI_H
49#include <cxxabi.h>
50#endif
51
Benjamin Kramer43a772e2011-09-19 17:56:04 +000052using namespace llvm;
53using namespace object;
54
55static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000056 UseDbg("g",
57 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000058
Kevin Enderbyb28ed012014-10-29 21:28:24 +000059static cl::opt<std::string> DSYMFile("dsym",
60 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000061
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062static cl::opt<bool> FullLeadingAddr("full-leading-addr",
63 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000064
65static cl::opt<bool>
66 PrintImmHex("print-imm-hex",
67 cl::desc("Use hex format for immediate values"));
68
Kevin Enderby13023a12015-01-15 23:19:11 +000069cl::opt<bool> llvm::UniversalHeaders("universal-headers",
70 cl::desc("Print Mach-O universal headers "
71 "(requires -macho)"));
72
Kevin Enderby131d1772015-01-09 19:22:37 +000073cl::opt<bool>
Kevin Enderby13023a12015-01-15 23:19:11 +000074 llvm::ArchiveHeaders("archive-headers",
75 cl::desc("Print archive headers for Mach-O archives "
76 "(requires -macho)"));
Kevin Enderby131d1772015-01-09 19:22:37 +000077
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +000078cl::opt<bool>
79 llvm::IndirectSymbols("indirect-symbols",
80 cl::desc("Print indirect symbol table for Mach-O "
81 "objects (requires -macho)"));
82
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000083static cl::list<std::string>
84 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
85 cl::ZeroOrMore);
86bool ArchAll = false;
87
Kevin Enderbyec5ca032014-08-18 20:21:02 +000088static std::string ThumbTripleName;
89
90static const Target *GetTarget(const MachOObjectFile *MachOObj,
91 const char **McpuDefault,
92 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +000093 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000094 if (TripleName.empty()) {
95 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +000096 llvm::Triple ThumbTriple = Triple();
97 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000098 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +000099 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000100 }
101
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000102 // Get the target specific parser.
103 std::string Error;
104 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000105 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000106 return TheTarget;
107
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000108 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
109 if (*ThumbTarget)
110 return TheTarget;
111
112 errs() << "llvm-objdump: error: unable to get target for '";
113 if (!TheTarget)
114 errs() << TripleName;
115 else
116 errs() << ThumbTripleName;
117 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000118 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000119}
120
Owen Andersond9243c42011-10-17 21:37:35 +0000121struct SymbolSorter {
122 bool operator()(const SymbolRef &A, const SymbolRef &B) {
123 SymbolRef::Type AType, BType;
124 A.getType(AType);
125 B.getType(BType);
126
127 uint64_t AAddr, BAddr;
128 if (AType != SymbolRef::ST_Function)
129 AAddr = 0;
130 else
131 A.getAddress(AAddr);
132 if (BType != SymbolRef::ST_Function)
133 BAddr = 0;
134 else
135 B.getAddress(BAddr);
136 return AAddr < BAddr;
137 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000138};
139
Kevin Enderby273ae012013-06-06 17:20:50 +0000140// Types for the storted data in code table that is built before disassembly
141// and the predicate function to sort them.
142typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
143typedef std::vector<DiceTableEntry> DiceTable;
144typedef DiceTable::iterator dice_table_iterator;
145
Kevin Enderby930fdc72014-11-06 19:00:13 +0000146// This is used to search for a data in code table entry for the PC being
147// disassembled. The j parameter has the PC in j.first. A single data in code
148// table entry can cover many bytes for each of its Kind's. So if the offset,
149// aka the i.first value, of the data in code table entry plus its Length
150// covers the PC being searched for this will return true. If not it will
151// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000152static bool compareDiceTableEntries(const DiceTableEntry &i,
153 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000154 uint16_t Length;
155 i.second.getLength(Length);
156
157 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000158}
159
Kevin Enderby930fdc72014-11-06 19:00:13 +0000160static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
161 unsigned short Kind) {
162 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000163
164 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000165 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000166 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000167 if (Length >= 4) {
168 if (!NoShowRawInsn)
169 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000170 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000171 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000172 Size = 4;
173 } else if (Length >= 2) {
174 if (!NoShowRawInsn)
175 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000176 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000177 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000178 Size = 2;
179 } else {
180 if (!NoShowRawInsn)
181 DumpBytes(StringRef(bytes, 2));
Kevin Enderby273ae012013-06-06 17:20:50 +0000182 Value = bytes[0];
183 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000184 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000185 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000186 if (Kind == MachO::DICE_KIND_DATA)
187 outs() << "\t@ KIND_DATA\n";
188 else
189 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000190 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000191 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000192 if (!NoShowRawInsn)
193 DumpBytes(StringRef(bytes, 1));
Kevin Enderby273ae012013-06-06 17:20:50 +0000194 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000195 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
196 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000197 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000198 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000199 if (!NoShowRawInsn)
200 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000201 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000202 outs() << "\t.short " << format("%5u", Value & 0xffff)
203 << "\t@ KIND_JUMP_TABLE16\n";
204 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000205 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000206 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000207 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
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 Enderby930fdc72014-11-06 19:00:13 +0000211 outs() << "\t.long " << Value;
212 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
213 outs() << "\t@ KIND_JUMP_TABLE32\n";
214 else
215 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
216 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000217 break;
218 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000219 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000220}
221
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000222static void getSectionsAndSymbols(const MachO::mach_header Header,
223 MachOObjectFile *MachOObj,
224 std::vector<SectionRef> &Sections,
225 std::vector<SymbolRef> &Symbols,
226 SmallVectorImpl<uint64_t> &FoundFns,
227 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000228 for (const SymbolRef &Symbol : MachOObj->symbols()) {
229 StringRef SymName;
230 Symbol.getName(SymName);
231 if (!SymName.startswith("ltmp"))
232 Symbols.push_back(Symbol);
233 }
Owen Andersond9243c42011-10-17 21:37:35 +0000234
Alexey Samsonov48803e52014-03-13 14:37:36 +0000235 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000236 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000237 Section.getName(SectName);
238 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000239 }
240
Rafael Espindola56f976f2013-04-18 18:08:55 +0000241 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000242 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000243 bool BaseSegmentAddressSet = false;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000244 for (unsigned i = 0;; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000245 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000246 // We found a function starts segment, parse the addresses for later
247 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000248 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000249 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000250
Charles Davis8bdfafd2013-09-01 04:28:48 +0000251 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000252 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
253 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000254 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000255 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000256 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000257 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000258 }
259 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000260
Charles Davis8bdfafd2013-09-01 04:28:48 +0000261 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000262 break;
263 else
264 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000265 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000266}
267
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000268static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
269 uint32_t n, uint32_t count,
270 uint32_t stride, uint64_t addr) {
271 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
272 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
273 if (n > nindirectsyms)
274 outs() << " (entries start past the end of the indirect symbol "
275 "table) (reserved1 field greater than the table size)";
276 else if (n + count > nindirectsyms)
277 outs() << " (entries extends past the end of the indirect symbol "
278 "table)";
279 outs() << "\n";
280 uint32_t cputype = O->getHeader().cputype;
281 if (cputype & MachO::CPU_ARCH_ABI64)
282 outs() << "address index";
283 else
284 outs() << "address index";
285 if (verbose)
286 outs() << " name\n";
287 else
288 outs() << "\n";
289 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
290 if (cputype & MachO::CPU_ARCH_ABI64)
291 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
292 else
293 outs() << format("0x%08" PRIx32, addr + j * stride) << " ";
294 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
295 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
296 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
297 outs() << "LOCAL\n";
298 continue;
299 }
300 if (indirect_symbol ==
301 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
302 outs() << "LOCAL ABSOLUTE\n";
303 continue;
304 }
305 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
306 outs() << "ABSOLUTE\n";
307 continue;
308 }
309 outs() << format("%5u ", indirect_symbol);
310 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
311 if (indirect_symbol < Symtab.nsyms) {
312 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
313 SymbolRef Symbol = *Sym;
314 StringRef SymName;
315 Symbol.getName(SymName);
316 outs() << SymName;
317 } else {
318 outs() << "?";
319 }
320 outs() << "\n";
321 }
322}
323
324static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
325 uint32_t LoadCommandCount = O->getHeader().ncmds;
326 MachOObjectFile::LoadCommandInfo Load = O->getFirstLoadCommandInfo();
327 for (unsigned I = 0;; ++I) {
328 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
329 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
330 for (unsigned J = 0; J < Seg.nsects; ++J) {
331 MachO::section_64 Sec = O->getSection64(Load, J);
332 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
333 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
334 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
335 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
336 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
337 section_type == MachO::S_SYMBOL_STUBS) {
338 uint32_t stride;
339 if (section_type == MachO::S_SYMBOL_STUBS)
340 stride = Sec.reserved2;
341 else
342 stride = 8;
343 if (stride == 0) {
344 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
345 << Sec.sectname << ") "
346 << "(size of stubs in reserved2 field is zero)\n";
347 continue;
348 }
349 uint32_t count = Sec.size / stride;
350 outs() << "Indirect symbols for (" << Sec.segname << ","
351 << Sec.sectname << ") " << count << " entries";
352 uint32_t n = Sec.reserved1;
353 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
354 }
355 }
356 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
357 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
358 for (unsigned J = 0; J < Seg.nsects; ++J) {
359 MachO::section Sec = O->getSection(Load, J);
360 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
361 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
362 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
363 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
364 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
365 section_type == MachO::S_SYMBOL_STUBS) {
366 uint32_t stride;
367 if (section_type == MachO::S_SYMBOL_STUBS)
368 stride = Sec.reserved2;
369 else
370 stride = 4;
371 if (stride == 0) {
372 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
373 << Sec.sectname << ") "
374 << "(size of stubs in reserved2 field is zero)\n";
375 continue;
376 }
377 uint32_t count = Sec.size / stride;
378 outs() << "Indirect symbols for (" << Sec.segname << ","
379 << Sec.sectname << ") " << count << " entries";
380 uint32_t n = Sec.reserved1;
381 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
382 }
383 }
384 }
385 if (I == LoadCommandCount - 1)
386 break;
387 else
388 Load = O->getNextLoadCommandInfo(Load);
389 }
390}
391
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000392// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
393// and if it is and there is a list of architecture flags is specified then
394// check to make sure this Mach-O file is one of those architectures or all
395// architectures were specified. If not then an error is generated and this
396// routine returns false. Else it returns true.
397static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
398 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
399 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
400 bool ArchFound = false;
401 MachO::mach_header H;
402 MachO::mach_header_64 H_64;
403 Triple T;
404 if (MachO->is64Bit()) {
405 H_64 = MachO->MachOObjectFile::getHeader64();
406 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
407 } else {
408 H = MachO->MachOObjectFile::getHeader();
409 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
410 }
411 unsigned i;
412 for (i = 0; i < ArchFlags.size(); ++i) {
413 if (ArchFlags[i] == T.getArchName())
414 ArchFound = true;
415 break;
416 }
417 if (!ArchFound) {
418 errs() << "llvm-objdump: file: " + Filename + " does not contain "
419 << "architecture: " + ArchFlags[i] + "\n";
420 return false;
421 }
422 }
423 return true;
424}
425
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000426static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF);
Rafael Espindola9b709252013-04-13 01:45:40 +0000427
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000428// ProcessMachO() is passed a single opened Mach-O file, which may be an
429// archive member and or in a slice of a universal file. It prints the
430// the file name and header info and then processes it according to the
431// command line options.
432static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
433 StringRef ArchiveMemberName = StringRef(),
434 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +0000435 // If we are doing some processing here on the Mach-O file print the header
436 // info. And don't print it otherwise like in the case of printing the
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000437 // UniversalHeaders or ArchiveHeaders.
Kevin Enderby131d1772015-01-09 19:22:37 +0000438 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000439 LazyBind || WeakBind || IndirectSymbols) {
Kevin Enderby131d1772015-01-09 19:22:37 +0000440 outs() << Filename;
441 if (!ArchiveMemberName.empty())
442 outs() << '(' << ArchiveMemberName << ')';
443 if (!ArchitectureName.empty())
444 outs() << " (architecture " << ArchitectureName << ")";
445 outs() << ":\n";
446 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000447
448 if (Disassemble)
449 DisassembleMachO(Filename, MachOOF);
Kevin Enderbya7bdc7e2015-01-22 18:55:27 +0000450 if (IndirectSymbols)
451 PrintIndirectSymbols(MachOOF, true);
Kevin Enderby98da6132015-01-20 21:47:46 +0000452 if (Relocations)
453 PrintRelocations(MachOOF);
454 if (SectionHeaders)
455 PrintSectionHeaders(MachOOF);
456 if (SectionContents)
457 PrintSectionContents(MachOOF);
458 if (SymbolTable)
459 PrintSymbolTable(MachOOF);
460 if (UnwindInfo)
461 printMachOUnwindInfo(MachOOF);
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000462 if (PrivateHeaders)
463 printMachOFileHeader(MachOOF);
464 if (ExportsTrie)
465 printExportsTrie(MachOOF);
466 if (Rebase)
467 printRebaseTable(MachOOF);
468 if (Bind)
469 printBindTable(MachOOF);
470 if (LazyBind)
471 printLazyBindTable(MachOOF);
472 if (WeakBind)
473 printWeakBindTable(MachOOF);
474}
475
Kevin Enderby131d1772015-01-09 19:22:37 +0000476// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
477static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
478 outs() << " cputype (" << cputype << ")\n";
479 outs() << " cpusubtype (" << cpusubtype << ")\n";
480}
481
482// printCPUType() helps print_fat_headers by printing the cputype and
483// pusubtype (symbolically for the one's it knows about).
484static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
485 switch (cputype) {
486 case MachO::CPU_TYPE_I386:
487 switch (cpusubtype) {
488 case MachO::CPU_SUBTYPE_I386_ALL:
489 outs() << " cputype CPU_TYPE_I386\n";
490 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
491 break;
492 default:
493 printUnknownCPUType(cputype, cpusubtype);
494 break;
495 }
496 break;
497 case MachO::CPU_TYPE_X86_64:
498 switch (cpusubtype) {
499 case MachO::CPU_SUBTYPE_X86_64_ALL:
500 outs() << " cputype CPU_TYPE_X86_64\n";
501 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
502 break;
503 case MachO::CPU_SUBTYPE_X86_64_H:
504 outs() << " cputype CPU_TYPE_X86_64\n";
505 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
506 break;
507 default:
508 printUnknownCPUType(cputype, cpusubtype);
509 break;
510 }
511 break;
512 case MachO::CPU_TYPE_ARM:
513 switch (cpusubtype) {
514 case MachO::CPU_SUBTYPE_ARM_ALL:
515 outs() << " cputype CPU_TYPE_ARM\n";
516 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
517 break;
518 case MachO::CPU_SUBTYPE_ARM_V4T:
519 outs() << " cputype CPU_TYPE_ARM\n";
520 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
521 break;
522 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
523 outs() << " cputype CPU_TYPE_ARM\n";
524 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
525 break;
526 case MachO::CPU_SUBTYPE_ARM_XSCALE:
527 outs() << " cputype CPU_TYPE_ARM\n";
528 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
529 break;
530 case MachO::CPU_SUBTYPE_ARM_V6:
531 outs() << " cputype CPU_TYPE_ARM\n";
532 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
533 break;
534 case MachO::CPU_SUBTYPE_ARM_V6M:
535 outs() << " cputype CPU_TYPE_ARM\n";
536 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
537 break;
538 case MachO::CPU_SUBTYPE_ARM_V7:
539 outs() << " cputype CPU_TYPE_ARM\n";
540 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
541 break;
542 case MachO::CPU_SUBTYPE_ARM_V7EM:
543 outs() << " cputype CPU_TYPE_ARM\n";
544 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
545 break;
546 case MachO::CPU_SUBTYPE_ARM_V7K:
547 outs() << " cputype CPU_TYPE_ARM\n";
548 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
549 break;
550 case MachO::CPU_SUBTYPE_ARM_V7M:
551 outs() << " cputype CPU_TYPE_ARM\n";
552 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
553 break;
554 case MachO::CPU_SUBTYPE_ARM_V7S:
555 outs() << " cputype CPU_TYPE_ARM\n";
556 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
557 break;
558 default:
559 printUnknownCPUType(cputype, cpusubtype);
560 break;
561 }
562 break;
563 case MachO::CPU_TYPE_ARM64:
564 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
565 case MachO::CPU_SUBTYPE_ARM64_ALL:
566 outs() << " cputype CPU_TYPE_ARM64\n";
567 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
568 break;
569 default:
570 printUnknownCPUType(cputype, cpusubtype);
571 break;
572 }
573 break;
574 default:
575 printUnknownCPUType(cputype, cpusubtype);
576 break;
577 }
578}
579
580static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
581 bool verbose) {
582 outs() << "Fat headers\n";
583 if (verbose)
584 outs() << "fat_magic FAT_MAGIC\n";
585 else
586 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
587
588 uint32_t nfat_arch = UB->getNumberOfObjects();
589 StringRef Buf = UB->getData();
590 uint64_t size = Buf.size();
591 uint64_t big_size = sizeof(struct MachO::fat_header) +
592 nfat_arch * sizeof(struct MachO::fat_arch);
593 outs() << "nfat_arch " << UB->getNumberOfObjects();
594 if (nfat_arch == 0)
595 outs() << " (malformed, contains zero architecture types)\n";
596 else if (big_size > size)
597 outs() << " (malformed, architectures past end of file)\n";
598 else
599 outs() << "\n";
600
601 for (uint32_t i = 0; i < nfat_arch; ++i) {
602 MachOUniversalBinary::ObjectForArch OFA(UB, i);
603 uint32_t cputype = OFA.getCPUType();
604 uint32_t cpusubtype = OFA.getCPUSubType();
605 outs() << "architecture ";
606 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
607 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
608 uint32_t other_cputype = other_OFA.getCPUType();
609 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
Kevin Enderby0512bd72015-01-09 21:55:03 +0000610 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
Kevin Enderby131d1772015-01-09 19:22:37 +0000611 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
Kevin Enderby0512bd72015-01-09 21:55:03 +0000612 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
Kevin Enderby131d1772015-01-09 19:22:37 +0000613 outs() << "(illegal duplicate architecture) ";
614 break;
Kevin Enderby0512bd72015-01-09 21:55:03 +0000615 }
Kevin Enderby131d1772015-01-09 19:22:37 +0000616 }
617 if (verbose) {
618 outs() << OFA.getArchTypeName() << "\n";
619 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
620 } else {
621 outs() << i << "\n";
622 outs() << " cputype " << cputype << "\n";
623 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
624 << "\n";
625 }
626 if (verbose &&
627 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
628 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
629 else
630 outs() << " capabilities "
631 << format("0x%" PRIx32,
632 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
633 outs() << " offset " << OFA.getOffset();
634 if (OFA.getOffset() > size)
635 outs() << " (past end of file)";
636 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
637 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
638 outs() << "\n";
639 outs() << " size " << OFA.getSize();
640 big_size = OFA.getOffset() + OFA.getSize();
641 if (big_size > size)
642 outs() << " (past end of file)";
643 outs() << "\n";
644 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
645 << ")\n";
646 }
647}
648
Kevin Enderby13023a12015-01-15 23:19:11 +0000649static void printArchiveChild(Archive::Child &C, bool verbose,
650 bool print_offset) {
651 if (print_offset)
652 outs() << C.getChildOffset() << "\t";
653 sys::fs::perms Mode = C.getAccessMode();
654 if (verbose) {
655 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
656 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
657 outs() << "-";
658 if (Mode & sys::fs::owner_read)
659 outs() << "r";
660 else
661 outs() << "-";
662 if (Mode & sys::fs::owner_write)
663 outs() << "w";
664 else
665 outs() << "-";
666 if (Mode & sys::fs::owner_exe)
667 outs() << "x";
668 else
669 outs() << "-";
670 if (Mode & sys::fs::group_read)
671 outs() << "r";
672 else
673 outs() << "-";
674 if (Mode & sys::fs::group_write)
675 outs() << "w";
676 else
677 outs() << "-";
678 if (Mode & sys::fs::group_exe)
679 outs() << "x";
680 else
681 outs() << "-";
682 if (Mode & sys::fs::others_read)
683 outs() << "r";
684 else
685 outs() << "-";
686 if (Mode & sys::fs::others_write)
687 outs() << "w";
688 else
689 outs() << "-";
690 if (Mode & sys::fs::others_exe)
691 outs() << "x";
692 else
693 outs() << "-";
694 } else {
695 outs() << format("0%o ", Mode);
696 }
697
698 unsigned UID = C.getUID();
699 outs() << format("%3d/", UID);
700 unsigned GID = C.getGID();
701 outs() << format("%-3d ", GID);
Kevin Enderbyc12718932015-01-16 22:10:36 +0000702 uint64_t Size = C.getRawSize();
Kevin Enderby13023a12015-01-15 23:19:11 +0000703 outs() << format("%5d ", Size);
704
705 StringRef RawLastModified = C.getRawLastModified();
706 if (verbose) {
707 unsigned Seconds;
708 if (RawLastModified.getAsInteger(10, Seconds))
709 outs() << "(date: \"%s\" contains non-decimal chars) " << RawLastModified;
710 else {
711 // Since cime(3) returns a 26 character string of the form:
712 // "Sun Sep 16 01:03:52 1973\n\0"
713 // just print 24 characters.
714 time_t t = Seconds;
715 outs() << format("%.24s ", ctime(&t));
716 }
717 } else {
718 outs() << RawLastModified << " ";
719 }
720
721 if (verbose) {
722 ErrorOr<StringRef> NameOrErr = C.getName();
723 if (NameOrErr.getError()) {
724 StringRef RawName = C.getRawName();
725 outs() << RawName << "\n";
726 } else {
727 StringRef Name = NameOrErr.get();
728 outs() << Name << "\n";
729 }
730 } else {
731 StringRef RawName = C.getRawName();
732 outs() << RawName << "\n";
733 }
734}
735
736static void printArchiveHeaders(Archive *A, bool verbose, bool print_offset) {
737 if (A->hasSymbolTable()) {
738 Archive::child_iterator S = A->getSymbolTableChild();
739 Archive::Child C = *S;
740 printArchiveChild(C, verbose, print_offset);
741 }
742 for (Archive::child_iterator I = A->child_begin(), E = A->child_end(); I != E;
743 ++I) {
744 Archive::Child C = *I;
745 printArchiveChild(C, verbose, print_offset);
746 }
747}
748
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000749// ParseInputMachO() parses the named Mach-O file in Filename and handles the
750// -arch flags selecting just those slices as specified by them and also parses
751// archive files. Then for each individual Mach-O file ProcessMachO() is
752// called to process the file based on the command line options.
753void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000754 // Check for -arch all and verifiy the -arch flags are valid.
755 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
756 if (ArchFlags[i] == "all") {
757 ArchAll = true;
758 } else {
759 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
760 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
761 "'for the -arch option\n";
762 return;
763 }
764 }
765 }
766
767 // Attempt to open the binary.
768 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
769 if (std::error_code EC = BinaryOrErr.getError()) {
770 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +0000771 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +0000772 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000773 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +0000774
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000775 if (Archive *A = dyn_cast<Archive>(&Bin)) {
776 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +0000777 if (ArchiveHeaders)
778 printArchiveHeaders(A, true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000779 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
780 I != E; ++I) {
781 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
782 if (ChildOrErr.getError())
783 continue;
784 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
785 if (!checkMachOAndArchFlags(O, Filename))
786 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000787 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000788 }
789 }
790 return;
791 }
Kevin Enderby131d1772015-01-09 19:22:37 +0000792 if (UniversalHeaders) {
793 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
794 printMachOUniversalHeaders(UB, true);
795 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000796 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
797 // If we have a list of architecture flags specified dump only those.
798 if (!ArchAll && ArchFlags.size() != 0) {
799 // Look for a slice in the universal binary that matches each ArchFlag.
800 bool ArchFound;
801 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
802 ArchFound = false;
803 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
804 E = UB->end_objects();
805 I != E; ++I) {
806 if (ArchFlags[i] == I->getArchTypeName()) {
807 ArchFound = true;
808 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
809 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000810 std::string ArchitectureName = "";
811 if (ArchFlags.size() > 1)
812 ArchitectureName = I->getArchTypeName();
813 if (ObjOrErr) {
814 ObjectFile &O = *ObjOrErr.get();
815 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000816 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000817 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
818 I->getAsArchive()) {
819 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000820 outs() << "Archive : " << Filename;
821 if (!ArchitectureName.empty())
822 outs() << " (architecture " << ArchitectureName << ")";
823 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +0000824 if (ArchiveHeaders)
825 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000826 for (Archive::child_iterator AI = A->child_begin(),
827 AE = A->child_end();
828 AI != AE; ++AI) {
829 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
830 if (ChildOrErr.getError())
831 continue;
832 if (MachOObjectFile *O =
833 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000834 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000835 }
836 }
837 }
838 }
839 if (!ArchFound) {
840 errs() << "llvm-objdump: file: " + Filename + " does not contain "
841 << "architecture: " + ArchFlags[i] + "\n";
842 return;
843 }
844 }
845 return;
846 }
847 // No architecture flags were specified so if this contains a slice that
848 // matches the host architecture dump only that.
849 if (!ArchAll) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000850 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
851 E = UB->end_objects();
852 I != E; ++I) {
Kevin Enderby0512bd72015-01-09 21:55:03 +0000853 if (MachOObjectFile::getHostArch().getArchName() ==
854 I->getArchTypeName()) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000855 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000856 std::string ArchiveName;
857 ArchiveName.clear();
858 if (ObjOrErr) {
859 ObjectFile &O = *ObjOrErr.get();
860 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000861 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000862 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
863 I->getAsArchive()) {
864 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000865 outs() << "Archive : " << Filename << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +0000866 if (ArchiveHeaders)
867 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000868 for (Archive::child_iterator AI = A->child_begin(),
869 AE = A->child_end();
870 AI != AE; ++AI) {
871 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
872 if (ChildOrErr.getError())
873 continue;
874 if (MachOObjectFile *O =
875 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000876 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000877 }
878 }
879 return;
880 }
881 }
882 }
883 // Either all architectures have been specified or none have been specified
884 // and this does not contain the host architecture so dump all the slices.
885 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
886 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
887 E = UB->end_objects();
888 I != E; ++I) {
889 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000890 std::string ArchitectureName = "";
891 if (moreThanOneArch)
892 ArchitectureName = I->getArchTypeName();
893 if (ObjOrErr) {
894 ObjectFile &Obj = *ObjOrErr.get();
895 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000896 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000897 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
898 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000899 outs() << "Archive : " << Filename;
900 if (!ArchitectureName.empty())
901 outs() << " (architecture " << ArchitectureName << ")";
902 outs() << "\n";
Kevin Enderby13023a12015-01-15 23:19:11 +0000903 if (ArchiveHeaders)
904 printArchiveHeaders(A.get(), true, false);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000905 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
906 AI != AE; ++AI) {
907 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
908 if (ChildOrErr.getError())
909 continue;
910 if (MachOObjectFile *O =
911 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
912 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000913 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
914 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000915 }
916 }
917 }
918 }
919 return;
920 }
921 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
922 if (!checkMachOAndArchFlags(O, Filename))
923 return;
924 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000925 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000926 } else
927 errs() << "llvm-objdump: '" << Filename << "': "
928 << "Object is not a Mach-O file type.\n";
929 } else
930 errs() << "llvm-objdump: '" << Filename << "': "
931 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +0000932}
933
Kevin Enderbybf246f52014-09-24 23:08:22 +0000934typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000935typedef std::pair<uint64_t, const char *> BindInfoEntry;
936typedef std::vector<BindInfoEntry> BindTable;
937typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000938
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000939// The block of info used by the Symbolizer call backs.
940struct DisassembleInfo {
941 bool verbose;
942 MachOObjectFile *O;
943 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000944 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000945 std::vector<SectionRef> *Sections;
946 const char *class_name;
947 const char *selector_name;
948 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +0000949 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000950 uint64_t adrp_addr;
951 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +0000952 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000953};
954
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000955// GuessSymbolName is passed the address of what might be a symbol and a
956// pointer to the DisassembleInfo struct. It returns the name of a symbol
957// with that address or nullptr if no symbol is found with that address.
958static const char *GuessSymbolName(uint64_t value,
959 struct DisassembleInfo *info) {
960 const char *SymbolName = nullptr;
961 // A DenseMap can't lookup up some values.
962 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
963 StringRef name = info->AddrMap->lookup(value);
964 if (!name.empty())
965 SymbolName = name.data();
966 }
967 return SymbolName;
968}
969
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000970// SymbolizerGetOpInfo() is the operand information call back function.
971// This is called to get the symbolic information for operand(s) of an
972// instruction when it is being done. This routine does this from
973// the relocation information, symbol table, etc. That block of information
974// is a pointer to the struct DisassembleInfo that was passed when the
975// disassembler context was created and passed to back to here when
976// called back by the disassembler for instruction operands that could have
977// relocation information. The address of the instruction containing operand is
978// at the Pc parameter. The immediate value the operand has is passed in
979// op_info->Value and is at Offset past the start of the instruction and has a
980// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
981// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
982// names and addends of the symbolic expression to add for the operand. The
983// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
984// information is returned then this function returns 1 else it returns 0.
985int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
986 uint64_t Size, int TagType, void *TagBuf) {
987 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
988 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000989 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000990
991 // Make sure all fields returned are zero if we don't set them.
992 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
993 op_info->Value = value;
994
995 // If the TagType is not the value 1 which it code knows about or if no
996 // verbose symbolic information is wanted then just return 0, indicating no
997 // information is being returned.
998 if (TagType != 1 || info->verbose == false)
999 return 0;
1000
1001 unsigned int Arch = info->O->getArch();
1002 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001003 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1004 return 0;
1005 // First search the section's relocation entries (if any) for an entry
1006 // for this section offset.
1007 uint32_t sect_addr = info->S.getAddress();
1008 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1009 bool reloc_found = false;
1010 DataRefImpl Rel;
1011 MachO::any_relocation_info RE;
1012 bool isExtern = false;
1013 SymbolRef Symbol;
1014 bool r_scattered = false;
1015 uint32_t r_value, pair_r_value, r_type;
1016 for (const RelocationRef &Reloc : info->S.relocations()) {
1017 uint64_t RelocOffset;
1018 Reloc.getOffset(RelocOffset);
1019 if (RelocOffset == sect_offset) {
1020 Rel = Reloc.getRawDataRefImpl();
1021 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +00001022 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001023 r_scattered = info->O->isRelocationScattered(RE);
1024 if (r_scattered) {
1025 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001026 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1027 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1028 DataRefImpl RelNext = Rel;
1029 info->O->moveRelocationNext(RelNext);
1030 MachO::any_relocation_info RENext;
1031 RENext = info->O->getRelocation(RelNext);
1032 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +00001033 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001034 else
1035 return 0;
1036 }
1037 } else {
1038 isExtern = info->O->getPlainRelocationExternal(RE);
1039 if (isExtern) {
1040 symbol_iterator RelocSym = Reloc.getSymbol();
1041 Symbol = *RelocSym;
1042 }
1043 }
1044 reloc_found = true;
1045 break;
1046 }
1047 }
1048 if (reloc_found && isExtern) {
1049 StringRef SymName;
1050 Symbol.getName(SymName);
1051 const char *name = SymName.data();
1052 op_info->AddSymbol.Present = 1;
1053 op_info->AddSymbol.Name = name;
1054 // For i386 extern relocation entries the value in the instruction is
1055 // the offset from the symbol, and value is already set in op_info->Value.
1056 return 1;
1057 }
1058 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1059 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1060 const char *add = GuessSymbolName(r_value, info);
1061 const char *sub = GuessSymbolName(pair_r_value, info);
1062 uint32_t offset = value - (r_value - pair_r_value);
1063 op_info->AddSymbol.Present = 1;
1064 if (add != nullptr)
1065 op_info->AddSymbol.Name = add;
1066 else
1067 op_info->AddSymbol.Value = r_value;
1068 op_info->SubtractSymbol.Present = 1;
1069 if (sub != nullptr)
1070 op_info->SubtractSymbol.Name = sub;
1071 else
1072 op_info->SubtractSymbol.Value = pair_r_value;
1073 op_info->Value = offset;
1074 return 1;
1075 }
1076 // TODO:
1077 // Second search the external relocation entries of a fully linked image
1078 // (if any) for an entry that matches this segment offset.
1079 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001080 return 0;
1081 } else if (Arch == Triple::x86_64) {
1082 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1083 return 0;
1084 // First search the section's relocation entries (if any) for an entry
1085 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +00001086 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001087 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1088 bool reloc_found = false;
1089 DataRefImpl Rel;
1090 MachO::any_relocation_info RE;
1091 bool isExtern = false;
1092 SymbolRef Symbol;
1093 for (const RelocationRef &Reloc : info->S.relocations()) {
1094 uint64_t RelocOffset;
1095 Reloc.getOffset(RelocOffset);
1096 if (RelocOffset == sect_offset) {
1097 Rel = Reloc.getRawDataRefImpl();
1098 RE = info->O->getRelocation(Rel);
1099 // NOTE: Scattered relocations don't exist on x86_64.
1100 isExtern = info->O->getPlainRelocationExternal(RE);
1101 if (isExtern) {
1102 symbol_iterator RelocSym = Reloc.getSymbol();
1103 Symbol = *RelocSym;
1104 }
1105 reloc_found = true;
1106 break;
1107 }
1108 }
1109 if (reloc_found && isExtern) {
1110 // The Value passed in will be adjusted by the Pc if the instruction
1111 // adds the Pc. But for x86_64 external relocation entries the Value
1112 // is the offset from the external symbol.
1113 if (info->O->getAnyRelocationPCRel(RE))
1114 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001115 StringRef SymName;
1116 Symbol.getName(SymName);
1117 const char *name = SymName.data();
1118 unsigned Type = info->O->getAnyRelocationType(RE);
1119 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1120 DataRefImpl RelNext = Rel;
1121 info->O->moveRelocationNext(RelNext);
1122 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1123 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1124 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1125 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1126 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1127 op_info->SubtractSymbol.Present = 1;
1128 op_info->SubtractSymbol.Name = name;
1129 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1130 Symbol = *RelocSymNext;
1131 StringRef SymNameNext;
1132 Symbol.getName(SymNameNext);
1133 name = SymNameNext.data();
1134 }
1135 }
1136 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
1137 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
1138 op_info->AddSymbol.Present = 1;
1139 op_info->AddSymbol.Name = name;
1140 return 1;
1141 }
1142 // TODO:
1143 // Second search the external relocation entries of a fully linked image
1144 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001145 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001146 return 0;
1147 } else if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +00001148 if (Offset != 0 || (Size != 4 && Size != 2))
1149 return 0;
1150 // First search the section's relocation entries (if any) for an entry
1151 // for this section offset.
1152 uint32_t sect_addr = info->S.getAddress();
1153 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1154 bool reloc_found = false;
1155 DataRefImpl Rel;
1156 MachO::any_relocation_info RE;
1157 bool isExtern = false;
1158 SymbolRef Symbol;
1159 bool r_scattered = false;
1160 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
1161 for (const RelocationRef &Reloc : info->S.relocations()) {
1162 uint64_t RelocOffset;
1163 Reloc.getOffset(RelocOffset);
1164 if (RelocOffset == sect_offset) {
1165 Rel = Reloc.getRawDataRefImpl();
1166 RE = info->O->getRelocation(Rel);
1167 r_length = info->O->getAnyRelocationLength(RE);
1168 r_scattered = info->O->isRelocationScattered(RE);
1169 if (r_scattered) {
1170 r_value = info->O->getScatteredRelocationValue(RE);
1171 r_type = info->O->getScatteredRelocationType(RE);
1172 } else {
1173 r_type = info->O->getAnyRelocationType(RE);
1174 isExtern = info->O->getPlainRelocationExternal(RE);
1175 if (isExtern) {
1176 symbol_iterator RelocSym = Reloc.getSymbol();
1177 Symbol = *RelocSym;
1178 }
1179 }
1180 if (r_type == MachO::ARM_RELOC_HALF ||
1181 r_type == MachO::ARM_RELOC_SECTDIFF ||
1182 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
1183 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1184 DataRefImpl RelNext = Rel;
1185 info->O->moveRelocationNext(RelNext);
1186 MachO::any_relocation_info RENext;
1187 RENext = info->O->getRelocation(RelNext);
1188 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
1189 if (info->O->isRelocationScattered(RENext))
1190 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1191 }
1192 reloc_found = true;
1193 break;
1194 }
1195 }
1196 if (reloc_found && isExtern) {
1197 StringRef SymName;
1198 Symbol.getName(SymName);
1199 const char *name = SymName.data();
1200 op_info->AddSymbol.Present = 1;
1201 op_info->AddSymbol.Name = name;
1202 if (value != 0) {
1203 switch (r_type) {
1204 case MachO::ARM_RELOC_HALF:
1205 if ((r_length & 0x1) == 1) {
1206 op_info->Value = value << 16 | other_half;
1207 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1208 } else {
1209 op_info->Value = other_half << 16 | value;
1210 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1211 }
1212 break;
1213 default:
1214 break;
1215 }
1216 } else {
1217 switch (r_type) {
1218 case MachO::ARM_RELOC_HALF:
1219 if ((r_length & 0x1) == 1) {
1220 op_info->Value = value << 16 | other_half;
1221 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1222 } else {
1223 op_info->Value = other_half << 16 | value;
1224 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1225 }
1226 break;
1227 default:
1228 break;
1229 }
1230 }
1231 return 1;
1232 }
1233 // If we have a branch that is not an external relocation entry then
1234 // return 0 so the code in tryAddingSymbolicOperand() can use the
1235 // SymbolLookUp call back with the branch target address to look up the
1236 // symbol and possiblity add an annotation for a symbol stub.
1237 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
1238 r_type == MachO::ARM_THUMB_RELOC_BR22))
1239 return 0;
1240
1241 uint32_t offset = 0;
1242 if (reloc_found) {
1243 if (r_type == MachO::ARM_RELOC_HALF ||
1244 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1245 if ((r_length & 0x1) == 1)
1246 value = value << 16 | other_half;
1247 else
1248 value = other_half << 16 | value;
1249 }
1250 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1251 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1252 offset = value - r_value;
1253 value = r_value;
1254 }
1255 }
1256
1257 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1258 if ((r_length & 0x1) == 1)
1259 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1260 else
1261 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1262 const char *add = GuessSymbolName(r_value, info);
1263 const char *sub = GuessSymbolName(pair_r_value, info);
1264 int32_t offset = value - (r_value - pair_r_value);
1265 op_info->AddSymbol.Present = 1;
1266 if (add != nullptr)
1267 op_info->AddSymbol.Name = add;
1268 else
1269 op_info->AddSymbol.Value = r_value;
1270 op_info->SubtractSymbol.Present = 1;
1271 if (sub != nullptr)
1272 op_info->SubtractSymbol.Name = sub;
1273 else
1274 op_info->SubtractSymbol.Value = pair_r_value;
1275 op_info->Value = offset;
1276 return 1;
1277 }
1278
1279 if (reloc_found == false)
1280 return 0;
1281
1282 op_info->AddSymbol.Present = 1;
1283 op_info->Value = offset;
1284 if (reloc_found) {
1285 if (r_type == MachO::ARM_RELOC_HALF) {
1286 if ((r_length & 0x1) == 1)
1287 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1288 else
1289 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1290 }
1291 }
1292 const char *add = GuessSymbolName(value, info);
1293 if (add != nullptr) {
1294 op_info->AddSymbol.Name = add;
1295 return 1;
1296 }
1297 op_info->AddSymbol.Value = value;
1298 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001299 } else if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001300 if (Offset != 0 || Size != 4)
1301 return 0;
1302 // First search the section's relocation entries (if any) for an entry
1303 // for this section offset.
1304 uint64_t sect_addr = info->S.getAddress();
1305 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1306 bool reloc_found = false;
1307 DataRefImpl Rel;
1308 MachO::any_relocation_info RE;
1309 bool isExtern = false;
1310 SymbolRef Symbol;
1311 uint32_t r_type = 0;
1312 for (const RelocationRef &Reloc : info->S.relocations()) {
1313 uint64_t RelocOffset;
1314 Reloc.getOffset(RelocOffset);
1315 if (RelocOffset == sect_offset) {
1316 Rel = Reloc.getRawDataRefImpl();
1317 RE = info->O->getRelocation(Rel);
1318 r_type = info->O->getAnyRelocationType(RE);
1319 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1320 DataRefImpl RelNext = Rel;
1321 info->O->moveRelocationNext(RelNext);
1322 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1323 if (value == 0) {
1324 value = info->O->getPlainRelocationSymbolNum(RENext);
1325 op_info->Value = value;
1326 }
1327 }
1328 // NOTE: Scattered relocations don't exist on arm64.
1329 isExtern = info->O->getPlainRelocationExternal(RE);
1330 if (isExtern) {
1331 symbol_iterator RelocSym = Reloc.getSymbol();
1332 Symbol = *RelocSym;
1333 }
1334 reloc_found = true;
1335 break;
1336 }
1337 }
1338 if (reloc_found && isExtern) {
1339 StringRef SymName;
1340 Symbol.getName(SymName);
1341 const char *name = SymName.data();
1342 op_info->AddSymbol.Present = 1;
1343 op_info->AddSymbol.Name = name;
1344
1345 switch (r_type) {
1346 case MachO::ARM64_RELOC_PAGE21:
1347 /* @page */
1348 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1349 break;
1350 case MachO::ARM64_RELOC_PAGEOFF12:
1351 /* @pageoff */
1352 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1353 break;
1354 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1355 /* @gotpage */
1356 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1357 break;
1358 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1359 /* @gotpageoff */
1360 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
1361 break;
1362 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
1363 /* @tvlppage is not implemented in llvm-mc */
1364 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
1365 break;
1366 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
1367 /* @tvlppageoff is not implemented in llvm-mc */
1368 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
1369 break;
1370 default:
1371 case MachO::ARM64_RELOC_BRANCH26:
1372 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
1373 break;
1374 }
1375 return 1;
1376 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001377 return 0;
1378 } else {
1379 return 0;
1380 }
1381}
1382
Kevin Enderbybf246f52014-09-24 23:08:22 +00001383// GuessCstringPointer is passed the address of what might be a pointer to a
1384// literal string in a cstring section. If that address is in a cstring section
1385// it returns a pointer to that string. Else it returns nullptr.
1386const char *GuessCstringPointer(uint64_t ReferenceValue,
1387 struct DisassembleInfo *info) {
1388 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1389 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1390 for (unsigned I = 0;; ++I) {
1391 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1392 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1393 for (unsigned J = 0; J < Seg.nsects; ++J) {
1394 MachO::section_64 Sec = info->O->getSection64(Load, J);
1395 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1396 if (section_type == MachO::S_CSTRING_LITERALS &&
1397 ReferenceValue >= Sec.addr &&
1398 ReferenceValue < Sec.addr + Sec.size) {
1399 uint64_t sect_offset = ReferenceValue - Sec.addr;
1400 uint64_t object_offset = Sec.offset + sect_offset;
1401 StringRef MachOContents = info->O->getData();
1402 uint64_t object_size = MachOContents.size();
1403 const char *object_addr = (const char *)MachOContents.data();
1404 if (object_offset < object_size) {
1405 const char *name = object_addr + object_offset;
1406 return name;
1407 } else {
1408 return nullptr;
1409 }
1410 }
1411 }
1412 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1413 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1414 for (unsigned J = 0; J < Seg.nsects; ++J) {
1415 MachO::section Sec = info->O->getSection(Load, J);
1416 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1417 if (section_type == MachO::S_CSTRING_LITERALS &&
1418 ReferenceValue >= Sec.addr &&
1419 ReferenceValue < Sec.addr + Sec.size) {
1420 uint64_t sect_offset = ReferenceValue - Sec.addr;
1421 uint64_t object_offset = Sec.offset + sect_offset;
1422 StringRef MachOContents = info->O->getData();
1423 uint64_t object_size = MachOContents.size();
1424 const char *object_addr = (const char *)MachOContents.data();
1425 if (object_offset < object_size) {
1426 const char *name = object_addr + object_offset;
1427 return name;
1428 } else {
1429 return nullptr;
1430 }
1431 }
1432 }
1433 }
1434 if (I == LoadCommandCount - 1)
1435 break;
1436 else
1437 Load = info->O->getNextLoadCommandInfo(Load);
1438 }
1439 return nullptr;
1440}
1441
Kevin Enderby85974882014-09-26 22:20:44 +00001442// GuessIndirectSymbol returns the name of the indirect symbol for the
1443// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
1444// an address of a symbol stub or a lazy or non-lazy pointer to associate the
1445// symbol name being referenced by the stub or pointer.
1446static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
1447 struct DisassembleInfo *info) {
1448 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1449 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1450 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
1451 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
1452 for (unsigned I = 0;; ++I) {
1453 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1454 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1455 for (unsigned J = 0; J < Seg.nsects; ++J) {
1456 MachO::section_64 Sec = info->O->getSection64(Load, J);
1457 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1458 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1459 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1460 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1461 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1462 section_type == MachO::S_SYMBOL_STUBS) &&
1463 ReferenceValue >= Sec.addr &&
1464 ReferenceValue < Sec.addr + Sec.size) {
1465 uint32_t stride;
1466 if (section_type == MachO::S_SYMBOL_STUBS)
1467 stride = Sec.reserved2;
1468 else
1469 stride = 8;
1470 if (stride == 0)
1471 return nullptr;
1472 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1473 if (index < Dysymtab.nindirectsyms) {
1474 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001475 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00001476 if (indirect_symbol < Symtab.nsyms) {
1477 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1478 SymbolRef Symbol = *Sym;
1479 StringRef SymName;
1480 Symbol.getName(SymName);
1481 const char *name = SymName.data();
1482 return name;
1483 }
1484 }
1485 }
1486 }
1487 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1488 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1489 for (unsigned J = 0; J < Seg.nsects; ++J) {
1490 MachO::section Sec = info->O->getSection(Load, J);
1491 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1492 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1493 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1494 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1495 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1496 section_type == MachO::S_SYMBOL_STUBS) &&
1497 ReferenceValue >= Sec.addr &&
1498 ReferenceValue < Sec.addr + Sec.size) {
1499 uint32_t stride;
1500 if (section_type == MachO::S_SYMBOL_STUBS)
1501 stride = Sec.reserved2;
1502 else
1503 stride = 4;
1504 if (stride == 0)
1505 return nullptr;
1506 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1507 if (index < Dysymtab.nindirectsyms) {
1508 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001509 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00001510 if (indirect_symbol < Symtab.nsyms) {
1511 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1512 SymbolRef Symbol = *Sym;
1513 StringRef SymName;
1514 Symbol.getName(SymName);
1515 const char *name = SymName.data();
1516 return name;
1517 }
1518 }
1519 }
1520 }
1521 }
1522 if (I == LoadCommandCount - 1)
1523 break;
1524 else
1525 Load = info->O->getNextLoadCommandInfo(Load);
1526 }
1527 return nullptr;
1528}
1529
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001530// method_reference() is called passing it the ReferenceName that might be
1531// a reference it to an Objective-C method call. If so then it allocates and
1532// assembles a method call string with the values last seen and saved in
1533// the DisassembleInfo's class_name and selector_name fields. This is saved
1534// into the method field of the info and any previous string is free'ed.
1535// Then the class_name field in the info is set to nullptr. The method call
1536// string is set into ReferenceName and ReferenceType is set to
1537// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
1538// then both ReferenceType and ReferenceName are left unchanged.
1539static void method_reference(struct DisassembleInfo *info,
1540 uint64_t *ReferenceType,
1541 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001542 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001543 if (*ReferenceName != nullptr) {
1544 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001545 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001546 if (info->method != nullptr)
1547 free(info->method);
1548 if (info->class_name != nullptr) {
1549 info->method = (char *)malloc(5 + strlen(info->class_name) +
1550 strlen(info->selector_name));
1551 if (info->method != nullptr) {
1552 strcpy(info->method, "+[");
1553 strcat(info->method, info->class_name);
1554 strcat(info->method, " ");
1555 strcat(info->method, info->selector_name);
1556 strcat(info->method, "]");
1557 *ReferenceName = info->method;
1558 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1559 }
1560 } else {
1561 info->method = (char *)malloc(9 + strlen(info->selector_name));
1562 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001563 if (Arch == Triple::x86_64)
1564 strcpy(info->method, "-[%rdi ");
1565 else if (Arch == Triple::aarch64)
1566 strcpy(info->method, "-[x0 ");
1567 else
1568 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001569 strcat(info->method, info->selector_name);
1570 strcat(info->method, "]");
1571 *ReferenceName = info->method;
1572 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1573 }
1574 }
1575 info->class_name = nullptr;
1576 }
1577 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001578 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001579 if (info->method != nullptr)
1580 free(info->method);
1581 info->method = (char *)malloc(17 + strlen(info->selector_name));
1582 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001583 if (Arch == Triple::x86_64)
1584 strcpy(info->method, "-[[%rdi super] ");
1585 else if (Arch == Triple::aarch64)
1586 strcpy(info->method, "-[[x0 super] ");
1587 else
1588 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001589 strcat(info->method, info->selector_name);
1590 strcat(info->method, "]");
1591 *ReferenceName = info->method;
1592 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1593 }
1594 info->class_name = nullptr;
1595 }
1596 }
1597 }
1598}
1599
1600// GuessPointerPointer() is passed the address of what might be a pointer to
1601// a reference to an Objective-C class, selector, message ref or cfstring.
1602// If so the value of the pointer is returned and one of the booleans are set
1603// to true. If not zero is returned and all the booleans are set to false.
1604static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
1605 struct DisassembleInfo *info,
1606 bool &classref, bool &selref, bool &msgref,
1607 bool &cfstring) {
1608 classref = false;
1609 selref = false;
1610 msgref = false;
1611 cfstring = false;
1612 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1613 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1614 for (unsigned I = 0;; ++I) {
1615 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1616 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1617 for (unsigned J = 0; J < Seg.nsects; ++J) {
1618 MachO::section_64 Sec = info->O->getSection64(Load, J);
1619 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
1620 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1621 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
1622 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
1623 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
1624 ReferenceValue >= Sec.addr &&
1625 ReferenceValue < Sec.addr + Sec.size) {
1626 uint64_t sect_offset = ReferenceValue - Sec.addr;
1627 uint64_t object_offset = Sec.offset + sect_offset;
1628 StringRef MachOContents = info->O->getData();
1629 uint64_t object_size = MachOContents.size();
1630 const char *object_addr = (const char *)MachOContents.data();
1631 if (object_offset < object_size) {
1632 uint64_t pointer_value;
1633 memcpy(&pointer_value, object_addr + object_offset,
1634 sizeof(uint64_t));
1635 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1636 sys::swapByteOrder(pointer_value);
1637 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
1638 selref = true;
1639 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1640 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
1641 classref = true;
1642 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
1643 ReferenceValue + 8 < Sec.addr + Sec.size) {
1644 msgref = true;
1645 memcpy(&pointer_value, object_addr + object_offset + 8,
1646 sizeof(uint64_t));
1647 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1648 sys::swapByteOrder(pointer_value);
1649 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
1650 cfstring = true;
1651 return pointer_value;
1652 } else {
1653 return 0;
1654 }
1655 }
1656 }
1657 }
1658 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
1659 if (I == LoadCommandCount - 1)
1660 break;
1661 else
1662 Load = info->O->getNextLoadCommandInfo(Load);
1663 }
1664 return 0;
1665}
1666
1667// get_pointer_64 returns a pointer to the bytes in the object file at the
1668// Address from a section in the Mach-O file. And indirectly returns the
1669// offset into the section, number of bytes left in the section past the offset
1670// and which section is was being referenced. If the Address is not in a
1671// section nullptr is returned.
1672const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1673 SectionRef &S, DisassembleInfo *info) {
1674 offset = 0;
1675 left = 0;
1676 S = SectionRef();
1677 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1678 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1679 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1680 if (Address >= SectAddress && Address < SectAddress + SectSize) {
1681 S = (*(info->Sections))[SectIdx];
1682 offset = Address - SectAddress;
1683 left = SectSize - offset;
1684 StringRef SectContents;
1685 ((*(info->Sections))[SectIdx]).getContents(SectContents);
1686 return SectContents.data() + offset;
1687 }
1688 }
1689 return nullptr;
1690}
1691
1692// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1693// the symbol indirectly through n_value. Based on the relocation information
1694// for the specified section offset in the specified section reference.
1695const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1696 DisassembleInfo *info, uint64_t &n_value) {
1697 n_value = 0;
1698 if (info->verbose == false)
1699 return nullptr;
1700
1701 // See if there is an external relocation entry at the sect_offset.
1702 bool reloc_found = false;
1703 DataRefImpl Rel;
1704 MachO::any_relocation_info RE;
1705 bool isExtern = false;
1706 SymbolRef Symbol;
1707 for (const RelocationRef &Reloc : S.relocations()) {
1708 uint64_t RelocOffset;
1709 Reloc.getOffset(RelocOffset);
1710 if (RelocOffset == sect_offset) {
1711 Rel = Reloc.getRawDataRefImpl();
1712 RE = info->O->getRelocation(Rel);
1713 if (info->O->isRelocationScattered(RE))
1714 continue;
1715 isExtern = info->O->getPlainRelocationExternal(RE);
1716 if (isExtern) {
1717 symbol_iterator RelocSym = Reloc.getSymbol();
1718 Symbol = *RelocSym;
1719 }
1720 reloc_found = true;
1721 break;
1722 }
1723 }
1724 // If there is an external relocation entry for a symbol in this section
1725 // at this section_offset then use that symbol's value for the n_value
1726 // and return its name.
1727 const char *SymbolName = nullptr;
1728 if (reloc_found && isExtern) {
1729 Symbol.getAddress(n_value);
1730 StringRef name;
1731 Symbol.getName(name);
1732 if (!name.empty()) {
1733 SymbolName = name.data();
1734 return SymbolName;
1735 }
1736 }
1737
1738 // TODO: For fully linked images, look through the external relocation
1739 // entries off the dynamic symtab command. For these the r_offset is from the
1740 // start of the first writeable segment in the Mach-O file. So the offset
1741 // to this section from that segment is passed to this routine by the caller,
1742 // as the database_offset. Which is the difference of the section's starting
1743 // address and the first writable segment.
1744 //
1745 // NOTE: need add passing the database_offset to this routine.
1746
1747 // TODO: We did not find an external relocation entry so look up the
1748 // ReferenceValue as an address of a symbol and if found return that symbol's
1749 // name.
1750 //
1751 // NOTE: need add passing the ReferenceValue to this routine. Then that code
1752 // would simply be this:
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001753 // SymbolName = GuessSymbolName(ReferenceValue, info);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001754
1755 return SymbolName;
1756}
1757
1758// These are structs in the Objective-C meta data and read to produce the
1759// comments for disassembly. While these are part of the ABI they are no
1760// public defintions. So the are here not in include/llvm/Support/MachO.h .
1761
1762// The cfstring object in a 64-bit Mach-O file.
1763struct cfstring64_t {
1764 uint64_t isa; // class64_t * (64-bit pointer)
1765 uint64_t flags; // flag bits
1766 uint64_t characters; // char * (64-bit pointer)
1767 uint64_t length; // number of non-NULL characters in above
1768};
1769
1770// The class object in a 64-bit Mach-O file.
1771struct class64_t {
1772 uint64_t isa; // class64_t * (64-bit pointer)
1773 uint64_t superclass; // class64_t * (64-bit pointer)
1774 uint64_t cache; // Cache (64-bit pointer)
1775 uint64_t vtable; // IMP * (64-bit pointer)
1776 uint64_t data; // class_ro64_t * (64-bit pointer)
1777};
1778
1779struct class_ro64_t {
1780 uint32_t flags;
1781 uint32_t instanceStart;
1782 uint32_t instanceSize;
1783 uint32_t reserved;
1784 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
1785 uint64_t name; // const char * (64-bit pointer)
1786 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
1787 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
1788 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
1789 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1790 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1791};
1792
1793inline void swapStruct(struct cfstring64_t &cfs) {
1794 sys::swapByteOrder(cfs.isa);
1795 sys::swapByteOrder(cfs.flags);
1796 sys::swapByteOrder(cfs.characters);
1797 sys::swapByteOrder(cfs.length);
1798}
1799
1800inline void swapStruct(struct class64_t &c) {
1801 sys::swapByteOrder(c.isa);
1802 sys::swapByteOrder(c.superclass);
1803 sys::swapByteOrder(c.cache);
1804 sys::swapByteOrder(c.vtable);
1805 sys::swapByteOrder(c.data);
1806}
1807
1808inline void swapStruct(struct class_ro64_t &cro) {
1809 sys::swapByteOrder(cro.flags);
1810 sys::swapByteOrder(cro.instanceStart);
1811 sys::swapByteOrder(cro.instanceSize);
1812 sys::swapByteOrder(cro.reserved);
1813 sys::swapByteOrder(cro.ivarLayout);
1814 sys::swapByteOrder(cro.name);
1815 sys::swapByteOrder(cro.baseMethods);
1816 sys::swapByteOrder(cro.baseProtocols);
1817 sys::swapByteOrder(cro.ivars);
1818 sys::swapByteOrder(cro.weakIvarLayout);
1819 sys::swapByteOrder(cro.baseProperties);
1820}
1821
1822static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1823 struct DisassembleInfo *info);
1824
1825// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1826// to an Objective-C class and returns the class name. It is also passed the
1827// address of the pointer, so when the pointer is zero as it can be in an .o
1828// file, that is used to look for an external relocation entry with a symbol
1829// name.
1830const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1831 uint64_t ReferenceValue,
1832 struct DisassembleInfo *info) {
1833 const char *r;
1834 uint32_t offset, left;
1835 SectionRef S;
1836
1837 // The pointer_value can be 0 in an object file and have a relocation
1838 // entry for the class symbol at the ReferenceValue (the address of the
1839 // pointer).
1840 if (pointer_value == 0) {
1841 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1842 if (r == nullptr || left < sizeof(uint64_t))
1843 return nullptr;
1844 uint64_t n_value;
1845 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1846 if (symbol_name == nullptr)
1847 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001848 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001849 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1850 return class_name + 2;
1851 else
1852 return nullptr;
1853 }
1854
1855 // The case were the pointer_value is non-zero and points to a class defined
1856 // in this Mach-O file.
1857 r = get_pointer_64(pointer_value, offset, left, S, info);
1858 if (r == nullptr || left < sizeof(struct class64_t))
1859 return nullptr;
1860 struct class64_t c;
1861 memcpy(&c, r, sizeof(struct class64_t));
1862 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1863 swapStruct(c);
1864 if (c.data == 0)
1865 return nullptr;
1866 r = get_pointer_64(c.data, offset, left, S, info);
1867 if (r == nullptr || left < sizeof(struct class_ro64_t))
1868 return nullptr;
1869 struct class_ro64_t cro;
1870 memcpy(&cro, r, sizeof(struct class_ro64_t));
1871 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1872 swapStruct(cro);
1873 if (cro.name == 0)
1874 return nullptr;
1875 const char *name = get_pointer_64(cro.name, offset, left, S, info);
1876 return name;
1877}
1878
1879// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1880// pointer to a cfstring and returns its name or nullptr.
1881const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1882 struct DisassembleInfo *info) {
1883 const char *r, *name;
1884 uint32_t offset, left;
1885 SectionRef S;
1886 struct cfstring64_t cfs;
1887 uint64_t cfs_characters;
1888
1889 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1890 if (r == nullptr || left < sizeof(struct cfstring64_t))
1891 return nullptr;
1892 memcpy(&cfs, r, sizeof(struct cfstring64_t));
1893 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1894 swapStruct(cfs);
1895 if (cfs.characters == 0) {
1896 uint64_t n_value;
1897 const char *symbol_name = get_symbol_64(
1898 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1899 if (symbol_name == nullptr)
1900 return nullptr;
1901 cfs_characters = n_value;
1902 } else
1903 cfs_characters = cfs.characters;
1904 name = get_pointer_64(cfs_characters, offset, left, S, info);
1905
1906 return name;
1907}
1908
1909// get_objc2_64bit_selref() is used for disassembly and is passed a the address
1910// of a pointer to an Objective-C selector reference when the pointer value is
1911// zero as in a .o file and is likely to have a external relocation entry with
1912// who's symbol's n_value is the real pointer to the selector name. If that is
1913// the case the real pointer to the selector name is returned else 0 is
1914// returned
1915uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1916 struct DisassembleInfo *info) {
1917 uint32_t offset, left;
1918 SectionRef S;
1919
1920 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1921 if (r == nullptr || left < sizeof(uint64_t))
1922 return 0;
1923 uint64_t n_value;
1924 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1925 if (symbol_name == nullptr)
1926 return 0;
1927 return n_value;
1928}
1929
Kevin Enderbybf246f52014-09-24 23:08:22 +00001930// GuessLiteralPointer returns a string which for the item in the Mach-O file
1931// for the address passed in as ReferenceValue for printing as a comment with
1932// the instruction and also returns the corresponding type of that item
1933// indirectly through ReferenceType.
1934//
1935// If ReferenceValue is an address of literal cstring then a pointer to the
1936// cstring is returned and ReferenceType is set to
1937// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1938//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001939// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1940// Class ref that name is returned and the ReferenceType is set accordingly.
1941//
1942// Lastly, literals which are Symbol address in a literal pool are looked for
1943// and if found the symbol name is returned and ReferenceType is set to
1944// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1945//
1946// If there is no item in the Mach-O file for the address passed in as
1947// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Kevin Enderbybf246f52014-09-24 23:08:22 +00001948const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1949 uint64_t *ReferenceType,
1950 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001951 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00001952 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00001953 uint64_t sect_offset = ReferencePC - sect_addr;
1954 bool reloc_found = false;
1955 DataRefImpl Rel;
1956 MachO::any_relocation_info RE;
1957 bool isExtern = false;
1958 SymbolRef Symbol;
1959 for (const RelocationRef &Reloc : info->S.relocations()) {
1960 uint64_t RelocOffset;
1961 Reloc.getOffset(RelocOffset);
1962 if (RelocOffset == sect_offset) {
1963 Rel = Reloc.getRawDataRefImpl();
1964 RE = info->O->getRelocation(Rel);
1965 if (info->O->isRelocationScattered(RE))
1966 continue;
1967 isExtern = info->O->getPlainRelocationExternal(RE);
1968 if (isExtern) {
1969 symbol_iterator RelocSym = Reloc.getSymbol();
1970 Symbol = *RelocSym;
1971 }
1972 reloc_found = true;
1973 break;
1974 }
1975 }
1976 // If there is an external relocation entry for a symbol in a section
1977 // then used that symbol's value for the value of the reference.
1978 if (reloc_found && isExtern) {
1979 if (info->O->getAnyRelocationPCRel(RE)) {
1980 unsigned Type = info->O->getAnyRelocationType(RE);
1981 if (Type == MachO::X86_64_RELOC_SIGNED) {
1982 Symbol.getAddress(ReferenceValue);
1983 }
1984 }
1985 }
1986
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001987 // Look for literals such as Objective-C CFStrings refs, Selector refs,
1988 // Message refs and Class refs.
1989 bool classref, selref, msgref, cfstring;
1990 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1991 selref, msgref, cfstring);
1992 if (classref == true && pointer_value == 0) {
1993 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1994 // And the pointer_value in that section is typically zero as it will be
1995 // set by dyld as part of the "bind information".
1996 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1997 if (name != nullptr) {
1998 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001999 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002000 if (class_name != nullptr && class_name[1] == '_' &&
2001 class_name[2] != '\0') {
2002 info->class_name = class_name + 2;
2003 return name;
2004 }
2005 }
2006 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002007
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002008 if (classref == true) {
2009 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
2010 const char *name =
2011 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
2012 if (name != nullptr)
2013 info->class_name = name;
2014 else
2015 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00002016 return name;
2017 }
2018
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002019 if (cfstring == true) {
2020 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
2021 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
2022 return name;
2023 }
2024
2025 if (selref == true && pointer_value == 0)
2026 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
2027
2028 if (pointer_value != 0)
2029 ReferenceValue = pointer_value;
2030
2031 const char *name = GuessCstringPointer(ReferenceValue, info);
2032 if (name) {
2033 if (pointer_value != 0 && selref == true) {
2034 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
2035 info->selector_name = name;
2036 } else if (pointer_value != 0 && msgref == true) {
2037 info->class_name = nullptr;
2038 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
2039 info->selector_name = name;
2040 } else
2041 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
2042 return name;
2043 }
2044
2045 // Lastly look for an indirect symbol with this ReferenceValue which is in
2046 // a literal pool. If found return that symbol name.
2047 name = GuessIndirectSymbol(ReferenceValue, info);
2048 if (name) {
2049 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
2050 return name;
2051 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002052
2053 return nullptr;
2054}
2055
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002056// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00002057// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002058// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
2059// is created and returns the symbol name that matches the ReferenceValue or
2060// nullptr if none. The ReferenceType is passed in for the IN type of
2061// reference the instruction is making from the values in defined in the header
2062// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
2063// Out type and the ReferenceName will also be set which is added as a comment
2064// to the disassembled instruction.
2065//
Kevin Enderby04bf6932014-10-28 23:39:46 +00002066#if HAVE_CXXABI_H
2067// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002068// returned through ReferenceName and ReferenceType is set to
2069// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00002070#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002071//
2072// When this is called to get a symbol name for a branch target then the
2073// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
2074// SymbolValue will be looked for in the indirect symbol table to determine if
2075// it is an address for a symbol stub. If so then the symbol name for that
2076// stub is returned indirectly through ReferenceName and then ReferenceType is
2077// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
2078//
Kevin Enderbybf246f52014-09-24 23:08:22 +00002079// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002080// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
2081// SymbolValue is checked to be an address of literal pointer, symbol pointer,
2082// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002083// set to correspond to that as well as setting the ReferenceName.
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002084const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
2085 uint64_t *ReferenceType,
2086 uint64_t ReferencePC,
2087 const char **ReferenceName) {
2088 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002089 // If no verbose symbolic information is wanted then just return nullptr.
2090 if (info->verbose == false) {
2091 *ReferenceName = nullptr;
2092 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002093 return nullptr;
2094 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00002095
Kevin Enderby9907d0a2014-11-04 00:43:16 +00002096 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
Kevin Enderbybf246f52014-09-24 23:08:22 +00002097
Kevin Enderby85974882014-09-26 22:20:44 +00002098 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
2099 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002100 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002101 method_reference(info, ReferenceType, ReferenceName);
2102 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
2103 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
2104 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00002105#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002106 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00002107 if (info->demangled_name != nullptr)
2108 free(info->demangled_name);
2109 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002110 info->demangled_name =
2111 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002112 if (info->demangled_name != nullptr) {
2113 *ReferenceName = info->demangled_name;
2114 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2115 } else
2116 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2117 } else
2118#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002119 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2120 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
2121 *ReferenceName =
2122 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00002123 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002124 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00002125 else
2126 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002127 // If this is arm64 and the reference is an adrp instruction save the
2128 // instruction, passed in ReferenceValue and the address of the instruction
2129 // for use later if we see and add immediate instruction.
2130 } else if (info->O->getArch() == Triple::aarch64 &&
2131 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
2132 info->adrp_inst = ReferenceValue;
2133 info->adrp_addr = ReferencePC;
2134 SymbolName = nullptr;
2135 *ReferenceName = nullptr;
2136 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2137 // If this is arm64 and reference is an add immediate instruction and we
2138 // have
2139 // seen an adrp instruction just before it and the adrp's Xd register
2140 // matches
2141 // this add's Xn register reconstruct the value being referenced and look to
2142 // see if it is a literal pointer. Note the add immediate instruction is
2143 // passed in ReferenceValue.
2144 } else if (info->O->getArch() == Triple::aarch64 &&
2145 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
2146 ReferencePC - 4 == info->adrp_addr &&
2147 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2148 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2149 uint32_t addxri_inst;
2150 uint64_t adrp_imm, addxri_imm;
2151
2152 adrp_imm =
2153 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2154 if (info->adrp_inst & 0x0200000)
2155 adrp_imm |= 0xfffffffffc000000LL;
2156
2157 addxri_inst = ReferenceValue;
2158 addxri_imm = (addxri_inst >> 10) & 0xfff;
2159 if (((addxri_inst >> 22) & 0x3) == 1)
2160 addxri_imm <<= 12;
2161
2162 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2163 (adrp_imm << 12) + addxri_imm;
2164
2165 *ReferenceName =
2166 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2167 if (*ReferenceName == nullptr)
2168 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2169 // If this is arm64 and the reference is a load register instruction and we
2170 // have seen an adrp instruction just before it and the adrp's Xd register
2171 // matches this add's Xn register reconstruct the value being referenced and
2172 // look to see if it is a literal pointer. Note the load register
2173 // instruction is passed in ReferenceValue.
2174 } else if (info->O->getArch() == Triple::aarch64 &&
2175 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
2176 ReferencePC - 4 == info->adrp_addr &&
2177 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
2178 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
2179 uint32_t ldrxui_inst;
2180 uint64_t adrp_imm, ldrxui_imm;
2181
2182 adrp_imm =
2183 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
2184 if (info->adrp_inst & 0x0200000)
2185 adrp_imm |= 0xfffffffffc000000LL;
2186
2187 ldrxui_inst = ReferenceValue;
2188 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
2189
2190 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
2191 (adrp_imm << 12) + (ldrxui_imm << 3);
2192
2193 *ReferenceName =
2194 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2195 if (*ReferenceName == nullptr)
2196 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2197 }
2198 // If this arm64 and is an load register (PC-relative) instruction the
2199 // ReferenceValue is the PC plus the immediate value.
2200 else if (info->O->getArch() == Triple::aarch64 &&
2201 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
2202 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
2203 *ReferenceName =
2204 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
2205 if (*ReferenceName == nullptr)
2206 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00002207 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00002208#if HAVE_CXXABI_H
2209 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
2210 if (info->demangled_name != nullptr)
2211 free(info->demangled_name);
2212 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002213 info->demangled_name =
2214 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002215 if (info->demangled_name != nullptr) {
2216 *ReferenceName = info->demangled_name;
2217 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
2218 }
2219 }
2220#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002221 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002222 *ReferenceName = nullptr;
2223 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
2224 }
2225
2226 return SymbolName;
2227}
2228
Kevin Enderbybf246f52014-09-24 23:08:22 +00002229/// \brief Emits the comments that are stored in the CommentStream.
2230/// Each comment in the CommentStream must end with a newline.
2231static void emitComments(raw_svector_ostream &CommentStream,
2232 SmallString<128> &CommentsToEmit,
2233 formatted_raw_ostream &FormattedOS,
2234 const MCAsmInfo &MAI) {
2235 // Flush the stream before taking its content.
2236 CommentStream.flush();
2237 StringRef Comments = CommentsToEmit.str();
2238 // Get the default information for printing a comment.
2239 const char *CommentBegin = MAI.getCommentString();
2240 unsigned CommentColumn = MAI.getCommentColumn();
2241 bool IsFirst = true;
2242 while (!Comments.empty()) {
2243 if (!IsFirst)
2244 FormattedOS << '\n';
2245 // Emit a line of comments.
2246 FormattedOS.PadToColumn(CommentColumn);
2247 size_t Position = Comments.find('\n');
2248 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2249 // Move after the newline character.
2250 Comments = Comments.substr(Position + 1);
2251 IsFirst = false;
2252 }
2253 FormattedOS.flush();
2254
2255 // Tell the comment stream that the vector changed underneath it.
2256 CommentsToEmit.clear();
2257 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002258}
2259
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002260static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002261 const char *McpuDefault = nullptr;
2262 const Target *ThumbTarget = nullptr;
2263 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002264 if (!TheTarget) {
2265 // GetTarget prints out stuff.
2266 return;
2267 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002268 if (MCPU.empty() && McpuDefault)
2269 MCPU = McpuDefault;
2270
Ahmed Charles56440fd2014-03-06 05:51:42 +00002271 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002272 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002273 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002274 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002275
Kevin Enderbyc9595622014-08-06 23:24:41 +00002276 // Package up features to be passed to target/subtarget
2277 std::string FeaturesStr;
2278 if (MAttrs.size()) {
2279 SubtargetFeatures Features;
2280 for (unsigned i = 0; i != MAttrs.size(); ++i)
2281 Features.AddFeature(MAttrs[i]);
2282 FeaturesStr = Features.getString();
2283 }
2284
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002285 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00002286 std::unique_ptr<const MCRegisterInfo> MRI(
2287 TheTarget->createMCRegInfo(TripleName));
2288 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00002289 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00002290 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00002291 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00002292 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002293 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002294 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002295 std::unique_ptr<MCSymbolizer> Symbolizer;
2296 struct DisassembleInfo SymbolizerInfo;
2297 std::unique_ptr<MCRelocationInfo> RelInfo(
2298 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2299 if (RelInfo) {
2300 Symbolizer.reset(TheTarget->createMCSymbolizer(
2301 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00002302 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002303 DisAsm->setSymbolizer(std::move(Symbolizer));
2304 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002305 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00002306 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2307 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00002308 // Set the display preference for hex vs. decimal immediates.
2309 IP->setPrintImmHex(PrintImmHex);
2310 // Comment stream and backing vector.
2311 SmallString<128> CommentsToEmit;
2312 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002313 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2314 // if it is done then arm64 comments for string literals don't get printed
2315 // and some constant get printed instead and not setting it causes intel
2316 // (32-bit and 64-bit) comments printed with different spacing before the
2317 // comment causing different diffs with the 'C' disassembler library API.
2318 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002319
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002320 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00002321 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002322 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002323 return;
2324 }
2325
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002326 // Set up thumb disassembler.
2327 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2328 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2329 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002330 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002331 std::unique_ptr<MCInstPrinter> ThumbIP;
2332 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002333 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2334 struct DisassembleInfo ThumbSymbolizerInfo;
2335 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002336 if (ThumbTarget) {
2337 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2338 ThumbAsmInfo.reset(
2339 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2340 ThumbSTI.reset(
2341 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2342 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2343 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00002344 MCContext *PtrThumbCtx = ThumbCtx.get();
2345 ThumbRelInfo.reset(
2346 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2347 if (ThumbRelInfo) {
2348 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2349 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
David Blaikie186db432015-01-18 20:45:48 +00002350 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
Kevin Enderby930fdc72014-11-06 19:00:13 +00002351 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2352 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002353 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2354 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2355 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
2356 *ThumbSTI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00002357 // Set the display preference for hex vs. decimal immediates.
2358 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002359 }
2360
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002361 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002362 errs() << "error: couldn't initialize disassembler for target "
2363 << ThumbTripleName << '\n';
2364 return;
2365 }
2366
Charles Davis8bdfafd2013-09-01 04:28:48 +00002367 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002368
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002369 // FIXME: Using the -cfg command line option, this code used to be able to
2370 // annotate relocations with the referenced symbol's name, and if this was
2371 // inside a __[cf]string section, the data it points to. This is now replaced
2372 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00002373 std::vector<SectionRef> Sections;
2374 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002375 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00002376 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002377
Kevin Enderby273ae012013-06-06 17:20:50 +00002378 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
2379 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002380
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002381 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00002382 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002383
Kevin Enderby273ae012013-06-06 17:20:50 +00002384 // Build a data in code table that is sorted on by the address of each entry.
2385 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00002386 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00002387 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00002388 else
2389 BaseAddress = BaseSegmentAddress;
2390 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00002391 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00002392 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00002393 uint32_t Offset;
2394 DI->getOffset(Offset);
2395 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
2396 }
2397 array_pod_sort(Dices.begin(), Dices.end());
2398
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002399#ifndef NDEBUG
2400 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
2401#else
2402 raw_ostream &DebugOut = nulls();
2403#endif
2404
Ahmed Charles56440fd2014-03-06 05:51:42 +00002405 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00002406 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00002407 // Try to find debug info and set up the DIContext for it.
2408 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00002409 // A separate DSym file path was specified, parse it as a macho file,
2410 // get the sections and supply it to the section name parsing machinery.
2411 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00002412 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00002413 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00002414 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00002415 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00002416 return;
2417 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00002418 DbgObj =
2419 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
2420 .get()
2421 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00002422 }
2423
Eric Christopher7370b552012-11-12 21:40:38 +00002424 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00002425 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00002426 }
2427
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002428 // TODO: For now this only disassembles the (__TEXT,__text) section (see the
2429 // checks in the code below at the top of this loop). It should allow a
2430 // darwin otool(1) like -s option to disassemble any named segment & section
2431 // that is marked as containing instructions with the attributes
2432 // S_ATTR_PURE_INSTRUCTIONS or S_ATTR_SOME_INSTRUCTIONS in the flags field of
2433 // the section structure.
2434 outs() << "(__TEXT,__text) section\n";
2435
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002436 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002437
Rafael Espindola80291272014-10-08 15:28:58 +00002438 bool SectIsText = Sections[SectIdx].isText();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002439 if (SectIsText == false)
2440 continue;
2441
Owen Andersond9243c42011-10-17 21:37:35 +00002442 StringRef SectName;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002443 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002444 continue; // Skip non-text sections
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002445
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00002446 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002447
Rafael Espindolab0f76a42013-04-05 15:15:22 +00002448 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
2449 if (SegmentName != "__TEXT")
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00002450 continue;
2451
Rafael Espindola7fc5b872014-11-12 02:04:27 +00002452 StringRef BytesStr;
2453 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00002454 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
2455 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00002456 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00002457
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002458 bool symbolTableWorked = false;
2459
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002460 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00002461 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
2462 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00002463 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00002464 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00002465 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00002466 RelocOffset -= SectionAddress;
2467
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00002468 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00002469
Rafael Espindola806f0062013-06-05 01:33:53 +00002470 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002471 }
2472 array_pod_sort(Relocs.begin(), Relocs.end());
2473
Kevin Enderbybf246f52014-09-24 23:08:22 +00002474 // Create a map of symbol addresses to symbol names for use by
2475 // the SymbolizerSymbolLookUp() routine.
2476 SymbolAddressMap AddrMap;
2477 for (const SymbolRef &Symbol : MachOOF->symbols()) {
2478 SymbolRef::Type ST;
2479 Symbol.getType(ST);
2480 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
2481 ST == SymbolRef::ST_Other) {
2482 uint64_t Address;
2483 Symbol.getAddress(Address);
2484 StringRef SymName;
2485 Symbol.getName(SymName);
2486 AddrMap[Address] = SymName;
2487 }
2488 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002489 // Set up the block of info used by the Symbolizer call backs.
2490 SymbolizerInfo.verbose = true;
2491 SymbolizerInfo.O = MachOOF;
2492 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00002493 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002494 SymbolizerInfo.Sections = &Sections;
2495 SymbolizerInfo.class_name = nullptr;
2496 SymbolizerInfo.selector_name = nullptr;
2497 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00002498 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00002499 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00002500 SymbolizerInfo.adrp_addr = 0;
2501 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002502 // Same for the ThumbSymbolizer
2503 ThumbSymbolizerInfo.verbose = true;
2504 ThumbSymbolizerInfo.O = MachOOF;
2505 ThumbSymbolizerInfo.S = Sections[SectIdx];
2506 ThumbSymbolizerInfo.AddrMap = &AddrMap;
2507 ThumbSymbolizerInfo.Sections = &Sections;
2508 ThumbSymbolizerInfo.class_name = nullptr;
2509 ThumbSymbolizerInfo.selector_name = nullptr;
2510 ThumbSymbolizerInfo.method = nullptr;
2511 ThumbSymbolizerInfo.demangled_name = nullptr;
2512 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00002513 ThumbSymbolizerInfo.adrp_addr = 0;
2514 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002515
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002516 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002517 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00002518 StringRef SymName;
2519 Symbols[SymIdx].getName(SymName);
2520
2521 SymbolRef::Type ST;
2522 Symbols[SymIdx].getType(ST);
2523 if (ST != SymbolRef::ST_Function)
2524 continue;
2525
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002526 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00002527 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00002528 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002529 continue;
2530
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002531 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00002532 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00002533 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00002534 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00002535 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00002536
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002537 // Stop disassembling either at the beginning of the next symbol or at
2538 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00002539 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00002540 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002541 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00002542 while (Symbols.size() > NextSymIdx) {
2543 SymbolRef::Type NextSymType;
2544 Symbols[NextSymIdx].getType(NextSymType);
2545 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00002546 containsNextSym =
2547 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00002548 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00002549 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00002550 break;
2551 }
2552 ++NextSymIdx;
2553 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002554
Rafael Espindola80291272014-10-08 15:28:58 +00002555 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002556 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00002557 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002558
2559 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00002560
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002561 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
2562 bool isThumb =
2563 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
2564
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002565 outs() << SymName << ":\n";
2566 DILineInfo lastLine;
2567 for (uint64_t Index = Start; Index < End; Index += Size) {
2568 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00002569
Kevin Enderbybf246f52014-09-24 23:08:22 +00002570 uint64_t PC = SectAddress + Index;
2571 if (FullLeadingAddr) {
2572 if (MachOOF->is64Bit())
2573 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002574 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00002575 outs() << format("%08" PRIx64, PC);
2576 } else {
2577 outs() << format("%8" PRIx64 ":", PC);
2578 }
2579 if (!NoShowRawInsn)
2580 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00002581
2582 // Check the data in code table here to see if this is data not an
2583 // instruction to be disassembled.
2584 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002585 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002586 dice_table_iterator DTI =
2587 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
2588 compareDiceTableEntries);
2589 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00002590 uint16_t Length;
2591 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00002592 uint16_t Kind;
2593 DTI->second.getKind(Kind);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00002594 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
2595 Index,
2596 Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002597 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
2598 (PC == (DTI->first + Length - 1)) && (Length & 1))
2599 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00002600 continue;
2601 }
2602
Kevin Enderbybf246f52014-09-24 23:08:22 +00002603 SmallVector<char, 64> AnnotationsBytes;
2604 raw_svector_ostream Annotations(AnnotationsBytes);
2605
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002606 bool gotInst;
2607 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00002608 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002609 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002610 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00002611 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00002612 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002613 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002614 if (!NoShowRawInsn) {
Aaron Ballman106fd7b2014-11-12 14:01:17 +00002615 DumpBytes(StringRef(
2616 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
Kevin Enderbybf246f52014-09-24 23:08:22 +00002617 }
2618 formatted_raw_ostream FormattedOS(outs());
2619 Annotations.flush();
2620 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002621 if (isThumb)
Kevin Enderbybf246f52014-09-24 23:08:22 +00002622 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002623 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00002624 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
2625 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00002626
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002627 // Print debug info.
2628 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002629 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002630 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00002631 if (dli != lastLine && dli.Line != 0)
2632 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
2633 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002634 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002635 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002636 outs() << "\n";
2637 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002638 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002639 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002640 outs() << format("\t.byte 0x%02x #bad opcode\n",
2641 *(Bytes.data() + Index) & 0xff);
2642 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002643 } else if (Arch == Triple::aarch64) {
2644 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
2645 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
2646 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
2647 (*(Bytes.data() + Index + 3) & 0xff) << 24;
2648 outs() << format("\t.long\t0x%08x\n", opcode);
2649 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002650 } else {
2651 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2652 if (Size == 0)
2653 Size = 1; // skip illegible bytes
2654 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002655 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002656 }
2657 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002658 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00002659 // Reading the symbol table didn't work, disassemble the whole section.
2660 uint64_t SectAddress = Sections[SectIdx].getAddress();
2661 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00002662 uint64_t InstSize;
2663 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00002664 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00002665
Kevin Enderbybf246f52014-09-24 23:08:22 +00002666 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00002667 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
2668 DebugOut, nulls())) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002669 if (FullLeadingAddr) {
2670 if (MachOOF->is64Bit())
2671 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002672 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00002673 outs() << format("%08" PRIx64, PC);
2674 } else {
2675 outs() << format("%8" PRIx64 ":", PC);
2676 }
2677 if (!NoShowRawInsn) {
2678 outs() << "\t";
Aaron Ballman106fd7b2014-11-12 14:01:17 +00002679 DumpBytes(
2680 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
2681 InstSize));
Kevin Enderbybf246f52014-09-24 23:08:22 +00002682 }
Bill Wendling4e68e062012-07-19 00:17:40 +00002683 IP->printInst(&Inst, outs(), "");
2684 outs() << "\n";
2685 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002686 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002687 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002688 outs() << format("\t.byte 0x%02x #bad opcode\n",
2689 *(Bytes.data() + Index) & 0xff);
2690 InstSize = 1; // skip exactly one illegible byte and move on.
2691 } else {
2692 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2693 if (InstSize == 0)
2694 InstSize = 1; // skip illegible bytes
2695 }
Bill Wendling4e68e062012-07-19 00:17:40 +00002696 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00002697 }
2698 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002699 // The TripleName's need to be reset if we are called again for a different
2700 // archtecture.
2701 TripleName = "";
2702 ThumbTripleName = "";
2703
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002704 if (SymbolizerInfo.method != nullptr)
2705 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002706 if (SymbolizerInfo.demangled_name != nullptr)
2707 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00002708 if (SymbolizerInfo.bindtable != nullptr)
2709 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002710 if (ThumbSymbolizerInfo.method != nullptr)
2711 free(ThumbSymbolizerInfo.method);
2712 if (ThumbSymbolizerInfo.demangled_name != nullptr)
2713 free(ThumbSymbolizerInfo.demangled_name);
2714 if (ThumbSymbolizerInfo.bindtable != nullptr)
2715 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002716 }
2717}
Tim Northover4bd286a2014-08-01 13:07:19 +00002718
Tim Northover39c70bb2014-08-12 11:52:59 +00002719//===----------------------------------------------------------------------===//
2720// __compact_unwind section dumping
2721//===----------------------------------------------------------------------===//
2722
Tim Northover4bd286a2014-08-01 13:07:19 +00002723namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00002724
2725template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002726 using llvm::support::little;
2727 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00002728
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002729 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2730 Buf += sizeof(T);
2731 return Val;
2732}
Tim Northover39c70bb2014-08-12 11:52:59 +00002733
Tim Northover4bd286a2014-08-01 13:07:19 +00002734struct CompactUnwindEntry {
2735 uint32_t OffsetInSection;
2736
2737 uint64_t FunctionAddr;
2738 uint32_t Length;
2739 uint32_t CompactEncoding;
2740 uint64_t PersonalityAddr;
2741 uint64_t LSDAAddr;
2742
2743 RelocationRef FunctionReloc;
2744 RelocationRef PersonalityReloc;
2745 RelocationRef LSDAReloc;
2746
2747 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002748 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002749 if (Is64)
2750 read<uint64_t>(Contents.data() + Offset);
2751 else
2752 read<uint32_t>(Contents.data() + Offset);
2753 }
2754
2755private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002756 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002757 FunctionAddr = readNext<UIntPtr>(Buf);
2758 Length = readNext<uint32_t>(Buf);
2759 CompactEncoding = readNext<uint32_t>(Buf);
2760 PersonalityAddr = readNext<UIntPtr>(Buf);
2761 LSDAAddr = readNext<UIntPtr>(Buf);
2762 }
2763};
2764}
2765
2766/// Given a relocation from __compact_unwind, consisting of the RelocationRef
2767/// and data being relocated, determine the best base Name and Addend to use for
2768/// display purposes.
2769///
2770/// 1. An Extern relocation will directly reference a symbol (and the data is
2771/// then already an addend), so use that.
2772/// 2. Otherwise the data is an offset in the object file's layout; try to find
2773// a symbol before it in the same section, and use the offset from there.
2774/// 3. Finally, if all that fails, fall back to an offset from the start of the
2775/// referenced section.
2776static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2777 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002778 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00002779 StringRef &Name, uint64_t &Addend) {
2780 if (Reloc.getSymbol() != Obj->symbol_end()) {
2781 Reloc.getSymbol()->getName(Name);
2782 Addend = Addr;
2783 return;
2784 }
2785
2786 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2787 SectionRef RelocSection = Obj->getRelocationSection(RE);
2788
Rafael Espindola80291272014-10-08 15:28:58 +00002789 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00002790
2791 auto Sym = Symbols.upper_bound(Addr);
2792 if (Sym == Symbols.begin()) {
2793 // The first symbol in the object is after this reference, the best we can
2794 // do is section-relative notation.
2795 RelocSection.getName(Name);
2796 Addend = Addr - SectionAddr;
2797 return;
2798 }
2799
2800 // Go back one so that SymbolAddress <= Addr.
2801 --Sym;
2802
2803 section_iterator SymSection = Obj->section_end();
2804 Sym->second.getSection(SymSection);
2805 if (RelocSection == *SymSection) {
2806 // There's a valid symbol in the same section before this reference.
2807 Sym->second.getName(Name);
2808 Addend = Addr - Sym->first;
2809 return;
2810 }
2811
2812 // There is a symbol before this reference, but it's in a different
2813 // section. Probably not helpful to mention it, so use the section name.
2814 RelocSection.getName(Name);
2815 Addend = Addr - SectionAddr;
2816}
2817
2818static void printUnwindRelocDest(const MachOObjectFile *Obj,
2819 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002820 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002821 StringRef Name;
2822 uint64_t Addend;
2823
Tim Northover0b0add52014-09-09 10:45:06 +00002824 if (!Reloc.getObjectFile())
2825 return;
2826
Tim Northover4bd286a2014-08-01 13:07:19 +00002827 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2828
2829 outs() << Name;
2830 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00002831 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00002832}
2833
2834static void
2835printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2836 std::map<uint64_t, SymbolRef> &Symbols,
2837 const SectionRef &CompactUnwind) {
2838
2839 assert(Obj->isLittleEndian() &&
2840 "There should not be a big-endian .o with __compact_unwind");
2841
2842 bool Is64 = Obj->is64Bit();
2843 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2844 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2845
2846 StringRef Contents;
2847 CompactUnwind.getContents(Contents);
2848
2849 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2850
2851 // First populate the initial raw offsets, encodings and so on from the entry.
2852 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2853 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2854 CompactUnwinds.push_back(Entry);
2855 }
2856
2857 // Next we need to look at the relocations to find out what objects are
2858 // actually being referred to.
2859 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2860 uint64_t RelocAddress;
2861 Reloc.getOffset(RelocAddress);
2862
2863 uint32_t EntryIdx = RelocAddress / EntrySize;
2864 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2865 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2866
2867 if (OffsetInEntry == 0)
2868 Entry.FunctionReloc = Reloc;
2869 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2870 Entry.PersonalityReloc = Reloc;
2871 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2872 Entry.LSDAReloc = Reloc;
2873 else
2874 llvm_unreachable("Unexpected relocation in __compact_unwind section");
2875 }
2876
2877 // Finally, we're ready to print the data we've gathered.
2878 outs() << "Contents of __compact_unwind section:\n";
2879 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00002880 outs() << " Entry at offset "
2881 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00002882
2883 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002884 outs() << " start: " << format("0x%" PRIx64,
2885 Entry.FunctionAddr) << ' ';
2886 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00002887 outs() << '\n';
2888
2889 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002890 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
2891 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00002892 // 3. The 32-bit compact encoding.
2893 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00002894 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00002895
2896 // 4. The personality function, if present.
2897 if (Entry.PersonalityReloc.getObjectFile()) {
2898 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00002899 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00002900 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2901 Entry.PersonalityAddr);
2902 outs() << '\n';
2903 }
2904
2905 // 5. This entry's language-specific data area.
2906 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002907 outs() << " LSDA: " << format("0x%" PRIx64,
2908 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00002909 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2910 outs() << '\n';
2911 }
2912 }
2913}
2914
Tim Northover39c70bb2014-08-12 11:52:59 +00002915//===----------------------------------------------------------------------===//
2916// __unwind_info section dumping
2917//===----------------------------------------------------------------------===//
2918
2919static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2920 const char *Pos = PageStart;
2921 uint32_t Kind = readNext<uint32_t>(Pos);
2922 (void)Kind;
2923 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2924
2925 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2926 uint16_t NumEntries = readNext<uint16_t>(Pos);
2927
2928 Pos = PageStart + EntriesStart;
2929 for (unsigned i = 0; i < NumEntries; ++i) {
2930 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2931 uint32_t Encoding = readNext<uint32_t>(Pos);
2932
2933 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002934 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2935 << ", "
2936 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002937 }
2938}
2939
2940static void printCompressedSecondLevelUnwindPage(
2941 const char *PageStart, uint32_t FunctionBase,
2942 const SmallVectorImpl<uint32_t> &CommonEncodings) {
2943 const char *Pos = PageStart;
2944 uint32_t Kind = readNext<uint32_t>(Pos);
2945 (void)Kind;
2946 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2947
2948 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2949 uint16_t NumEntries = readNext<uint16_t>(Pos);
2950
2951 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
2952 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00002953 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
2954 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00002955
2956 Pos = PageStart + EntriesStart;
2957 for (unsigned i = 0; i < NumEntries; ++i) {
2958 uint32_t Entry = readNext<uint32_t>(Pos);
2959 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
2960 uint32_t EncodingIdx = Entry >> 24;
2961
2962 uint32_t Encoding;
2963 if (EncodingIdx < CommonEncodings.size())
2964 Encoding = CommonEncodings[EncodingIdx];
2965 else
2966 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
2967
2968 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002969 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2970 << ", "
2971 << "encoding[" << EncodingIdx
2972 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002973 }
2974}
2975
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002976static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
2977 std::map<uint64_t, SymbolRef> &Symbols,
2978 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00002979
2980 assert(Obj->isLittleEndian() &&
2981 "There should not be a big-endian .o with __unwind_info");
2982
2983 outs() << "Contents of __unwind_info section:\n";
2984
2985 StringRef Contents;
2986 UnwindInfo.getContents(Contents);
2987 const char *Pos = Contents.data();
2988
2989 //===----------------------------------
2990 // Section header
2991 //===----------------------------------
2992
2993 uint32_t Version = readNext<uint32_t>(Pos);
2994 outs() << " Version: "
2995 << format("0x%" PRIx32, Version) << '\n';
2996 assert(Version == 1 && "only understand version 1");
2997
2998 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
2999 outs() << " Common encodings array section offset: "
3000 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
3001 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
3002 outs() << " Number of common encodings in array: "
3003 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
3004
3005 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
3006 outs() << " Personality function array section offset: "
3007 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
3008 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
3009 outs() << " Number of personality functions in array: "
3010 << format("0x%" PRIx32, NumPersonalities) << '\n';
3011
3012 uint32_t IndicesStart = readNext<uint32_t>(Pos);
3013 outs() << " Index array section offset: "
3014 << format("0x%" PRIx32, IndicesStart) << '\n';
3015 uint32_t NumIndices = readNext<uint32_t>(Pos);
3016 outs() << " Number of indices in array: "
3017 << format("0x%" PRIx32, NumIndices) << '\n';
3018
3019 //===----------------------------------
3020 // A shared list of common encodings
3021 //===----------------------------------
3022
3023 // These occupy indices in the range [0, N] whenever an encoding is referenced
3024 // from a compressed 2nd level index table. In practice the linker only
3025 // creates ~128 of these, so that indices are available to embed encodings in
3026 // the 2nd level index.
3027
3028 SmallVector<uint32_t, 64> CommonEncodings;
3029 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
3030 Pos = Contents.data() + CommonEncodingsStart;
3031 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
3032 uint32_t Encoding = readNext<uint32_t>(Pos);
3033 CommonEncodings.push_back(Encoding);
3034
3035 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
3036 << '\n';
3037 }
3038
Tim Northover39c70bb2014-08-12 11:52:59 +00003039 //===----------------------------------
3040 // Personality functions used in this executable
3041 //===----------------------------------
3042
3043 // There should be only a handful of these (one per source language,
3044 // roughly). Particularly since they only get 2 bits in the compact encoding.
3045
3046 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
3047 Pos = Contents.data() + PersonalitiesStart;
3048 for (unsigned i = 0; i < NumPersonalities; ++i) {
3049 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
3050 outs() << " personality[" << i + 1
3051 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
3052 }
3053
3054 //===----------------------------------
3055 // The level 1 index entries
3056 //===----------------------------------
3057
3058 // These specify an approximate place to start searching for the more detailed
3059 // information, sorted by PC.
3060
3061 struct IndexEntry {
3062 uint32_t FunctionOffset;
3063 uint32_t SecondLevelPageStart;
3064 uint32_t LSDAStart;
3065 };
3066
3067 SmallVector<IndexEntry, 4> IndexEntries;
3068
3069 outs() << " Top level indices: (count = " << NumIndices << ")\n";
3070 Pos = Contents.data() + IndicesStart;
3071 for (unsigned i = 0; i < NumIndices; ++i) {
3072 IndexEntry Entry;
3073
3074 Entry.FunctionOffset = readNext<uint32_t>(Pos);
3075 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
3076 Entry.LSDAStart = readNext<uint32_t>(Pos);
3077 IndexEntries.push_back(Entry);
3078
3079 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003080 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
3081 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00003082 << "2nd level page offset="
3083 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003084 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003085 }
3086
Tim Northover39c70bb2014-08-12 11:52:59 +00003087 //===----------------------------------
3088 // Next come the LSDA tables
3089 //===----------------------------------
3090
3091 // The LSDA layout is rather implicit: it's a contiguous array of entries from
3092 // the first top-level index's LSDAOffset to the last (sentinel).
3093
3094 outs() << " LSDA descriptors:\n";
3095 Pos = Contents.data() + IndexEntries[0].LSDAStart;
3096 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
3097 (2 * sizeof(uint32_t));
3098 for (int i = 0; i < NumLSDAs; ++i) {
3099 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
3100 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
3101 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003102 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
3103 << ", "
3104 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00003105 }
3106
3107 //===----------------------------------
3108 // Finally, the 2nd level indices
3109 //===----------------------------------
3110
3111 // Generally these are 4K in size, and have 2 possible forms:
3112 // + Regular stores up to 511 entries with disparate encodings
3113 // + Compressed stores up to 1021 entries if few enough compact encoding
3114 // values are used.
3115 outs() << " Second level indices:\n";
3116 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
3117 // The final sentinel top-level index has no associated 2nd level page
3118 if (IndexEntries[i].SecondLevelPageStart == 0)
3119 break;
3120
3121 outs() << " Second level index[" << i << "]: "
3122 << "offset in section="
3123 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
3124 << ", "
3125 << "base function offset="
3126 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
3127
3128 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00003129 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00003130 if (Kind == 2)
3131 printRegularSecondLevelUnwindPage(Pos);
3132 else if (Kind == 3)
3133 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
3134 CommonEncodings);
3135 else
3136 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00003137 }
3138}
3139
Tim Northover4bd286a2014-08-01 13:07:19 +00003140void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
3141 std::map<uint64_t, SymbolRef> Symbols;
3142 for (const SymbolRef &SymRef : Obj->symbols()) {
3143 // Discard any undefined or absolute symbols. They're not going to take part
3144 // in the convenience lookup for unwind info and just take up resources.
3145 section_iterator Section = Obj->section_end();
3146 SymRef.getSection(Section);
3147 if (Section == Obj->section_end())
3148 continue;
3149
3150 uint64_t Addr;
3151 SymRef.getAddress(Addr);
3152 Symbols.insert(std::make_pair(Addr, SymRef));
3153 }
3154
3155 for (const SectionRef &Section : Obj->sections()) {
3156 StringRef SectName;
3157 Section.getName(SectName);
3158 if (SectName == "__compact_unwind")
3159 printMachOCompactUnwindSection(Obj, Symbols, Section);
3160 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00003161 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00003162 else if (SectName == "__eh_frame")
3163 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00003164 }
3165}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003166
3167static void PrintMachHeader(uint32_t magic, uint32_t cputype,
3168 uint32_t cpusubtype, uint32_t filetype,
3169 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
3170 bool verbose) {
3171 outs() << "Mach header\n";
3172 outs() << " magic cputype cpusubtype caps filetype ncmds "
3173 "sizeofcmds flags\n";
3174 if (verbose) {
3175 if (magic == MachO::MH_MAGIC)
3176 outs() << " MH_MAGIC";
3177 else if (magic == MachO::MH_MAGIC_64)
3178 outs() << "MH_MAGIC_64";
3179 else
3180 outs() << format(" 0x%08" PRIx32, magic);
3181 switch (cputype) {
3182 case MachO::CPU_TYPE_I386:
3183 outs() << " I386";
3184 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3185 case MachO::CPU_SUBTYPE_I386_ALL:
3186 outs() << " ALL";
3187 break;
3188 default:
3189 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3190 break;
3191 }
3192 break;
3193 case MachO::CPU_TYPE_X86_64:
3194 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00003195 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3196 case MachO::CPU_SUBTYPE_X86_64_ALL:
3197 outs() << " ALL";
3198 break;
3199 case MachO::CPU_SUBTYPE_X86_64_H:
3200 outs() << " Haswell";
3201 break;
3202 default:
3203 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3204 break;
3205 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003206 break;
3207 case MachO::CPU_TYPE_ARM:
3208 outs() << " ARM";
3209 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3210 case MachO::CPU_SUBTYPE_ARM_ALL:
3211 outs() << " ALL";
3212 break;
3213 case MachO::CPU_SUBTYPE_ARM_V4T:
3214 outs() << " V4T";
3215 break;
3216 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
3217 outs() << " V5TEJ";
3218 break;
3219 case MachO::CPU_SUBTYPE_ARM_XSCALE:
3220 outs() << " XSCALE";
3221 break;
3222 case MachO::CPU_SUBTYPE_ARM_V6:
3223 outs() << " V6";
3224 break;
3225 case MachO::CPU_SUBTYPE_ARM_V6M:
3226 outs() << " V6M";
3227 break;
3228 case MachO::CPU_SUBTYPE_ARM_V7:
3229 outs() << " V7";
3230 break;
3231 case MachO::CPU_SUBTYPE_ARM_V7EM:
3232 outs() << " V7EM";
3233 break;
3234 case MachO::CPU_SUBTYPE_ARM_V7K:
3235 outs() << " V7K";
3236 break;
3237 case MachO::CPU_SUBTYPE_ARM_V7M:
3238 outs() << " V7M";
3239 break;
3240 case MachO::CPU_SUBTYPE_ARM_V7S:
3241 outs() << " V7S";
3242 break;
3243 default:
3244 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3245 break;
3246 }
3247 break;
3248 case MachO::CPU_TYPE_ARM64:
3249 outs() << " ARM64";
3250 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3251 case MachO::CPU_SUBTYPE_ARM64_ALL:
3252 outs() << " ALL";
3253 break;
3254 default:
3255 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3256 break;
3257 }
3258 break;
3259 case MachO::CPU_TYPE_POWERPC:
3260 outs() << " PPC";
3261 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3262 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3263 outs() << " ALL";
3264 break;
3265 default:
3266 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3267 break;
3268 }
3269 break;
3270 case MachO::CPU_TYPE_POWERPC64:
3271 outs() << " PPC64";
3272 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3273 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3274 outs() << " ALL";
3275 break;
3276 default:
3277 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3278 break;
3279 }
3280 break;
3281 }
3282 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003283 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003284 } else {
3285 outs() << format(" 0x%02" PRIx32,
3286 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3287 }
3288 switch (filetype) {
3289 case MachO::MH_OBJECT:
3290 outs() << " OBJECT";
3291 break;
3292 case MachO::MH_EXECUTE:
3293 outs() << " EXECUTE";
3294 break;
3295 case MachO::MH_FVMLIB:
3296 outs() << " FVMLIB";
3297 break;
3298 case MachO::MH_CORE:
3299 outs() << " CORE";
3300 break;
3301 case MachO::MH_PRELOAD:
3302 outs() << " PRELOAD";
3303 break;
3304 case MachO::MH_DYLIB:
3305 outs() << " DYLIB";
3306 break;
3307 case MachO::MH_DYLIB_STUB:
3308 outs() << " DYLIB_STUB";
3309 break;
3310 case MachO::MH_DYLINKER:
3311 outs() << " DYLINKER";
3312 break;
3313 case MachO::MH_BUNDLE:
3314 outs() << " BUNDLE";
3315 break;
3316 case MachO::MH_DSYM:
3317 outs() << " DSYM";
3318 break;
3319 case MachO::MH_KEXT_BUNDLE:
3320 outs() << " KEXTBUNDLE";
3321 break;
3322 default:
3323 outs() << format(" %10u", filetype);
3324 break;
3325 }
3326 outs() << format(" %5u", ncmds);
3327 outs() << format(" %10u", sizeofcmds);
3328 uint32_t f = flags;
3329 if (f & MachO::MH_NOUNDEFS) {
3330 outs() << " NOUNDEFS";
3331 f &= ~MachO::MH_NOUNDEFS;
3332 }
3333 if (f & MachO::MH_INCRLINK) {
3334 outs() << " INCRLINK";
3335 f &= ~MachO::MH_INCRLINK;
3336 }
3337 if (f & MachO::MH_DYLDLINK) {
3338 outs() << " DYLDLINK";
3339 f &= ~MachO::MH_DYLDLINK;
3340 }
3341 if (f & MachO::MH_BINDATLOAD) {
3342 outs() << " BINDATLOAD";
3343 f &= ~MachO::MH_BINDATLOAD;
3344 }
3345 if (f & MachO::MH_PREBOUND) {
3346 outs() << " PREBOUND";
3347 f &= ~MachO::MH_PREBOUND;
3348 }
3349 if (f & MachO::MH_SPLIT_SEGS) {
3350 outs() << " SPLIT_SEGS";
3351 f &= ~MachO::MH_SPLIT_SEGS;
3352 }
3353 if (f & MachO::MH_LAZY_INIT) {
3354 outs() << " LAZY_INIT";
3355 f &= ~MachO::MH_LAZY_INIT;
3356 }
3357 if (f & MachO::MH_TWOLEVEL) {
3358 outs() << " TWOLEVEL";
3359 f &= ~MachO::MH_TWOLEVEL;
3360 }
3361 if (f & MachO::MH_FORCE_FLAT) {
3362 outs() << " FORCE_FLAT";
3363 f &= ~MachO::MH_FORCE_FLAT;
3364 }
3365 if (f & MachO::MH_NOMULTIDEFS) {
3366 outs() << " NOMULTIDEFS";
3367 f &= ~MachO::MH_NOMULTIDEFS;
3368 }
3369 if (f & MachO::MH_NOFIXPREBINDING) {
3370 outs() << " NOFIXPREBINDING";
3371 f &= ~MachO::MH_NOFIXPREBINDING;
3372 }
3373 if (f & MachO::MH_PREBINDABLE) {
3374 outs() << " PREBINDABLE";
3375 f &= ~MachO::MH_PREBINDABLE;
3376 }
3377 if (f & MachO::MH_ALLMODSBOUND) {
3378 outs() << " ALLMODSBOUND";
3379 f &= ~MachO::MH_ALLMODSBOUND;
3380 }
3381 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
3382 outs() << " SUBSECTIONS_VIA_SYMBOLS";
3383 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
3384 }
3385 if (f & MachO::MH_CANONICAL) {
3386 outs() << " CANONICAL";
3387 f &= ~MachO::MH_CANONICAL;
3388 }
3389 if (f & MachO::MH_WEAK_DEFINES) {
3390 outs() << " WEAK_DEFINES";
3391 f &= ~MachO::MH_WEAK_DEFINES;
3392 }
3393 if (f & MachO::MH_BINDS_TO_WEAK) {
3394 outs() << " BINDS_TO_WEAK";
3395 f &= ~MachO::MH_BINDS_TO_WEAK;
3396 }
3397 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
3398 outs() << " ALLOW_STACK_EXECUTION";
3399 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
3400 }
3401 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
3402 outs() << " DEAD_STRIPPABLE_DYLIB";
3403 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
3404 }
3405 if (f & MachO::MH_PIE) {
3406 outs() << " PIE";
3407 f &= ~MachO::MH_PIE;
3408 }
3409 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
3410 outs() << " NO_REEXPORTED_DYLIBS";
3411 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
3412 }
3413 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
3414 outs() << " MH_HAS_TLV_DESCRIPTORS";
3415 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
3416 }
3417 if (f & MachO::MH_NO_HEAP_EXECUTION) {
3418 outs() << " MH_NO_HEAP_EXECUTION";
3419 f &= ~MachO::MH_NO_HEAP_EXECUTION;
3420 }
3421 if (f & MachO::MH_APP_EXTENSION_SAFE) {
3422 outs() << " APP_EXTENSION_SAFE";
3423 f &= ~MachO::MH_APP_EXTENSION_SAFE;
3424 }
3425 if (f != 0 || flags == 0)
3426 outs() << format(" 0x%08" PRIx32, f);
3427 } else {
3428 outs() << format(" 0x%08" PRIx32, magic);
3429 outs() << format(" %7d", cputype);
3430 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3431 outs() << format(" 0x%02" PRIx32,
3432 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3433 outs() << format(" %10u", filetype);
3434 outs() << format(" %5u", ncmds);
3435 outs() << format(" %10u", sizeofcmds);
3436 outs() << format(" 0x%08" PRIx32, flags);
3437 }
3438 outs() << "\n";
3439}
3440
Kevin Enderby956366c2014-08-29 22:30:52 +00003441static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
3442 StringRef SegName, uint64_t vmaddr,
3443 uint64_t vmsize, uint64_t fileoff,
3444 uint64_t filesize, uint32_t maxprot,
3445 uint32_t initprot, uint32_t nsects,
3446 uint32_t flags, uint32_t object_size,
3447 bool verbose) {
3448 uint64_t expected_cmdsize;
3449 if (cmd == MachO::LC_SEGMENT) {
3450 outs() << " cmd LC_SEGMENT\n";
3451 expected_cmdsize = nsects;
3452 expected_cmdsize *= sizeof(struct MachO::section);
3453 expected_cmdsize += sizeof(struct MachO::segment_command);
3454 } else {
3455 outs() << " cmd LC_SEGMENT_64\n";
3456 expected_cmdsize = nsects;
3457 expected_cmdsize *= sizeof(struct MachO::section_64);
3458 expected_cmdsize += sizeof(struct MachO::segment_command_64);
3459 }
3460 outs() << " cmdsize " << cmdsize;
3461 if (cmdsize != expected_cmdsize)
3462 outs() << " Inconsistent size\n";
3463 else
3464 outs() << "\n";
3465 outs() << " segname " << SegName << "\n";
3466 if (cmd == MachO::LC_SEGMENT_64) {
3467 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
3468 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
3469 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00003470 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
3471 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00003472 }
3473 outs() << " fileoff " << fileoff;
3474 if (fileoff > object_size)
3475 outs() << " (past end of file)\n";
3476 else
3477 outs() << "\n";
3478 outs() << " filesize " << filesize;
3479 if (fileoff + filesize > object_size)
3480 outs() << " (past end of file)\n";
3481 else
3482 outs() << "\n";
3483 if (verbose) {
3484 if ((maxprot &
3485 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3486 MachO::VM_PROT_EXECUTE)) != 0)
3487 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
3488 else {
3489 if (maxprot & MachO::VM_PROT_READ)
3490 outs() << " maxprot r";
3491 else
3492 outs() << " maxprot -";
3493 if (maxprot & MachO::VM_PROT_WRITE)
3494 outs() << "w";
3495 else
3496 outs() << "-";
3497 if (maxprot & MachO::VM_PROT_EXECUTE)
3498 outs() << "x\n";
3499 else
3500 outs() << "-\n";
3501 }
3502 if ((initprot &
3503 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3504 MachO::VM_PROT_EXECUTE)) != 0)
3505 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
3506 else {
3507 if (initprot & MachO::VM_PROT_READ)
3508 outs() << " initprot r";
3509 else
3510 outs() << " initprot -";
3511 if (initprot & MachO::VM_PROT_WRITE)
3512 outs() << "w";
3513 else
3514 outs() << "-";
3515 if (initprot & MachO::VM_PROT_EXECUTE)
3516 outs() << "x\n";
3517 else
3518 outs() << "-\n";
3519 }
3520 } else {
3521 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
3522 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
3523 }
3524 outs() << " nsects " << nsects << "\n";
3525 if (verbose) {
3526 outs() << " flags";
3527 if (flags == 0)
3528 outs() << " (none)\n";
3529 else {
3530 if (flags & MachO::SG_HIGHVM) {
3531 outs() << " HIGHVM";
3532 flags &= ~MachO::SG_HIGHVM;
3533 }
3534 if (flags & MachO::SG_FVMLIB) {
3535 outs() << " FVMLIB";
3536 flags &= ~MachO::SG_FVMLIB;
3537 }
3538 if (flags & MachO::SG_NORELOC) {
3539 outs() << " NORELOC";
3540 flags &= ~MachO::SG_NORELOC;
3541 }
3542 if (flags & MachO::SG_PROTECTED_VERSION_1) {
3543 outs() << " PROTECTED_VERSION_1";
3544 flags &= ~MachO::SG_PROTECTED_VERSION_1;
3545 }
3546 if (flags)
3547 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
3548 else
3549 outs() << "\n";
3550 }
3551 } else {
3552 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
3553 }
3554}
3555
3556static void PrintSection(const char *sectname, const char *segname,
3557 uint64_t addr, uint64_t size, uint32_t offset,
3558 uint32_t align, uint32_t reloff, uint32_t nreloc,
3559 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
3560 uint32_t cmd, const char *sg_segname,
3561 uint32_t filetype, uint32_t object_size,
3562 bool verbose) {
3563 outs() << "Section\n";
3564 outs() << " sectname " << format("%.16s\n", sectname);
3565 outs() << " segname " << format("%.16s", segname);
3566 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
3567 outs() << " (does not match segment)\n";
3568 else
3569 outs() << "\n";
3570 if (cmd == MachO::LC_SEGMENT_64) {
3571 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
3572 outs() << " size " << format("0x%016" PRIx64, size);
3573 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00003574 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
3575 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00003576 }
3577 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
3578 outs() << " (past end of file)\n";
3579 else
3580 outs() << "\n";
3581 outs() << " offset " << offset;
3582 if (offset > object_size)
3583 outs() << " (past end of file)\n";
3584 else
3585 outs() << "\n";
3586 uint32_t align_shifted = 1 << align;
3587 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
3588 outs() << " reloff " << reloff;
3589 if (reloff > object_size)
3590 outs() << " (past end of file)\n";
3591 else
3592 outs() << "\n";
3593 outs() << " nreloc " << nreloc;
3594 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
3595 outs() << " (past end of file)\n";
3596 else
3597 outs() << "\n";
3598 uint32_t section_type = flags & MachO::SECTION_TYPE;
3599 if (verbose) {
3600 outs() << " type";
3601 if (section_type == MachO::S_REGULAR)
3602 outs() << " S_REGULAR\n";
3603 else if (section_type == MachO::S_ZEROFILL)
3604 outs() << " S_ZEROFILL\n";
3605 else if (section_type == MachO::S_CSTRING_LITERALS)
3606 outs() << " S_CSTRING_LITERALS\n";
3607 else if (section_type == MachO::S_4BYTE_LITERALS)
3608 outs() << " S_4BYTE_LITERALS\n";
3609 else if (section_type == MachO::S_8BYTE_LITERALS)
3610 outs() << " S_8BYTE_LITERALS\n";
3611 else if (section_type == MachO::S_16BYTE_LITERALS)
3612 outs() << " S_16BYTE_LITERALS\n";
3613 else if (section_type == MachO::S_LITERAL_POINTERS)
3614 outs() << " S_LITERAL_POINTERS\n";
3615 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
3616 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
3617 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
3618 outs() << " S_LAZY_SYMBOL_POINTERS\n";
3619 else if (section_type == MachO::S_SYMBOL_STUBS)
3620 outs() << " S_SYMBOL_STUBS\n";
3621 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
3622 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
3623 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
3624 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
3625 else if (section_type == MachO::S_COALESCED)
3626 outs() << " S_COALESCED\n";
3627 else if (section_type == MachO::S_INTERPOSING)
3628 outs() << " S_INTERPOSING\n";
3629 else if (section_type == MachO::S_DTRACE_DOF)
3630 outs() << " S_DTRACE_DOF\n";
3631 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
3632 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
3633 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
3634 outs() << " S_THREAD_LOCAL_REGULAR\n";
3635 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
3636 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
3637 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
3638 outs() << " S_THREAD_LOCAL_VARIABLES\n";
3639 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3640 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
3641 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
3642 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
3643 else
3644 outs() << format("0x%08" PRIx32, section_type) << "\n";
3645 outs() << "attributes";
3646 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
3647 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
3648 outs() << " PURE_INSTRUCTIONS";
3649 if (section_attributes & MachO::S_ATTR_NO_TOC)
3650 outs() << " NO_TOC";
3651 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
3652 outs() << " STRIP_STATIC_SYMS";
3653 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
3654 outs() << " NO_DEAD_STRIP";
3655 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
3656 outs() << " LIVE_SUPPORT";
3657 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
3658 outs() << " SELF_MODIFYING_CODE";
3659 if (section_attributes & MachO::S_ATTR_DEBUG)
3660 outs() << " DEBUG";
3661 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
3662 outs() << " SOME_INSTRUCTIONS";
3663 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
3664 outs() << " EXT_RELOC";
3665 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
3666 outs() << " LOC_RELOC";
3667 if (section_attributes == 0)
3668 outs() << " (none)";
3669 outs() << "\n";
3670 } else
3671 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
3672 outs() << " reserved1 " << reserved1;
3673 if (section_type == MachO::S_SYMBOL_STUBS ||
3674 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3675 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3676 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3677 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3678 outs() << " (index into indirect symbol table)\n";
3679 else
3680 outs() << "\n";
3681 outs() << " reserved2 " << reserved2;
3682 if (section_type == MachO::S_SYMBOL_STUBS)
3683 outs() << " (size of stubs)\n";
3684 else
3685 outs() << "\n";
3686}
3687
David Majnemer73cc6ff2014-11-13 19:48:56 +00003688static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00003689 uint32_t object_size) {
3690 outs() << " cmd LC_SYMTAB\n";
3691 outs() << " cmdsize " << st.cmdsize;
3692 if (st.cmdsize != sizeof(struct MachO::symtab_command))
3693 outs() << " Incorrect size\n";
3694 else
3695 outs() << "\n";
3696 outs() << " symoff " << st.symoff;
3697 if (st.symoff > object_size)
3698 outs() << " (past end of file)\n";
3699 else
3700 outs() << "\n";
3701 outs() << " nsyms " << st.nsyms;
3702 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00003703 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003704 big_size = st.nsyms;
3705 big_size *= sizeof(struct MachO::nlist_64);
3706 big_size += st.symoff;
3707 if (big_size > object_size)
3708 outs() << " (past end of file)\n";
3709 else
3710 outs() << "\n";
3711 } else {
3712 big_size = st.nsyms;
3713 big_size *= sizeof(struct MachO::nlist);
3714 big_size += st.symoff;
3715 if (big_size > object_size)
3716 outs() << " (past end of file)\n";
3717 else
3718 outs() << "\n";
3719 }
3720 outs() << " stroff " << st.stroff;
3721 if (st.stroff > object_size)
3722 outs() << " (past end of file)\n";
3723 else
3724 outs() << "\n";
3725 outs() << " strsize " << st.strsize;
3726 big_size = st.stroff;
3727 big_size += st.strsize;
3728 if (big_size > object_size)
3729 outs() << " (past end of file)\n";
3730 else
3731 outs() << "\n";
3732}
3733
3734static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3735 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00003736 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003737 outs() << " cmd LC_DYSYMTAB\n";
3738 outs() << " cmdsize " << dyst.cmdsize;
3739 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3740 outs() << " Incorrect size\n";
3741 else
3742 outs() << "\n";
3743 outs() << " ilocalsym " << dyst.ilocalsym;
3744 if (dyst.ilocalsym > nsyms)
3745 outs() << " (greater than the number of symbols)\n";
3746 else
3747 outs() << "\n";
3748 outs() << " nlocalsym " << dyst.nlocalsym;
3749 uint64_t big_size;
3750 big_size = dyst.ilocalsym;
3751 big_size += dyst.nlocalsym;
3752 if (big_size > nsyms)
3753 outs() << " (past the end of the symbol table)\n";
3754 else
3755 outs() << "\n";
3756 outs() << " iextdefsym " << dyst.iextdefsym;
3757 if (dyst.iextdefsym > nsyms)
3758 outs() << " (greater than the number of symbols)\n";
3759 else
3760 outs() << "\n";
3761 outs() << " nextdefsym " << dyst.nextdefsym;
3762 big_size = dyst.iextdefsym;
3763 big_size += dyst.nextdefsym;
3764 if (big_size > nsyms)
3765 outs() << " (past the end of the symbol table)\n";
3766 else
3767 outs() << "\n";
3768 outs() << " iundefsym " << dyst.iundefsym;
3769 if (dyst.iundefsym > nsyms)
3770 outs() << " (greater than the number of symbols)\n";
3771 else
3772 outs() << "\n";
3773 outs() << " nundefsym " << dyst.nundefsym;
3774 big_size = dyst.iundefsym;
3775 big_size += dyst.nundefsym;
3776 if (big_size > nsyms)
3777 outs() << " (past the end of the symbol table)\n";
3778 else
3779 outs() << "\n";
3780 outs() << " tocoff " << dyst.tocoff;
3781 if (dyst.tocoff > object_size)
3782 outs() << " (past end of file)\n";
3783 else
3784 outs() << "\n";
3785 outs() << " ntoc " << dyst.ntoc;
3786 big_size = dyst.ntoc;
3787 big_size *= sizeof(struct MachO::dylib_table_of_contents);
3788 big_size += dyst.tocoff;
3789 if (big_size > object_size)
3790 outs() << " (past end of file)\n";
3791 else
3792 outs() << "\n";
3793 outs() << " modtaboff " << dyst.modtaboff;
3794 if (dyst.modtaboff > object_size)
3795 outs() << " (past end of file)\n";
3796 else
3797 outs() << "\n";
3798 outs() << " nmodtab " << dyst.nmodtab;
3799 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00003800 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003801 modtabend = dyst.nmodtab;
3802 modtabend *= sizeof(struct MachO::dylib_module_64);
3803 modtabend += dyst.modtaboff;
3804 } else {
3805 modtabend = dyst.nmodtab;
3806 modtabend *= sizeof(struct MachO::dylib_module);
3807 modtabend += dyst.modtaboff;
3808 }
3809 if (modtabend > object_size)
3810 outs() << " (past end of file)\n";
3811 else
3812 outs() << "\n";
3813 outs() << " extrefsymoff " << dyst.extrefsymoff;
3814 if (dyst.extrefsymoff > object_size)
3815 outs() << " (past end of file)\n";
3816 else
3817 outs() << "\n";
3818 outs() << " nextrefsyms " << dyst.nextrefsyms;
3819 big_size = dyst.nextrefsyms;
3820 big_size *= sizeof(struct MachO::dylib_reference);
3821 big_size += dyst.extrefsymoff;
3822 if (big_size > object_size)
3823 outs() << " (past end of file)\n";
3824 else
3825 outs() << "\n";
3826 outs() << " indirectsymoff " << dyst.indirectsymoff;
3827 if (dyst.indirectsymoff > object_size)
3828 outs() << " (past end of file)\n";
3829 else
3830 outs() << "\n";
3831 outs() << " nindirectsyms " << dyst.nindirectsyms;
3832 big_size = dyst.nindirectsyms;
3833 big_size *= sizeof(uint32_t);
3834 big_size += dyst.indirectsymoff;
3835 if (big_size > object_size)
3836 outs() << " (past end of file)\n";
3837 else
3838 outs() << "\n";
3839 outs() << " extreloff " << dyst.extreloff;
3840 if (dyst.extreloff > object_size)
3841 outs() << " (past end of file)\n";
3842 else
3843 outs() << "\n";
3844 outs() << " nextrel " << dyst.nextrel;
3845 big_size = dyst.nextrel;
3846 big_size *= sizeof(struct MachO::relocation_info);
3847 big_size += dyst.extreloff;
3848 if (big_size > object_size)
3849 outs() << " (past end of file)\n";
3850 else
3851 outs() << "\n";
3852 outs() << " locreloff " << dyst.locreloff;
3853 if (dyst.locreloff > object_size)
3854 outs() << " (past end of file)\n";
3855 else
3856 outs() << "\n";
3857 outs() << " nlocrel " << dyst.nlocrel;
3858 big_size = dyst.nlocrel;
3859 big_size *= sizeof(struct MachO::relocation_info);
3860 big_size += dyst.locreloff;
3861 if (big_size > object_size)
3862 outs() << " (past end of file)\n";
3863 else
3864 outs() << "\n";
3865}
3866
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003867static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3868 uint32_t object_size) {
3869 if (dc.cmd == MachO::LC_DYLD_INFO)
3870 outs() << " cmd LC_DYLD_INFO\n";
3871 else
3872 outs() << " cmd LC_DYLD_INFO_ONLY\n";
3873 outs() << " cmdsize " << dc.cmdsize;
3874 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3875 outs() << " Incorrect size\n";
3876 else
3877 outs() << "\n";
3878 outs() << " rebase_off " << dc.rebase_off;
3879 if (dc.rebase_off > object_size)
3880 outs() << " (past end of file)\n";
3881 else
3882 outs() << "\n";
3883 outs() << " rebase_size " << dc.rebase_size;
3884 uint64_t big_size;
3885 big_size = dc.rebase_off;
3886 big_size += dc.rebase_size;
3887 if (big_size > object_size)
3888 outs() << " (past end of file)\n";
3889 else
3890 outs() << "\n";
3891 outs() << " bind_off " << dc.bind_off;
3892 if (dc.bind_off > object_size)
3893 outs() << " (past end of file)\n";
3894 else
3895 outs() << "\n";
3896 outs() << " bind_size " << dc.bind_size;
3897 big_size = dc.bind_off;
3898 big_size += dc.bind_size;
3899 if (big_size > object_size)
3900 outs() << " (past end of file)\n";
3901 else
3902 outs() << "\n";
3903 outs() << " weak_bind_off " << dc.weak_bind_off;
3904 if (dc.weak_bind_off > object_size)
3905 outs() << " (past end of file)\n";
3906 else
3907 outs() << "\n";
3908 outs() << " weak_bind_size " << dc.weak_bind_size;
3909 big_size = dc.weak_bind_off;
3910 big_size += dc.weak_bind_size;
3911 if (big_size > object_size)
3912 outs() << " (past end of file)\n";
3913 else
3914 outs() << "\n";
3915 outs() << " lazy_bind_off " << dc.lazy_bind_off;
3916 if (dc.lazy_bind_off > object_size)
3917 outs() << " (past end of file)\n";
3918 else
3919 outs() << "\n";
3920 outs() << " lazy_bind_size " << dc.lazy_bind_size;
3921 big_size = dc.lazy_bind_off;
3922 big_size += dc.lazy_bind_size;
3923 if (big_size > object_size)
3924 outs() << " (past end of file)\n";
3925 else
3926 outs() << "\n";
3927 outs() << " export_off " << dc.export_off;
3928 if (dc.export_off > object_size)
3929 outs() << " (past end of file)\n";
3930 else
3931 outs() << "\n";
3932 outs() << " export_size " << dc.export_size;
3933 big_size = dc.export_off;
3934 big_size += dc.export_size;
3935 if (big_size > object_size)
3936 outs() << " (past end of file)\n";
3937 else
3938 outs() << "\n";
3939}
3940
3941static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3942 const char *Ptr) {
3943 if (dyld.cmd == MachO::LC_ID_DYLINKER)
3944 outs() << " cmd LC_ID_DYLINKER\n";
3945 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3946 outs() << " cmd LC_LOAD_DYLINKER\n";
3947 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3948 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
3949 else
3950 outs() << " cmd ?(" << dyld.cmd << ")\n";
3951 outs() << " cmdsize " << dyld.cmdsize;
3952 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
3953 outs() << " Incorrect size\n";
3954 else
3955 outs() << "\n";
3956 if (dyld.name >= dyld.cmdsize)
3957 outs() << " name ?(bad offset " << dyld.name << ")\n";
3958 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003959 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003960 outs() << " name " << P << " (offset " << dyld.name << ")\n";
3961 }
3962}
3963
3964static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
3965 outs() << " cmd LC_UUID\n";
3966 outs() << " cmdsize " << uuid.cmdsize;
3967 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
3968 outs() << " Incorrect size\n";
3969 else
3970 outs() << "\n";
3971 outs() << " uuid ";
3972 outs() << format("%02" PRIX32, uuid.uuid[0]);
3973 outs() << format("%02" PRIX32, uuid.uuid[1]);
3974 outs() << format("%02" PRIX32, uuid.uuid[2]);
3975 outs() << format("%02" PRIX32, uuid.uuid[3]);
3976 outs() << "-";
3977 outs() << format("%02" PRIX32, uuid.uuid[4]);
3978 outs() << format("%02" PRIX32, uuid.uuid[5]);
3979 outs() << "-";
3980 outs() << format("%02" PRIX32, uuid.uuid[6]);
3981 outs() << format("%02" PRIX32, uuid.uuid[7]);
3982 outs() << "-";
3983 outs() << format("%02" PRIX32, uuid.uuid[8]);
3984 outs() << format("%02" PRIX32, uuid.uuid[9]);
3985 outs() << "-";
3986 outs() << format("%02" PRIX32, uuid.uuid[10]);
3987 outs() << format("%02" PRIX32, uuid.uuid[11]);
3988 outs() << format("%02" PRIX32, uuid.uuid[12]);
3989 outs() << format("%02" PRIX32, uuid.uuid[13]);
3990 outs() << format("%02" PRIX32, uuid.uuid[14]);
3991 outs() << format("%02" PRIX32, uuid.uuid[15]);
3992 outs() << "\n";
3993}
3994
Kevin Enderby66d51fc2015-01-08 00:25:24 +00003995static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00003996 outs() << " cmd LC_RPATH\n";
3997 outs() << " cmdsize " << rpath.cmdsize;
3998 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
3999 outs() << " Incorrect size\n";
4000 else
4001 outs() << "\n";
4002 if (rpath.path >= rpath.cmdsize)
4003 outs() << " path ?(bad offset " << rpath.path << ")\n";
4004 else {
4005 const char *P = (const char *)(Ptr) + rpath.path;
4006 outs() << " path " << P << " (offset " << rpath.path << ")\n";
4007 }
4008}
4009
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004010static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
4011 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
4012 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
4013 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
4014 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
4015 else
4016 outs() << " cmd " << vd.cmd << " (?)\n";
4017 outs() << " cmdsize " << vd.cmdsize;
4018 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
4019 outs() << " Incorrect size\n";
4020 else
4021 outs() << "\n";
4022 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
4023 << ((vd.version >> 8) & 0xff);
4024 if ((vd.version & 0xff) != 0)
4025 outs() << "." << (vd.version & 0xff);
4026 outs() << "\n";
4027 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00004028 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004029 else {
4030 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
4031 << ((vd.sdk >> 8) & 0xff);
4032 }
4033 if ((vd.sdk & 0xff) != 0)
4034 outs() << "." << (vd.sdk & 0xff);
4035 outs() << "\n";
4036}
4037
4038static void PrintSourceVersionCommand(MachO::source_version_command sd) {
4039 outs() << " cmd LC_SOURCE_VERSION\n";
4040 outs() << " cmdsize " << sd.cmdsize;
4041 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
4042 outs() << " Incorrect size\n";
4043 else
4044 outs() << "\n";
4045 uint64_t a = (sd.version >> 40) & 0xffffff;
4046 uint64_t b = (sd.version >> 30) & 0x3ff;
4047 uint64_t c = (sd.version >> 20) & 0x3ff;
4048 uint64_t d = (sd.version >> 10) & 0x3ff;
4049 uint64_t e = sd.version & 0x3ff;
4050 outs() << " version " << a << "." << b;
4051 if (e != 0)
4052 outs() << "." << c << "." << d << "." << e;
4053 else if (d != 0)
4054 outs() << "." << c << "." << d;
4055 else if (c != 0)
4056 outs() << "." << c;
4057 outs() << "\n";
4058}
4059
4060static void PrintEntryPointCommand(MachO::entry_point_command ep) {
4061 outs() << " cmd LC_MAIN\n";
4062 outs() << " cmdsize " << ep.cmdsize;
4063 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
4064 outs() << " Incorrect size\n";
4065 else
4066 outs() << "\n";
4067 outs() << " entryoff " << ep.entryoff << "\n";
4068 outs() << " stacksize " << ep.stacksize << "\n";
4069}
4070
Kevin Enderby0804f4672014-12-16 23:25:52 +00004071static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
4072 uint32_t object_size) {
4073 outs() << " cmd LC_ENCRYPTION_INFO\n";
4074 outs() << " cmdsize " << ec.cmdsize;
4075 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
4076 outs() << " Incorrect size\n";
4077 else
4078 outs() << "\n";
4079 outs() << " cryptoff " << ec.cryptoff;
4080 if (ec.cryptoff > object_size)
4081 outs() << " (past end of file)\n";
4082 else
4083 outs() << "\n";
4084 outs() << " cryptsize " << ec.cryptsize;
4085 if (ec.cryptsize > object_size)
4086 outs() << " (past end of file)\n";
4087 else
4088 outs() << "\n";
4089 outs() << " cryptid " << ec.cryptid << "\n";
4090}
4091
Kevin Enderby57538292014-12-17 01:01:30 +00004092static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004093 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00004094 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
4095 outs() << " cmdsize " << ec.cmdsize;
4096 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
4097 outs() << " Incorrect size\n";
4098 else
4099 outs() << "\n";
4100 outs() << " cryptoff " << ec.cryptoff;
4101 if (ec.cryptoff > object_size)
4102 outs() << " (past end of file)\n";
4103 else
4104 outs() << "\n";
4105 outs() << " cryptsize " << ec.cryptsize;
4106 if (ec.cryptsize > object_size)
4107 outs() << " (past end of file)\n";
4108 else
4109 outs() << "\n";
4110 outs() << " cryptid " << ec.cryptid << "\n";
4111 outs() << " pad " << ec.pad << "\n";
4112}
4113
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004114static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
4115 const char *Ptr) {
4116 outs() << " cmd LC_LINKER_OPTION\n";
4117 outs() << " cmdsize " << lo.cmdsize;
4118 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
4119 outs() << " Incorrect size\n";
4120 else
4121 outs() << "\n";
4122 outs() << " count " << lo.count << "\n";
4123 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
4124 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
4125 uint32_t i = 0;
4126 while (left > 0) {
4127 while (*string == '\0' && left > 0) {
4128 string++;
4129 left--;
4130 }
4131 if (left > 0) {
4132 i++;
4133 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00004134 uint32_t NullPos = StringRef(string, left).find('\0');
4135 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004136 string += len;
4137 left -= len;
4138 }
4139 }
4140 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004141 outs() << " count " << lo.count << " does not match number of strings "
4142 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004143}
4144
Kevin Enderbyb4b79312014-12-18 19:24:35 +00004145static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
4146 const char *Ptr) {
4147 outs() << " cmd LC_SUB_FRAMEWORK\n";
4148 outs() << " cmdsize " << sub.cmdsize;
4149 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
4150 outs() << " Incorrect size\n";
4151 else
4152 outs() << "\n";
4153 if (sub.umbrella < sub.cmdsize) {
4154 const char *P = Ptr + sub.umbrella;
4155 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
4156 } else {
4157 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
4158 }
4159}
4160
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00004161static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
4162 const char *Ptr) {
4163 outs() << " cmd LC_SUB_UMBRELLA\n";
4164 outs() << " cmdsize " << sub.cmdsize;
4165 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
4166 outs() << " Incorrect size\n";
4167 else
4168 outs() << "\n";
4169 if (sub.sub_umbrella < sub.cmdsize) {
4170 const char *P = Ptr + sub.sub_umbrella;
4171 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
4172 } else {
4173 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
4174 }
4175}
4176
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004177static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004178 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004179 outs() << " cmd LC_SUB_LIBRARY\n";
4180 outs() << " cmdsize " << sub.cmdsize;
4181 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
4182 outs() << " Incorrect size\n";
4183 else
4184 outs() << "\n";
4185 if (sub.sub_library < sub.cmdsize) {
4186 const char *P = Ptr + sub.sub_library;
4187 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
4188 } else {
4189 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
4190 }
4191}
4192
Kevin Enderby186eac32014-12-19 21:06:24 +00004193static void PrintSubClientCommand(MachO::sub_client_command sub,
4194 const char *Ptr) {
4195 outs() << " cmd LC_SUB_CLIENT\n";
4196 outs() << " cmdsize " << sub.cmdsize;
4197 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
4198 outs() << " Incorrect size\n";
4199 else
4200 outs() << "\n";
4201 if (sub.client < sub.cmdsize) {
4202 const char *P = Ptr + sub.client;
4203 outs() << " client " << P << " (offset " << sub.client << ")\n";
4204 } else {
4205 outs() << " client ?(bad offset " << sub.client << ")\n";
4206 }
4207}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004208
Kevin Enderby52e4ce42014-12-19 22:25:22 +00004209static void PrintRoutinesCommand(MachO::routines_command r) {
4210 outs() << " cmd LC_ROUTINES\n";
4211 outs() << " cmdsize " << r.cmdsize;
4212 if (r.cmdsize != sizeof(struct MachO::routines_command))
4213 outs() << " Incorrect size\n";
4214 else
4215 outs() << "\n";
4216 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
4217 outs() << " init_module " << r.init_module << "\n";
4218 outs() << " reserved1 " << r.reserved1 << "\n";
4219 outs() << " reserved2 " << r.reserved2 << "\n";
4220 outs() << " reserved3 " << r.reserved3 << "\n";
4221 outs() << " reserved4 " << r.reserved4 << "\n";
4222 outs() << " reserved5 " << r.reserved5 << "\n";
4223 outs() << " reserved6 " << r.reserved6 << "\n";
4224}
4225
4226static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
4227 outs() << " cmd LC_ROUTINES_64\n";
4228 outs() << " cmdsize " << r.cmdsize;
4229 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
4230 outs() << " Incorrect size\n";
4231 else
4232 outs() << "\n";
4233 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
4234 outs() << " init_module " << r.init_module << "\n";
4235 outs() << " reserved1 " << r.reserved1 << "\n";
4236 outs() << " reserved2 " << r.reserved2 << "\n";
4237 outs() << " reserved3 " << r.reserved3 << "\n";
4238 outs() << " reserved4 " << r.reserved4 << "\n";
4239 outs() << " reserved5 " << r.reserved5 << "\n";
4240 outs() << " reserved6 " << r.reserved6 << "\n";
4241}
4242
Kevin Enderby48ef5342014-12-23 22:56:39 +00004243static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4244 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4245 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4246 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4247 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4248 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4249 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4250 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4251 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4252 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4253 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4254 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4255 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4256 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4257 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4258 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4259 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4260 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4261 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4262 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4263 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4264 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4265}
4266
Kevin Enderby227df342014-12-23 23:43:59 +00004267static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004268 uint32_t f;
4269 outs() << "\t mmst_reg ";
4270 for (f = 0; f < 10; f++)
4271 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4272 outs() << "\n";
4273 outs() << "\t mmst_rsrv ";
4274 for (f = 0; f < 6; f++)
4275 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4276 outs() << "\n";
4277}
4278
Kevin Enderbyaefb0032014-12-24 00:16:51 +00004279static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004280 uint32_t f;
4281 outs() << "\t xmm_reg ";
4282 for (f = 0; f < 16; f++)
4283 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4284 outs() << "\n";
4285}
4286
4287static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4288 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4289 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4290 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4291 outs() << " denorm " << fpu.fpu_fcw.denorm;
4292 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4293 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4294 outs() << " undfl " << fpu.fpu_fcw.undfl;
4295 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4296 outs() << "\t\t pc ";
4297 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4298 outs() << "FP_PREC_24B ";
4299 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4300 outs() << "FP_PREC_53B ";
4301 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4302 outs() << "FP_PREC_64B ";
4303 else
4304 outs() << fpu.fpu_fcw.pc << " ";
4305 outs() << "rc ";
4306 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4307 outs() << "FP_RND_NEAR ";
4308 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4309 outs() << "FP_RND_DOWN ";
4310 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4311 outs() << "FP_RND_UP ";
4312 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004313 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004314 outs() << "\n";
4315 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4316 outs() << " denorm " << fpu.fpu_fsw.denorm;
4317 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4318 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4319 outs() << " undfl " << fpu.fpu_fsw.undfl;
4320 outs() << " precis " << fpu.fpu_fsw.precis;
4321 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4322 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4323 outs() << " c0 " << fpu.fpu_fsw.c0;
4324 outs() << " c1 " << fpu.fpu_fsw.c1;
4325 outs() << " c2 " << fpu.fpu_fsw.c2;
4326 outs() << " tos " << fpu.fpu_fsw.tos;
4327 outs() << " c3 " << fpu.fpu_fsw.c3;
4328 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4329 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4330 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4331 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4332 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4333 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4334 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4335 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4336 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4337 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4338 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4339 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4340 outs() << "\n";
4341 outs() << "\t fpu_stmm0:\n";
4342 Print_mmst_reg(fpu.fpu_stmm0);
4343 outs() << "\t fpu_stmm1:\n";
4344 Print_mmst_reg(fpu.fpu_stmm1);
4345 outs() << "\t fpu_stmm2:\n";
4346 Print_mmst_reg(fpu.fpu_stmm2);
4347 outs() << "\t fpu_stmm3:\n";
4348 Print_mmst_reg(fpu.fpu_stmm3);
4349 outs() << "\t fpu_stmm4:\n";
4350 Print_mmst_reg(fpu.fpu_stmm4);
4351 outs() << "\t fpu_stmm5:\n";
4352 Print_mmst_reg(fpu.fpu_stmm5);
4353 outs() << "\t fpu_stmm6:\n";
4354 Print_mmst_reg(fpu.fpu_stmm6);
4355 outs() << "\t fpu_stmm7:\n";
4356 Print_mmst_reg(fpu.fpu_stmm7);
4357 outs() << "\t fpu_xmm0:\n";
4358 Print_xmm_reg(fpu.fpu_xmm0);
4359 outs() << "\t fpu_xmm1:\n";
4360 Print_xmm_reg(fpu.fpu_xmm1);
4361 outs() << "\t fpu_xmm2:\n";
4362 Print_xmm_reg(fpu.fpu_xmm2);
4363 outs() << "\t fpu_xmm3:\n";
4364 Print_xmm_reg(fpu.fpu_xmm3);
4365 outs() << "\t fpu_xmm4:\n";
4366 Print_xmm_reg(fpu.fpu_xmm4);
4367 outs() << "\t fpu_xmm5:\n";
4368 Print_xmm_reg(fpu.fpu_xmm5);
4369 outs() << "\t fpu_xmm6:\n";
4370 Print_xmm_reg(fpu.fpu_xmm6);
4371 outs() << "\t fpu_xmm7:\n";
4372 Print_xmm_reg(fpu.fpu_xmm7);
4373 outs() << "\t fpu_xmm8:\n";
4374 Print_xmm_reg(fpu.fpu_xmm8);
4375 outs() << "\t fpu_xmm9:\n";
4376 Print_xmm_reg(fpu.fpu_xmm9);
4377 outs() << "\t fpu_xmm10:\n";
4378 Print_xmm_reg(fpu.fpu_xmm10);
4379 outs() << "\t fpu_xmm11:\n";
4380 Print_xmm_reg(fpu.fpu_xmm11);
4381 outs() << "\t fpu_xmm12:\n";
4382 Print_xmm_reg(fpu.fpu_xmm12);
4383 outs() << "\t fpu_xmm13:\n";
4384 Print_xmm_reg(fpu.fpu_xmm13);
4385 outs() << "\t fpu_xmm14:\n";
4386 Print_xmm_reg(fpu.fpu_xmm14);
4387 outs() << "\t fpu_xmm15:\n";
4388 Print_xmm_reg(fpu.fpu_xmm15);
4389 outs() << "\t fpu_rsrv4:\n";
4390 for (uint32_t f = 0; f < 6; f++) {
4391 outs() << "\t ";
4392 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004393 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004394 outs() << "\n";
4395 }
4396 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
4397 outs() << "\n";
4398}
4399
4400static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
4401 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
4402 outs() << " err " << format("0x%08" PRIx32, exc64.err);
4403 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
4404}
4405
4406static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
4407 bool isLittleEndian, uint32_t cputype) {
4408 if (t.cmd == MachO::LC_THREAD)
4409 outs() << " cmd LC_THREAD\n";
4410 else if (t.cmd == MachO::LC_UNIXTHREAD)
4411 outs() << " cmd LC_UNIXTHREAD\n";
4412 else
4413 outs() << " cmd " << t.cmd << " (unknown)\n";
4414 outs() << " cmdsize " << t.cmdsize;
4415 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
4416 outs() << " Incorrect size\n";
4417 else
4418 outs() << "\n";
4419
4420 const char *begin = Ptr + sizeof(struct MachO::thread_command);
4421 const char *end = Ptr + t.cmdsize;
4422 uint32_t flavor, count, left;
4423 if (cputype == MachO::CPU_TYPE_X86_64) {
4424 while (begin < end) {
4425 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4426 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4427 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004428 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004429 flavor = 0;
4430 begin = end;
4431 }
4432 if (isLittleEndian != sys::IsLittleEndianHost)
4433 sys::swapByteOrder(flavor);
4434 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4435 memcpy((char *)&count, begin, sizeof(uint32_t));
4436 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004437 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004438 count = 0;
4439 begin = end;
4440 }
4441 if (isLittleEndian != sys::IsLittleEndianHost)
4442 sys::swapByteOrder(count);
4443 if (flavor == MachO::x86_THREAD_STATE64) {
4444 outs() << " flavor x86_THREAD_STATE64\n";
4445 if (count == MachO::x86_THREAD_STATE64_COUNT)
4446 outs() << " count x86_THREAD_STATE64_COUNT\n";
4447 else
4448 outs() << " count " << count
4449 << " (not x86_THREAD_STATE64_COUNT)\n";
4450 MachO::x86_thread_state64_t cpu64;
4451 left = end - begin;
4452 if (left >= sizeof(MachO::x86_thread_state64_t)) {
4453 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
4454 begin += sizeof(MachO::x86_thread_state64_t);
4455 } else {
4456 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
4457 memcpy(&cpu64, begin, left);
4458 begin += left;
4459 }
4460 if (isLittleEndian != sys::IsLittleEndianHost)
4461 swapStruct(cpu64);
4462 Print_x86_thread_state64_t(cpu64);
4463 } else if (flavor == MachO::x86_THREAD_STATE) {
4464 outs() << " flavor x86_THREAD_STATE\n";
4465 if (count == MachO::x86_THREAD_STATE_COUNT)
4466 outs() << " count x86_THREAD_STATE_COUNT\n";
4467 else
4468 outs() << " count " << count
4469 << " (not x86_THREAD_STATE_COUNT)\n";
4470 struct MachO::x86_thread_state_t ts;
4471 left = end - begin;
4472 if (left >= sizeof(MachO::x86_thread_state_t)) {
4473 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
4474 begin += sizeof(MachO::x86_thread_state_t);
4475 } else {
4476 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
4477 memcpy(&ts, begin, left);
4478 begin += left;
4479 }
4480 if (isLittleEndian != sys::IsLittleEndianHost)
4481 swapStruct(ts);
4482 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
4483 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
4484 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
4485 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
4486 else
4487 outs() << "tsh.count " << ts.tsh.count
4488 << " (not x86_THREAD_STATE64_COUNT\n";
4489 Print_x86_thread_state64_t(ts.uts.ts64);
4490 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004491 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
4492 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004493 }
4494 } else if (flavor == MachO::x86_FLOAT_STATE) {
4495 outs() << " flavor x86_FLOAT_STATE\n";
4496 if (count == MachO::x86_FLOAT_STATE_COUNT)
4497 outs() << " count x86_FLOAT_STATE_COUNT\n";
4498 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004499 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004500 struct MachO::x86_float_state_t fs;
4501 left = end - begin;
4502 if (left >= sizeof(MachO::x86_float_state_t)) {
4503 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
4504 begin += sizeof(MachO::x86_float_state_t);
4505 } else {
4506 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
4507 memcpy(&fs, begin, left);
4508 begin += left;
4509 }
4510 if (isLittleEndian != sys::IsLittleEndianHost)
4511 swapStruct(fs);
4512 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
4513 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004514 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00004515 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
4516 else
4517 outs() << "fsh.count " << fs.fsh.count
4518 << " (not x86_FLOAT_STATE64_COUNT\n";
4519 Print_x86_float_state_t(fs.ufs.fs64);
4520 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004521 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
4522 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004523 }
4524 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
4525 outs() << " flavor x86_EXCEPTION_STATE\n";
4526 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
4527 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
4528 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004529 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00004530 << " (not x86_EXCEPTION_STATE_COUNT)\n";
4531 struct MachO::x86_exception_state_t es;
4532 left = end - begin;
4533 if (left >= sizeof(MachO::x86_exception_state_t)) {
4534 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
4535 begin += sizeof(MachO::x86_exception_state_t);
4536 } else {
4537 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
4538 memcpy(&es, begin, left);
4539 begin += left;
4540 }
4541 if (isLittleEndian != sys::IsLittleEndianHost)
4542 swapStruct(es);
4543 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
4544 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004545 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00004546 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
4547 else
4548 outs() << "\t esh.count " << es.esh.count
4549 << " (not x86_EXCEPTION_STATE64_COUNT\n";
4550 Print_x86_exception_state_t(es.ues.es64);
4551 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004552 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
4553 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004554 }
4555 } else {
4556 outs() << " flavor " << flavor << " (unknown)\n";
4557 outs() << " count " << count << "\n";
4558 outs() << " state (unknown)\n";
4559 begin += count * sizeof(uint32_t);
4560 }
4561 }
4562 } else {
4563 while (begin < end) {
4564 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4565 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4566 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004567 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004568 flavor = 0;
4569 begin = end;
4570 }
4571 if (isLittleEndian != sys::IsLittleEndianHost)
4572 sys::swapByteOrder(flavor);
4573 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4574 memcpy((char *)&count, begin, sizeof(uint32_t));
4575 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004576 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004577 count = 0;
4578 begin = end;
4579 }
4580 if (isLittleEndian != sys::IsLittleEndianHost)
4581 sys::swapByteOrder(count);
4582 outs() << " flavor " << flavor << "\n";
4583 outs() << " count " << count << "\n";
4584 outs() << " state (Unknown cputype/cpusubtype)\n";
4585 begin += count * sizeof(uint32_t);
4586 }
4587 }
4588}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004589
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004590static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
4591 if (dl.cmd == MachO::LC_ID_DYLIB)
4592 outs() << " cmd LC_ID_DYLIB\n";
4593 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
4594 outs() << " cmd LC_LOAD_DYLIB\n";
4595 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
4596 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
4597 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
4598 outs() << " cmd LC_REEXPORT_DYLIB\n";
4599 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
4600 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
4601 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
4602 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
4603 else
4604 outs() << " cmd " << dl.cmd << " (unknown)\n";
4605 outs() << " cmdsize " << dl.cmdsize;
4606 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
4607 outs() << " Incorrect size\n";
4608 else
4609 outs() << "\n";
4610 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004611 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004612 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
4613 } else {
4614 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
4615 }
4616 outs() << " time stamp " << dl.dylib.timestamp << " ";
4617 time_t t = dl.dylib.timestamp;
4618 outs() << ctime(&t);
4619 outs() << " current version ";
4620 if (dl.dylib.current_version == 0xffffffff)
4621 outs() << "n/a\n";
4622 else
4623 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
4624 << ((dl.dylib.current_version >> 8) & 0xff) << "."
4625 << (dl.dylib.current_version & 0xff) << "\n";
4626 outs() << "compatibility version ";
4627 if (dl.dylib.compatibility_version == 0xffffffff)
4628 outs() << "n/a\n";
4629 else
4630 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
4631 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
4632 << (dl.dylib.compatibility_version & 0xff) << "\n";
4633}
4634
4635static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
4636 uint32_t object_size) {
4637 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
4638 outs() << " cmd LC_FUNCTION_STARTS\n";
4639 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
4640 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
4641 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
4642 outs() << " cmd LC_FUNCTION_STARTS\n";
4643 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
4644 outs() << " cmd LC_DATA_IN_CODE\n";
4645 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
4646 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
4647 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
4648 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
4649 else
4650 outs() << " cmd " << ld.cmd << " (?)\n";
4651 outs() << " cmdsize " << ld.cmdsize;
4652 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
4653 outs() << " Incorrect size\n";
4654 else
4655 outs() << "\n";
4656 outs() << " dataoff " << ld.dataoff;
4657 if (ld.dataoff > object_size)
4658 outs() << " (past end of file)\n";
4659 else
4660 outs() << "\n";
4661 outs() << " datasize " << ld.datasize;
4662 uint64_t big_size = ld.dataoff;
4663 big_size += ld.datasize;
4664 if (big_size > object_size)
4665 outs() << " (past end of file)\n";
4666 else
4667 outs() << "\n";
4668}
4669
Kevin Enderby956366c2014-08-29 22:30:52 +00004670static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
4671 uint32_t filetype, uint32_t cputype,
4672 bool verbose) {
Filipe Cabecinhase71bd0c2015-01-06 17:08:26 +00004673 if (ncmds == 0)
4674 return;
Kevin Enderby956366c2014-08-29 22:30:52 +00004675 StringRef Buf = Obj->getData();
4676 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
4677 for (unsigned i = 0;; ++i) {
4678 outs() << "Load command " << i << "\n";
4679 if (Command.C.cmd == MachO::LC_SEGMENT) {
4680 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
4681 const char *sg_segname = SLC.segname;
4682 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
4683 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
4684 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
4685 verbose);
4686 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00004687 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00004688 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
4689 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
4690 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
4691 }
4692 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
4693 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
4694 const char *sg_segname = SLC_64.segname;
4695 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
4696 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
4697 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
4698 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
4699 for (unsigned j = 0; j < SLC_64.nsects; j++) {
4700 MachO::section_64 S_64 = Obj->getSection64(Command, j);
4701 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
4702 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
4703 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
4704 sg_segname, filetype, Buf.size(), verbose);
4705 }
4706 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
4707 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00004708 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00004709 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
4710 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
4711 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00004712 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
4713 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004714 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
4715 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
4716 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
4717 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
4718 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
4719 Command.C.cmd == MachO::LC_ID_DYLINKER ||
4720 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
4721 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
4722 PrintDyldLoadCommand(Dyld, Command.Ptr);
4723 } else if (Command.C.cmd == MachO::LC_UUID) {
4724 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
4725 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00004726 } else if (Command.C.cmd == MachO::LC_RPATH) {
4727 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
4728 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00004729 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
4730 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004731 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
4732 PrintVersionMinLoadCommand(Vd);
4733 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
4734 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
4735 PrintSourceVersionCommand(Sd);
4736 } else if (Command.C.cmd == MachO::LC_MAIN) {
4737 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
4738 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00004739 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004740 MachO::encryption_info_command Ei =
4741 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00004742 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00004743 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004744 MachO::encryption_info_command_64 Ei =
4745 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00004746 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004747 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004748 MachO::linker_option_command Lo =
4749 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004750 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00004751 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
4752 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
4753 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00004754 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
4755 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
4756 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004757 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
4758 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
4759 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00004760 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
4761 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
4762 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00004763 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
4764 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
4765 PrintRoutinesCommand(Rc);
4766 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
4767 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
4768 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00004769 } else if (Command.C.cmd == MachO::LC_THREAD ||
4770 Command.C.cmd == MachO::LC_UNIXTHREAD) {
4771 MachO::thread_command Tc = Obj->getThreadCommand(Command);
4772 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00004773 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
4774 Command.C.cmd == MachO::LC_ID_DYLIB ||
4775 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
4776 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
4777 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
4778 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004779 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
4780 PrintDylibCommand(Dl, Command.Ptr);
4781 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
4782 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
4783 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
4784 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
4785 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
4786 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
4787 MachO::linkedit_data_command Ld =
4788 Obj->getLinkeditDataLoadCommand(Command);
4789 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00004790 } else {
4791 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
4792 << ")\n";
4793 outs() << " cmdsize " << Command.C.cmdsize << "\n";
4794 // TODO: get and print the raw bytes of the load command.
4795 }
4796 // TODO: print all the other kinds of load commands.
4797 if (i == ncmds - 1)
4798 break;
4799 else
4800 Command = Obj->getNextLoadCommandInfo(Command);
4801 }
4802}
4803
4804static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
4805 uint32_t &filetype, uint32_t &cputype,
4806 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004807 if (Obj->is64Bit()) {
4808 MachO::mach_header_64 H_64;
4809 H_64 = Obj->getHeader64();
4810 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
4811 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00004812 ncmds = H_64.ncmds;
4813 filetype = H_64.filetype;
4814 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004815 } else {
4816 MachO::mach_header H;
4817 H = Obj->getHeader();
4818 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
4819 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00004820 ncmds = H.ncmds;
4821 filetype = H.filetype;
4822 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004823 }
4824}
4825
4826void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
4827 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00004828 uint32_t ncmds = 0;
4829 uint32_t filetype = 0;
4830 uint32_t cputype = 0;
4831 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
4832 PrintLoadCommands(file, ncmds, filetype, cputype, true);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004833}
Nick Kledzikd04bc352014-08-30 00:20:14 +00004834
4835//===----------------------------------------------------------------------===//
4836// export trie dumping
4837//===----------------------------------------------------------------------===//
4838
4839void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004840 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
4841 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00004842 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
4843 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
4844 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4845 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
4846 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4847 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
4848 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
4849 if (ReExport)
4850 outs() << "[re-export] ";
4851 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004852 outs() << format("0x%08llX ",
4853 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004854 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00004855 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004856 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00004857 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00004858 if (WeakDef) {
4859 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004860 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004861 }
4862 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004863 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00004864 outs() << ", ";
4865 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004866 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004867 }
4868 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004869 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00004870 outs() << ", ";
4871 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004872 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004873 }
4874 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004875 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00004876 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004877 outs() << format("resolver=0x%08llX", Entry.other());
4878 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004879 }
4880 outs() << "]";
4881 }
4882 if (ReExport) {
4883 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004884 int Ordinal = Entry.other() - 1;
4885 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
4886 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00004887 outs() << " (from " << DylibName << ")";
4888 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004889 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00004890 }
4891 outs() << "\n";
4892 }
4893}
Nick Kledzikac431442014-09-12 21:34:15 +00004894
Nick Kledzikac431442014-09-12 21:34:15 +00004895//===----------------------------------------------------------------------===//
4896// rebase table dumping
4897//===----------------------------------------------------------------------===//
4898
4899namespace {
4900class SegInfo {
4901public:
4902 SegInfo(const object::MachOObjectFile *Obj);
4903
4904 StringRef segmentName(uint32_t SegIndex);
4905 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
4906 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
4907
4908private:
4909 struct SectionInfo {
4910 uint64_t Address;
4911 uint64_t Size;
4912 StringRef SectionName;
4913 StringRef SegmentName;
4914 uint64_t OffsetInSegment;
4915 uint64_t SegmentStartAddress;
4916 uint32_t SegmentIndex;
4917 };
4918 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
4919 SmallVector<SectionInfo, 32> Sections;
4920};
4921}
4922
4923SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
4924 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00004925 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00004926 StringRef CurSegName;
4927 uint64_t CurSegAddress;
4928 for (const SectionRef &Section : Obj->sections()) {
4929 SectionInfo Info;
4930 if (error(Section.getName(Info.SectionName)))
4931 return;
Rafael Espindola80291272014-10-08 15:28:58 +00004932 Info.Address = Section.getAddress();
4933 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00004934 Info.SegmentName =
4935 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4936 if (!Info.SegmentName.equals(CurSegName)) {
4937 ++CurSegIndex;
4938 CurSegName = Info.SegmentName;
4939 CurSegAddress = Info.Address;
4940 }
4941 Info.SegmentIndex = CurSegIndex - 1;
4942 Info.OffsetInSegment = Info.Address - CurSegAddress;
4943 Info.SegmentStartAddress = CurSegAddress;
4944 Sections.push_back(Info);
4945 }
4946}
4947
4948StringRef SegInfo::segmentName(uint32_t SegIndex) {
4949 for (const SectionInfo &SI : Sections) {
4950 if (SI.SegmentIndex == SegIndex)
4951 return SI.SegmentName;
4952 }
4953 llvm_unreachable("invalid segIndex");
4954}
4955
4956const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
4957 uint64_t OffsetInSeg) {
4958 for (const SectionInfo &SI : Sections) {
4959 if (SI.SegmentIndex != SegIndex)
4960 continue;
4961 if (SI.OffsetInSegment > OffsetInSeg)
4962 continue;
4963 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
4964 continue;
4965 return SI;
4966 }
4967 llvm_unreachable("segIndex and offset not in any section");
4968}
4969
4970StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
4971 return findSection(SegIndex, OffsetInSeg).SectionName;
4972}
4973
4974uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4975 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4976 return SI.SegmentStartAddress + OffsetInSeg;
4977}
4978
4979void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
4980 // Build table of sections so names can used in final output.
4981 SegInfo sectionTable(Obj);
4982
4983 outs() << "segment section address type\n";
4984 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
4985 uint32_t SegIndex = Entry.segmentIndex();
4986 uint64_t OffsetInSeg = Entry.segmentOffset();
4987 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4988 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4989 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4990
4991 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004992 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
4993 SegmentName.str().c_str(), SectionName.str().c_str(),
4994 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00004995 }
4996}
Nick Kledzik56ebef42014-09-16 01:41:51 +00004997
4998static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
4999 StringRef DylibName;
5000 switch (Ordinal) {
5001 case MachO::BIND_SPECIAL_DYLIB_SELF:
5002 return "this-image";
5003 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
5004 return "main-executable";
5005 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
5006 return "flat-namespace";
5007 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00005008 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005009 std::error_code EC =
5010 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00005011 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00005012 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00005013 return DylibName;
5014 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00005015 }
Nick Kledzikabd29872014-09-16 22:03:13 +00005016 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005017}
5018
5019//===----------------------------------------------------------------------===//
5020// bind table dumping
5021//===----------------------------------------------------------------------===//
5022
5023void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
5024 // Build table of sections so names can used in final output.
5025 SegInfo sectionTable(Obj);
5026
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005027 outs() << "segment section address type "
5028 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005029 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
5030 uint32_t SegIndex = Entry.segmentIndex();
5031 uint64_t OffsetInSeg = Entry.segmentOffset();
5032 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5033 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5034 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5035
5036 // Table lines look like:
5037 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005038 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00005039 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005040 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005041 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005042 << left_justify(SectionName, 18) << " "
5043 << format_hex(Address, 10, true) << " "
5044 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005045 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005046 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005047 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005048 }
5049}
5050
5051//===----------------------------------------------------------------------===//
5052// lazy bind table dumping
5053//===----------------------------------------------------------------------===//
5054
5055void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
5056 // Build table of sections so names can used in final output.
5057 SegInfo sectionTable(Obj);
5058
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005059 outs() << "segment section address "
5060 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005061 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
5062 uint32_t SegIndex = Entry.segmentIndex();
5063 uint64_t OffsetInSeg = Entry.segmentOffset();
5064 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5065 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5066 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5067
5068 // Table lines look like:
5069 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005070 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005071 << left_justify(SectionName, 18) << " "
5072 << format_hex(Address, 10, true) << " "
5073 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00005074 << Entry.symbolName() << "\n";
5075 }
5076}
5077
Nick Kledzik56ebef42014-09-16 01:41:51 +00005078//===----------------------------------------------------------------------===//
5079// weak bind table dumping
5080//===----------------------------------------------------------------------===//
5081
5082void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
5083 // Build table of sections so names can used in final output.
5084 SegInfo sectionTable(Obj);
5085
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005086 outs() << "segment section address "
5087 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005088 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
5089 // Strong symbols don't have a location to update.
5090 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005091 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00005092 << Entry.symbolName() << "\n";
5093 continue;
5094 }
5095 uint32_t SegIndex = Entry.segmentIndex();
5096 uint64_t OffsetInSeg = Entry.segmentOffset();
5097 StringRef SegmentName = sectionTable.segmentName(SegIndex);
5098 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
5099 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5100
5101 // Table lines look like:
5102 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005103 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00005104 << left_justify(SectionName, 18) << " "
5105 << format_hex(Address, 10, true) << " "
5106 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00005107 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
5108 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00005109 }
5110}
5111
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005112// get_dyld_bind_info_symbolname() is used for disassembly and passed an
5113// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
5114// information for that address. If the address is found its binding symbol
5115// name is returned. If not nullptr is returned.
5116static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
5117 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00005118 if (info->bindtable == nullptr) {
5119 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005120 SegInfo sectionTable(info->O);
5121 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
5122 uint32_t SegIndex = Entry.segmentIndex();
5123 uint64_t OffsetInSeg = Entry.segmentOffset();
5124 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
5125 const char *SymbolName = nullptr;
5126 StringRef name = Entry.symbolName();
5127 if (!name.empty())
5128 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00005129 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005130 }
5131 }
Kevin Enderby078be602014-10-23 19:53:12 +00005132 for (bind_table_iterator BI = info->bindtable->begin(),
5133 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00005134 BI != BE; ++BI) {
5135 uint64_t Address = BI->first;
5136 if (ReferenceValue == Address) {
5137 const char *SymbolName = BI->second;
5138 return SymbolName;
5139 }
5140 }
5141 return nullptr;
5142}