blob: 153edfab52c7072b5fb6d43a7776a06d95d5bd03 [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"
37#include "llvm/Support/GraphWriter.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/MemoryBuffer.h"
Kevin Enderbybf246f52014-09-24 23:08:22 +000040#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#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 Enderby131d1772015-01-09 19:22:37 +000069cl::opt<bool>
70 llvm::UniversalHeaders("universal-headers",
71 cl::desc("Print Mach-O universal headers"));
72
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +000073static cl::list<std::string>
74 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
75 cl::ZeroOrMore);
76bool ArchAll = false;
77
Kevin Enderbyec5ca032014-08-18 20:21:02 +000078static std::string ThumbTripleName;
79
80static const Target *GetTarget(const MachOObjectFile *MachOObj,
81 const char **McpuDefault,
82 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +000083 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000084 if (TripleName.empty()) {
85 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +000086 llvm::Triple ThumbTriple = Triple();
87 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000088 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +000089 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +000090 }
91
Benjamin Kramer43a772e2011-09-19 17:56:04 +000092 // Get the target specific parser.
93 std::string Error;
94 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +000095 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +000096 return TheTarget;
97
Kevin Enderbyec5ca032014-08-18 20:21:02 +000098 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
99 if (*ThumbTarget)
100 return TheTarget;
101
102 errs() << "llvm-objdump: error: unable to get target for '";
103 if (!TheTarget)
104 errs() << TripleName;
105 else
106 errs() << ThumbTripleName;
107 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +0000108 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000109}
110
Owen Andersond9243c42011-10-17 21:37:35 +0000111struct SymbolSorter {
112 bool operator()(const SymbolRef &A, const SymbolRef &B) {
113 SymbolRef::Type AType, BType;
114 A.getType(AType);
115 B.getType(BType);
116
117 uint64_t AAddr, BAddr;
118 if (AType != SymbolRef::ST_Function)
119 AAddr = 0;
120 else
121 A.getAddress(AAddr);
122 if (BType != SymbolRef::ST_Function)
123 BAddr = 0;
124 else
125 B.getAddress(BAddr);
126 return AAddr < BAddr;
127 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000128};
129
Kevin Enderby273ae012013-06-06 17:20:50 +0000130// Types for the storted data in code table that is built before disassembly
131// and the predicate function to sort them.
132typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
133typedef std::vector<DiceTableEntry> DiceTable;
134typedef DiceTable::iterator dice_table_iterator;
135
Kevin Enderby930fdc72014-11-06 19:00:13 +0000136// This is used to search for a data in code table entry for the PC being
137// disassembled. The j parameter has the PC in j.first. A single data in code
138// table entry can cover many bytes for each of its Kind's. So if the offset,
139// aka the i.first value, of the data in code table entry plus its Length
140// covers the PC being searched for this will return true. If not it will
141// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000142static bool compareDiceTableEntries(const DiceTableEntry &i,
143 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000144 uint16_t Length;
145 i.second.getLength(Length);
146
147 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000148}
149
Kevin Enderby930fdc72014-11-06 19:00:13 +0000150static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
151 unsigned short Kind) {
152 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000153
154 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000155 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000156 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000157 if (Length >= 4) {
158 if (!NoShowRawInsn)
159 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000160 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000161 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000162 Size = 4;
163 } else if (Length >= 2) {
164 if (!NoShowRawInsn)
165 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000166 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000167 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000168 Size = 2;
169 } else {
170 if (!NoShowRawInsn)
171 DumpBytes(StringRef(bytes, 2));
Kevin Enderby273ae012013-06-06 17:20:50 +0000172 Value = bytes[0];
173 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000174 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000175 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000176 if (Kind == MachO::DICE_KIND_DATA)
177 outs() << "\t@ KIND_DATA\n";
178 else
179 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000180 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000181 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000182 if (!NoShowRawInsn)
183 DumpBytes(StringRef(bytes, 1));
Kevin Enderby273ae012013-06-06 17:20:50 +0000184 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000185 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
186 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000187 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000188 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000189 if (!NoShowRawInsn)
190 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000191 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000192 outs() << "\t.short " << format("%5u", Value & 0xffff)
193 << "\t@ KIND_JUMP_TABLE16\n";
194 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000195 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000196 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000197 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
198 if (!NoShowRawInsn)
199 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000200 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000201 outs() << "\t.long " << Value;
202 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
203 outs() << "\t@ KIND_JUMP_TABLE32\n";
204 else
205 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
206 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000207 break;
208 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000209 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000210}
211
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000212static void getSectionsAndSymbols(const MachO::mach_header Header,
213 MachOObjectFile *MachOObj,
214 std::vector<SectionRef> &Sections,
215 std::vector<SymbolRef> &Symbols,
216 SmallVectorImpl<uint64_t> &FoundFns,
217 uint64_t &BaseSegmentAddress) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000218 for (const SymbolRef &Symbol : MachOObj->symbols()) {
219 StringRef SymName;
220 Symbol.getName(SymName);
221 if (!SymName.startswith("ltmp"))
222 Symbols.push_back(Symbol);
223 }
Owen Andersond9243c42011-10-17 21:37:35 +0000224
Alexey Samsonov48803e52014-03-13 14:37:36 +0000225 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000226 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000227 Section.getName(SectName);
228 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000229 }
230
Rafael Espindola56f976f2013-04-18 18:08:55 +0000231 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000232 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000233 bool BaseSegmentAddressSet = false;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000234 for (unsigned i = 0;; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000235 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000236 // We found a function starts segment, parse the addresses for later
237 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000238 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000239 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000240
Charles Davis8bdfafd2013-09-01 04:28:48 +0000241 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000242 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
243 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000244 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000245 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000246 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000247 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000248 }
249 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000250
Charles Davis8bdfafd2013-09-01 04:28:48 +0000251 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000252 break;
253 else
254 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000255 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000256}
257
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000258// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
259// and if it is and there is a list of architecture flags is specified then
260// check to make sure this Mach-O file is one of those architectures or all
261// architectures were specified. If not then an error is generated and this
262// routine returns false. Else it returns true.
263static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
264 if (isa<MachOObjectFile>(O) && !ArchAll && ArchFlags.size() != 0) {
265 MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(O);
266 bool ArchFound = false;
267 MachO::mach_header H;
268 MachO::mach_header_64 H_64;
269 Triple T;
270 if (MachO->is64Bit()) {
271 H_64 = MachO->MachOObjectFile::getHeader64();
272 T = MachOObjectFile::getArch(H_64.cputype, H_64.cpusubtype);
273 } else {
274 H = MachO->MachOObjectFile::getHeader();
275 T = MachOObjectFile::getArch(H.cputype, H.cpusubtype);
276 }
277 unsigned i;
278 for (i = 0; i < ArchFlags.size(); ++i) {
279 if (ArchFlags[i] == T.getArchName())
280 ArchFound = true;
281 break;
282 }
283 if (!ArchFound) {
284 errs() << "llvm-objdump: file: " + Filename + " does not contain "
285 << "architecture: " + ArchFlags[i] + "\n";
286 return false;
287 }
288 }
289 return true;
290}
291
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000292static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF);
Rafael Espindola9b709252013-04-13 01:45:40 +0000293
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000294// ProcessMachO() is passed a single opened Mach-O file, which may be an
295// archive member and or in a slice of a universal file. It prints the
296// the file name and header info and then processes it according to the
297// command line options.
298static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
299 StringRef ArchiveMemberName = StringRef(),
300 StringRef ArchitectureName = StringRef()) {
Kevin Enderby131d1772015-01-09 19:22:37 +0000301 // If we are doing some processing here on the Mach-O file print the header
302 // info. And don't print it otherwise like in the case of printing the
303 // UniversalHeaders.
304 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind ||
305 LazyBind || WeakBind) {
306 outs() << Filename;
307 if (!ArchiveMemberName.empty())
308 outs() << '(' << ArchiveMemberName << ')';
309 if (!ArchitectureName.empty())
310 outs() << " (architecture " << ArchitectureName << ")";
311 outs() << ":\n";
312 }
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000313
314 if (Disassemble)
315 DisassembleMachO(Filename, MachOOF);
316 // TODO: These should/could be printed in Darwin's otool(1) or nm(1) style
317 // for -macho. Or just used a new option that maps to the otool(1)
318 // option like -r, -l, etc. Or just the normal llvm-objdump option
319 // but now for this slice so that the -arch options can be used.
320 // if (Relocations)
321 // PrintRelocations(MachOOF);
322 // if (SectionHeaders)
323 // PrintSectionHeaders(MachOOF);
324 // if (SectionContents)
325 // PrintSectionContents(MachOOF);
326 // if (SymbolTable)
327 // PrintSymbolTable(MachOOF);
328 // if (UnwindInfo)
329 // PrintUnwindInfo(MachOOF);
330 if (PrivateHeaders)
331 printMachOFileHeader(MachOOF);
332 if (ExportsTrie)
333 printExportsTrie(MachOOF);
334 if (Rebase)
335 printRebaseTable(MachOOF);
336 if (Bind)
337 printBindTable(MachOOF);
338 if (LazyBind)
339 printLazyBindTable(MachOOF);
340 if (WeakBind)
341 printWeakBindTable(MachOOF);
342}
343
Kevin Enderby131d1772015-01-09 19:22:37 +0000344// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
345static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
346 outs() << " cputype (" << cputype << ")\n";
347 outs() << " cpusubtype (" << cpusubtype << ")\n";
348}
349
350// printCPUType() helps print_fat_headers by printing the cputype and
351// pusubtype (symbolically for the one's it knows about).
352static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
353 switch (cputype) {
354 case MachO::CPU_TYPE_I386:
355 switch (cpusubtype) {
356 case MachO::CPU_SUBTYPE_I386_ALL:
357 outs() << " cputype CPU_TYPE_I386\n";
358 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
359 break;
360 default:
361 printUnknownCPUType(cputype, cpusubtype);
362 break;
363 }
364 break;
365 case MachO::CPU_TYPE_X86_64:
366 switch (cpusubtype) {
367 case MachO::CPU_SUBTYPE_X86_64_ALL:
368 outs() << " cputype CPU_TYPE_X86_64\n";
369 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
370 break;
371 case MachO::CPU_SUBTYPE_X86_64_H:
372 outs() << " cputype CPU_TYPE_X86_64\n";
373 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
374 break;
375 default:
376 printUnknownCPUType(cputype, cpusubtype);
377 break;
378 }
379 break;
380 case MachO::CPU_TYPE_ARM:
381 switch (cpusubtype) {
382 case MachO::CPU_SUBTYPE_ARM_ALL:
383 outs() << " cputype CPU_TYPE_ARM\n";
384 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
385 break;
386 case MachO::CPU_SUBTYPE_ARM_V4T:
387 outs() << " cputype CPU_TYPE_ARM\n";
388 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
389 break;
390 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
391 outs() << " cputype CPU_TYPE_ARM\n";
392 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
393 break;
394 case MachO::CPU_SUBTYPE_ARM_XSCALE:
395 outs() << " cputype CPU_TYPE_ARM\n";
396 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
397 break;
398 case MachO::CPU_SUBTYPE_ARM_V6:
399 outs() << " cputype CPU_TYPE_ARM\n";
400 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
401 break;
402 case MachO::CPU_SUBTYPE_ARM_V6M:
403 outs() << " cputype CPU_TYPE_ARM\n";
404 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
405 break;
406 case MachO::CPU_SUBTYPE_ARM_V7:
407 outs() << " cputype CPU_TYPE_ARM\n";
408 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
409 break;
410 case MachO::CPU_SUBTYPE_ARM_V7EM:
411 outs() << " cputype CPU_TYPE_ARM\n";
412 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
413 break;
414 case MachO::CPU_SUBTYPE_ARM_V7K:
415 outs() << " cputype CPU_TYPE_ARM\n";
416 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
417 break;
418 case MachO::CPU_SUBTYPE_ARM_V7M:
419 outs() << " cputype CPU_TYPE_ARM\n";
420 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
421 break;
422 case MachO::CPU_SUBTYPE_ARM_V7S:
423 outs() << " cputype CPU_TYPE_ARM\n";
424 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
425 break;
426 default:
427 printUnknownCPUType(cputype, cpusubtype);
428 break;
429 }
430 break;
431 case MachO::CPU_TYPE_ARM64:
432 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
433 case MachO::CPU_SUBTYPE_ARM64_ALL:
434 outs() << " cputype CPU_TYPE_ARM64\n";
435 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
436 break;
437 default:
438 printUnknownCPUType(cputype, cpusubtype);
439 break;
440 }
441 break;
442 default:
443 printUnknownCPUType(cputype, cpusubtype);
444 break;
445 }
446}
447
448static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
449 bool verbose) {
450 outs() << "Fat headers\n";
451 if (verbose)
452 outs() << "fat_magic FAT_MAGIC\n";
453 else
454 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
455
456 uint32_t nfat_arch = UB->getNumberOfObjects();
457 StringRef Buf = UB->getData();
458 uint64_t size = Buf.size();
459 uint64_t big_size = sizeof(struct MachO::fat_header) +
460 nfat_arch * sizeof(struct MachO::fat_arch);
461 outs() << "nfat_arch " << UB->getNumberOfObjects();
462 if (nfat_arch == 0)
463 outs() << " (malformed, contains zero architecture types)\n";
464 else if (big_size > size)
465 outs() << " (malformed, architectures past end of file)\n";
466 else
467 outs() << "\n";
468
469 for (uint32_t i = 0; i < nfat_arch; ++i) {
470 MachOUniversalBinary::ObjectForArch OFA(UB, i);
471 uint32_t cputype = OFA.getCPUType();
472 uint32_t cpusubtype = OFA.getCPUSubType();
473 outs() << "architecture ";
474 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
475 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
476 uint32_t other_cputype = other_OFA.getCPUType();
477 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
478 if (cputype != 0 && cpusubtype != 0 &&
479 cputype == other_cputype &&
480 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
481 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK))
482 outs() << "(illegal duplicate architecture) ";
483 break;
484 }
485 if (verbose) {
486 outs() << OFA.getArchTypeName() << "\n";
487 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
488 } else {
489 outs() << i << "\n";
490 outs() << " cputype " << cputype << "\n";
491 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
492 << "\n";
493 }
494 if (verbose &&
495 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
496 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
497 else
498 outs() << " capabilities "
499 << format("0x%" PRIx32,
500 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
501 outs() << " offset " << OFA.getOffset();
502 if (OFA.getOffset() > size)
503 outs() << " (past end of file)";
504 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
505 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
506 outs() << "\n";
507 outs() << " size " << OFA.getSize();
508 big_size = OFA.getOffset() + OFA.getSize();
509 if (big_size > size)
510 outs() << " (past end of file)";
511 outs() << "\n";
512 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
513 << ")\n";
514 }
515}
516
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000517// ParseInputMachO() parses the named Mach-O file in Filename and handles the
518// -arch flags selecting just those slices as specified by them and also parses
519// archive files. Then for each individual Mach-O file ProcessMachO() is
520// called to process the file based on the command line options.
521void llvm::ParseInputMachO(StringRef Filename) {
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000522 // Check for -arch all and verifiy the -arch flags are valid.
523 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
524 if (ArchFlags[i] == "all") {
525 ArchAll = true;
526 } else {
527 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
528 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
529 "'for the -arch option\n";
530 return;
531 }
532 }
533 }
534
535 // Attempt to open the binary.
536 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
537 if (std::error_code EC = BinaryOrErr.getError()) {
538 errs() << "llvm-objdump: '" << Filename << "': " << EC.message() << ".\n";
Rafael Espindolade882cd2014-12-03 23:29:34 +0000539 return;
Kevin Enderby3f0ffab2014-12-03 22:29:40 +0000540 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000541 Binary &Bin = *BinaryOrErr.get().getBinary();
Kevin Enderby3f0ffab2014-12-03 22:29:40 +0000542
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000543 if (Archive *A = dyn_cast<Archive>(&Bin)) {
544 outs() << "Archive : " << Filename << "\n";
545 for (Archive::child_iterator I = A->child_begin(), E = A->child_end();
546 I != E; ++I) {
547 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = I->getAsBinary();
548 if (ChildOrErr.getError())
549 continue;
550 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
551 if (!checkMachOAndArchFlags(O, Filename))
552 return;
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000553 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000554 }
555 }
556 return;
557 }
Kevin Enderby131d1772015-01-09 19:22:37 +0000558 if (UniversalHeaders) {
559 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
560 printMachOUniversalHeaders(UB, true);
561 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000562 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
563 // If we have a list of architecture flags specified dump only those.
564 if (!ArchAll && ArchFlags.size() != 0) {
565 // Look for a slice in the universal binary that matches each ArchFlag.
566 bool ArchFound;
567 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
568 ArchFound = false;
569 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
570 E = UB->end_objects();
571 I != E; ++I) {
572 if (ArchFlags[i] == I->getArchTypeName()) {
573 ArchFound = true;
574 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr =
575 I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000576 std::string ArchitectureName = "";
577 if (ArchFlags.size() > 1)
578 ArchitectureName = I->getArchTypeName();
579 if (ObjOrErr) {
580 ObjectFile &O = *ObjOrErr.get();
581 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000582 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000583 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
584 I->getAsArchive()) {
585 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000586 outs() << "Archive : " << Filename;
587 if (!ArchitectureName.empty())
588 outs() << " (architecture " << ArchitectureName << ")";
589 outs() << "\n";
590 for (Archive::child_iterator AI = A->child_begin(),
591 AE = A->child_end();
592 AI != AE; ++AI) {
593 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
594 if (ChildOrErr.getError())
595 continue;
596 if (MachOObjectFile *O =
597 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000598 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000599 }
600 }
601 }
602 }
603 if (!ArchFound) {
604 errs() << "llvm-objdump: file: " + Filename + " does not contain "
605 << "architecture: " + ArchFlags[i] + "\n";
606 return;
607 }
608 }
609 return;
610 }
611 // No architecture flags were specified so if this contains a slice that
612 // matches the host architecture dump only that.
613 if (!ArchAll) {
614 StringRef HostArchName = MachOObjectFile::getHostArch().getArchName();
615 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
616 E = UB->end_objects();
617 I != E; ++I) {
618 if (HostArchName == I->getArchTypeName()) {
619 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000620 std::string ArchiveName;
621 ArchiveName.clear();
622 if (ObjOrErr) {
623 ObjectFile &O = *ObjOrErr.get();
624 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000625 ProcessMachO(Filename, MachOOF);
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000626 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr =
627 I->getAsArchive()) {
628 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000629 outs() << "Archive : " << Filename << "\n";
630 for (Archive::child_iterator AI = A->child_begin(),
631 AE = A->child_end();
632 AI != AE; ++AI) {
633 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
634 if (ChildOrErr.getError())
635 continue;
636 if (MachOObjectFile *O =
637 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000638 ProcessMachO(Filename, O, O->getFileName());
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000639 }
640 }
641 return;
642 }
643 }
644 }
645 // Either all architectures have been specified or none have been specified
646 // and this does not contain the host architecture so dump all the slices.
647 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
648 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
649 E = UB->end_objects();
650 I != E; ++I) {
651 ErrorOr<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000652 std::string ArchitectureName = "";
653 if (moreThanOneArch)
654 ArchitectureName = I->getArchTypeName();
655 if (ObjOrErr) {
656 ObjectFile &Obj = *ObjOrErr.get();
657 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000658 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
Rafael Espindola0bfe8282014-12-09 21:05:36 +0000659 } else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
660 std::unique_ptr<Archive> &A = *AOrErr;
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000661 outs() << "Archive : " << Filename;
662 if (!ArchitectureName.empty())
663 outs() << " (architecture " << ArchitectureName << ")";
664 outs() << "\n";
665 for (Archive::child_iterator AI = A->child_begin(), AE = A->child_end();
666 AI != AE; ++AI) {
667 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = AI->getAsBinary();
668 if (ChildOrErr.getError())
669 continue;
670 if (MachOObjectFile *O =
671 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
672 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000673 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
674 ArchitectureName);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000675 }
676 }
677 }
678 }
679 return;
680 }
681 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
682 if (!checkMachOAndArchFlags(O, Filename))
683 return;
684 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
Kevin Enderbye2297dd2015-01-07 21:02:18 +0000685 ProcessMachO(Filename, MachOOF);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +0000686 } else
687 errs() << "llvm-objdump: '" << Filename << "': "
688 << "Object is not a Mach-O file type.\n";
689 } else
690 errs() << "llvm-objdump: '" << Filename << "': "
691 << "Unrecognized file type.\n";
Rafael Espindola9b709252013-04-13 01:45:40 +0000692}
693
Kevin Enderbybf246f52014-09-24 23:08:22 +0000694typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000695typedef std::pair<uint64_t, const char *> BindInfoEntry;
696typedef std::vector<BindInfoEntry> BindTable;
697typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000698
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000699// The block of info used by the Symbolizer call backs.
700struct DisassembleInfo {
701 bool verbose;
702 MachOObjectFile *O;
703 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000704 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000705 std::vector<SectionRef> *Sections;
706 const char *class_name;
707 const char *selector_name;
708 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +0000709 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000710 uint64_t adrp_addr;
711 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +0000712 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000713};
714
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000715// GuessSymbolName is passed the address of what might be a symbol and a
716// pointer to the DisassembleInfo struct. It returns the name of a symbol
717// with that address or nullptr if no symbol is found with that address.
718static const char *GuessSymbolName(uint64_t value,
719 struct DisassembleInfo *info) {
720 const char *SymbolName = nullptr;
721 // A DenseMap can't lookup up some values.
722 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
723 StringRef name = info->AddrMap->lookup(value);
724 if (!name.empty())
725 SymbolName = name.data();
726 }
727 return SymbolName;
728}
729
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000730// SymbolizerGetOpInfo() is the operand information call back function.
731// This is called to get the symbolic information for operand(s) of an
732// instruction when it is being done. This routine does this from
733// the relocation information, symbol table, etc. That block of information
734// is a pointer to the struct DisassembleInfo that was passed when the
735// disassembler context was created and passed to back to here when
736// called back by the disassembler for instruction operands that could have
737// relocation information. The address of the instruction containing operand is
738// at the Pc parameter. The immediate value the operand has is passed in
739// op_info->Value and is at Offset past the start of the instruction and has a
740// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
741// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
742// names and addends of the symbolic expression to add for the operand. The
743// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
744// information is returned then this function returns 1 else it returns 0.
745int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
746 uint64_t Size, int TagType, void *TagBuf) {
747 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
748 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000749 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000750
751 // Make sure all fields returned are zero if we don't set them.
752 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
753 op_info->Value = value;
754
755 // If the TagType is not the value 1 which it code knows about or if no
756 // verbose symbolic information is wanted then just return 0, indicating no
757 // information is being returned.
758 if (TagType != 1 || info->verbose == false)
759 return 0;
760
761 unsigned int Arch = info->O->getArch();
762 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000763 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
764 return 0;
765 // First search the section's relocation entries (if any) for an entry
766 // for this section offset.
767 uint32_t sect_addr = info->S.getAddress();
768 uint32_t sect_offset = (Pc + Offset) - sect_addr;
769 bool reloc_found = false;
770 DataRefImpl Rel;
771 MachO::any_relocation_info RE;
772 bool isExtern = false;
773 SymbolRef Symbol;
774 bool r_scattered = false;
775 uint32_t r_value, pair_r_value, r_type;
776 for (const RelocationRef &Reloc : info->S.relocations()) {
777 uint64_t RelocOffset;
778 Reloc.getOffset(RelocOffset);
779 if (RelocOffset == sect_offset) {
780 Rel = Reloc.getRawDataRefImpl();
781 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +0000782 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000783 r_scattered = info->O->isRelocationScattered(RE);
784 if (r_scattered) {
785 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000786 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
787 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
788 DataRefImpl RelNext = Rel;
789 info->O->moveRelocationNext(RelNext);
790 MachO::any_relocation_info RENext;
791 RENext = info->O->getRelocation(RelNext);
792 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +0000793 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000794 else
795 return 0;
796 }
797 } else {
798 isExtern = info->O->getPlainRelocationExternal(RE);
799 if (isExtern) {
800 symbol_iterator RelocSym = Reloc.getSymbol();
801 Symbol = *RelocSym;
802 }
803 }
804 reloc_found = true;
805 break;
806 }
807 }
808 if (reloc_found && isExtern) {
809 StringRef SymName;
810 Symbol.getName(SymName);
811 const char *name = SymName.data();
812 op_info->AddSymbol.Present = 1;
813 op_info->AddSymbol.Name = name;
814 // For i386 extern relocation entries the value in the instruction is
815 // the offset from the symbol, and value is already set in op_info->Value.
816 return 1;
817 }
818 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
819 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
820 const char *add = GuessSymbolName(r_value, info);
821 const char *sub = GuessSymbolName(pair_r_value, info);
822 uint32_t offset = value - (r_value - pair_r_value);
823 op_info->AddSymbol.Present = 1;
824 if (add != nullptr)
825 op_info->AddSymbol.Name = add;
826 else
827 op_info->AddSymbol.Value = r_value;
828 op_info->SubtractSymbol.Present = 1;
829 if (sub != nullptr)
830 op_info->SubtractSymbol.Name = sub;
831 else
832 op_info->SubtractSymbol.Value = pair_r_value;
833 op_info->Value = offset;
834 return 1;
835 }
836 // TODO:
837 // Second search the external relocation entries of a fully linked image
838 // (if any) for an entry that matches this segment offset.
839 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000840 return 0;
841 } else if (Arch == Triple::x86_64) {
842 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
843 return 0;
844 // First search the section's relocation entries (if any) for an entry
845 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +0000846 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000847 uint64_t sect_offset = (Pc + Offset) - sect_addr;
848 bool reloc_found = false;
849 DataRefImpl Rel;
850 MachO::any_relocation_info RE;
851 bool isExtern = false;
852 SymbolRef Symbol;
853 for (const RelocationRef &Reloc : info->S.relocations()) {
854 uint64_t RelocOffset;
855 Reloc.getOffset(RelocOffset);
856 if (RelocOffset == sect_offset) {
857 Rel = Reloc.getRawDataRefImpl();
858 RE = info->O->getRelocation(Rel);
859 // NOTE: Scattered relocations don't exist on x86_64.
860 isExtern = info->O->getPlainRelocationExternal(RE);
861 if (isExtern) {
862 symbol_iterator RelocSym = Reloc.getSymbol();
863 Symbol = *RelocSym;
864 }
865 reloc_found = true;
866 break;
867 }
868 }
869 if (reloc_found && isExtern) {
870 // The Value passed in will be adjusted by the Pc if the instruction
871 // adds the Pc. But for x86_64 external relocation entries the Value
872 // is the offset from the external symbol.
873 if (info->O->getAnyRelocationPCRel(RE))
874 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000875 StringRef SymName;
876 Symbol.getName(SymName);
877 const char *name = SymName.data();
878 unsigned Type = info->O->getAnyRelocationType(RE);
879 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
880 DataRefImpl RelNext = Rel;
881 info->O->moveRelocationNext(RelNext);
882 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
883 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
884 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
885 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
886 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
887 op_info->SubtractSymbol.Present = 1;
888 op_info->SubtractSymbol.Name = name;
889 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
890 Symbol = *RelocSymNext;
891 StringRef SymNameNext;
892 Symbol.getName(SymNameNext);
893 name = SymNameNext.data();
894 }
895 }
896 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
897 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
898 op_info->AddSymbol.Present = 1;
899 op_info->AddSymbol.Name = name;
900 return 1;
901 }
902 // TODO:
903 // Second search the external relocation entries of a fully linked image
904 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000905 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000906 return 0;
907 } else if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000908 if (Offset != 0 || (Size != 4 && Size != 2))
909 return 0;
910 // First search the section's relocation entries (if any) for an entry
911 // for this section offset.
912 uint32_t sect_addr = info->S.getAddress();
913 uint32_t sect_offset = (Pc + Offset) - sect_addr;
914 bool reloc_found = false;
915 DataRefImpl Rel;
916 MachO::any_relocation_info RE;
917 bool isExtern = false;
918 SymbolRef Symbol;
919 bool r_scattered = false;
920 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
921 for (const RelocationRef &Reloc : info->S.relocations()) {
922 uint64_t RelocOffset;
923 Reloc.getOffset(RelocOffset);
924 if (RelocOffset == sect_offset) {
925 Rel = Reloc.getRawDataRefImpl();
926 RE = info->O->getRelocation(Rel);
927 r_length = info->O->getAnyRelocationLength(RE);
928 r_scattered = info->O->isRelocationScattered(RE);
929 if (r_scattered) {
930 r_value = info->O->getScatteredRelocationValue(RE);
931 r_type = info->O->getScatteredRelocationType(RE);
932 } else {
933 r_type = info->O->getAnyRelocationType(RE);
934 isExtern = info->O->getPlainRelocationExternal(RE);
935 if (isExtern) {
936 symbol_iterator RelocSym = Reloc.getSymbol();
937 Symbol = *RelocSym;
938 }
939 }
940 if (r_type == MachO::ARM_RELOC_HALF ||
941 r_type == MachO::ARM_RELOC_SECTDIFF ||
942 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
943 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
944 DataRefImpl RelNext = Rel;
945 info->O->moveRelocationNext(RelNext);
946 MachO::any_relocation_info RENext;
947 RENext = info->O->getRelocation(RelNext);
948 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
949 if (info->O->isRelocationScattered(RENext))
950 pair_r_value = info->O->getScatteredRelocationValue(RENext);
951 }
952 reloc_found = true;
953 break;
954 }
955 }
956 if (reloc_found && isExtern) {
957 StringRef SymName;
958 Symbol.getName(SymName);
959 const char *name = SymName.data();
960 op_info->AddSymbol.Present = 1;
961 op_info->AddSymbol.Name = name;
962 if (value != 0) {
963 switch (r_type) {
964 case MachO::ARM_RELOC_HALF:
965 if ((r_length & 0x1) == 1) {
966 op_info->Value = value << 16 | other_half;
967 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
968 } else {
969 op_info->Value = other_half << 16 | value;
970 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
971 }
972 break;
973 default:
974 break;
975 }
976 } else {
977 switch (r_type) {
978 case MachO::ARM_RELOC_HALF:
979 if ((r_length & 0x1) == 1) {
980 op_info->Value = value << 16 | other_half;
981 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
982 } else {
983 op_info->Value = other_half << 16 | value;
984 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
985 }
986 break;
987 default:
988 break;
989 }
990 }
991 return 1;
992 }
993 // If we have a branch that is not an external relocation entry then
994 // return 0 so the code in tryAddingSymbolicOperand() can use the
995 // SymbolLookUp call back with the branch target address to look up the
996 // symbol and possiblity add an annotation for a symbol stub.
997 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
998 r_type == MachO::ARM_THUMB_RELOC_BR22))
999 return 0;
1000
1001 uint32_t offset = 0;
1002 if (reloc_found) {
1003 if (r_type == MachO::ARM_RELOC_HALF ||
1004 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1005 if ((r_length & 0x1) == 1)
1006 value = value << 16 | other_half;
1007 else
1008 value = other_half << 16 | value;
1009 }
1010 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
1011 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
1012 offset = value - r_value;
1013 value = r_value;
1014 }
1015 }
1016
1017 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
1018 if ((r_length & 0x1) == 1)
1019 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1020 else
1021 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1022 const char *add = GuessSymbolName(r_value, info);
1023 const char *sub = GuessSymbolName(pair_r_value, info);
1024 int32_t offset = value - (r_value - pair_r_value);
1025 op_info->AddSymbol.Present = 1;
1026 if (add != nullptr)
1027 op_info->AddSymbol.Name = add;
1028 else
1029 op_info->AddSymbol.Value = r_value;
1030 op_info->SubtractSymbol.Present = 1;
1031 if (sub != nullptr)
1032 op_info->SubtractSymbol.Name = sub;
1033 else
1034 op_info->SubtractSymbol.Value = pair_r_value;
1035 op_info->Value = offset;
1036 return 1;
1037 }
1038
1039 if (reloc_found == false)
1040 return 0;
1041
1042 op_info->AddSymbol.Present = 1;
1043 op_info->Value = offset;
1044 if (reloc_found) {
1045 if (r_type == MachO::ARM_RELOC_HALF) {
1046 if ((r_length & 0x1) == 1)
1047 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
1048 else
1049 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
1050 }
1051 }
1052 const char *add = GuessSymbolName(value, info);
1053 if (add != nullptr) {
1054 op_info->AddSymbol.Name = add;
1055 return 1;
1056 }
1057 op_info->AddSymbol.Value = value;
1058 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001059 } else if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001060 if (Offset != 0 || Size != 4)
1061 return 0;
1062 // First search the section's relocation entries (if any) for an entry
1063 // for this section offset.
1064 uint64_t sect_addr = info->S.getAddress();
1065 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1066 bool reloc_found = false;
1067 DataRefImpl Rel;
1068 MachO::any_relocation_info RE;
1069 bool isExtern = false;
1070 SymbolRef Symbol;
1071 uint32_t r_type = 0;
1072 for (const RelocationRef &Reloc : info->S.relocations()) {
1073 uint64_t RelocOffset;
1074 Reloc.getOffset(RelocOffset);
1075 if (RelocOffset == sect_offset) {
1076 Rel = Reloc.getRawDataRefImpl();
1077 RE = info->O->getRelocation(Rel);
1078 r_type = info->O->getAnyRelocationType(RE);
1079 if (r_type == MachO::ARM64_RELOC_ADDEND) {
1080 DataRefImpl RelNext = Rel;
1081 info->O->moveRelocationNext(RelNext);
1082 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1083 if (value == 0) {
1084 value = info->O->getPlainRelocationSymbolNum(RENext);
1085 op_info->Value = value;
1086 }
1087 }
1088 // NOTE: Scattered relocations don't exist on arm64.
1089 isExtern = info->O->getPlainRelocationExternal(RE);
1090 if (isExtern) {
1091 symbol_iterator RelocSym = Reloc.getSymbol();
1092 Symbol = *RelocSym;
1093 }
1094 reloc_found = true;
1095 break;
1096 }
1097 }
1098 if (reloc_found && isExtern) {
1099 StringRef SymName;
1100 Symbol.getName(SymName);
1101 const char *name = SymName.data();
1102 op_info->AddSymbol.Present = 1;
1103 op_info->AddSymbol.Name = name;
1104
1105 switch (r_type) {
1106 case MachO::ARM64_RELOC_PAGE21:
1107 /* @page */
1108 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
1109 break;
1110 case MachO::ARM64_RELOC_PAGEOFF12:
1111 /* @pageoff */
1112 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
1113 break;
1114 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
1115 /* @gotpage */
1116 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
1117 break;
1118 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
1119 /* @gotpageoff */
1120 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
1121 break;
1122 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
1123 /* @tvlppage is not implemented in llvm-mc */
1124 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
1125 break;
1126 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
1127 /* @tvlppageoff is not implemented in llvm-mc */
1128 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
1129 break;
1130 default:
1131 case MachO::ARM64_RELOC_BRANCH26:
1132 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
1133 break;
1134 }
1135 return 1;
1136 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001137 return 0;
1138 } else {
1139 return 0;
1140 }
1141}
1142
Kevin Enderbybf246f52014-09-24 23:08:22 +00001143// GuessCstringPointer is passed the address of what might be a pointer to a
1144// literal string in a cstring section. If that address is in a cstring section
1145// it returns a pointer to that string. Else it returns nullptr.
1146const char *GuessCstringPointer(uint64_t ReferenceValue,
1147 struct DisassembleInfo *info) {
1148 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1149 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1150 for (unsigned I = 0;; ++I) {
1151 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1152 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1153 for (unsigned J = 0; J < Seg.nsects; ++J) {
1154 MachO::section_64 Sec = info->O->getSection64(Load, J);
1155 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1156 if (section_type == MachO::S_CSTRING_LITERALS &&
1157 ReferenceValue >= Sec.addr &&
1158 ReferenceValue < Sec.addr + Sec.size) {
1159 uint64_t sect_offset = ReferenceValue - Sec.addr;
1160 uint64_t object_offset = Sec.offset + sect_offset;
1161 StringRef MachOContents = info->O->getData();
1162 uint64_t object_size = MachOContents.size();
1163 const char *object_addr = (const char *)MachOContents.data();
1164 if (object_offset < object_size) {
1165 const char *name = object_addr + object_offset;
1166 return name;
1167 } else {
1168 return nullptr;
1169 }
1170 }
1171 }
1172 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1173 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1174 for (unsigned J = 0; J < Seg.nsects; ++J) {
1175 MachO::section Sec = info->O->getSection(Load, J);
1176 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1177 if (section_type == MachO::S_CSTRING_LITERALS &&
1178 ReferenceValue >= Sec.addr &&
1179 ReferenceValue < Sec.addr + Sec.size) {
1180 uint64_t sect_offset = ReferenceValue - Sec.addr;
1181 uint64_t object_offset = Sec.offset + sect_offset;
1182 StringRef MachOContents = info->O->getData();
1183 uint64_t object_size = MachOContents.size();
1184 const char *object_addr = (const char *)MachOContents.data();
1185 if (object_offset < object_size) {
1186 const char *name = object_addr + object_offset;
1187 return name;
1188 } else {
1189 return nullptr;
1190 }
1191 }
1192 }
1193 }
1194 if (I == LoadCommandCount - 1)
1195 break;
1196 else
1197 Load = info->O->getNextLoadCommandInfo(Load);
1198 }
1199 return nullptr;
1200}
1201
Kevin Enderby85974882014-09-26 22:20:44 +00001202// GuessIndirectSymbol returns the name of the indirect symbol for the
1203// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
1204// an address of a symbol stub or a lazy or non-lazy pointer to associate the
1205// symbol name being referenced by the stub or pointer.
1206static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
1207 struct DisassembleInfo *info) {
1208 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1209 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1210 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
1211 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
1212 for (unsigned I = 0;; ++I) {
1213 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1214 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1215 for (unsigned J = 0; J < Seg.nsects; ++J) {
1216 MachO::section_64 Sec = info->O->getSection64(Load, J);
1217 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1218 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1219 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1220 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1221 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1222 section_type == MachO::S_SYMBOL_STUBS) &&
1223 ReferenceValue >= Sec.addr &&
1224 ReferenceValue < Sec.addr + Sec.size) {
1225 uint32_t stride;
1226 if (section_type == MachO::S_SYMBOL_STUBS)
1227 stride = Sec.reserved2;
1228 else
1229 stride = 8;
1230 if (stride == 0)
1231 return nullptr;
1232 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1233 if (index < Dysymtab.nindirectsyms) {
1234 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001235 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00001236 if (indirect_symbol < Symtab.nsyms) {
1237 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1238 SymbolRef Symbol = *Sym;
1239 StringRef SymName;
1240 Symbol.getName(SymName);
1241 const char *name = SymName.data();
1242 return name;
1243 }
1244 }
1245 }
1246 }
1247 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1248 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
1249 for (unsigned J = 0; J < Seg.nsects; ++J) {
1250 MachO::section Sec = info->O->getSection(Load, J);
1251 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
1252 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
1253 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
1254 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
1255 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
1256 section_type == MachO::S_SYMBOL_STUBS) &&
1257 ReferenceValue >= Sec.addr &&
1258 ReferenceValue < Sec.addr + Sec.size) {
1259 uint32_t stride;
1260 if (section_type == MachO::S_SYMBOL_STUBS)
1261 stride = Sec.reserved2;
1262 else
1263 stride = 4;
1264 if (stride == 0)
1265 return nullptr;
1266 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
1267 if (index < Dysymtab.nindirectsyms) {
1268 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001269 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +00001270 if (indirect_symbol < Symtab.nsyms) {
1271 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
1272 SymbolRef Symbol = *Sym;
1273 StringRef SymName;
1274 Symbol.getName(SymName);
1275 const char *name = SymName.data();
1276 return name;
1277 }
1278 }
1279 }
1280 }
1281 }
1282 if (I == LoadCommandCount - 1)
1283 break;
1284 else
1285 Load = info->O->getNextLoadCommandInfo(Load);
1286 }
1287 return nullptr;
1288}
1289
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001290// method_reference() is called passing it the ReferenceName that might be
1291// a reference it to an Objective-C method call. If so then it allocates and
1292// assembles a method call string with the values last seen and saved in
1293// the DisassembleInfo's class_name and selector_name fields. This is saved
1294// into the method field of the info and any previous string is free'ed.
1295// Then the class_name field in the info is set to nullptr. The method call
1296// string is set into ReferenceName and ReferenceType is set to
1297// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
1298// then both ReferenceType and ReferenceName are left unchanged.
1299static void method_reference(struct DisassembleInfo *info,
1300 uint64_t *ReferenceType,
1301 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001302 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001303 if (*ReferenceName != nullptr) {
1304 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001305 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001306 if (info->method != nullptr)
1307 free(info->method);
1308 if (info->class_name != nullptr) {
1309 info->method = (char *)malloc(5 + strlen(info->class_name) +
1310 strlen(info->selector_name));
1311 if (info->method != nullptr) {
1312 strcpy(info->method, "+[");
1313 strcat(info->method, info->class_name);
1314 strcat(info->method, " ");
1315 strcat(info->method, info->selector_name);
1316 strcat(info->method, "]");
1317 *ReferenceName = info->method;
1318 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1319 }
1320 } else {
1321 info->method = (char *)malloc(9 + strlen(info->selector_name));
1322 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001323 if (Arch == Triple::x86_64)
1324 strcpy(info->method, "-[%rdi ");
1325 else if (Arch == Triple::aarch64)
1326 strcpy(info->method, "-[x0 ");
1327 else
1328 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001329 strcat(info->method, info->selector_name);
1330 strcat(info->method, "]");
1331 *ReferenceName = info->method;
1332 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1333 }
1334 }
1335 info->class_name = nullptr;
1336 }
1337 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001338 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001339 if (info->method != nullptr)
1340 free(info->method);
1341 info->method = (char *)malloc(17 + strlen(info->selector_name));
1342 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001343 if (Arch == Triple::x86_64)
1344 strcpy(info->method, "-[[%rdi super] ");
1345 else if (Arch == Triple::aarch64)
1346 strcpy(info->method, "-[[x0 super] ");
1347 else
1348 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001349 strcat(info->method, info->selector_name);
1350 strcat(info->method, "]");
1351 *ReferenceName = info->method;
1352 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
1353 }
1354 info->class_name = nullptr;
1355 }
1356 }
1357 }
1358}
1359
1360// GuessPointerPointer() is passed the address of what might be a pointer to
1361// a reference to an Objective-C class, selector, message ref or cfstring.
1362// If so the value of the pointer is returned and one of the booleans are set
1363// to true. If not zero is returned and all the booleans are set to false.
1364static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
1365 struct DisassembleInfo *info,
1366 bool &classref, bool &selref, bool &msgref,
1367 bool &cfstring) {
1368 classref = false;
1369 selref = false;
1370 msgref = false;
1371 cfstring = false;
1372 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
1373 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
1374 for (unsigned I = 0;; ++I) {
1375 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1376 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
1377 for (unsigned J = 0; J < Seg.nsects; ++J) {
1378 MachO::section_64 Sec = info->O->getSection64(Load, J);
1379 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
1380 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1381 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
1382 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
1383 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
1384 ReferenceValue >= Sec.addr &&
1385 ReferenceValue < Sec.addr + Sec.size) {
1386 uint64_t sect_offset = ReferenceValue - Sec.addr;
1387 uint64_t object_offset = Sec.offset + sect_offset;
1388 StringRef MachOContents = info->O->getData();
1389 uint64_t object_size = MachOContents.size();
1390 const char *object_addr = (const char *)MachOContents.data();
1391 if (object_offset < object_size) {
1392 uint64_t pointer_value;
1393 memcpy(&pointer_value, object_addr + object_offset,
1394 sizeof(uint64_t));
1395 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1396 sys::swapByteOrder(pointer_value);
1397 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
1398 selref = true;
1399 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
1400 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
1401 classref = true;
1402 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
1403 ReferenceValue + 8 < Sec.addr + Sec.size) {
1404 msgref = true;
1405 memcpy(&pointer_value, object_addr + object_offset + 8,
1406 sizeof(uint64_t));
1407 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1408 sys::swapByteOrder(pointer_value);
1409 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
1410 cfstring = true;
1411 return pointer_value;
1412 } else {
1413 return 0;
1414 }
1415 }
1416 }
1417 }
1418 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
1419 if (I == LoadCommandCount - 1)
1420 break;
1421 else
1422 Load = info->O->getNextLoadCommandInfo(Load);
1423 }
1424 return 0;
1425}
1426
1427// get_pointer_64 returns a pointer to the bytes in the object file at the
1428// Address from a section in the Mach-O file. And indirectly returns the
1429// offset into the section, number of bytes left in the section past the offset
1430// and which section is was being referenced. If the Address is not in a
1431// section nullptr is returned.
1432const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1433 SectionRef &S, DisassembleInfo *info) {
1434 offset = 0;
1435 left = 0;
1436 S = SectionRef();
1437 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1438 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1439 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1440 if (Address >= SectAddress && Address < SectAddress + SectSize) {
1441 S = (*(info->Sections))[SectIdx];
1442 offset = Address - SectAddress;
1443 left = SectSize - offset;
1444 StringRef SectContents;
1445 ((*(info->Sections))[SectIdx]).getContents(SectContents);
1446 return SectContents.data() + offset;
1447 }
1448 }
1449 return nullptr;
1450}
1451
1452// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1453// the symbol indirectly through n_value. Based on the relocation information
1454// for the specified section offset in the specified section reference.
1455const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1456 DisassembleInfo *info, uint64_t &n_value) {
1457 n_value = 0;
1458 if (info->verbose == false)
1459 return nullptr;
1460
1461 // See if there is an external relocation entry at the sect_offset.
1462 bool reloc_found = false;
1463 DataRefImpl Rel;
1464 MachO::any_relocation_info RE;
1465 bool isExtern = false;
1466 SymbolRef Symbol;
1467 for (const RelocationRef &Reloc : S.relocations()) {
1468 uint64_t RelocOffset;
1469 Reloc.getOffset(RelocOffset);
1470 if (RelocOffset == sect_offset) {
1471 Rel = Reloc.getRawDataRefImpl();
1472 RE = info->O->getRelocation(Rel);
1473 if (info->O->isRelocationScattered(RE))
1474 continue;
1475 isExtern = info->O->getPlainRelocationExternal(RE);
1476 if (isExtern) {
1477 symbol_iterator RelocSym = Reloc.getSymbol();
1478 Symbol = *RelocSym;
1479 }
1480 reloc_found = true;
1481 break;
1482 }
1483 }
1484 // If there is an external relocation entry for a symbol in this section
1485 // at this section_offset then use that symbol's value for the n_value
1486 // and return its name.
1487 const char *SymbolName = nullptr;
1488 if (reloc_found && isExtern) {
1489 Symbol.getAddress(n_value);
1490 StringRef name;
1491 Symbol.getName(name);
1492 if (!name.empty()) {
1493 SymbolName = name.data();
1494 return SymbolName;
1495 }
1496 }
1497
1498 // TODO: For fully linked images, look through the external relocation
1499 // entries off the dynamic symtab command. For these the r_offset is from the
1500 // start of the first writeable segment in the Mach-O file. So the offset
1501 // to this section from that segment is passed to this routine by the caller,
1502 // as the database_offset. Which is the difference of the section's starting
1503 // address and the first writable segment.
1504 //
1505 // NOTE: need add passing the database_offset to this routine.
1506
1507 // TODO: We did not find an external relocation entry so look up the
1508 // ReferenceValue as an address of a symbol and if found return that symbol's
1509 // name.
1510 //
1511 // NOTE: need add passing the ReferenceValue to this routine. Then that code
1512 // would simply be this:
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001513 // SymbolName = GuessSymbolName(ReferenceValue, info);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001514
1515 return SymbolName;
1516}
1517
1518// These are structs in the Objective-C meta data and read to produce the
1519// comments for disassembly. While these are part of the ABI they are no
1520// public defintions. So the are here not in include/llvm/Support/MachO.h .
1521
1522// The cfstring object in a 64-bit Mach-O file.
1523struct cfstring64_t {
1524 uint64_t isa; // class64_t * (64-bit pointer)
1525 uint64_t flags; // flag bits
1526 uint64_t characters; // char * (64-bit pointer)
1527 uint64_t length; // number of non-NULL characters in above
1528};
1529
1530// The class object in a 64-bit Mach-O file.
1531struct class64_t {
1532 uint64_t isa; // class64_t * (64-bit pointer)
1533 uint64_t superclass; // class64_t * (64-bit pointer)
1534 uint64_t cache; // Cache (64-bit pointer)
1535 uint64_t vtable; // IMP * (64-bit pointer)
1536 uint64_t data; // class_ro64_t * (64-bit pointer)
1537};
1538
1539struct class_ro64_t {
1540 uint32_t flags;
1541 uint32_t instanceStart;
1542 uint32_t instanceSize;
1543 uint32_t reserved;
1544 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
1545 uint64_t name; // const char * (64-bit pointer)
1546 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
1547 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
1548 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
1549 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1550 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1551};
1552
1553inline void swapStruct(struct cfstring64_t &cfs) {
1554 sys::swapByteOrder(cfs.isa);
1555 sys::swapByteOrder(cfs.flags);
1556 sys::swapByteOrder(cfs.characters);
1557 sys::swapByteOrder(cfs.length);
1558}
1559
1560inline void swapStruct(struct class64_t &c) {
1561 sys::swapByteOrder(c.isa);
1562 sys::swapByteOrder(c.superclass);
1563 sys::swapByteOrder(c.cache);
1564 sys::swapByteOrder(c.vtable);
1565 sys::swapByteOrder(c.data);
1566}
1567
1568inline void swapStruct(struct class_ro64_t &cro) {
1569 sys::swapByteOrder(cro.flags);
1570 sys::swapByteOrder(cro.instanceStart);
1571 sys::swapByteOrder(cro.instanceSize);
1572 sys::swapByteOrder(cro.reserved);
1573 sys::swapByteOrder(cro.ivarLayout);
1574 sys::swapByteOrder(cro.name);
1575 sys::swapByteOrder(cro.baseMethods);
1576 sys::swapByteOrder(cro.baseProtocols);
1577 sys::swapByteOrder(cro.ivars);
1578 sys::swapByteOrder(cro.weakIvarLayout);
1579 sys::swapByteOrder(cro.baseProperties);
1580}
1581
1582static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1583 struct DisassembleInfo *info);
1584
1585// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1586// to an Objective-C class and returns the class name. It is also passed the
1587// address of the pointer, so when the pointer is zero as it can be in an .o
1588// file, that is used to look for an external relocation entry with a symbol
1589// name.
1590const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1591 uint64_t ReferenceValue,
1592 struct DisassembleInfo *info) {
1593 const char *r;
1594 uint32_t offset, left;
1595 SectionRef S;
1596
1597 // The pointer_value can be 0 in an object file and have a relocation
1598 // entry for the class symbol at the ReferenceValue (the address of the
1599 // pointer).
1600 if (pointer_value == 0) {
1601 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1602 if (r == nullptr || left < sizeof(uint64_t))
1603 return nullptr;
1604 uint64_t n_value;
1605 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1606 if (symbol_name == nullptr)
1607 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001608 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001609 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1610 return class_name + 2;
1611 else
1612 return nullptr;
1613 }
1614
1615 // The case were the pointer_value is non-zero and points to a class defined
1616 // in this Mach-O file.
1617 r = get_pointer_64(pointer_value, offset, left, S, info);
1618 if (r == nullptr || left < sizeof(struct class64_t))
1619 return nullptr;
1620 struct class64_t c;
1621 memcpy(&c, r, sizeof(struct class64_t));
1622 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1623 swapStruct(c);
1624 if (c.data == 0)
1625 return nullptr;
1626 r = get_pointer_64(c.data, offset, left, S, info);
1627 if (r == nullptr || left < sizeof(struct class_ro64_t))
1628 return nullptr;
1629 struct class_ro64_t cro;
1630 memcpy(&cro, r, sizeof(struct class_ro64_t));
1631 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1632 swapStruct(cro);
1633 if (cro.name == 0)
1634 return nullptr;
1635 const char *name = get_pointer_64(cro.name, offset, left, S, info);
1636 return name;
1637}
1638
1639// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1640// pointer to a cfstring and returns its name or nullptr.
1641const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1642 struct DisassembleInfo *info) {
1643 const char *r, *name;
1644 uint32_t offset, left;
1645 SectionRef S;
1646 struct cfstring64_t cfs;
1647 uint64_t cfs_characters;
1648
1649 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1650 if (r == nullptr || left < sizeof(struct cfstring64_t))
1651 return nullptr;
1652 memcpy(&cfs, r, sizeof(struct cfstring64_t));
1653 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1654 swapStruct(cfs);
1655 if (cfs.characters == 0) {
1656 uint64_t n_value;
1657 const char *symbol_name = get_symbol_64(
1658 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1659 if (symbol_name == nullptr)
1660 return nullptr;
1661 cfs_characters = n_value;
1662 } else
1663 cfs_characters = cfs.characters;
1664 name = get_pointer_64(cfs_characters, offset, left, S, info);
1665
1666 return name;
1667}
1668
1669// get_objc2_64bit_selref() is used for disassembly and is passed a the address
1670// of a pointer to an Objective-C selector reference when the pointer value is
1671// zero as in a .o file and is likely to have a external relocation entry with
1672// who's symbol's n_value is the real pointer to the selector name. If that is
1673// the case the real pointer to the selector name is returned else 0 is
1674// returned
1675uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1676 struct DisassembleInfo *info) {
1677 uint32_t offset, left;
1678 SectionRef S;
1679
1680 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1681 if (r == nullptr || left < sizeof(uint64_t))
1682 return 0;
1683 uint64_t n_value;
1684 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1685 if (symbol_name == nullptr)
1686 return 0;
1687 return n_value;
1688}
1689
Kevin Enderbybf246f52014-09-24 23:08:22 +00001690// GuessLiteralPointer returns a string which for the item in the Mach-O file
1691// for the address passed in as ReferenceValue for printing as a comment with
1692// the instruction and also returns the corresponding type of that item
1693// indirectly through ReferenceType.
1694//
1695// If ReferenceValue is an address of literal cstring then a pointer to the
1696// cstring is returned and ReferenceType is set to
1697// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1698//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001699// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1700// Class ref that name is returned and the ReferenceType is set accordingly.
1701//
1702// Lastly, literals which are Symbol address in a literal pool are looked for
1703// and if found the symbol name is returned and ReferenceType is set to
1704// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1705//
1706// If there is no item in the Mach-O file for the address passed in as
1707// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Kevin Enderbybf246f52014-09-24 23:08:22 +00001708const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1709 uint64_t *ReferenceType,
1710 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001711 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00001712 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00001713 uint64_t sect_offset = ReferencePC - sect_addr;
1714 bool reloc_found = false;
1715 DataRefImpl Rel;
1716 MachO::any_relocation_info RE;
1717 bool isExtern = false;
1718 SymbolRef Symbol;
1719 for (const RelocationRef &Reloc : info->S.relocations()) {
1720 uint64_t RelocOffset;
1721 Reloc.getOffset(RelocOffset);
1722 if (RelocOffset == sect_offset) {
1723 Rel = Reloc.getRawDataRefImpl();
1724 RE = info->O->getRelocation(Rel);
1725 if (info->O->isRelocationScattered(RE))
1726 continue;
1727 isExtern = info->O->getPlainRelocationExternal(RE);
1728 if (isExtern) {
1729 symbol_iterator RelocSym = Reloc.getSymbol();
1730 Symbol = *RelocSym;
1731 }
1732 reloc_found = true;
1733 break;
1734 }
1735 }
1736 // If there is an external relocation entry for a symbol in a section
1737 // then used that symbol's value for the value of the reference.
1738 if (reloc_found && isExtern) {
1739 if (info->O->getAnyRelocationPCRel(RE)) {
1740 unsigned Type = info->O->getAnyRelocationType(RE);
1741 if (Type == MachO::X86_64_RELOC_SIGNED) {
1742 Symbol.getAddress(ReferenceValue);
1743 }
1744 }
1745 }
1746
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001747 // Look for literals such as Objective-C CFStrings refs, Selector refs,
1748 // Message refs and Class refs.
1749 bool classref, selref, msgref, cfstring;
1750 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1751 selref, msgref, cfstring);
1752 if (classref == true && pointer_value == 0) {
1753 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1754 // And the pointer_value in that section is typically zero as it will be
1755 // set by dyld as part of the "bind information".
1756 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1757 if (name != nullptr) {
1758 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001759 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001760 if (class_name != nullptr && class_name[1] == '_' &&
1761 class_name[2] != '\0') {
1762 info->class_name = class_name + 2;
1763 return name;
1764 }
1765 }
1766 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001767
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001768 if (classref == true) {
1769 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1770 const char *name =
1771 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1772 if (name != nullptr)
1773 info->class_name = name;
1774 else
1775 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00001776 return name;
1777 }
1778
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001779 if (cfstring == true) {
1780 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1781 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1782 return name;
1783 }
1784
1785 if (selref == true && pointer_value == 0)
1786 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1787
1788 if (pointer_value != 0)
1789 ReferenceValue = pointer_value;
1790
1791 const char *name = GuessCstringPointer(ReferenceValue, info);
1792 if (name) {
1793 if (pointer_value != 0 && selref == true) {
1794 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1795 info->selector_name = name;
1796 } else if (pointer_value != 0 && msgref == true) {
1797 info->class_name = nullptr;
1798 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1799 info->selector_name = name;
1800 } else
1801 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1802 return name;
1803 }
1804
1805 // Lastly look for an indirect symbol with this ReferenceValue which is in
1806 // a literal pool. If found return that symbol name.
1807 name = GuessIndirectSymbol(ReferenceValue, info);
1808 if (name) {
1809 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1810 return name;
1811 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001812
1813 return nullptr;
1814}
1815
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001816// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00001817// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001818// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1819// is created and returns the symbol name that matches the ReferenceValue or
1820// nullptr if none. The ReferenceType is passed in for the IN type of
1821// reference the instruction is making from the values in defined in the header
1822// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1823// Out type and the ReferenceName will also be set which is added as a comment
1824// to the disassembled instruction.
1825//
Kevin Enderby04bf6932014-10-28 23:39:46 +00001826#if HAVE_CXXABI_H
1827// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001828// returned through ReferenceName and ReferenceType is set to
1829// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00001830#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001831//
1832// When this is called to get a symbol name for a branch target then the
1833// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1834// SymbolValue will be looked for in the indirect symbol table to determine if
1835// it is an address for a symbol stub. If so then the symbol name for that
1836// stub is returned indirectly through ReferenceName and then ReferenceType is
1837// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1838//
Kevin Enderbybf246f52014-09-24 23:08:22 +00001839// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001840// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1841// SymbolValue is checked to be an address of literal pointer, symbol pointer,
1842// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001843// set to correspond to that as well as setting the ReferenceName.
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001844const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1845 uint64_t *ReferenceType,
1846 uint64_t ReferencePC,
1847 const char **ReferenceName) {
1848 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001849 // If no verbose symbolic information is wanted then just return nullptr.
1850 if (info->verbose == false) {
1851 *ReferenceName = nullptr;
1852 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001853 return nullptr;
1854 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001855
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001856 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
Kevin Enderbybf246f52014-09-24 23:08:22 +00001857
Kevin Enderby85974882014-09-26 22:20:44 +00001858 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1859 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001860 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001861 method_reference(info, ReferenceType, ReferenceName);
1862 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1863 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1864 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00001865#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001866 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00001867 if (info->demangled_name != nullptr)
1868 free(info->demangled_name);
1869 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001870 info->demangled_name =
1871 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001872 if (info->demangled_name != nullptr) {
1873 *ReferenceName = info->demangled_name;
1874 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1875 } else
1876 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1877 } else
1878#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001879 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1880 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1881 *ReferenceName =
1882 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00001883 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001884 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00001885 else
1886 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001887 // If this is arm64 and the reference is an adrp instruction save the
1888 // instruction, passed in ReferenceValue and the address of the instruction
1889 // for use later if we see and add immediate instruction.
1890 } else if (info->O->getArch() == Triple::aarch64 &&
1891 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
1892 info->adrp_inst = ReferenceValue;
1893 info->adrp_addr = ReferencePC;
1894 SymbolName = nullptr;
1895 *ReferenceName = nullptr;
1896 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1897 // If this is arm64 and reference is an add immediate instruction and we
1898 // have
1899 // seen an adrp instruction just before it and the adrp's Xd register
1900 // matches
1901 // this add's Xn register reconstruct the value being referenced and look to
1902 // see if it is a literal pointer. Note the add immediate instruction is
1903 // passed in ReferenceValue.
1904 } else if (info->O->getArch() == Triple::aarch64 &&
1905 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
1906 ReferencePC - 4 == info->adrp_addr &&
1907 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
1908 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
1909 uint32_t addxri_inst;
1910 uint64_t adrp_imm, addxri_imm;
1911
1912 adrp_imm =
1913 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
1914 if (info->adrp_inst & 0x0200000)
1915 adrp_imm |= 0xfffffffffc000000LL;
1916
1917 addxri_inst = ReferenceValue;
1918 addxri_imm = (addxri_inst >> 10) & 0xfff;
1919 if (((addxri_inst >> 22) & 0x3) == 1)
1920 addxri_imm <<= 12;
1921
1922 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
1923 (adrp_imm << 12) + addxri_imm;
1924
1925 *ReferenceName =
1926 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1927 if (*ReferenceName == nullptr)
1928 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1929 // If this is arm64 and the reference is a load register instruction and we
1930 // have seen an adrp instruction just before it and the adrp's Xd register
1931 // matches this add's Xn register reconstruct the value being referenced and
1932 // look to see if it is a literal pointer. Note the load register
1933 // instruction is passed in ReferenceValue.
1934 } else if (info->O->getArch() == Triple::aarch64 &&
1935 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
1936 ReferencePC - 4 == info->adrp_addr &&
1937 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
1938 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
1939 uint32_t ldrxui_inst;
1940 uint64_t adrp_imm, ldrxui_imm;
1941
1942 adrp_imm =
1943 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
1944 if (info->adrp_inst & 0x0200000)
1945 adrp_imm |= 0xfffffffffc000000LL;
1946
1947 ldrxui_inst = ReferenceValue;
1948 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
1949
1950 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
1951 (adrp_imm << 12) + (ldrxui_imm << 3);
1952
1953 *ReferenceName =
1954 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1955 if (*ReferenceName == nullptr)
1956 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1957 }
1958 // If this arm64 and is an load register (PC-relative) instruction the
1959 // ReferenceValue is the PC plus the immediate value.
1960 else if (info->O->getArch() == Triple::aarch64 &&
1961 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
1962 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
1963 *ReferenceName =
1964 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1965 if (*ReferenceName == nullptr)
1966 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00001967 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00001968#if HAVE_CXXABI_H
1969 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1970 if (info->demangled_name != nullptr)
1971 free(info->demangled_name);
1972 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001973 info->demangled_name =
1974 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001975 if (info->demangled_name != nullptr) {
1976 *ReferenceName = info->demangled_name;
1977 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1978 }
1979 }
1980#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001981 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001982 *ReferenceName = nullptr;
1983 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1984 }
1985
1986 return SymbolName;
1987}
1988
Kevin Enderbybf246f52014-09-24 23:08:22 +00001989/// \brief Emits the comments that are stored in the CommentStream.
1990/// Each comment in the CommentStream must end with a newline.
1991static void emitComments(raw_svector_ostream &CommentStream,
1992 SmallString<128> &CommentsToEmit,
1993 formatted_raw_ostream &FormattedOS,
1994 const MCAsmInfo &MAI) {
1995 // Flush the stream before taking its content.
1996 CommentStream.flush();
1997 StringRef Comments = CommentsToEmit.str();
1998 // Get the default information for printing a comment.
1999 const char *CommentBegin = MAI.getCommentString();
2000 unsigned CommentColumn = MAI.getCommentColumn();
2001 bool IsFirst = true;
2002 while (!Comments.empty()) {
2003 if (!IsFirst)
2004 FormattedOS << '\n';
2005 // Emit a line of comments.
2006 FormattedOS.PadToColumn(CommentColumn);
2007 size_t Position = Comments.find('\n');
2008 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
2009 // Move after the newline character.
2010 Comments = Comments.substr(Position + 1);
2011 IsFirst = false;
2012 }
2013 FormattedOS.flush();
2014
2015 // Tell the comment stream that the vector changed underneath it.
2016 CommentsToEmit.clear();
2017 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002018}
2019
Kevin Enderbye2297dd2015-01-07 21:02:18 +00002020static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002021 const char *McpuDefault = nullptr;
2022 const Target *ThumbTarget = nullptr;
2023 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002024 if (!TheTarget) {
2025 // GetTarget prints out stuff.
2026 return;
2027 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002028 if (MCPU.empty() && McpuDefault)
2029 MCPU = McpuDefault;
2030
Ahmed Charles56440fd2014-03-06 05:51:42 +00002031 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002032 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002033 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002034 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002035
Kevin Enderbyc9595622014-08-06 23:24:41 +00002036 // Package up features to be passed to target/subtarget
2037 std::string FeaturesStr;
2038 if (MAttrs.size()) {
2039 SubtargetFeatures Features;
2040 for (unsigned i = 0; i != MAttrs.size(); ++i)
2041 Features.AddFeature(MAttrs[i]);
2042 FeaturesStr = Features.getString();
2043 }
2044
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002045 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00002046 std::unique_ptr<const MCRegisterInfo> MRI(
2047 TheTarget->createMCRegInfo(TripleName));
2048 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00002049 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00002050 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00002051 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00002052 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002053 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002054 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002055 std::unique_ptr<MCSymbolizer> Symbolizer;
2056 struct DisassembleInfo SymbolizerInfo;
2057 std::unique_ptr<MCRelocationInfo> RelInfo(
2058 TheTarget->createMCRelocationInfo(TripleName, Ctx));
2059 if (RelInfo) {
2060 Symbolizer.reset(TheTarget->createMCSymbolizer(
2061 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2062 &SymbolizerInfo, &Ctx, RelInfo.release()));
2063 DisAsm->setSymbolizer(std::move(Symbolizer));
2064 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002065 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00002066 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
2067 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00002068 // Set the display preference for hex vs. decimal immediates.
2069 IP->setPrintImmHex(PrintImmHex);
2070 // Comment stream and backing vector.
2071 SmallString<128> CommentsToEmit;
2072 raw_svector_ostream CommentStream(CommentsToEmit);
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002073 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
2074 // if it is done then arm64 comments for string literals don't get printed
2075 // and some constant get printed instead and not setting it causes intel
2076 // (32-bit and 64-bit) comments printed with different spacing before the
2077 // comment causing different diffs with the 'C' disassembler library API.
2078 // IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002079
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002080 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00002081 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002082 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002083 return;
2084 }
2085
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002086 // Set up thumb disassembler.
2087 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
2088 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
2089 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002090 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002091 std::unique_ptr<MCInstPrinter> ThumbIP;
2092 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002093 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
2094 struct DisassembleInfo ThumbSymbolizerInfo;
2095 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002096 if (ThumbTarget) {
2097 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
2098 ThumbAsmInfo.reset(
2099 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
2100 ThumbSTI.reset(
2101 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
2102 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
2103 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00002104 MCContext *PtrThumbCtx = ThumbCtx.get();
2105 ThumbRelInfo.reset(
2106 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
2107 if (ThumbRelInfo) {
2108 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
2109 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
2110 &ThumbSymbolizerInfo, PtrThumbCtx, ThumbRelInfo.release()));
2111 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
2112 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002113 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
2114 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
2115 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
2116 *ThumbSTI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00002117 // Set the display preference for hex vs. decimal immediates.
2118 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002119 }
2120
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002121 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002122 errs() << "error: couldn't initialize disassembler for target "
2123 << ThumbTripleName << '\n';
2124 return;
2125 }
2126
Charles Davis8bdfafd2013-09-01 04:28:48 +00002127 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002128
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002129 // FIXME: Using the -cfg command line option, this code used to be able to
2130 // annotate relocations with the referenced symbol's name, and if this was
2131 // inside a __[cf]string section, the data it points to. This is now replaced
2132 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00002133 std::vector<SectionRef> Sections;
2134 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002135 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00002136 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002137
Kevin Enderby273ae012013-06-06 17:20:50 +00002138 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
2139 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002140
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002141 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00002142 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002143
Kevin Enderby273ae012013-06-06 17:20:50 +00002144 // Build a data in code table that is sorted on by the address of each entry.
2145 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00002146 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00002147 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00002148 else
2149 BaseAddress = BaseSegmentAddress;
2150 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00002151 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00002152 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00002153 uint32_t Offset;
2154 DI->getOffset(Offset);
2155 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
2156 }
2157 array_pod_sort(Dices.begin(), Dices.end());
2158
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002159#ifndef NDEBUG
2160 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
2161#else
2162 raw_ostream &DebugOut = nulls();
2163#endif
2164
Ahmed Charles56440fd2014-03-06 05:51:42 +00002165 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00002166 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00002167 // Try to find debug info and set up the DIContext for it.
2168 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00002169 // A separate DSym file path was specified, parse it as a macho file,
2170 // get the sections and supply it to the section name parsing machinery.
2171 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00002172 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00002173 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00002174 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00002175 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00002176 return;
2177 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00002178 DbgObj =
2179 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
2180 .get()
2181 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00002182 }
2183
Eric Christopher7370b552012-11-12 21:40:38 +00002184 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00002185 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00002186 }
2187
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002188 // TODO: For now this only disassembles the (__TEXT,__text) section (see the
2189 // checks in the code below at the top of this loop). It should allow a
2190 // darwin otool(1) like -s option to disassemble any named segment & section
2191 // that is marked as containing instructions with the attributes
2192 // S_ATTR_PURE_INSTRUCTIONS or S_ATTR_SOME_INSTRUCTIONS in the flags field of
2193 // the section structure.
2194 outs() << "(__TEXT,__text) section\n";
2195
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002196 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002197
Rafael Espindola80291272014-10-08 15:28:58 +00002198 bool SectIsText = Sections[SectIdx].isText();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002199 if (SectIsText == false)
2200 continue;
2201
Owen Andersond9243c42011-10-17 21:37:35 +00002202 StringRef SectName;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002203 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002204 continue; // Skip non-text sections
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002205
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00002206 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002207
Rafael Espindolab0f76a42013-04-05 15:15:22 +00002208 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
2209 if (SegmentName != "__TEXT")
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00002210 continue;
2211
Rafael Espindola7fc5b872014-11-12 02:04:27 +00002212 StringRef BytesStr;
2213 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00002214 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
2215 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00002216 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00002217
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002218 bool symbolTableWorked = false;
2219
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002220 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00002221 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
2222 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00002223 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00002224 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00002225 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00002226 RelocOffset -= SectionAddress;
2227
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00002228 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00002229
Rafael Espindola806f0062013-06-05 01:33:53 +00002230 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002231 }
2232 array_pod_sort(Relocs.begin(), Relocs.end());
2233
Kevin Enderbybf246f52014-09-24 23:08:22 +00002234 // Create a map of symbol addresses to symbol names for use by
2235 // the SymbolizerSymbolLookUp() routine.
2236 SymbolAddressMap AddrMap;
2237 for (const SymbolRef &Symbol : MachOOF->symbols()) {
2238 SymbolRef::Type ST;
2239 Symbol.getType(ST);
2240 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
2241 ST == SymbolRef::ST_Other) {
2242 uint64_t Address;
2243 Symbol.getAddress(Address);
2244 StringRef SymName;
2245 Symbol.getName(SymName);
2246 AddrMap[Address] = SymName;
2247 }
2248 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002249 // Set up the block of info used by the Symbolizer call backs.
2250 SymbolizerInfo.verbose = true;
2251 SymbolizerInfo.O = MachOOF;
2252 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00002253 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002254 SymbolizerInfo.Sections = &Sections;
2255 SymbolizerInfo.class_name = nullptr;
2256 SymbolizerInfo.selector_name = nullptr;
2257 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00002258 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00002259 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00002260 SymbolizerInfo.adrp_addr = 0;
2261 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002262 // Same for the ThumbSymbolizer
2263 ThumbSymbolizerInfo.verbose = true;
2264 ThumbSymbolizerInfo.O = MachOOF;
2265 ThumbSymbolizerInfo.S = Sections[SectIdx];
2266 ThumbSymbolizerInfo.AddrMap = &AddrMap;
2267 ThumbSymbolizerInfo.Sections = &Sections;
2268 ThumbSymbolizerInfo.class_name = nullptr;
2269 ThumbSymbolizerInfo.selector_name = nullptr;
2270 ThumbSymbolizerInfo.method = nullptr;
2271 ThumbSymbolizerInfo.demangled_name = nullptr;
2272 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00002273 ThumbSymbolizerInfo.adrp_addr = 0;
2274 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00002275
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002276 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002277 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00002278 StringRef SymName;
2279 Symbols[SymIdx].getName(SymName);
2280
2281 SymbolRef::Type ST;
2282 Symbols[SymIdx].getType(ST);
2283 if (ST != SymbolRef::ST_Function)
2284 continue;
2285
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002286 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00002287 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00002288 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002289 continue;
2290
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002291 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00002292 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00002293 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00002294 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00002295 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00002296
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00002297 // Stop disassembling either at the beginning of the next symbol or at
2298 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00002299 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00002300 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002301 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00002302 while (Symbols.size() > NextSymIdx) {
2303 SymbolRef::Type NextSymType;
2304 Symbols[NextSymIdx].getType(NextSymType);
2305 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00002306 containsNextSym =
2307 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00002308 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00002309 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00002310 break;
2311 }
2312 ++NextSymIdx;
2313 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002314
Rafael Espindola80291272014-10-08 15:28:58 +00002315 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002316 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00002317 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002318
2319 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00002320
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002321 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
2322 bool isThumb =
2323 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
2324
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002325 outs() << SymName << ":\n";
2326 DILineInfo lastLine;
2327 for (uint64_t Index = Start; Index < End; Index += Size) {
2328 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00002329
Kevin Enderbybf246f52014-09-24 23:08:22 +00002330 uint64_t PC = SectAddress + Index;
2331 if (FullLeadingAddr) {
2332 if (MachOOF->is64Bit())
2333 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002334 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00002335 outs() << format("%08" PRIx64, PC);
2336 } else {
2337 outs() << format("%8" PRIx64 ":", PC);
2338 }
2339 if (!NoShowRawInsn)
2340 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00002341
2342 // Check the data in code table here to see if this is data not an
2343 // instruction to be disassembled.
2344 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00002345 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002346 dice_table_iterator DTI =
2347 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
2348 compareDiceTableEntries);
2349 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00002350 uint16_t Length;
2351 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00002352 uint16_t Kind;
2353 DTI->second.getKind(Kind);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00002354 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
2355 Index,
2356 Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00002357 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
2358 (PC == (DTI->first + Length - 1)) && (Length & 1))
2359 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00002360 continue;
2361 }
2362
Kevin Enderbybf246f52014-09-24 23:08:22 +00002363 SmallVector<char, 64> AnnotationsBytes;
2364 raw_svector_ostream Annotations(AnnotationsBytes);
2365
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002366 bool gotInst;
2367 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00002368 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002369 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002370 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00002371 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00002372 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002373 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002374 if (!NoShowRawInsn) {
Aaron Ballman106fd7b2014-11-12 14:01:17 +00002375 DumpBytes(StringRef(
2376 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
Kevin Enderbybf246f52014-09-24 23:08:22 +00002377 }
2378 formatted_raw_ostream FormattedOS(outs());
2379 Annotations.flush();
2380 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002381 if (isThumb)
Kevin Enderbybf246f52014-09-24 23:08:22 +00002382 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00002383 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00002384 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
2385 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00002386
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002387 // Print debug info.
2388 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002389 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002390 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00002391 if (dli != lastLine && dli.Line != 0)
2392 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
2393 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002394 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002395 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002396 outs() << "\n";
2397 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002398 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002399 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002400 outs() << format("\t.byte 0x%02x #bad opcode\n",
2401 *(Bytes.data() + Index) & 0xff);
2402 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00002403 } else if (Arch == Triple::aarch64) {
2404 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
2405 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
2406 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
2407 (*(Bytes.data() + Index + 3) & 0xff) << 24;
2408 outs() << format("\t.long\t0x%08x\n", opcode);
2409 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002410 } else {
2411 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2412 if (Size == 0)
2413 Size = 1; // skip illegible bytes
2414 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002415 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002416 }
2417 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00002418 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00002419 // Reading the symbol table didn't work, disassemble the whole section.
2420 uint64_t SectAddress = Sections[SectIdx].getAddress();
2421 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00002422 uint64_t InstSize;
2423 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00002424 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00002425
Kevin Enderbybf246f52014-09-24 23:08:22 +00002426 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00002427 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
2428 DebugOut, nulls())) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00002429 if (FullLeadingAddr) {
2430 if (MachOOF->is64Bit())
2431 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002432 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00002433 outs() << format("%08" PRIx64, PC);
2434 } else {
2435 outs() << format("%8" PRIx64 ":", PC);
2436 }
2437 if (!NoShowRawInsn) {
2438 outs() << "\t";
Aaron Ballman106fd7b2014-11-12 14:01:17 +00002439 DumpBytes(
2440 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
2441 InstSize));
Kevin Enderbybf246f52014-09-24 23:08:22 +00002442 }
Bill Wendling4e68e062012-07-19 00:17:40 +00002443 IP->printInst(&Inst, outs(), "");
2444 outs() << "\n";
2445 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002446 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002447 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002448 outs() << format("\t.byte 0x%02x #bad opcode\n",
2449 *(Bytes.data() + Index) & 0xff);
2450 InstSize = 1; // skip exactly one illegible byte and move on.
2451 } else {
2452 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2453 if (InstSize == 0)
2454 InstSize = 1; // skip illegible bytes
2455 }
Bill Wendling4e68e062012-07-19 00:17:40 +00002456 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00002457 }
2458 }
Kevin Enderbyef3ad2f2014-12-04 23:56:27 +00002459 // The TripleName's need to be reset if we are called again for a different
2460 // archtecture.
2461 TripleName = "";
2462 ThumbTripleName = "";
2463
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002464 if (SymbolizerInfo.method != nullptr)
2465 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002466 if (SymbolizerInfo.demangled_name != nullptr)
2467 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00002468 if (SymbolizerInfo.bindtable != nullptr)
2469 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002470 if (ThumbSymbolizerInfo.method != nullptr)
2471 free(ThumbSymbolizerInfo.method);
2472 if (ThumbSymbolizerInfo.demangled_name != nullptr)
2473 free(ThumbSymbolizerInfo.demangled_name);
2474 if (ThumbSymbolizerInfo.bindtable != nullptr)
2475 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002476 }
2477}
Tim Northover4bd286a2014-08-01 13:07:19 +00002478
Tim Northover39c70bb2014-08-12 11:52:59 +00002479//===----------------------------------------------------------------------===//
2480// __compact_unwind section dumping
2481//===----------------------------------------------------------------------===//
2482
Tim Northover4bd286a2014-08-01 13:07:19 +00002483namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00002484
2485template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002486 using llvm::support::little;
2487 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00002488
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002489 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2490 Buf += sizeof(T);
2491 return Val;
2492}
Tim Northover39c70bb2014-08-12 11:52:59 +00002493
Tim Northover4bd286a2014-08-01 13:07:19 +00002494struct CompactUnwindEntry {
2495 uint32_t OffsetInSection;
2496
2497 uint64_t FunctionAddr;
2498 uint32_t Length;
2499 uint32_t CompactEncoding;
2500 uint64_t PersonalityAddr;
2501 uint64_t LSDAAddr;
2502
2503 RelocationRef FunctionReloc;
2504 RelocationRef PersonalityReloc;
2505 RelocationRef LSDAReloc;
2506
2507 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002508 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002509 if (Is64)
2510 read<uint64_t>(Contents.data() + Offset);
2511 else
2512 read<uint32_t>(Contents.data() + Offset);
2513 }
2514
2515private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002516 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002517 FunctionAddr = readNext<UIntPtr>(Buf);
2518 Length = readNext<uint32_t>(Buf);
2519 CompactEncoding = readNext<uint32_t>(Buf);
2520 PersonalityAddr = readNext<UIntPtr>(Buf);
2521 LSDAAddr = readNext<UIntPtr>(Buf);
2522 }
2523};
2524}
2525
2526/// Given a relocation from __compact_unwind, consisting of the RelocationRef
2527/// and data being relocated, determine the best base Name and Addend to use for
2528/// display purposes.
2529///
2530/// 1. An Extern relocation will directly reference a symbol (and the data is
2531/// then already an addend), so use that.
2532/// 2. Otherwise the data is an offset in the object file's layout; try to find
2533// a symbol before it in the same section, and use the offset from there.
2534/// 3. Finally, if all that fails, fall back to an offset from the start of the
2535/// referenced section.
2536static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2537 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002538 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00002539 StringRef &Name, uint64_t &Addend) {
2540 if (Reloc.getSymbol() != Obj->symbol_end()) {
2541 Reloc.getSymbol()->getName(Name);
2542 Addend = Addr;
2543 return;
2544 }
2545
2546 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2547 SectionRef RelocSection = Obj->getRelocationSection(RE);
2548
Rafael Espindola80291272014-10-08 15:28:58 +00002549 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00002550
2551 auto Sym = Symbols.upper_bound(Addr);
2552 if (Sym == Symbols.begin()) {
2553 // The first symbol in the object is after this reference, the best we can
2554 // do is section-relative notation.
2555 RelocSection.getName(Name);
2556 Addend = Addr - SectionAddr;
2557 return;
2558 }
2559
2560 // Go back one so that SymbolAddress <= Addr.
2561 --Sym;
2562
2563 section_iterator SymSection = Obj->section_end();
2564 Sym->second.getSection(SymSection);
2565 if (RelocSection == *SymSection) {
2566 // There's a valid symbol in the same section before this reference.
2567 Sym->second.getName(Name);
2568 Addend = Addr - Sym->first;
2569 return;
2570 }
2571
2572 // There is a symbol before this reference, but it's in a different
2573 // section. Probably not helpful to mention it, so use the section name.
2574 RelocSection.getName(Name);
2575 Addend = Addr - SectionAddr;
2576}
2577
2578static void printUnwindRelocDest(const MachOObjectFile *Obj,
2579 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002580 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002581 StringRef Name;
2582 uint64_t Addend;
2583
Tim Northover0b0add52014-09-09 10:45:06 +00002584 if (!Reloc.getObjectFile())
2585 return;
2586
Tim Northover4bd286a2014-08-01 13:07:19 +00002587 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2588
2589 outs() << Name;
2590 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00002591 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00002592}
2593
2594static void
2595printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2596 std::map<uint64_t, SymbolRef> &Symbols,
2597 const SectionRef &CompactUnwind) {
2598
2599 assert(Obj->isLittleEndian() &&
2600 "There should not be a big-endian .o with __compact_unwind");
2601
2602 bool Is64 = Obj->is64Bit();
2603 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2604 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2605
2606 StringRef Contents;
2607 CompactUnwind.getContents(Contents);
2608
2609 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2610
2611 // First populate the initial raw offsets, encodings and so on from the entry.
2612 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2613 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2614 CompactUnwinds.push_back(Entry);
2615 }
2616
2617 // Next we need to look at the relocations to find out what objects are
2618 // actually being referred to.
2619 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2620 uint64_t RelocAddress;
2621 Reloc.getOffset(RelocAddress);
2622
2623 uint32_t EntryIdx = RelocAddress / EntrySize;
2624 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2625 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2626
2627 if (OffsetInEntry == 0)
2628 Entry.FunctionReloc = Reloc;
2629 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2630 Entry.PersonalityReloc = Reloc;
2631 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2632 Entry.LSDAReloc = Reloc;
2633 else
2634 llvm_unreachable("Unexpected relocation in __compact_unwind section");
2635 }
2636
2637 // Finally, we're ready to print the data we've gathered.
2638 outs() << "Contents of __compact_unwind section:\n";
2639 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00002640 outs() << " Entry at offset "
2641 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00002642
2643 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002644 outs() << " start: " << format("0x%" PRIx64,
2645 Entry.FunctionAddr) << ' ';
2646 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00002647 outs() << '\n';
2648
2649 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002650 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
2651 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00002652 // 3. The 32-bit compact encoding.
2653 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00002654 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00002655
2656 // 4. The personality function, if present.
2657 if (Entry.PersonalityReloc.getObjectFile()) {
2658 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00002659 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00002660 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2661 Entry.PersonalityAddr);
2662 outs() << '\n';
2663 }
2664
2665 // 5. This entry's language-specific data area.
2666 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002667 outs() << " LSDA: " << format("0x%" PRIx64,
2668 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00002669 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2670 outs() << '\n';
2671 }
2672 }
2673}
2674
Tim Northover39c70bb2014-08-12 11:52:59 +00002675//===----------------------------------------------------------------------===//
2676// __unwind_info section dumping
2677//===----------------------------------------------------------------------===//
2678
2679static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2680 const char *Pos = PageStart;
2681 uint32_t Kind = readNext<uint32_t>(Pos);
2682 (void)Kind;
2683 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2684
2685 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2686 uint16_t NumEntries = readNext<uint16_t>(Pos);
2687
2688 Pos = PageStart + EntriesStart;
2689 for (unsigned i = 0; i < NumEntries; ++i) {
2690 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2691 uint32_t Encoding = readNext<uint32_t>(Pos);
2692
2693 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002694 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2695 << ", "
2696 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002697 }
2698}
2699
2700static void printCompressedSecondLevelUnwindPage(
2701 const char *PageStart, uint32_t FunctionBase,
2702 const SmallVectorImpl<uint32_t> &CommonEncodings) {
2703 const char *Pos = PageStart;
2704 uint32_t Kind = readNext<uint32_t>(Pos);
2705 (void)Kind;
2706 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2707
2708 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2709 uint16_t NumEntries = readNext<uint16_t>(Pos);
2710
2711 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
2712 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00002713 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
2714 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00002715
2716 Pos = PageStart + EntriesStart;
2717 for (unsigned i = 0; i < NumEntries; ++i) {
2718 uint32_t Entry = readNext<uint32_t>(Pos);
2719 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
2720 uint32_t EncodingIdx = Entry >> 24;
2721
2722 uint32_t Encoding;
2723 if (EncodingIdx < CommonEncodings.size())
2724 Encoding = CommonEncodings[EncodingIdx];
2725 else
2726 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
2727
2728 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002729 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2730 << ", "
2731 << "encoding[" << EncodingIdx
2732 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002733 }
2734}
2735
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002736static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
2737 std::map<uint64_t, SymbolRef> &Symbols,
2738 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00002739
2740 assert(Obj->isLittleEndian() &&
2741 "There should not be a big-endian .o with __unwind_info");
2742
2743 outs() << "Contents of __unwind_info section:\n";
2744
2745 StringRef Contents;
2746 UnwindInfo.getContents(Contents);
2747 const char *Pos = Contents.data();
2748
2749 //===----------------------------------
2750 // Section header
2751 //===----------------------------------
2752
2753 uint32_t Version = readNext<uint32_t>(Pos);
2754 outs() << " Version: "
2755 << format("0x%" PRIx32, Version) << '\n';
2756 assert(Version == 1 && "only understand version 1");
2757
2758 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
2759 outs() << " Common encodings array section offset: "
2760 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
2761 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
2762 outs() << " Number of common encodings in array: "
2763 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
2764
2765 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
2766 outs() << " Personality function array section offset: "
2767 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
2768 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
2769 outs() << " Number of personality functions in array: "
2770 << format("0x%" PRIx32, NumPersonalities) << '\n';
2771
2772 uint32_t IndicesStart = readNext<uint32_t>(Pos);
2773 outs() << " Index array section offset: "
2774 << format("0x%" PRIx32, IndicesStart) << '\n';
2775 uint32_t NumIndices = readNext<uint32_t>(Pos);
2776 outs() << " Number of indices in array: "
2777 << format("0x%" PRIx32, NumIndices) << '\n';
2778
2779 //===----------------------------------
2780 // A shared list of common encodings
2781 //===----------------------------------
2782
2783 // These occupy indices in the range [0, N] whenever an encoding is referenced
2784 // from a compressed 2nd level index table. In practice the linker only
2785 // creates ~128 of these, so that indices are available to embed encodings in
2786 // the 2nd level index.
2787
2788 SmallVector<uint32_t, 64> CommonEncodings;
2789 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
2790 Pos = Contents.data() + CommonEncodingsStart;
2791 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
2792 uint32_t Encoding = readNext<uint32_t>(Pos);
2793 CommonEncodings.push_back(Encoding);
2794
2795 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
2796 << '\n';
2797 }
2798
Tim Northover39c70bb2014-08-12 11:52:59 +00002799 //===----------------------------------
2800 // Personality functions used in this executable
2801 //===----------------------------------
2802
2803 // There should be only a handful of these (one per source language,
2804 // roughly). Particularly since they only get 2 bits in the compact encoding.
2805
2806 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
2807 Pos = Contents.data() + PersonalitiesStart;
2808 for (unsigned i = 0; i < NumPersonalities; ++i) {
2809 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
2810 outs() << " personality[" << i + 1
2811 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
2812 }
2813
2814 //===----------------------------------
2815 // The level 1 index entries
2816 //===----------------------------------
2817
2818 // These specify an approximate place to start searching for the more detailed
2819 // information, sorted by PC.
2820
2821 struct IndexEntry {
2822 uint32_t FunctionOffset;
2823 uint32_t SecondLevelPageStart;
2824 uint32_t LSDAStart;
2825 };
2826
2827 SmallVector<IndexEntry, 4> IndexEntries;
2828
2829 outs() << " Top level indices: (count = " << NumIndices << ")\n";
2830 Pos = Contents.data() + IndicesStart;
2831 for (unsigned i = 0; i < NumIndices; ++i) {
2832 IndexEntry Entry;
2833
2834 Entry.FunctionOffset = readNext<uint32_t>(Pos);
2835 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
2836 Entry.LSDAStart = readNext<uint32_t>(Pos);
2837 IndexEntries.push_back(Entry);
2838
2839 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002840 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
2841 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00002842 << "2nd level page offset="
2843 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002844 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002845 }
2846
Tim Northover39c70bb2014-08-12 11:52:59 +00002847 //===----------------------------------
2848 // Next come the LSDA tables
2849 //===----------------------------------
2850
2851 // The LSDA layout is rather implicit: it's a contiguous array of entries from
2852 // the first top-level index's LSDAOffset to the last (sentinel).
2853
2854 outs() << " LSDA descriptors:\n";
2855 Pos = Contents.data() + IndexEntries[0].LSDAStart;
2856 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2857 (2 * sizeof(uint32_t));
2858 for (int i = 0; i < NumLSDAs; ++i) {
2859 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2860 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2861 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002862 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2863 << ", "
2864 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002865 }
2866
2867 //===----------------------------------
2868 // Finally, the 2nd level indices
2869 //===----------------------------------
2870
2871 // Generally these are 4K in size, and have 2 possible forms:
2872 // + Regular stores up to 511 entries with disparate encodings
2873 // + Compressed stores up to 1021 entries if few enough compact encoding
2874 // values are used.
2875 outs() << " Second level indices:\n";
2876 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2877 // The final sentinel top-level index has no associated 2nd level page
2878 if (IndexEntries[i].SecondLevelPageStart == 0)
2879 break;
2880
2881 outs() << " Second level index[" << i << "]: "
2882 << "offset in section="
2883 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2884 << ", "
2885 << "base function offset="
2886 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2887
2888 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00002889 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00002890 if (Kind == 2)
2891 printRegularSecondLevelUnwindPage(Pos);
2892 else if (Kind == 3)
2893 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2894 CommonEncodings);
2895 else
2896 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00002897 }
2898}
2899
Tim Northover4bd286a2014-08-01 13:07:19 +00002900void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2901 std::map<uint64_t, SymbolRef> Symbols;
2902 for (const SymbolRef &SymRef : Obj->symbols()) {
2903 // Discard any undefined or absolute symbols. They're not going to take part
2904 // in the convenience lookup for unwind info and just take up resources.
2905 section_iterator Section = Obj->section_end();
2906 SymRef.getSection(Section);
2907 if (Section == Obj->section_end())
2908 continue;
2909
2910 uint64_t Addr;
2911 SymRef.getAddress(Addr);
2912 Symbols.insert(std::make_pair(Addr, SymRef));
2913 }
2914
2915 for (const SectionRef &Section : Obj->sections()) {
2916 StringRef SectName;
2917 Section.getName(SectName);
2918 if (SectName == "__compact_unwind")
2919 printMachOCompactUnwindSection(Obj, Symbols, Section);
2920 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00002921 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00002922 else if (SectName == "__eh_frame")
2923 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00002924 }
2925}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002926
2927static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2928 uint32_t cpusubtype, uint32_t filetype,
2929 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2930 bool verbose) {
2931 outs() << "Mach header\n";
2932 outs() << " magic cputype cpusubtype caps filetype ncmds "
2933 "sizeofcmds flags\n";
2934 if (verbose) {
2935 if (magic == MachO::MH_MAGIC)
2936 outs() << " MH_MAGIC";
2937 else if (magic == MachO::MH_MAGIC_64)
2938 outs() << "MH_MAGIC_64";
2939 else
2940 outs() << format(" 0x%08" PRIx32, magic);
2941 switch (cputype) {
2942 case MachO::CPU_TYPE_I386:
2943 outs() << " I386";
2944 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2945 case MachO::CPU_SUBTYPE_I386_ALL:
2946 outs() << " ALL";
2947 break;
2948 default:
2949 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2950 break;
2951 }
2952 break;
2953 case MachO::CPU_TYPE_X86_64:
2954 outs() << " X86_64";
Kevin Enderby131d1772015-01-09 19:22:37 +00002955 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2956 case MachO::CPU_SUBTYPE_X86_64_ALL:
2957 outs() << " ALL";
2958 break;
2959 case MachO::CPU_SUBTYPE_X86_64_H:
2960 outs() << " Haswell";
2961 break;
2962 default:
2963 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2964 break;
2965 }
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002966 break;
2967 case MachO::CPU_TYPE_ARM:
2968 outs() << " ARM";
2969 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2970 case MachO::CPU_SUBTYPE_ARM_ALL:
2971 outs() << " ALL";
2972 break;
2973 case MachO::CPU_SUBTYPE_ARM_V4T:
2974 outs() << " V4T";
2975 break;
2976 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2977 outs() << " V5TEJ";
2978 break;
2979 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2980 outs() << " XSCALE";
2981 break;
2982 case MachO::CPU_SUBTYPE_ARM_V6:
2983 outs() << " V6";
2984 break;
2985 case MachO::CPU_SUBTYPE_ARM_V6M:
2986 outs() << " V6M";
2987 break;
2988 case MachO::CPU_SUBTYPE_ARM_V7:
2989 outs() << " V7";
2990 break;
2991 case MachO::CPU_SUBTYPE_ARM_V7EM:
2992 outs() << " V7EM";
2993 break;
2994 case MachO::CPU_SUBTYPE_ARM_V7K:
2995 outs() << " V7K";
2996 break;
2997 case MachO::CPU_SUBTYPE_ARM_V7M:
2998 outs() << " V7M";
2999 break;
3000 case MachO::CPU_SUBTYPE_ARM_V7S:
3001 outs() << " V7S";
3002 break;
3003 default:
3004 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3005 break;
3006 }
3007 break;
3008 case MachO::CPU_TYPE_ARM64:
3009 outs() << " ARM64";
3010 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3011 case MachO::CPU_SUBTYPE_ARM64_ALL:
3012 outs() << " ALL";
3013 break;
3014 default:
3015 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3016 break;
3017 }
3018 break;
3019 case MachO::CPU_TYPE_POWERPC:
3020 outs() << " PPC";
3021 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3022 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3023 outs() << " ALL";
3024 break;
3025 default:
3026 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3027 break;
3028 }
3029 break;
3030 case MachO::CPU_TYPE_POWERPC64:
3031 outs() << " PPC64";
3032 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
3033 case MachO::CPU_SUBTYPE_POWERPC_ALL:
3034 outs() << " ALL";
3035 break;
3036 default:
3037 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3038 break;
3039 }
3040 break;
3041 }
3042 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003043 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003044 } else {
3045 outs() << format(" 0x%02" PRIx32,
3046 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3047 }
3048 switch (filetype) {
3049 case MachO::MH_OBJECT:
3050 outs() << " OBJECT";
3051 break;
3052 case MachO::MH_EXECUTE:
3053 outs() << " EXECUTE";
3054 break;
3055 case MachO::MH_FVMLIB:
3056 outs() << " FVMLIB";
3057 break;
3058 case MachO::MH_CORE:
3059 outs() << " CORE";
3060 break;
3061 case MachO::MH_PRELOAD:
3062 outs() << " PRELOAD";
3063 break;
3064 case MachO::MH_DYLIB:
3065 outs() << " DYLIB";
3066 break;
3067 case MachO::MH_DYLIB_STUB:
3068 outs() << " DYLIB_STUB";
3069 break;
3070 case MachO::MH_DYLINKER:
3071 outs() << " DYLINKER";
3072 break;
3073 case MachO::MH_BUNDLE:
3074 outs() << " BUNDLE";
3075 break;
3076 case MachO::MH_DSYM:
3077 outs() << " DSYM";
3078 break;
3079 case MachO::MH_KEXT_BUNDLE:
3080 outs() << " KEXTBUNDLE";
3081 break;
3082 default:
3083 outs() << format(" %10u", filetype);
3084 break;
3085 }
3086 outs() << format(" %5u", ncmds);
3087 outs() << format(" %10u", sizeofcmds);
3088 uint32_t f = flags;
3089 if (f & MachO::MH_NOUNDEFS) {
3090 outs() << " NOUNDEFS";
3091 f &= ~MachO::MH_NOUNDEFS;
3092 }
3093 if (f & MachO::MH_INCRLINK) {
3094 outs() << " INCRLINK";
3095 f &= ~MachO::MH_INCRLINK;
3096 }
3097 if (f & MachO::MH_DYLDLINK) {
3098 outs() << " DYLDLINK";
3099 f &= ~MachO::MH_DYLDLINK;
3100 }
3101 if (f & MachO::MH_BINDATLOAD) {
3102 outs() << " BINDATLOAD";
3103 f &= ~MachO::MH_BINDATLOAD;
3104 }
3105 if (f & MachO::MH_PREBOUND) {
3106 outs() << " PREBOUND";
3107 f &= ~MachO::MH_PREBOUND;
3108 }
3109 if (f & MachO::MH_SPLIT_SEGS) {
3110 outs() << " SPLIT_SEGS";
3111 f &= ~MachO::MH_SPLIT_SEGS;
3112 }
3113 if (f & MachO::MH_LAZY_INIT) {
3114 outs() << " LAZY_INIT";
3115 f &= ~MachO::MH_LAZY_INIT;
3116 }
3117 if (f & MachO::MH_TWOLEVEL) {
3118 outs() << " TWOLEVEL";
3119 f &= ~MachO::MH_TWOLEVEL;
3120 }
3121 if (f & MachO::MH_FORCE_FLAT) {
3122 outs() << " FORCE_FLAT";
3123 f &= ~MachO::MH_FORCE_FLAT;
3124 }
3125 if (f & MachO::MH_NOMULTIDEFS) {
3126 outs() << " NOMULTIDEFS";
3127 f &= ~MachO::MH_NOMULTIDEFS;
3128 }
3129 if (f & MachO::MH_NOFIXPREBINDING) {
3130 outs() << " NOFIXPREBINDING";
3131 f &= ~MachO::MH_NOFIXPREBINDING;
3132 }
3133 if (f & MachO::MH_PREBINDABLE) {
3134 outs() << " PREBINDABLE";
3135 f &= ~MachO::MH_PREBINDABLE;
3136 }
3137 if (f & MachO::MH_ALLMODSBOUND) {
3138 outs() << " ALLMODSBOUND";
3139 f &= ~MachO::MH_ALLMODSBOUND;
3140 }
3141 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
3142 outs() << " SUBSECTIONS_VIA_SYMBOLS";
3143 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
3144 }
3145 if (f & MachO::MH_CANONICAL) {
3146 outs() << " CANONICAL";
3147 f &= ~MachO::MH_CANONICAL;
3148 }
3149 if (f & MachO::MH_WEAK_DEFINES) {
3150 outs() << " WEAK_DEFINES";
3151 f &= ~MachO::MH_WEAK_DEFINES;
3152 }
3153 if (f & MachO::MH_BINDS_TO_WEAK) {
3154 outs() << " BINDS_TO_WEAK";
3155 f &= ~MachO::MH_BINDS_TO_WEAK;
3156 }
3157 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
3158 outs() << " ALLOW_STACK_EXECUTION";
3159 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
3160 }
3161 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
3162 outs() << " DEAD_STRIPPABLE_DYLIB";
3163 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
3164 }
3165 if (f & MachO::MH_PIE) {
3166 outs() << " PIE";
3167 f &= ~MachO::MH_PIE;
3168 }
3169 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
3170 outs() << " NO_REEXPORTED_DYLIBS";
3171 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
3172 }
3173 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
3174 outs() << " MH_HAS_TLV_DESCRIPTORS";
3175 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
3176 }
3177 if (f & MachO::MH_NO_HEAP_EXECUTION) {
3178 outs() << " MH_NO_HEAP_EXECUTION";
3179 f &= ~MachO::MH_NO_HEAP_EXECUTION;
3180 }
3181 if (f & MachO::MH_APP_EXTENSION_SAFE) {
3182 outs() << " APP_EXTENSION_SAFE";
3183 f &= ~MachO::MH_APP_EXTENSION_SAFE;
3184 }
3185 if (f != 0 || flags == 0)
3186 outs() << format(" 0x%08" PRIx32, f);
3187 } else {
3188 outs() << format(" 0x%08" PRIx32, magic);
3189 outs() << format(" %7d", cputype);
3190 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
3191 outs() << format(" 0x%02" PRIx32,
3192 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
3193 outs() << format(" %10u", filetype);
3194 outs() << format(" %5u", ncmds);
3195 outs() << format(" %10u", sizeofcmds);
3196 outs() << format(" 0x%08" PRIx32, flags);
3197 }
3198 outs() << "\n";
3199}
3200
Kevin Enderby956366c2014-08-29 22:30:52 +00003201static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
3202 StringRef SegName, uint64_t vmaddr,
3203 uint64_t vmsize, uint64_t fileoff,
3204 uint64_t filesize, uint32_t maxprot,
3205 uint32_t initprot, uint32_t nsects,
3206 uint32_t flags, uint32_t object_size,
3207 bool verbose) {
3208 uint64_t expected_cmdsize;
3209 if (cmd == MachO::LC_SEGMENT) {
3210 outs() << " cmd LC_SEGMENT\n";
3211 expected_cmdsize = nsects;
3212 expected_cmdsize *= sizeof(struct MachO::section);
3213 expected_cmdsize += sizeof(struct MachO::segment_command);
3214 } else {
3215 outs() << " cmd LC_SEGMENT_64\n";
3216 expected_cmdsize = nsects;
3217 expected_cmdsize *= sizeof(struct MachO::section_64);
3218 expected_cmdsize += sizeof(struct MachO::segment_command_64);
3219 }
3220 outs() << " cmdsize " << cmdsize;
3221 if (cmdsize != expected_cmdsize)
3222 outs() << " Inconsistent size\n";
3223 else
3224 outs() << "\n";
3225 outs() << " segname " << SegName << "\n";
3226 if (cmd == MachO::LC_SEGMENT_64) {
3227 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
3228 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
3229 } else {
Kevin Enderbyadb7c432014-12-16 18:58:11 +00003230 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
3231 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
Kevin Enderby956366c2014-08-29 22:30:52 +00003232 }
3233 outs() << " fileoff " << fileoff;
3234 if (fileoff > object_size)
3235 outs() << " (past end of file)\n";
3236 else
3237 outs() << "\n";
3238 outs() << " filesize " << filesize;
3239 if (fileoff + filesize > object_size)
3240 outs() << " (past end of file)\n";
3241 else
3242 outs() << "\n";
3243 if (verbose) {
3244 if ((maxprot &
3245 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3246 MachO::VM_PROT_EXECUTE)) != 0)
3247 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
3248 else {
3249 if (maxprot & MachO::VM_PROT_READ)
3250 outs() << " maxprot r";
3251 else
3252 outs() << " maxprot -";
3253 if (maxprot & MachO::VM_PROT_WRITE)
3254 outs() << "w";
3255 else
3256 outs() << "-";
3257 if (maxprot & MachO::VM_PROT_EXECUTE)
3258 outs() << "x\n";
3259 else
3260 outs() << "-\n";
3261 }
3262 if ((initprot &
3263 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
3264 MachO::VM_PROT_EXECUTE)) != 0)
3265 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
3266 else {
3267 if (initprot & MachO::VM_PROT_READ)
3268 outs() << " initprot r";
3269 else
3270 outs() << " initprot -";
3271 if (initprot & MachO::VM_PROT_WRITE)
3272 outs() << "w";
3273 else
3274 outs() << "-";
3275 if (initprot & MachO::VM_PROT_EXECUTE)
3276 outs() << "x\n";
3277 else
3278 outs() << "-\n";
3279 }
3280 } else {
3281 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
3282 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
3283 }
3284 outs() << " nsects " << nsects << "\n";
3285 if (verbose) {
3286 outs() << " flags";
3287 if (flags == 0)
3288 outs() << " (none)\n";
3289 else {
3290 if (flags & MachO::SG_HIGHVM) {
3291 outs() << " HIGHVM";
3292 flags &= ~MachO::SG_HIGHVM;
3293 }
3294 if (flags & MachO::SG_FVMLIB) {
3295 outs() << " FVMLIB";
3296 flags &= ~MachO::SG_FVMLIB;
3297 }
3298 if (flags & MachO::SG_NORELOC) {
3299 outs() << " NORELOC";
3300 flags &= ~MachO::SG_NORELOC;
3301 }
3302 if (flags & MachO::SG_PROTECTED_VERSION_1) {
3303 outs() << " PROTECTED_VERSION_1";
3304 flags &= ~MachO::SG_PROTECTED_VERSION_1;
3305 }
3306 if (flags)
3307 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
3308 else
3309 outs() << "\n";
3310 }
3311 } else {
3312 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
3313 }
3314}
3315
3316static void PrintSection(const char *sectname, const char *segname,
3317 uint64_t addr, uint64_t size, uint32_t offset,
3318 uint32_t align, uint32_t reloff, uint32_t nreloc,
3319 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
3320 uint32_t cmd, const char *sg_segname,
3321 uint32_t filetype, uint32_t object_size,
3322 bool verbose) {
3323 outs() << "Section\n";
3324 outs() << " sectname " << format("%.16s\n", sectname);
3325 outs() << " segname " << format("%.16s", segname);
3326 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
3327 outs() << " (does not match segment)\n";
3328 else
3329 outs() << "\n";
3330 if (cmd == MachO::LC_SEGMENT_64) {
3331 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
3332 outs() << " size " << format("0x%016" PRIx64, size);
3333 } else {
Kevin Enderby75594b62014-12-16 21:00:25 +00003334 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
3335 outs() << " size " << format("0x%08" PRIx64, size);
Kevin Enderby956366c2014-08-29 22:30:52 +00003336 }
3337 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
3338 outs() << " (past end of file)\n";
3339 else
3340 outs() << "\n";
3341 outs() << " offset " << offset;
3342 if (offset > object_size)
3343 outs() << " (past end of file)\n";
3344 else
3345 outs() << "\n";
3346 uint32_t align_shifted = 1 << align;
3347 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
3348 outs() << " reloff " << reloff;
3349 if (reloff > object_size)
3350 outs() << " (past end of file)\n";
3351 else
3352 outs() << "\n";
3353 outs() << " nreloc " << nreloc;
3354 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
3355 outs() << " (past end of file)\n";
3356 else
3357 outs() << "\n";
3358 uint32_t section_type = flags & MachO::SECTION_TYPE;
3359 if (verbose) {
3360 outs() << " type";
3361 if (section_type == MachO::S_REGULAR)
3362 outs() << " S_REGULAR\n";
3363 else if (section_type == MachO::S_ZEROFILL)
3364 outs() << " S_ZEROFILL\n";
3365 else if (section_type == MachO::S_CSTRING_LITERALS)
3366 outs() << " S_CSTRING_LITERALS\n";
3367 else if (section_type == MachO::S_4BYTE_LITERALS)
3368 outs() << " S_4BYTE_LITERALS\n";
3369 else if (section_type == MachO::S_8BYTE_LITERALS)
3370 outs() << " S_8BYTE_LITERALS\n";
3371 else if (section_type == MachO::S_16BYTE_LITERALS)
3372 outs() << " S_16BYTE_LITERALS\n";
3373 else if (section_type == MachO::S_LITERAL_POINTERS)
3374 outs() << " S_LITERAL_POINTERS\n";
3375 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
3376 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
3377 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
3378 outs() << " S_LAZY_SYMBOL_POINTERS\n";
3379 else if (section_type == MachO::S_SYMBOL_STUBS)
3380 outs() << " S_SYMBOL_STUBS\n";
3381 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
3382 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
3383 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
3384 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
3385 else if (section_type == MachO::S_COALESCED)
3386 outs() << " S_COALESCED\n";
3387 else if (section_type == MachO::S_INTERPOSING)
3388 outs() << " S_INTERPOSING\n";
3389 else if (section_type == MachO::S_DTRACE_DOF)
3390 outs() << " S_DTRACE_DOF\n";
3391 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
3392 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
3393 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
3394 outs() << " S_THREAD_LOCAL_REGULAR\n";
3395 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
3396 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
3397 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
3398 outs() << " S_THREAD_LOCAL_VARIABLES\n";
3399 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3400 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
3401 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
3402 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
3403 else
3404 outs() << format("0x%08" PRIx32, section_type) << "\n";
3405 outs() << "attributes";
3406 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
3407 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
3408 outs() << " PURE_INSTRUCTIONS";
3409 if (section_attributes & MachO::S_ATTR_NO_TOC)
3410 outs() << " NO_TOC";
3411 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
3412 outs() << " STRIP_STATIC_SYMS";
3413 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
3414 outs() << " NO_DEAD_STRIP";
3415 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
3416 outs() << " LIVE_SUPPORT";
3417 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
3418 outs() << " SELF_MODIFYING_CODE";
3419 if (section_attributes & MachO::S_ATTR_DEBUG)
3420 outs() << " DEBUG";
3421 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
3422 outs() << " SOME_INSTRUCTIONS";
3423 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
3424 outs() << " EXT_RELOC";
3425 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
3426 outs() << " LOC_RELOC";
3427 if (section_attributes == 0)
3428 outs() << " (none)";
3429 outs() << "\n";
3430 } else
3431 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
3432 outs() << " reserved1 " << reserved1;
3433 if (section_type == MachO::S_SYMBOL_STUBS ||
3434 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3435 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3436 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3437 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
3438 outs() << " (index into indirect symbol table)\n";
3439 else
3440 outs() << "\n";
3441 outs() << " reserved2 " << reserved2;
3442 if (section_type == MachO::S_SYMBOL_STUBS)
3443 outs() << " (size of stubs)\n";
3444 else
3445 outs() << "\n";
3446}
3447
David Majnemer73cc6ff2014-11-13 19:48:56 +00003448static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00003449 uint32_t object_size) {
3450 outs() << " cmd LC_SYMTAB\n";
3451 outs() << " cmdsize " << st.cmdsize;
3452 if (st.cmdsize != sizeof(struct MachO::symtab_command))
3453 outs() << " Incorrect size\n";
3454 else
3455 outs() << "\n";
3456 outs() << " symoff " << st.symoff;
3457 if (st.symoff > object_size)
3458 outs() << " (past end of file)\n";
3459 else
3460 outs() << "\n";
3461 outs() << " nsyms " << st.nsyms;
3462 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00003463 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003464 big_size = st.nsyms;
3465 big_size *= sizeof(struct MachO::nlist_64);
3466 big_size += st.symoff;
3467 if (big_size > object_size)
3468 outs() << " (past end of file)\n";
3469 else
3470 outs() << "\n";
3471 } else {
3472 big_size = st.nsyms;
3473 big_size *= sizeof(struct MachO::nlist);
3474 big_size += st.symoff;
3475 if (big_size > object_size)
3476 outs() << " (past end of file)\n";
3477 else
3478 outs() << "\n";
3479 }
3480 outs() << " stroff " << st.stroff;
3481 if (st.stroff > object_size)
3482 outs() << " (past end of file)\n";
3483 else
3484 outs() << "\n";
3485 outs() << " strsize " << st.strsize;
3486 big_size = st.stroff;
3487 big_size += st.strsize;
3488 if (big_size > object_size)
3489 outs() << " (past end of file)\n";
3490 else
3491 outs() << "\n";
3492}
3493
3494static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3495 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00003496 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003497 outs() << " cmd LC_DYSYMTAB\n";
3498 outs() << " cmdsize " << dyst.cmdsize;
3499 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3500 outs() << " Incorrect size\n";
3501 else
3502 outs() << "\n";
3503 outs() << " ilocalsym " << dyst.ilocalsym;
3504 if (dyst.ilocalsym > nsyms)
3505 outs() << " (greater than the number of symbols)\n";
3506 else
3507 outs() << "\n";
3508 outs() << " nlocalsym " << dyst.nlocalsym;
3509 uint64_t big_size;
3510 big_size = dyst.ilocalsym;
3511 big_size += dyst.nlocalsym;
3512 if (big_size > nsyms)
3513 outs() << " (past the end of the symbol table)\n";
3514 else
3515 outs() << "\n";
3516 outs() << " iextdefsym " << dyst.iextdefsym;
3517 if (dyst.iextdefsym > nsyms)
3518 outs() << " (greater than the number of symbols)\n";
3519 else
3520 outs() << "\n";
3521 outs() << " nextdefsym " << dyst.nextdefsym;
3522 big_size = dyst.iextdefsym;
3523 big_size += dyst.nextdefsym;
3524 if (big_size > nsyms)
3525 outs() << " (past the end of the symbol table)\n";
3526 else
3527 outs() << "\n";
3528 outs() << " iundefsym " << dyst.iundefsym;
3529 if (dyst.iundefsym > nsyms)
3530 outs() << " (greater than the number of symbols)\n";
3531 else
3532 outs() << "\n";
3533 outs() << " nundefsym " << dyst.nundefsym;
3534 big_size = dyst.iundefsym;
3535 big_size += dyst.nundefsym;
3536 if (big_size > nsyms)
3537 outs() << " (past the end of the symbol table)\n";
3538 else
3539 outs() << "\n";
3540 outs() << " tocoff " << dyst.tocoff;
3541 if (dyst.tocoff > object_size)
3542 outs() << " (past end of file)\n";
3543 else
3544 outs() << "\n";
3545 outs() << " ntoc " << dyst.ntoc;
3546 big_size = dyst.ntoc;
3547 big_size *= sizeof(struct MachO::dylib_table_of_contents);
3548 big_size += dyst.tocoff;
3549 if (big_size > object_size)
3550 outs() << " (past end of file)\n";
3551 else
3552 outs() << "\n";
3553 outs() << " modtaboff " << dyst.modtaboff;
3554 if (dyst.modtaboff > object_size)
3555 outs() << " (past end of file)\n";
3556 else
3557 outs() << "\n";
3558 outs() << " nmodtab " << dyst.nmodtab;
3559 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00003560 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003561 modtabend = dyst.nmodtab;
3562 modtabend *= sizeof(struct MachO::dylib_module_64);
3563 modtabend += dyst.modtaboff;
3564 } else {
3565 modtabend = dyst.nmodtab;
3566 modtabend *= sizeof(struct MachO::dylib_module);
3567 modtabend += dyst.modtaboff;
3568 }
3569 if (modtabend > object_size)
3570 outs() << " (past end of file)\n";
3571 else
3572 outs() << "\n";
3573 outs() << " extrefsymoff " << dyst.extrefsymoff;
3574 if (dyst.extrefsymoff > object_size)
3575 outs() << " (past end of file)\n";
3576 else
3577 outs() << "\n";
3578 outs() << " nextrefsyms " << dyst.nextrefsyms;
3579 big_size = dyst.nextrefsyms;
3580 big_size *= sizeof(struct MachO::dylib_reference);
3581 big_size += dyst.extrefsymoff;
3582 if (big_size > object_size)
3583 outs() << " (past end of file)\n";
3584 else
3585 outs() << "\n";
3586 outs() << " indirectsymoff " << dyst.indirectsymoff;
3587 if (dyst.indirectsymoff > object_size)
3588 outs() << " (past end of file)\n";
3589 else
3590 outs() << "\n";
3591 outs() << " nindirectsyms " << dyst.nindirectsyms;
3592 big_size = dyst.nindirectsyms;
3593 big_size *= sizeof(uint32_t);
3594 big_size += dyst.indirectsymoff;
3595 if (big_size > object_size)
3596 outs() << " (past end of file)\n";
3597 else
3598 outs() << "\n";
3599 outs() << " extreloff " << dyst.extreloff;
3600 if (dyst.extreloff > object_size)
3601 outs() << " (past end of file)\n";
3602 else
3603 outs() << "\n";
3604 outs() << " nextrel " << dyst.nextrel;
3605 big_size = dyst.nextrel;
3606 big_size *= sizeof(struct MachO::relocation_info);
3607 big_size += dyst.extreloff;
3608 if (big_size > object_size)
3609 outs() << " (past end of file)\n";
3610 else
3611 outs() << "\n";
3612 outs() << " locreloff " << dyst.locreloff;
3613 if (dyst.locreloff > object_size)
3614 outs() << " (past end of file)\n";
3615 else
3616 outs() << "\n";
3617 outs() << " nlocrel " << dyst.nlocrel;
3618 big_size = dyst.nlocrel;
3619 big_size *= sizeof(struct MachO::relocation_info);
3620 big_size += dyst.locreloff;
3621 if (big_size > object_size)
3622 outs() << " (past end of file)\n";
3623 else
3624 outs() << "\n";
3625}
3626
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003627static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3628 uint32_t object_size) {
3629 if (dc.cmd == MachO::LC_DYLD_INFO)
3630 outs() << " cmd LC_DYLD_INFO\n";
3631 else
3632 outs() << " cmd LC_DYLD_INFO_ONLY\n";
3633 outs() << " cmdsize " << dc.cmdsize;
3634 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3635 outs() << " Incorrect size\n";
3636 else
3637 outs() << "\n";
3638 outs() << " rebase_off " << dc.rebase_off;
3639 if (dc.rebase_off > object_size)
3640 outs() << " (past end of file)\n";
3641 else
3642 outs() << "\n";
3643 outs() << " rebase_size " << dc.rebase_size;
3644 uint64_t big_size;
3645 big_size = dc.rebase_off;
3646 big_size += dc.rebase_size;
3647 if (big_size > object_size)
3648 outs() << " (past end of file)\n";
3649 else
3650 outs() << "\n";
3651 outs() << " bind_off " << dc.bind_off;
3652 if (dc.bind_off > object_size)
3653 outs() << " (past end of file)\n";
3654 else
3655 outs() << "\n";
3656 outs() << " bind_size " << dc.bind_size;
3657 big_size = dc.bind_off;
3658 big_size += dc.bind_size;
3659 if (big_size > object_size)
3660 outs() << " (past end of file)\n";
3661 else
3662 outs() << "\n";
3663 outs() << " weak_bind_off " << dc.weak_bind_off;
3664 if (dc.weak_bind_off > object_size)
3665 outs() << " (past end of file)\n";
3666 else
3667 outs() << "\n";
3668 outs() << " weak_bind_size " << dc.weak_bind_size;
3669 big_size = dc.weak_bind_off;
3670 big_size += dc.weak_bind_size;
3671 if (big_size > object_size)
3672 outs() << " (past end of file)\n";
3673 else
3674 outs() << "\n";
3675 outs() << " lazy_bind_off " << dc.lazy_bind_off;
3676 if (dc.lazy_bind_off > object_size)
3677 outs() << " (past end of file)\n";
3678 else
3679 outs() << "\n";
3680 outs() << " lazy_bind_size " << dc.lazy_bind_size;
3681 big_size = dc.lazy_bind_off;
3682 big_size += dc.lazy_bind_size;
3683 if (big_size > object_size)
3684 outs() << " (past end of file)\n";
3685 else
3686 outs() << "\n";
3687 outs() << " export_off " << dc.export_off;
3688 if (dc.export_off > object_size)
3689 outs() << " (past end of file)\n";
3690 else
3691 outs() << "\n";
3692 outs() << " export_size " << dc.export_size;
3693 big_size = dc.export_off;
3694 big_size += dc.export_size;
3695 if (big_size > object_size)
3696 outs() << " (past end of file)\n";
3697 else
3698 outs() << "\n";
3699}
3700
3701static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3702 const char *Ptr) {
3703 if (dyld.cmd == MachO::LC_ID_DYLINKER)
3704 outs() << " cmd LC_ID_DYLINKER\n";
3705 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3706 outs() << " cmd LC_LOAD_DYLINKER\n";
3707 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3708 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
3709 else
3710 outs() << " cmd ?(" << dyld.cmd << ")\n";
3711 outs() << " cmdsize " << dyld.cmdsize;
3712 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
3713 outs() << " Incorrect size\n";
3714 else
3715 outs() << "\n";
3716 if (dyld.name >= dyld.cmdsize)
3717 outs() << " name ?(bad offset " << dyld.name << ")\n";
3718 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003719 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003720 outs() << " name " << P << " (offset " << dyld.name << ")\n";
3721 }
3722}
3723
3724static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
3725 outs() << " cmd LC_UUID\n";
3726 outs() << " cmdsize " << uuid.cmdsize;
3727 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
3728 outs() << " Incorrect size\n";
3729 else
3730 outs() << "\n";
3731 outs() << " uuid ";
3732 outs() << format("%02" PRIX32, uuid.uuid[0]);
3733 outs() << format("%02" PRIX32, uuid.uuid[1]);
3734 outs() << format("%02" PRIX32, uuid.uuid[2]);
3735 outs() << format("%02" PRIX32, uuid.uuid[3]);
3736 outs() << "-";
3737 outs() << format("%02" PRIX32, uuid.uuid[4]);
3738 outs() << format("%02" PRIX32, uuid.uuid[5]);
3739 outs() << "-";
3740 outs() << format("%02" PRIX32, uuid.uuid[6]);
3741 outs() << format("%02" PRIX32, uuid.uuid[7]);
3742 outs() << "-";
3743 outs() << format("%02" PRIX32, uuid.uuid[8]);
3744 outs() << format("%02" PRIX32, uuid.uuid[9]);
3745 outs() << "-";
3746 outs() << format("%02" PRIX32, uuid.uuid[10]);
3747 outs() << format("%02" PRIX32, uuid.uuid[11]);
3748 outs() << format("%02" PRIX32, uuid.uuid[12]);
3749 outs() << format("%02" PRIX32, uuid.uuid[13]);
3750 outs() << format("%02" PRIX32, uuid.uuid[14]);
3751 outs() << format("%02" PRIX32, uuid.uuid[15]);
3752 outs() << "\n";
3753}
3754
Kevin Enderby66d51fc2015-01-08 00:25:24 +00003755static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00003756 outs() << " cmd LC_RPATH\n";
3757 outs() << " cmdsize " << rpath.cmdsize;
3758 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
3759 outs() << " Incorrect size\n";
3760 else
3761 outs() << "\n";
3762 if (rpath.path >= rpath.cmdsize)
3763 outs() << " path ?(bad offset " << rpath.path << ")\n";
3764 else {
3765 const char *P = (const char *)(Ptr) + rpath.path;
3766 outs() << " path " << P << " (offset " << rpath.path << ")\n";
3767 }
3768}
3769
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003770static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
3771 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
3772 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
3773 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
3774 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
3775 else
3776 outs() << " cmd " << vd.cmd << " (?)\n";
3777 outs() << " cmdsize " << vd.cmdsize;
3778 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
3779 outs() << " Incorrect size\n";
3780 else
3781 outs() << "\n";
3782 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
3783 << ((vd.version >> 8) & 0xff);
3784 if ((vd.version & 0xff) != 0)
3785 outs() << "." << (vd.version & 0xff);
3786 outs() << "\n";
3787 if (vd.sdk == 0)
Kevin Enderby57538292014-12-17 01:01:30 +00003788 outs() << " sdk n/a";
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003789 else {
3790 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
3791 << ((vd.sdk >> 8) & 0xff);
3792 }
3793 if ((vd.sdk & 0xff) != 0)
3794 outs() << "." << (vd.sdk & 0xff);
3795 outs() << "\n";
3796}
3797
3798static void PrintSourceVersionCommand(MachO::source_version_command sd) {
3799 outs() << " cmd LC_SOURCE_VERSION\n";
3800 outs() << " cmdsize " << sd.cmdsize;
3801 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
3802 outs() << " Incorrect size\n";
3803 else
3804 outs() << "\n";
3805 uint64_t a = (sd.version >> 40) & 0xffffff;
3806 uint64_t b = (sd.version >> 30) & 0x3ff;
3807 uint64_t c = (sd.version >> 20) & 0x3ff;
3808 uint64_t d = (sd.version >> 10) & 0x3ff;
3809 uint64_t e = sd.version & 0x3ff;
3810 outs() << " version " << a << "." << b;
3811 if (e != 0)
3812 outs() << "." << c << "." << d << "." << e;
3813 else if (d != 0)
3814 outs() << "." << c << "." << d;
3815 else if (c != 0)
3816 outs() << "." << c;
3817 outs() << "\n";
3818}
3819
3820static void PrintEntryPointCommand(MachO::entry_point_command ep) {
3821 outs() << " cmd LC_MAIN\n";
3822 outs() << " cmdsize " << ep.cmdsize;
3823 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
3824 outs() << " Incorrect size\n";
3825 else
3826 outs() << "\n";
3827 outs() << " entryoff " << ep.entryoff << "\n";
3828 outs() << " stacksize " << ep.stacksize << "\n";
3829}
3830
Kevin Enderby0804f4672014-12-16 23:25:52 +00003831static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
3832 uint32_t object_size) {
3833 outs() << " cmd LC_ENCRYPTION_INFO\n";
3834 outs() << " cmdsize " << ec.cmdsize;
3835 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
3836 outs() << " Incorrect size\n";
3837 else
3838 outs() << "\n";
3839 outs() << " cryptoff " << ec.cryptoff;
3840 if (ec.cryptoff > object_size)
3841 outs() << " (past end of file)\n";
3842 else
3843 outs() << "\n";
3844 outs() << " cryptsize " << ec.cryptsize;
3845 if (ec.cryptsize > object_size)
3846 outs() << " (past end of file)\n";
3847 else
3848 outs() << "\n";
3849 outs() << " cryptid " << ec.cryptid << "\n";
3850}
3851
Kevin Enderby57538292014-12-17 01:01:30 +00003852static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00003853 uint32_t object_size) {
Kevin Enderby57538292014-12-17 01:01:30 +00003854 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
3855 outs() << " cmdsize " << ec.cmdsize;
3856 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
3857 outs() << " Incorrect size\n";
3858 else
3859 outs() << "\n";
3860 outs() << " cryptoff " << ec.cryptoff;
3861 if (ec.cryptoff > object_size)
3862 outs() << " (past end of file)\n";
3863 else
3864 outs() << "\n";
3865 outs() << " cryptsize " << ec.cryptsize;
3866 if (ec.cryptsize > object_size)
3867 outs() << " (past end of file)\n";
3868 else
3869 outs() << "\n";
3870 outs() << " cryptid " << ec.cryptid << "\n";
3871 outs() << " pad " << ec.pad << "\n";
3872}
3873
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00003874static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
3875 const char *Ptr) {
3876 outs() << " cmd LC_LINKER_OPTION\n";
3877 outs() << " cmdsize " << lo.cmdsize;
3878 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
3879 outs() << " Incorrect size\n";
3880 else
3881 outs() << "\n";
3882 outs() << " count " << lo.count << "\n";
3883 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
3884 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
3885 uint32_t i = 0;
3886 while (left > 0) {
3887 while (*string == '\0' && left > 0) {
3888 string++;
3889 left--;
3890 }
3891 if (left > 0) {
3892 i++;
3893 outs() << " string #" << i << " " << format("%.*s\n", left, string);
David Majnemerd4449ed2014-12-20 08:24:43 +00003894 uint32_t NullPos = StringRef(string, left).find('\0');
3895 uint32_t len = std::min(NullPos, left) + 1;
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00003896 string += len;
3897 left -= len;
3898 }
3899 }
3900 if (lo.count != i)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00003901 outs() << " count " << lo.count << " does not match number of strings "
3902 << i << "\n";
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00003903}
3904
Kevin Enderbyb4b79312014-12-18 19:24:35 +00003905static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
3906 const char *Ptr) {
3907 outs() << " cmd LC_SUB_FRAMEWORK\n";
3908 outs() << " cmdsize " << sub.cmdsize;
3909 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
3910 outs() << " Incorrect size\n";
3911 else
3912 outs() << "\n";
3913 if (sub.umbrella < sub.cmdsize) {
3914 const char *P = Ptr + sub.umbrella;
3915 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
3916 } else {
3917 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
3918 }
3919}
3920
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00003921static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
3922 const char *Ptr) {
3923 outs() << " cmd LC_SUB_UMBRELLA\n";
3924 outs() << " cmdsize " << sub.cmdsize;
3925 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
3926 outs() << " Incorrect size\n";
3927 else
3928 outs() << "\n";
3929 if (sub.sub_umbrella < sub.cmdsize) {
3930 const char *P = Ptr + sub.sub_umbrella;
3931 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
3932 } else {
3933 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
3934 }
3935}
3936
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00003937static void PrintSubLibraryCommand(MachO::sub_library_command sub,
Kevin Enderby66d51fc2015-01-08 00:25:24 +00003938 const char *Ptr) {
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00003939 outs() << " cmd LC_SUB_LIBRARY\n";
3940 outs() << " cmdsize " << sub.cmdsize;
3941 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
3942 outs() << " Incorrect size\n";
3943 else
3944 outs() << "\n";
3945 if (sub.sub_library < sub.cmdsize) {
3946 const char *P = Ptr + sub.sub_library;
3947 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
3948 } else {
3949 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
3950 }
3951}
3952
Kevin Enderby186eac32014-12-19 21:06:24 +00003953static void PrintSubClientCommand(MachO::sub_client_command sub,
3954 const char *Ptr) {
3955 outs() << " cmd LC_SUB_CLIENT\n";
3956 outs() << " cmdsize " << sub.cmdsize;
3957 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
3958 outs() << " Incorrect size\n";
3959 else
3960 outs() << "\n";
3961 if (sub.client < sub.cmdsize) {
3962 const char *P = Ptr + sub.client;
3963 outs() << " client " << P << " (offset " << sub.client << ")\n";
3964 } else {
3965 outs() << " client ?(bad offset " << sub.client << ")\n";
3966 }
3967}
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00003968
Kevin Enderby52e4ce42014-12-19 22:25:22 +00003969static void PrintRoutinesCommand(MachO::routines_command r) {
3970 outs() << " cmd LC_ROUTINES\n";
3971 outs() << " cmdsize " << r.cmdsize;
3972 if (r.cmdsize != sizeof(struct MachO::routines_command))
3973 outs() << " Incorrect size\n";
3974 else
3975 outs() << "\n";
3976 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
3977 outs() << " init_module " << r.init_module << "\n";
3978 outs() << " reserved1 " << r.reserved1 << "\n";
3979 outs() << " reserved2 " << r.reserved2 << "\n";
3980 outs() << " reserved3 " << r.reserved3 << "\n";
3981 outs() << " reserved4 " << r.reserved4 << "\n";
3982 outs() << " reserved5 " << r.reserved5 << "\n";
3983 outs() << " reserved6 " << r.reserved6 << "\n";
3984}
3985
3986static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
3987 outs() << " cmd LC_ROUTINES_64\n";
3988 outs() << " cmdsize " << r.cmdsize;
3989 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
3990 outs() << " Incorrect size\n";
3991 else
3992 outs() << "\n";
3993 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
3994 outs() << " init_module " << r.init_module << "\n";
3995 outs() << " reserved1 " << r.reserved1 << "\n";
3996 outs() << " reserved2 " << r.reserved2 << "\n";
3997 outs() << " reserved3 " << r.reserved3 << "\n";
3998 outs() << " reserved4 " << r.reserved4 << "\n";
3999 outs() << " reserved5 " << r.reserved5 << "\n";
4000 outs() << " reserved6 " << r.reserved6 << "\n";
4001}
4002
Kevin Enderby48ef5342014-12-23 22:56:39 +00004003static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
4004 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
4005 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
4006 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
4007 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
4008 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
4009 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
4010 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
4011 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
4012 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
4013 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
4014 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
4015 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
4016 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
4017 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
4018 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
4019 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
4020 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
4021 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
4022 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
4023 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
4024 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
4025}
4026
Kevin Enderby227df342014-12-23 23:43:59 +00004027static void Print_mmst_reg(MachO::mmst_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004028 uint32_t f;
4029 outs() << "\t mmst_reg ";
4030 for (f = 0; f < 10; f++)
4031 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
4032 outs() << "\n";
4033 outs() << "\t mmst_rsrv ";
4034 for (f = 0; f < 6; f++)
4035 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
4036 outs() << "\n";
4037}
4038
Kevin Enderbyaefb0032014-12-24 00:16:51 +00004039static void Print_xmm_reg(MachO::xmm_reg_t &r) {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004040 uint32_t f;
4041 outs() << "\t xmm_reg ";
4042 for (f = 0; f < 16; f++)
4043 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
4044 outs() << "\n";
4045}
4046
4047static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
4048 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
4049 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
4050 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
4051 outs() << " denorm " << fpu.fpu_fcw.denorm;
4052 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
4053 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
4054 outs() << " undfl " << fpu.fpu_fcw.undfl;
4055 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
4056 outs() << "\t\t pc ";
4057 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
4058 outs() << "FP_PREC_24B ";
4059 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
4060 outs() << "FP_PREC_53B ";
4061 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
4062 outs() << "FP_PREC_64B ";
4063 else
4064 outs() << fpu.fpu_fcw.pc << " ";
4065 outs() << "rc ";
4066 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
4067 outs() << "FP_RND_NEAR ";
4068 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
4069 outs() << "FP_RND_DOWN ";
4070 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
4071 outs() << "FP_RND_UP ";
4072 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004073 outs() << "FP_CHOP ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004074 outs() << "\n";
4075 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
4076 outs() << " denorm " << fpu.fpu_fsw.denorm;
4077 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
4078 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
4079 outs() << " undfl " << fpu.fpu_fsw.undfl;
4080 outs() << " precis " << fpu.fpu_fsw.precis;
4081 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
4082 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
4083 outs() << " c0 " << fpu.fpu_fsw.c0;
4084 outs() << " c1 " << fpu.fpu_fsw.c1;
4085 outs() << " c2 " << fpu.fpu_fsw.c2;
4086 outs() << " tos " << fpu.fpu_fsw.tos;
4087 outs() << " c3 " << fpu.fpu_fsw.c3;
4088 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
4089 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
4090 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
4091 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
4092 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
4093 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
4094 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
4095 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
4096 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
4097 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
4098 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
4099 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
4100 outs() << "\n";
4101 outs() << "\t fpu_stmm0:\n";
4102 Print_mmst_reg(fpu.fpu_stmm0);
4103 outs() << "\t fpu_stmm1:\n";
4104 Print_mmst_reg(fpu.fpu_stmm1);
4105 outs() << "\t fpu_stmm2:\n";
4106 Print_mmst_reg(fpu.fpu_stmm2);
4107 outs() << "\t fpu_stmm3:\n";
4108 Print_mmst_reg(fpu.fpu_stmm3);
4109 outs() << "\t fpu_stmm4:\n";
4110 Print_mmst_reg(fpu.fpu_stmm4);
4111 outs() << "\t fpu_stmm5:\n";
4112 Print_mmst_reg(fpu.fpu_stmm5);
4113 outs() << "\t fpu_stmm6:\n";
4114 Print_mmst_reg(fpu.fpu_stmm6);
4115 outs() << "\t fpu_stmm7:\n";
4116 Print_mmst_reg(fpu.fpu_stmm7);
4117 outs() << "\t fpu_xmm0:\n";
4118 Print_xmm_reg(fpu.fpu_xmm0);
4119 outs() << "\t fpu_xmm1:\n";
4120 Print_xmm_reg(fpu.fpu_xmm1);
4121 outs() << "\t fpu_xmm2:\n";
4122 Print_xmm_reg(fpu.fpu_xmm2);
4123 outs() << "\t fpu_xmm3:\n";
4124 Print_xmm_reg(fpu.fpu_xmm3);
4125 outs() << "\t fpu_xmm4:\n";
4126 Print_xmm_reg(fpu.fpu_xmm4);
4127 outs() << "\t fpu_xmm5:\n";
4128 Print_xmm_reg(fpu.fpu_xmm5);
4129 outs() << "\t fpu_xmm6:\n";
4130 Print_xmm_reg(fpu.fpu_xmm6);
4131 outs() << "\t fpu_xmm7:\n";
4132 Print_xmm_reg(fpu.fpu_xmm7);
4133 outs() << "\t fpu_xmm8:\n";
4134 Print_xmm_reg(fpu.fpu_xmm8);
4135 outs() << "\t fpu_xmm9:\n";
4136 Print_xmm_reg(fpu.fpu_xmm9);
4137 outs() << "\t fpu_xmm10:\n";
4138 Print_xmm_reg(fpu.fpu_xmm10);
4139 outs() << "\t fpu_xmm11:\n";
4140 Print_xmm_reg(fpu.fpu_xmm11);
4141 outs() << "\t fpu_xmm12:\n";
4142 Print_xmm_reg(fpu.fpu_xmm12);
4143 outs() << "\t fpu_xmm13:\n";
4144 Print_xmm_reg(fpu.fpu_xmm13);
4145 outs() << "\t fpu_xmm14:\n";
4146 Print_xmm_reg(fpu.fpu_xmm14);
4147 outs() << "\t fpu_xmm15:\n";
4148 Print_xmm_reg(fpu.fpu_xmm15);
4149 outs() << "\t fpu_rsrv4:\n";
4150 for (uint32_t f = 0; f < 6; f++) {
4151 outs() << "\t ";
4152 for (uint32_t g = 0; g < 16; g++)
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004153 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004154 outs() << "\n";
4155 }
4156 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
4157 outs() << "\n";
4158}
4159
4160static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
4161 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
4162 outs() << " err " << format("0x%08" PRIx32, exc64.err);
4163 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
4164}
4165
4166static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
4167 bool isLittleEndian, uint32_t cputype) {
4168 if (t.cmd == MachO::LC_THREAD)
4169 outs() << " cmd LC_THREAD\n";
4170 else if (t.cmd == MachO::LC_UNIXTHREAD)
4171 outs() << " cmd LC_UNIXTHREAD\n";
4172 else
4173 outs() << " cmd " << t.cmd << " (unknown)\n";
4174 outs() << " cmdsize " << t.cmdsize;
4175 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
4176 outs() << " Incorrect size\n";
4177 else
4178 outs() << "\n";
4179
4180 const char *begin = Ptr + sizeof(struct MachO::thread_command);
4181 const char *end = Ptr + t.cmdsize;
4182 uint32_t flavor, count, left;
4183 if (cputype == MachO::CPU_TYPE_X86_64) {
4184 while (begin < end) {
4185 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4186 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4187 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004188 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004189 flavor = 0;
4190 begin = end;
4191 }
4192 if (isLittleEndian != sys::IsLittleEndianHost)
4193 sys::swapByteOrder(flavor);
4194 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4195 memcpy((char *)&count, begin, sizeof(uint32_t));
4196 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004197 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004198 count = 0;
4199 begin = end;
4200 }
4201 if (isLittleEndian != sys::IsLittleEndianHost)
4202 sys::swapByteOrder(count);
4203 if (flavor == MachO::x86_THREAD_STATE64) {
4204 outs() << " flavor x86_THREAD_STATE64\n";
4205 if (count == MachO::x86_THREAD_STATE64_COUNT)
4206 outs() << " count x86_THREAD_STATE64_COUNT\n";
4207 else
4208 outs() << " count " << count
4209 << " (not x86_THREAD_STATE64_COUNT)\n";
4210 MachO::x86_thread_state64_t cpu64;
4211 left = end - begin;
4212 if (left >= sizeof(MachO::x86_thread_state64_t)) {
4213 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
4214 begin += sizeof(MachO::x86_thread_state64_t);
4215 } else {
4216 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
4217 memcpy(&cpu64, begin, left);
4218 begin += left;
4219 }
4220 if (isLittleEndian != sys::IsLittleEndianHost)
4221 swapStruct(cpu64);
4222 Print_x86_thread_state64_t(cpu64);
4223 } else if (flavor == MachO::x86_THREAD_STATE) {
4224 outs() << " flavor x86_THREAD_STATE\n";
4225 if (count == MachO::x86_THREAD_STATE_COUNT)
4226 outs() << " count x86_THREAD_STATE_COUNT\n";
4227 else
4228 outs() << " count " << count
4229 << " (not x86_THREAD_STATE_COUNT)\n";
4230 struct MachO::x86_thread_state_t ts;
4231 left = end - begin;
4232 if (left >= sizeof(MachO::x86_thread_state_t)) {
4233 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
4234 begin += sizeof(MachO::x86_thread_state_t);
4235 } else {
4236 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
4237 memcpy(&ts, begin, left);
4238 begin += left;
4239 }
4240 if (isLittleEndian != sys::IsLittleEndianHost)
4241 swapStruct(ts);
4242 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
4243 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
4244 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
4245 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
4246 else
4247 outs() << "tsh.count " << ts.tsh.count
4248 << " (not x86_THREAD_STATE64_COUNT\n";
4249 Print_x86_thread_state64_t(ts.uts.ts64);
4250 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004251 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
4252 << ts.tsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004253 }
4254 } else if (flavor == MachO::x86_FLOAT_STATE) {
4255 outs() << " flavor x86_FLOAT_STATE\n";
4256 if (count == MachO::x86_FLOAT_STATE_COUNT)
4257 outs() << " count x86_FLOAT_STATE_COUNT\n";
4258 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004259 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004260 struct MachO::x86_float_state_t fs;
4261 left = end - begin;
4262 if (left >= sizeof(MachO::x86_float_state_t)) {
4263 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
4264 begin += sizeof(MachO::x86_float_state_t);
4265 } else {
4266 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
4267 memcpy(&fs, begin, left);
4268 begin += left;
4269 }
4270 if (isLittleEndian != sys::IsLittleEndianHost)
4271 swapStruct(fs);
4272 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
4273 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004274 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00004275 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
4276 else
4277 outs() << "fsh.count " << fs.fsh.count
4278 << " (not x86_FLOAT_STATE64_COUNT\n";
4279 Print_x86_float_state_t(fs.ufs.fs64);
4280 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004281 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
4282 << fs.fsh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004283 }
4284 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
4285 outs() << " flavor x86_EXCEPTION_STATE\n";
4286 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
4287 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
4288 else
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004289 outs() << " count " << count
Kevin Enderby48ef5342014-12-23 22:56:39 +00004290 << " (not x86_EXCEPTION_STATE_COUNT)\n";
4291 struct MachO::x86_exception_state_t es;
4292 left = end - begin;
4293 if (left >= sizeof(MachO::x86_exception_state_t)) {
4294 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
4295 begin += sizeof(MachO::x86_exception_state_t);
4296 } else {
4297 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
4298 memcpy(&es, begin, left);
4299 begin += left;
4300 }
4301 if (isLittleEndian != sys::IsLittleEndianHost)
4302 swapStruct(es);
4303 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
4304 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004305 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
Kevin Enderby48ef5342014-12-23 22:56:39 +00004306 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
4307 else
4308 outs() << "\t esh.count " << es.esh.count
4309 << " (not x86_EXCEPTION_STATE64_COUNT\n";
4310 Print_x86_exception_state_t(es.ues.es64);
4311 } else {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004312 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
4313 << es.esh.count << "\n";
Kevin Enderby48ef5342014-12-23 22:56:39 +00004314 }
4315 } else {
4316 outs() << " flavor " << flavor << " (unknown)\n";
4317 outs() << " count " << count << "\n";
4318 outs() << " state (unknown)\n";
4319 begin += count * sizeof(uint32_t);
4320 }
4321 }
4322 } else {
4323 while (begin < end) {
4324 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4325 memcpy((char *)&flavor, begin, sizeof(uint32_t));
4326 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004327 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004328 flavor = 0;
4329 begin = end;
4330 }
4331 if (isLittleEndian != sys::IsLittleEndianHost)
4332 sys::swapByteOrder(flavor);
4333 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
4334 memcpy((char *)&count, begin, sizeof(uint32_t));
4335 begin += sizeof(uint32_t);
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004336 } else {
Kevin Enderby48ef5342014-12-23 22:56:39 +00004337 count = 0;
4338 begin = end;
4339 }
4340 if (isLittleEndian != sys::IsLittleEndianHost)
4341 sys::swapByteOrder(count);
4342 outs() << " flavor " << flavor << "\n";
4343 outs() << " count " << count << "\n";
4344 outs() << " state (Unknown cputype/cpusubtype)\n";
4345 begin += count * sizeof(uint32_t);
4346 }
4347 }
4348}
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004349
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004350static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
4351 if (dl.cmd == MachO::LC_ID_DYLIB)
4352 outs() << " cmd LC_ID_DYLIB\n";
4353 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
4354 outs() << " cmd LC_LOAD_DYLIB\n";
4355 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
4356 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
4357 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
4358 outs() << " cmd LC_REEXPORT_DYLIB\n";
4359 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
4360 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
4361 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
4362 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
4363 else
4364 outs() << " cmd " << dl.cmd << " (unknown)\n";
4365 outs() << " cmdsize " << dl.cmdsize;
4366 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
4367 outs() << " Incorrect size\n";
4368 else
4369 outs() << "\n";
4370 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004371 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004372 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
4373 } else {
4374 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
4375 }
4376 outs() << " time stamp " << dl.dylib.timestamp << " ";
4377 time_t t = dl.dylib.timestamp;
4378 outs() << ctime(&t);
4379 outs() << " current version ";
4380 if (dl.dylib.current_version == 0xffffffff)
4381 outs() << "n/a\n";
4382 else
4383 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
4384 << ((dl.dylib.current_version >> 8) & 0xff) << "."
4385 << (dl.dylib.current_version & 0xff) << "\n";
4386 outs() << "compatibility version ";
4387 if (dl.dylib.compatibility_version == 0xffffffff)
4388 outs() << "n/a\n";
4389 else
4390 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
4391 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
4392 << (dl.dylib.compatibility_version & 0xff) << "\n";
4393}
4394
4395static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
4396 uint32_t object_size) {
4397 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
4398 outs() << " cmd LC_FUNCTION_STARTS\n";
4399 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
4400 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
4401 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
4402 outs() << " cmd LC_FUNCTION_STARTS\n";
4403 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
4404 outs() << " cmd LC_DATA_IN_CODE\n";
4405 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
4406 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
4407 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
4408 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
4409 else
4410 outs() << " cmd " << ld.cmd << " (?)\n";
4411 outs() << " cmdsize " << ld.cmdsize;
4412 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
4413 outs() << " Incorrect size\n";
4414 else
4415 outs() << "\n";
4416 outs() << " dataoff " << ld.dataoff;
4417 if (ld.dataoff > object_size)
4418 outs() << " (past end of file)\n";
4419 else
4420 outs() << "\n";
4421 outs() << " datasize " << ld.datasize;
4422 uint64_t big_size = ld.dataoff;
4423 big_size += ld.datasize;
4424 if (big_size > object_size)
4425 outs() << " (past end of file)\n";
4426 else
4427 outs() << "\n";
4428}
4429
Kevin Enderby956366c2014-08-29 22:30:52 +00004430static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
4431 uint32_t filetype, uint32_t cputype,
4432 bool verbose) {
Filipe Cabecinhase71bd0c2015-01-06 17:08:26 +00004433 if (ncmds == 0)
4434 return;
Kevin Enderby956366c2014-08-29 22:30:52 +00004435 StringRef Buf = Obj->getData();
4436 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
4437 for (unsigned i = 0;; ++i) {
4438 outs() << "Load command " << i << "\n";
4439 if (Command.C.cmd == MachO::LC_SEGMENT) {
4440 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
4441 const char *sg_segname = SLC.segname;
4442 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
4443 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
4444 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
4445 verbose);
4446 for (unsigned j = 0; j < SLC.nsects; j++) {
Kevin Enderbyc9713382014-12-16 01:14:45 +00004447 MachO::section S = Obj->getSection(Command, j);
Kevin Enderby956366c2014-08-29 22:30:52 +00004448 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
4449 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
4450 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
4451 }
4452 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
4453 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
4454 const char *sg_segname = SLC_64.segname;
4455 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
4456 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
4457 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
4458 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
4459 for (unsigned j = 0; j < SLC_64.nsects; j++) {
4460 MachO::section_64 S_64 = Obj->getSection64(Command, j);
4461 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
4462 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
4463 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
4464 sg_segname, filetype, Buf.size(), verbose);
4465 }
4466 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
4467 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00004468 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00004469 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
4470 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
4471 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00004472 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
4473 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004474 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
4475 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
4476 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
4477 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
4478 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
4479 Command.C.cmd == MachO::LC_ID_DYLINKER ||
4480 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
4481 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
4482 PrintDyldLoadCommand(Dyld, Command.Ptr);
4483 } else if (Command.C.cmd == MachO::LC_UUID) {
4484 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
4485 PrintUuidLoadCommand(Uuid);
Jean-Daniel Dupas00cc1f52014-12-04 07:37:02 +00004486 } else if (Command.C.cmd == MachO::LC_RPATH) {
4487 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
4488 PrintRpathLoadCommand(Rpath, Command.Ptr);
Kevin Enderby1ff0ecc2014-12-16 21:48:27 +00004489 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
4490 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004491 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
4492 PrintVersionMinLoadCommand(Vd);
4493 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
4494 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
4495 PrintSourceVersionCommand(Sd);
4496 } else if (Command.C.cmd == MachO::LC_MAIN) {
4497 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
4498 PrintEntryPointCommand(Ep);
Kevin Enderby0804f4672014-12-16 23:25:52 +00004499 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004500 MachO::encryption_info_command Ei =
4501 Obj->getEncryptionInfoCommand(Command);
Kevin Enderby0804f4672014-12-16 23:25:52 +00004502 PrintEncryptionInfoCommand(Ei, Buf.size());
Kevin Enderby57538292014-12-17 01:01:30 +00004503 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004504 MachO::encryption_info_command_64 Ei =
4505 Obj->getEncryptionInfoCommand64(Command);
Kevin Enderby57538292014-12-17 01:01:30 +00004506 PrintEncryptionInfoCommand64(Ei, Buf.size());
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004507 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
Kevin Enderby66d51fc2015-01-08 00:25:24 +00004508 MachO::linker_option_command Lo =
4509 Obj->getLinkerOptionLoadCommand(Command);
Kevin Enderbyd0b6b7f2014-12-18 00:53:40 +00004510 PrintLinkerOptionCommand(Lo, Command.Ptr);
Kevin Enderbyb4b79312014-12-18 19:24:35 +00004511 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
4512 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
4513 PrintSubFrameworkCommand(Sf, Command.Ptr);
Kevin Enderbya2bd8d92014-12-18 23:13:26 +00004514 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
4515 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
4516 PrintSubUmbrellaCommand(Sf, Command.Ptr);
Kevin Enderby36c8d3a2014-12-19 19:48:16 +00004517 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
4518 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
4519 PrintSubLibraryCommand(Sl, Command.Ptr);
Kevin Enderby186eac32014-12-19 21:06:24 +00004520 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
4521 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
4522 PrintSubClientCommand(Sc, Command.Ptr);
Kevin Enderby52e4ce42014-12-19 22:25:22 +00004523 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
4524 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
4525 PrintRoutinesCommand(Rc);
4526 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
4527 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
4528 PrintRoutinesCommand64(Rc);
Kevin Enderby48ef5342014-12-23 22:56:39 +00004529 } else if (Command.C.cmd == MachO::LC_THREAD ||
4530 Command.C.cmd == MachO::LC_UNIXTHREAD) {
4531 MachO::thread_command Tc = Obj->getThreadCommand(Command);
4532 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
Nick Kledzik15558912014-10-16 18:58:20 +00004533 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
4534 Command.C.cmd == MachO::LC_ID_DYLIB ||
4535 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
4536 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
4537 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
4538 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00004539 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
4540 PrintDylibCommand(Dl, Command.Ptr);
4541 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
4542 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
4543 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
4544 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
4545 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
4546 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
4547 MachO::linkedit_data_command Ld =
4548 Obj->getLinkeditDataLoadCommand(Command);
4549 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00004550 } else {
4551 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
4552 << ")\n";
4553 outs() << " cmdsize " << Command.C.cmdsize << "\n";
4554 // TODO: get and print the raw bytes of the load command.
4555 }
4556 // TODO: print all the other kinds of load commands.
4557 if (i == ncmds - 1)
4558 break;
4559 else
4560 Command = Obj->getNextLoadCommandInfo(Command);
4561 }
4562}
4563
4564static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
4565 uint32_t &filetype, uint32_t &cputype,
4566 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004567 if (Obj->is64Bit()) {
4568 MachO::mach_header_64 H_64;
4569 H_64 = Obj->getHeader64();
4570 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
4571 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00004572 ncmds = H_64.ncmds;
4573 filetype = H_64.filetype;
4574 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004575 } else {
4576 MachO::mach_header H;
4577 H = Obj->getHeader();
4578 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
4579 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00004580 ncmds = H.ncmds;
4581 filetype = H.filetype;
4582 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004583 }
4584}
4585
4586void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
4587 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00004588 uint32_t ncmds = 0;
4589 uint32_t filetype = 0;
4590 uint32_t cputype = 0;
4591 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
4592 PrintLoadCommands(file, ncmds, filetype, cputype, true);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00004593}
Nick Kledzikd04bc352014-08-30 00:20:14 +00004594
4595//===----------------------------------------------------------------------===//
4596// export trie dumping
4597//===----------------------------------------------------------------------===//
4598
4599void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004600 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
4601 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00004602 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
4603 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
4604 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4605 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
4606 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
4607 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
4608 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
4609 if (ReExport)
4610 outs() << "[re-export] ";
4611 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004612 outs() << format("0x%08llX ",
4613 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004614 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00004615 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004616 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00004617 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00004618 if (WeakDef) {
4619 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004620 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004621 }
4622 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004623 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00004624 outs() << ", ";
4625 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004626 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004627 }
4628 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004629 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00004630 outs() << ", ";
4631 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004632 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004633 }
4634 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004635 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00004636 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004637 outs() << format("resolver=0x%08llX", Entry.other());
4638 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00004639 }
4640 outs() << "]";
4641 }
4642 if (ReExport) {
4643 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004644 int Ordinal = Entry.other() - 1;
4645 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
4646 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00004647 outs() << " (from " << DylibName << ")";
4648 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00004649 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00004650 }
4651 outs() << "\n";
4652 }
4653}
Nick Kledzikac431442014-09-12 21:34:15 +00004654
Nick Kledzikac431442014-09-12 21:34:15 +00004655//===----------------------------------------------------------------------===//
4656// rebase table dumping
4657//===----------------------------------------------------------------------===//
4658
4659namespace {
4660class SegInfo {
4661public:
4662 SegInfo(const object::MachOObjectFile *Obj);
4663
4664 StringRef segmentName(uint32_t SegIndex);
4665 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
4666 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
4667
4668private:
4669 struct SectionInfo {
4670 uint64_t Address;
4671 uint64_t Size;
4672 StringRef SectionName;
4673 StringRef SegmentName;
4674 uint64_t OffsetInSegment;
4675 uint64_t SegmentStartAddress;
4676 uint32_t SegmentIndex;
4677 };
4678 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
4679 SmallVector<SectionInfo, 32> Sections;
4680};
4681}
4682
4683SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
4684 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00004685 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00004686 StringRef CurSegName;
4687 uint64_t CurSegAddress;
4688 for (const SectionRef &Section : Obj->sections()) {
4689 SectionInfo Info;
4690 if (error(Section.getName(Info.SectionName)))
4691 return;
Rafael Espindola80291272014-10-08 15:28:58 +00004692 Info.Address = Section.getAddress();
4693 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00004694 Info.SegmentName =
4695 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
4696 if (!Info.SegmentName.equals(CurSegName)) {
4697 ++CurSegIndex;
4698 CurSegName = Info.SegmentName;
4699 CurSegAddress = Info.Address;
4700 }
4701 Info.SegmentIndex = CurSegIndex - 1;
4702 Info.OffsetInSegment = Info.Address - CurSegAddress;
4703 Info.SegmentStartAddress = CurSegAddress;
4704 Sections.push_back(Info);
4705 }
4706}
4707
4708StringRef SegInfo::segmentName(uint32_t SegIndex) {
4709 for (const SectionInfo &SI : Sections) {
4710 if (SI.SegmentIndex == SegIndex)
4711 return SI.SegmentName;
4712 }
4713 llvm_unreachable("invalid segIndex");
4714}
4715
4716const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
4717 uint64_t OffsetInSeg) {
4718 for (const SectionInfo &SI : Sections) {
4719 if (SI.SegmentIndex != SegIndex)
4720 continue;
4721 if (SI.OffsetInSegment > OffsetInSeg)
4722 continue;
4723 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
4724 continue;
4725 return SI;
4726 }
4727 llvm_unreachable("segIndex and offset not in any section");
4728}
4729
4730StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
4731 return findSection(SegIndex, OffsetInSeg).SectionName;
4732}
4733
4734uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
4735 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
4736 return SI.SegmentStartAddress + OffsetInSeg;
4737}
4738
4739void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
4740 // Build table of sections so names can used in final output.
4741 SegInfo sectionTable(Obj);
4742
4743 outs() << "segment section address type\n";
4744 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
4745 uint32_t SegIndex = Entry.segmentIndex();
4746 uint64_t OffsetInSeg = Entry.segmentOffset();
4747 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4748 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4749 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4750
4751 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004752 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
4753 SegmentName.str().c_str(), SectionName.str().c_str(),
4754 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00004755 }
4756}
Nick Kledzik56ebef42014-09-16 01:41:51 +00004757
4758static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
4759 StringRef DylibName;
4760 switch (Ordinal) {
4761 case MachO::BIND_SPECIAL_DYLIB_SELF:
4762 return "this-image";
4763 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
4764 return "main-executable";
4765 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
4766 return "flat-namespace";
4767 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00004768 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004769 std::error_code EC =
4770 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00004771 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00004772 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00004773 return DylibName;
4774 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00004775 }
Nick Kledzikabd29872014-09-16 22:03:13 +00004776 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00004777}
4778
4779//===----------------------------------------------------------------------===//
4780// bind table dumping
4781//===----------------------------------------------------------------------===//
4782
4783void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
4784 // Build table of sections so names can used in final output.
4785 SegInfo sectionTable(Obj);
4786
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004787 outs() << "segment section address type "
4788 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00004789 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
4790 uint32_t SegIndex = Entry.segmentIndex();
4791 uint64_t OffsetInSeg = Entry.segmentOffset();
4792 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4793 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4794 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4795
4796 // Table lines look like:
4797 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004798 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00004799 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004800 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004801 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004802 << left_justify(SectionName, 18) << " "
4803 << format_hex(Address, 10, true) << " "
4804 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004805 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004806 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004807 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00004808 }
4809}
4810
4811//===----------------------------------------------------------------------===//
4812// lazy bind table dumping
4813//===----------------------------------------------------------------------===//
4814
4815void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
4816 // Build table of sections so names can used in final output.
4817 SegInfo sectionTable(Obj);
4818
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004819 outs() << "segment section address "
4820 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00004821 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
4822 uint32_t SegIndex = Entry.segmentIndex();
4823 uint64_t OffsetInSeg = Entry.segmentOffset();
4824 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4825 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4826 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4827
4828 // Table lines look like:
4829 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004830 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004831 << left_justify(SectionName, 18) << " "
4832 << format_hex(Address, 10, true) << " "
4833 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00004834 << Entry.symbolName() << "\n";
4835 }
4836}
4837
Nick Kledzik56ebef42014-09-16 01:41:51 +00004838//===----------------------------------------------------------------------===//
4839// weak bind table dumping
4840//===----------------------------------------------------------------------===//
4841
4842void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
4843 // Build table of sections so names can used in final output.
4844 SegInfo sectionTable(Obj);
4845
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004846 outs() << "segment section address "
4847 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00004848 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
4849 // Strong symbols don't have a location to update.
4850 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004851 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00004852 << Entry.symbolName() << "\n";
4853 continue;
4854 }
4855 uint32_t SegIndex = Entry.segmentIndex();
4856 uint64_t OffsetInSeg = Entry.segmentOffset();
4857 StringRef SegmentName = sectionTable.segmentName(SegIndex);
4858 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
4859 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4860
4861 // Table lines look like:
4862 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004863 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00004864 << left_justify(SectionName, 18) << " "
4865 << format_hex(Address, 10, true) << " "
4866 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00004867 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
4868 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00004869 }
4870}
4871
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004872// get_dyld_bind_info_symbolname() is used for disassembly and passed an
4873// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
4874// information for that address. If the address is found its binding symbol
4875// name is returned. If not nullptr is returned.
4876static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4877 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00004878 if (info->bindtable == nullptr) {
4879 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004880 SegInfo sectionTable(info->O);
4881 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
4882 uint32_t SegIndex = Entry.segmentIndex();
4883 uint64_t OffsetInSeg = Entry.segmentOffset();
4884 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
4885 const char *SymbolName = nullptr;
4886 StringRef name = Entry.symbolName();
4887 if (!name.empty())
4888 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00004889 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004890 }
4891 }
Kevin Enderby078be602014-10-23 19:53:12 +00004892 for (bind_table_iterator BI = info->bindtable->begin(),
4893 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00004894 BI != BE; ++BI) {
4895 uint64_t Address = BI->first;
4896 if (ReferenceValue == Address) {
4897 const char *SymbolName = BI->second;
4898 return SymbolName;
4899 }
4900 }
4901 return nullptr;
4902}