blob: 3a28703ab0d6cbb2376a6cbb5af075d3789791a2 [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"
Rafael Espindola9b709252013-04-13 01:45:40 +000031#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000034#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/Format.h"
36#include "llvm/Support/GraphWriter.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/MemoryBuffer.h"
Kevin Enderbybf246f52014-09-24 23:08:22 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/TargetRegistry.h"
41#include "llvm/Support/TargetSelect.h"
42#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include <algorithm>
44#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000045#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000046
47#if HAVE_CXXABI_H
48#include <cxxabi.h>
49#endif
50
Benjamin Kramer43a772e2011-09-19 17:56:04 +000051using namespace llvm;
52using namespace object;
53
54static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000055 UseDbg("g",
56 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000057
Kevin Enderbyb28ed012014-10-29 21:28:24 +000058static cl::opt<std::string> DSYMFile("dsym",
59 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000060
Kevin Enderbyb28ed012014-10-29 21:28:24 +000061static cl::opt<bool> FullLeadingAddr("full-leading-addr",
62 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000063
64static cl::opt<bool>
65 PrintImmHex("print-imm-hex",
66 cl::desc("Use hex format for immediate values"));
67
Kevin Enderbyec5ca032014-08-18 20:21:02 +000068static std::string ThumbTripleName;
69
70static const Target *GetTarget(const MachOObjectFile *MachOObj,
71 const char **McpuDefault,
72 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +000073 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000074 if (TripleName.empty()) {
75 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +000076 llvm::Triple ThumbTriple = Triple();
77 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000078 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +000079 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +000080 }
81
Benjamin Kramer43a772e2011-09-19 17:56:04 +000082 // Get the target specific parser.
83 std::string Error;
84 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +000085 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +000086 return TheTarget;
87
Kevin Enderbyec5ca032014-08-18 20:21:02 +000088 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
89 if (*ThumbTarget)
90 return TheTarget;
91
92 errs() << "llvm-objdump: error: unable to get target for '";
93 if (!TheTarget)
94 errs() << TripleName;
95 else
96 errs() << ThumbTripleName;
97 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +000098 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +000099}
100
Owen Andersond9243c42011-10-17 21:37:35 +0000101struct SymbolSorter {
102 bool operator()(const SymbolRef &A, const SymbolRef &B) {
103 SymbolRef::Type AType, BType;
104 A.getType(AType);
105 B.getType(BType);
106
107 uint64_t AAddr, BAddr;
108 if (AType != SymbolRef::ST_Function)
109 AAddr = 0;
110 else
111 A.getAddress(AAddr);
112 if (BType != SymbolRef::ST_Function)
113 BAddr = 0;
114 else
115 B.getAddress(BAddr);
116 return AAddr < BAddr;
117 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000118};
119
Kevin Enderby273ae012013-06-06 17:20:50 +0000120// Types for the storted data in code table that is built before disassembly
121// and the predicate function to sort them.
122typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
123typedef std::vector<DiceTableEntry> DiceTable;
124typedef DiceTable::iterator dice_table_iterator;
125
Kevin Enderby930fdc72014-11-06 19:00:13 +0000126// This is used to search for a data in code table entry for the PC being
127// disassembled. The j parameter has the PC in j.first. A single data in code
128// table entry can cover many bytes for each of its Kind's. So if the offset,
129// aka the i.first value, of the data in code table entry plus its Length
130// covers the PC being searched for this will return true. If not it will
131// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000132static bool compareDiceTableEntries(const DiceTableEntry &i,
133 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000134 uint16_t Length;
135 i.second.getLength(Length);
136
137 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000138}
139
Kevin Enderby930fdc72014-11-06 19:00:13 +0000140static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
141 unsigned short Kind) {
142 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000143
144 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000145 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000146 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000147 if (Length >= 4) {
148 if (!NoShowRawInsn)
149 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000150 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000151 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000152 Size = 4;
153 } else if (Length >= 2) {
154 if (!NoShowRawInsn)
155 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000156 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000157 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000158 Size = 2;
159 } else {
160 if (!NoShowRawInsn)
161 DumpBytes(StringRef(bytes, 2));
Kevin Enderby273ae012013-06-06 17:20:50 +0000162 Value = bytes[0];
163 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000164 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000165 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000166 if (Kind == MachO::DICE_KIND_DATA)
167 outs() << "\t@ KIND_DATA\n";
168 else
169 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000170 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000171 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000172 if (!NoShowRawInsn)
173 DumpBytes(StringRef(bytes, 1));
Kevin Enderby273ae012013-06-06 17:20:50 +0000174 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000175 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
176 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000177 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000178 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000179 if (!NoShowRawInsn)
180 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000181 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000182 outs() << "\t.short " << format("%5u", Value & 0xffff)
183 << "\t@ KIND_JUMP_TABLE16\n";
184 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000185 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000186 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000187 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
188 if (!NoShowRawInsn)
189 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000190 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000191 outs() << "\t.long " << Value;
192 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
193 outs() << "\t@ KIND_JUMP_TABLE32\n";
194 else
195 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
196 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000197 break;
198 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000199 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000200}
201
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000202static void getSectionsAndSymbols(const MachO::mach_header Header,
203 MachOObjectFile *MachOObj,
204 std::vector<SectionRef> &Sections,
205 std::vector<SymbolRef> &Symbols,
206 SmallVectorImpl<uint64_t> &FoundFns,
207 uint64_t &BaseSegmentAddress) {
208 for (const SymbolRef &Symbol : MachOObj->symbols())
209 Symbols.push_back(Symbol);
Owen Andersond9243c42011-10-17 21:37:35 +0000210
Alexey Samsonov48803e52014-03-13 14:37:36 +0000211 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000212 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000213 Section.getName(SectName);
214 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000215 }
216
Rafael Espindola56f976f2013-04-18 18:08:55 +0000217 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000218 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000219 bool BaseSegmentAddressSet = false;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000220 for (unsigned i = 0;; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000221 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000222 // We found a function starts segment, parse the addresses for later
223 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000224 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000225 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000226
Charles Davis8bdfafd2013-09-01 04:28:48 +0000227 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000228 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
229 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000230 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000231 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000232 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000233 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000234 }
235 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000236
Charles Davis8bdfafd2013-09-01 04:28:48 +0000237 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000238 break;
239 else
240 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000241 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000242}
243
Rafael Espindola9b709252013-04-13 01:45:40 +0000244static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindola56f976f2013-04-18 18:08:55 +0000245 MachOObjectFile *MachOOF);
Rafael Espindola9b709252013-04-13 01:45:40 +0000246
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000247void llvm::DisassembleInputMachO(StringRef Filename) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000248 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000249 MemoryBuffer::getFileOrSTDIN(Filename);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000250 if (std::error_code EC = BuffOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000251 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000252 return;
253 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000254 std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000255
Rafael Espindola48af1c22014-08-19 18:44:46 +0000256 std::unique_ptr<MachOObjectFile> MachOOF = std::move(
257 ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000258
Rafael Espindola56f976f2013-04-18 18:08:55 +0000259 DisassembleInputMachO2(Filename, MachOOF.get());
Rafael Espindola9b709252013-04-13 01:45:40 +0000260}
261
Kevin Enderbybf246f52014-09-24 23:08:22 +0000262typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000263typedef std::pair<uint64_t, const char *> BindInfoEntry;
264typedef std::vector<BindInfoEntry> BindTable;
265typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000266
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000267// The block of info used by the Symbolizer call backs.
268struct DisassembleInfo {
269 bool verbose;
270 MachOObjectFile *O;
271 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000272 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000273 std::vector<SectionRef> *Sections;
274 const char *class_name;
275 const char *selector_name;
276 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +0000277 char *demangled_name;
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000278 uint64_t adrp_addr;
279 uint32_t adrp_inst;
Kevin Enderby078be602014-10-23 19:53:12 +0000280 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000281};
282
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000283// GuessSymbolName is passed the address of what might be a symbol and a
284// pointer to the DisassembleInfo struct. It returns the name of a symbol
285// with that address or nullptr if no symbol is found with that address.
286static const char *GuessSymbolName(uint64_t value,
287 struct DisassembleInfo *info) {
288 const char *SymbolName = nullptr;
289 // A DenseMap can't lookup up some values.
290 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
291 StringRef name = info->AddrMap->lookup(value);
292 if (!name.empty())
293 SymbolName = name.data();
294 }
295 return SymbolName;
296}
297
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000298// SymbolizerGetOpInfo() is the operand information call back function.
299// This is called to get the symbolic information for operand(s) of an
300// instruction when it is being done. This routine does this from
301// the relocation information, symbol table, etc. That block of information
302// is a pointer to the struct DisassembleInfo that was passed when the
303// disassembler context was created and passed to back to here when
304// called back by the disassembler for instruction operands that could have
305// relocation information. The address of the instruction containing operand is
306// at the Pc parameter. The immediate value the operand has is passed in
307// op_info->Value and is at Offset past the start of the instruction and has a
308// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
309// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
310// names and addends of the symbolic expression to add for the operand. The
311// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
312// information is returned then this function returns 1 else it returns 0.
313int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
314 uint64_t Size, int TagType, void *TagBuf) {
315 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
316 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000317 uint64_t value = op_info->Value;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000318
319 // Make sure all fields returned are zero if we don't set them.
320 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
321 op_info->Value = value;
322
323 // If the TagType is not the value 1 which it code knows about or if no
324 // verbose symbolic information is wanted then just return 0, indicating no
325 // information is being returned.
326 if (TagType != 1 || info->verbose == false)
327 return 0;
328
329 unsigned int Arch = info->O->getArch();
330 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000331 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
332 return 0;
333 // First search the section's relocation entries (if any) for an entry
334 // for this section offset.
335 uint32_t sect_addr = info->S.getAddress();
336 uint32_t sect_offset = (Pc + Offset) - sect_addr;
337 bool reloc_found = false;
338 DataRefImpl Rel;
339 MachO::any_relocation_info RE;
340 bool isExtern = false;
341 SymbolRef Symbol;
342 bool r_scattered = false;
343 uint32_t r_value, pair_r_value, r_type;
344 for (const RelocationRef &Reloc : info->S.relocations()) {
345 uint64_t RelocOffset;
346 Reloc.getOffset(RelocOffset);
347 if (RelocOffset == sect_offset) {
348 Rel = Reloc.getRawDataRefImpl();
349 RE = info->O->getRelocation(Rel);
Kevin Enderby3eb73e12014-11-11 19:16:45 +0000350 r_type = info->O->getAnyRelocationType(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000351 r_scattered = info->O->isRelocationScattered(RE);
352 if (r_scattered) {
353 r_value = info->O->getScatteredRelocationValue(RE);
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000354 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
355 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
356 DataRefImpl RelNext = Rel;
357 info->O->moveRelocationNext(RelNext);
358 MachO::any_relocation_info RENext;
359 RENext = info->O->getRelocation(RelNext);
360 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +0000361 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000362 else
363 return 0;
364 }
365 } else {
366 isExtern = info->O->getPlainRelocationExternal(RE);
367 if (isExtern) {
368 symbol_iterator RelocSym = Reloc.getSymbol();
369 Symbol = *RelocSym;
370 }
371 }
372 reloc_found = true;
373 break;
374 }
375 }
376 if (reloc_found && isExtern) {
377 StringRef SymName;
378 Symbol.getName(SymName);
379 const char *name = SymName.data();
380 op_info->AddSymbol.Present = 1;
381 op_info->AddSymbol.Name = name;
382 // For i386 extern relocation entries the value in the instruction is
383 // the offset from the symbol, and value is already set in op_info->Value.
384 return 1;
385 }
386 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
387 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
388 const char *add = GuessSymbolName(r_value, info);
389 const char *sub = GuessSymbolName(pair_r_value, info);
390 uint32_t offset = value - (r_value - pair_r_value);
391 op_info->AddSymbol.Present = 1;
392 if (add != nullptr)
393 op_info->AddSymbol.Name = add;
394 else
395 op_info->AddSymbol.Value = r_value;
396 op_info->SubtractSymbol.Present = 1;
397 if (sub != nullptr)
398 op_info->SubtractSymbol.Name = sub;
399 else
400 op_info->SubtractSymbol.Value = pair_r_value;
401 op_info->Value = offset;
402 return 1;
403 }
404 // TODO:
405 // Second search the external relocation entries of a fully linked image
406 // (if any) for an entry that matches this segment offset.
407 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000408 return 0;
409 } else if (Arch == Triple::x86_64) {
410 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
411 return 0;
412 // First search the section's relocation entries (if any) for an entry
413 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +0000414 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000415 uint64_t sect_offset = (Pc + Offset) - sect_addr;
416 bool reloc_found = false;
417 DataRefImpl Rel;
418 MachO::any_relocation_info RE;
419 bool isExtern = false;
420 SymbolRef Symbol;
421 for (const RelocationRef &Reloc : info->S.relocations()) {
422 uint64_t RelocOffset;
423 Reloc.getOffset(RelocOffset);
424 if (RelocOffset == sect_offset) {
425 Rel = Reloc.getRawDataRefImpl();
426 RE = info->O->getRelocation(Rel);
427 // NOTE: Scattered relocations don't exist on x86_64.
428 isExtern = info->O->getPlainRelocationExternal(RE);
429 if (isExtern) {
430 symbol_iterator RelocSym = Reloc.getSymbol();
431 Symbol = *RelocSym;
432 }
433 reloc_found = true;
434 break;
435 }
436 }
437 if (reloc_found && isExtern) {
438 // The Value passed in will be adjusted by the Pc if the instruction
439 // adds the Pc. But for x86_64 external relocation entries the Value
440 // is the offset from the external symbol.
441 if (info->O->getAnyRelocationPCRel(RE))
442 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000443 StringRef SymName;
444 Symbol.getName(SymName);
445 const char *name = SymName.data();
446 unsigned Type = info->O->getAnyRelocationType(RE);
447 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
448 DataRefImpl RelNext = Rel;
449 info->O->moveRelocationNext(RelNext);
450 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
451 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
452 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
453 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
454 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
455 op_info->SubtractSymbol.Present = 1;
456 op_info->SubtractSymbol.Name = name;
457 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
458 Symbol = *RelocSymNext;
459 StringRef SymNameNext;
460 Symbol.getName(SymNameNext);
461 name = SymNameNext.data();
462 }
463 }
464 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
465 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
466 op_info->AddSymbol.Present = 1;
467 op_info->AddSymbol.Name = name;
468 return 1;
469 }
470 // TODO:
471 // Second search the external relocation entries of a fully linked image
472 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000473 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000474 return 0;
475 } else if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000476 if (Offset != 0 || (Size != 4 && Size != 2))
477 return 0;
478 // First search the section's relocation entries (if any) for an entry
479 // for this section offset.
480 uint32_t sect_addr = info->S.getAddress();
481 uint32_t sect_offset = (Pc + Offset) - sect_addr;
482 bool reloc_found = false;
483 DataRefImpl Rel;
484 MachO::any_relocation_info RE;
485 bool isExtern = false;
486 SymbolRef Symbol;
487 bool r_scattered = false;
488 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
489 for (const RelocationRef &Reloc : info->S.relocations()) {
490 uint64_t RelocOffset;
491 Reloc.getOffset(RelocOffset);
492 if (RelocOffset == sect_offset) {
493 Rel = Reloc.getRawDataRefImpl();
494 RE = info->O->getRelocation(Rel);
495 r_length = info->O->getAnyRelocationLength(RE);
496 r_scattered = info->O->isRelocationScattered(RE);
497 if (r_scattered) {
498 r_value = info->O->getScatteredRelocationValue(RE);
499 r_type = info->O->getScatteredRelocationType(RE);
500 } else {
501 r_type = info->O->getAnyRelocationType(RE);
502 isExtern = info->O->getPlainRelocationExternal(RE);
503 if (isExtern) {
504 symbol_iterator RelocSym = Reloc.getSymbol();
505 Symbol = *RelocSym;
506 }
507 }
508 if (r_type == MachO::ARM_RELOC_HALF ||
509 r_type == MachO::ARM_RELOC_SECTDIFF ||
510 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
511 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
512 DataRefImpl RelNext = Rel;
513 info->O->moveRelocationNext(RelNext);
514 MachO::any_relocation_info RENext;
515 RENext = info->O->getRelocation(RelNext);
516 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
517 if (info->O->isRelocationScattered(RENext))
518 pair_r_value = info->O->getScatteredRelocationValue(RENext);
519 }
520 reloc_found = true;
521 break;
522 }
523 }
524 if (reloc_found && isExtern) {
525 StringRef SymName;
526 Symbol.getName(SymName);
527 const char *name = SymName.data();
528 op_info->AddSymbol.Present = 1;
529 op_info->AddSymbol.Name = name;
530 if (value != 0) {
531 switch (r_type) {
532 case MachO::ARM_RELOC_HALF:
533 if ((r_length & 0x1) == 1) {
534 op_info->Value = value << 16 | other_half;
535 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
536 } else {
537 op_info->Value = other_half << 16 | value;
538 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
539 }
540 break;
541 default:
542 break;
543 }
544 } else {
545 switch (r_type) {
546 case MachO::ARM_RELOC_HALF:
547 if ((r_length & 0x1) == 1) {
548 op_info->Value = value << 16 | other_half;
549 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
550 } else {
551 op_info->Value = other_half << 16 | value;
552 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
553 }
554 break;
555 default:
556 break;
557 }
558 }
559 return 1;
560 }
561 // If we have a branch that is not an external relocation entry then
562 // return 0 so the code in tryAddingSymbolicOperand() can use the
563 // SymbolLookUp call back with the branch target address to look up the
564 // symbol and possiblity add an annotation for a symbol stub.
565 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
566 r_type == MachO::ARM_THUMB_RELOC_BR22))
567 return 0;
568
569 uint32_t offset = 0;
570 if (reloc_found) {
571 if (r_type == MachO::ARM_RELOC_HALF ||
572 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
573 if ((r_length & 0x1) == 1)
574 value = value << 16 | other_half;
575 else
576 value = other_half << 16 | value;
577 }
578 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
579 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
580 offset = value - r_value;
581 value = r_value;
582 }
583 }
584
585 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
586 if ((r_length & 0x1) == 1)
587 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
588 else
589 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
590 const char *add = GuessSymbolName(r_value, info);
591 const char *sub = GuessSymbolName(pair_r_value, info);
592 int32_t offset = value - (r_value - pair_r_value);
593 op_info->AddSymbol.Present = 1;
594 if (add != nullptr)
595 op_info->AddSymbol.Name = add;
596 else
597 op_info->AddSymbol.Value = r_value;
598 op_info->SubtractSymbol.Present = 1;
599 if (sub != nullptr)
600 op_info->SubtractSymbol.Name = sub;
601 else
602 op_info->SubtractSymbol.Value = pair_r_value;
603 op_info->Value = offset;
604 return 1;
605 }
606
607 if (reloc_found == false)
608 return 0;
609
610 op_info->AddSymbol.Present = 1;
611 op_info->Value = offset;
612 if (reloc_found) {
613 if (r_type == MachO::ARM_RELOC_HALF) {
614 if ((r_length & 0x1) == 1)
615 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
616 else
617 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
618 }
619 }
620 const char *add = GuessSymbolName(value, info);
621 if (add != nullptr) {
622 op_info->AddSymbol.Name = add;
623 return 1;
624 }
625 op_info->AddSymbol.Value = value;
626 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000627 } else if (Arch == Triple::aarch64) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000628 if (Offset != 0 || Size != 4)
629 return 0;
630 // First search the section's relocation entries (if any) for an entry
631 // for this section offset.
632 uint64_t sect_addr = info->S.getAddress();
633 uint64_t sect_offset = (Pc + Offset) - sect_addr;
634 bool reloc_found = false;
635 DataRefImpl Rel;
636 MachO::any_relocation_info RE;
637 bool isExtern = false;
638 SymbolRef Symbol;
639 uint32_t r_type = 0;
640 for (const RelocationRef &Reloc : info->S.relocations()) {
641 uint64_t RelocOffset;
642 Reloc.getOffset(RelocOffset);
643 if (RelocOffset == sect_offset) {
644 Rel = Reloc.getRawDataRefImpl();
645 RE = info->O->getRelocation(Rel);
646 r_type = info->O->getAnyRelocationType(RE);
647 if (r_type == MachO::ARM64_RELOC_ADDEND) {
648 DataRefImpl RelNext = Rel;
649 info->O->moveRelocationNext(RelNext);
650 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
651 if (value == 0) {
652 value = info->O->getPlainRelocationSymbolNum(RENext);
653 op_info->Value = value;
654 }
655 }
656 // NOTE: Scattered relocations don't exist on arm64.
657 isExtern = info->O->getPlainRelocationExternal(RE);
658 if (isExtern) {
659 symbol_iterator RelocSym = Reloc.getSymbol();
660 Symbol = *RelocSym;
661 }
662 reloc_found = true;
663 break;
664 }
665 }
666 if (reloc_found && isExtern) {
667 StringRef SymName;
668 Symbol.getName(SymName);
669 const char *name = SymName.data();
670 op_info->AddSymbol.Present = 1;
671 op_info->AddSymbol.Name = name;
672
673 switch (r_type) {
674 case MachO::ARM64_RELOC_PAGE21:
675 /* @page */
676 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
677 break;
678 case MachO::ARM64_RELOC_PAGEOFF12:
679 /* @pageoff */
680 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
681 break;
682 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
683 /* @gotpage */
684 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
685 break;
686 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
687 /* @gotpageoff */
688 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
689 break;
690 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
691 /* @tvlppage is not implemented in llvm-mc */
692 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
693 break;
694 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
695 /* @tvlppageoff is not implemented in llvm-mc */
696 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
697 break;
698 default:
699 case MachO::ARM64_RELOC_BRANCH26:
700 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
701 break;
702 }
703 return 1;
704 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000705 return 0;
706 } else {
707 return 0;
708 }
709}
710
Kevin Enderbybf246f52014-09-24 23:08:22 +0000711// GuessCstringPointer is passed the address of what might be a pointer to a
712// literal string in a cstring section. If that address is in a cstring section
713// it returns a pointer to that string. Else it returns nullptr.
714const char *GuessCstringPointer(uint64_t ReferenceValue,
715 struct DisassembleInfo *info) {
716 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
717 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
718 for (unsigned I = 0;; ++I) {
719 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
720 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
721 for (unsigned J = 0; J < Seg.nsects; ++J) {
722 MachO::section_64 Sec = info->O->getSection64(Load, J);
723 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
724 if (section_type == MachO::S_CSTRING_LITERALS &&
725 ReferenceValue >= Sec.addr &&
726 ReferenceValue < Sec.addr + Sec.size) {
727 uint64_t sect_offset = ReferenceValue - Sec.addr;
728 uint64_t object_offset = Sec.offset + sect_offset;
729 StringRef MachOContents = info->O->getData();
730 uint64_t object_size = MachOContents.size();
731 const char *object_addr = (const char *)MachOContents.data();
732 if (object_offset < object_size) {
733 const char *name = object_addr + object_offset;
734 return name;
735 } else {
736 return nullptr;
737 }
738 }
739 }
740 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
741 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
742 for (unsigned J = 0; J < Seg.nsects; ++J) {
743 MachO::section Sec = info->O->getSection(Load, J);
744 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
745 if (section_type == MachO::S_CSTRING_LITERALS &&
746 ReferenceValue >= Sec.addr &&
747 ReferenceValue < Sec.addr + Sec.size) {
748 uint64_t sect_offset = ReferenceValue - Sec.addr;
749 uint64_t object_offset = Sec.offset + sect_offset;
750 StringRef MachOContents = info->O->getData();
751 uint64_t object_size = MachOContents.size();
752 const char *object_addr = (const char *)MachOContents.data();
753 if (object_offset < object_size) {
754 const char *name = object_addr + object_offset;
755 return name;
756 } else {
757 return nullptr;
758 }
759 }
760 }
761 }
762 if (I == LoadCommandCount - 1)
763 break;
764 else
765 Load = info->O->getNextLoadCommandInfo(Load);
766 }
767 return nullptr;
768}
769
Kevin Enderby85974882014-09-26 22:20:44 +0000770// GuessIndirectSymbol returns the name of the indirect symbol for the
771// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
772// an address of a symbol stub or a lazy or non-lazy pointer to associate the
773// symbol name being referenced by the stub or pointer.
774static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
775 struct DisassembleInfo *info) {
776 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
777 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
778 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
779 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
780 for (unsigned I = 0;; ++I) {
781 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
782 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
783 for (unsigned J = 0; J < Seg.nsects; ++J) {
784 MachO::section_64 Sec = info->O->getSection64(Load, J);
785 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
786 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
787 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
788 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
789 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
790 section_type == MachO::S_SYMBOL_STUBS) &&
791 ReferenceValue >= Sec.addr &&
792 ReferenceValue < Sec.addr + Sec.size) {
793 uint32_t stride;
794 if (section_type == MachO::S_SYMBOL_STUBS)
795 stride = Sec.reserved2;
796 else
797 stride = 8;
798 if (stride == 0)
799 return nullptr;
800 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
801 if (index < Dysymtab.nindirectsyms) {
802 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000803 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +0000804 if (indirect_symbol < Symtab.nsyms) {
805 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
806 SymbolRef Symbol = *Sym;
807 StringRef SymName;
808 Symbol.getName(SymName);
809 const char *name = SymName.data();
810 return name;
811 }
812 }
813 }
814 }
815 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
816 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
817 for (unsigned J = 0; J < Seg.nsects; ++J) {
818 MachO::section Sec = info->O->getSection(Load, J);
819 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
820 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
821 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
822 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
823 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
824 section_type == MachO::S_SYMBOL_STUBS) &&
825 ReferenceValue >= Sec.addr &&
826 ReferenceValue < Sec.addr + Sec.size) {
827 uint32_t stride;
828 if (section_type == MachO::S_SYMBOL_STUBS)
829 stride = Sec.reserved2;
830 else
831 stride = 4;
832 if (stride == 0)
833 return nullptr;
834 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
835 if (index < Dysymtab.nindirectsyms) {
836 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000837 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +0000838 if (indirect_symbol < Symtab.nsyms) {
839 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
840 SymbolRef Symbol = *Sym;
841 StringRef SymName;
842 Symbol.getName(SymName);
843 const char *name = SymName.data();
844 return name;
845 }
846 }
847 }
848 }
849 }
850 if (I == LoadCommandCount - 1)
851 break;
852 else
853 Load = info->O->getNextLoadCommandInfo(Load);
854 }
855 return nullptr;
856}
857
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000858// method_reference() is called passing it the ReferenceName that might be
859// a reference it to an Objective-C method call. If so then it allocates and
860// assembles a method call string with the values last seen and saved in
861// the DisassembleInfo's class_name and selector_name fields. This is saved
862// into the method field of the info and any previous string is free'ed.
863// Then the class_name field in the info is set to nullptr. The method call
864// string is set into ReferenceName and ReferenceType is set to
865// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
866// then both ReferenceType and ReferenceName are left unchanged.
867static void method_reference(struct DisassembleInfo *info,
868 uint64_t *ReferenceType,
869 const char **ReferenceName) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000870 unsigned int Arch = info->O->getArch();
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000871 if (*ReferenceName != nullptr) {
872 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000873 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000874 if (info->method != nullptr)
875 free(info->method);
876 if (info->class_name != nullptr) {
877 info->method = (char *)malloc(5 + strlen(info->class_name) +
878 strlen(info->selector_name));
879 if (info->method != nullptr) {
880 strcpy(info->method, "+[");
881 strcat(info->method, info->class_name);
882 strcat(info->method, " ");
883 strcat(info->method, info->selector_name);
884 strcat(info->method, "]");
885 *ReferenceName = info->method;
886 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
887 }
888 } else {
889 info->method = (char *)malloc(9 + strlen(info->selector_name));
890 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000891 if (Arch == Triple::x86_64)
892 strcpy(info->method, "-[%rdi ");
893 else if (Arch == Triple::aarch64)
894 strcpy(info->method, "-[x0 ");
895 else
896 strcpy(info->method, "-[r? ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000897 strcat(info->method, info->selector_name);
898 strcat(info->method, "]");
899 *ReferenceName = info->method;
900 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
901 }
902 }
903 info->class_name = nullptr;
904 }
905 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000906 if (info->selector_name != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000907 if (info->method != nullptr)
908 free(info->method);
909 info->method = (char *)malloc(17 + strlen(info->selector_name));
910 if (info->method != nullptr) {
Kevin Enderbyae3c1262014-11-14 21:52:18 +0000911 if (Arch == Triple::x86_64)
912 strcpy(info->method, "-[[%rdi super] ");
913 else if (Arch == Triple::aarch64)
914 strcpy(info->method, "-[[x0 super] ");
915 else
916 strcpy(info->method, "-[[r? super] ");
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000917 strcat(info->method, info->selector_name);
918 strcat(info->method, "]");
919 *ReferenceName = info->method;
920 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
921 }
922 info->class_name = nullptr;
923 }
924 }
925 }
926}
927
928// GuessPointerPointer() is passed the address of what might be a pointer to
929// a reference to an Objective-C class, selector, message ref or cfstring.
930// If so the value of the pointer is returned and one of the booleans are set
931// to true. If not zero is returned and all the booleans are set to false.
932static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
933 struct DisassembleInfo *info,
934 bool &classref, bool &selref, bool &msgref,
935 bool &cfstring) {
936 classref = false;
937 selref = false;
938 msgref = false;
939 cfstring = false;
940 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
941 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
942 for (unsigned I = 0;; ++I) {
943 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
944 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
945 for (unsigned J = 0; J < Seg.nsects; ++J) {
946 MachO::section_64 Sec = info->O->getSection64(Load, J);
947 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
948 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
949 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
950 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
951 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
952 ReferenceValue >= Sec.addr &&
953 ReferenceValue < Sec.addr + Sec.size) {
954 uint64_t sect_offset = ReferenceValue - Sec.addr;
955 uint64_t object_offset = Sec.offset + sect_offset;
956 StringRef MachOContents = info->O->getData();
957 uint64_t object_size = MachOContents.size();
958 const char *object_addr = (const char *)MachOContents.data();
959 if (object_offset < object_size) {
960 uint64_t pointer_value;
961 memcpy(&pointer_value, object_addr + object_offset,
962 sizeof(uint64_t));
963 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
964 sys::swapByteOrder(pointer_value);
965 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
966 selref = true;
967 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
968 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
969 classref = true;
970 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
971 ReferenceValue + 8 < Sec.addr + Sec.size) {
972 msgref = true;
973 memcpy(&pointer_value, object_addr + object_offset + 8,
974 sizeof(uint64_t));
975 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
976 sys::swapByteOrder(pointer_value);
977 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
978 cfstring = true;
979 return pointer_value;
980 } else {
981 return 0;
982 }
983 }
984 }
985 }
986 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
987 if (I == LoadCommandCount - 1)
988 break;
989 else
990 Load = info->O->getNextLoadCommandInfo(Load);
991 }
992 return 0;
993}
994
995// get_pointer_64 returns a pointer to the bytes in the object file at the
996// Address from a section in the Mach-O file. And indirectly returns the
997// offset into the section, number of bytes left in the section past the offset
998// and which section is was being referenced. If the Address is not in a
999// section nullptr is returned.
1000const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1001 SectionRef &S, DisassembleInfo *info) {
1002 offset = 0;
1003 left = 0;
1004 S = SectionRef();
1005 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1006 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1007 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1008 if (Address >= SectAddress && Address < SectAddress + SectSize) {
1009 S = (*(info->Sections))[SectIdx];
1010 offset = Address - SectAddress;
1011 left = SectSize - offset;
1012 StringRef SectContents;
1013 ((*(info->Sections))[SectIdx]).getContents(SectContents);
1014 return SectContents.data() + offset;
1015 }
1016 }
1017 return nullptr;
1018}
1019
1020// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1021// the symbol indirectly through n_value. Based on the relocation information
1022// for the specified section offset in the specified section reference.
1023const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1024 DisassembleInfo *info, uint64_t &n_value) {
1025 n_value = 0;
1026 if (info->verbose == false)
1027 return nullptr;
1028
1029 // See if there is an external relocation entry at the sect_offset.
1030 bool reloc_found = false;
1031 DataRefImpl Rel;
1032 MachO::any_relocation_info RE;
1033 bool isExtern = false;
1034 SymbolRef Symbol;
1035 for (const RelocationRef &Reloc : S.relocations()) {
1036 uint64_t RelocOffset;
1037 Reloc.getOffset(RelocOffset);
1038 if (RelocOffset == sect_offset) {
1039 Rel = Reloc.getRawDataRefImpl();
1040 RE = info->O->getRelocation(Rel);
1041 if (info->O->isRelocationScattered(RE))
1042 continue;
1043 isExtern = info->O->getPlainRelocationExternal(RE);
1044 if (isExtern) {
1045 symbol_iterator RelocSym = Reloc.getSymbol();
1046 Symbol = *RelocSym;
1047 }
1048 reloc_found = true;
1049 break;
1050 }
1051 }
1052 // If there is an external relocation entry for a symbol in this section
1053 // at this section_offset then use that symbol's value for the n_value
1054 // and return its name.
1055 const char *SymbolName = nullptr;
1056 if (reloc_found && isExtern) {
1057 Symbol.getAddress(n_value);
1058 StringRef name;
1059 Symbol.getName(name);
1060 if (!name.empty()) {
1061 SymbolName = name.data();
1062 return SymbolName;
1063 }
1064 }
1065
1066 // TODO: For fully linked images, look through the external relocation
1067 // entries off the dynamic symtab command. For these the r_offset is from the
1068 // start of the first writeable segment in the Mach-O file. So the offset
1069 // to this section from that segment is passed to this routine by the caller,
1070 // as the database_offset. Which is the difference of the section's starting
1071 // address and the first writable segment.
1072 //
1073 // NOTE: need add passing the database_offset to this routine.
1074
1075 // TODO: We did not find an external relocation entry so look up the
1076 // ReferenceValue as an address of a symbol and if found return that symbol's
1077 // name.
1078 //
1079 // NOTE: need add passing the ReferenceValue to this routine. Then that code
1080 // would simply be this:
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001081 // SymbolName = GuessSymbolName(ReferenceValue, info);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001082
1083 return SymbolName;
1084}
1085
1086// These are structs in the Objective-C meta data and read to produce the
1087// comments for disassembly. While these are part of the ABI they are no
1088// public defintions. So the are here not in include/llvm/Support/MachO.h .
1089
1090// The cfstring object in a 64-bit Mach-O file.
1091struct cfstring64_t {
1092 uint64_t isa; // class64_t * (64-bit pointer)
1093 uint64_t flags; // flag bits
1094 uint64_t characters; // char * (64-bit pointer)
1095 uint64_t length; // number of non-NULL characters in above
1096};
1097
1098// The class object in a 64-bit Mach-O file.
1099struct class64_t {
1100 uint64_t isa; // class64_t * (64-bit pointer)
1101 uint64_t superclass; // class64_t * (64-bit pointer)
1102 uint64_t cache; // Cache (64-bit pointer)
1103 uint64_t vtable; // IMP * (64-bit pointer)
1104 uint64_t data; // class_ro64_t * (64-bit pointer)
1105};
1106
1107struct class_ro64_t {
1108 uint32_t flags;
1109 uint32_t instanceStart;
1110 uint32_t instanceSize;
1111 uint32_t reserved;
1112 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
1113 uint64_t name; // const char * (64-bit pointer)
1114 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
1115 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
1116 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
1117 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1118 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1119};
1120
1121inline void swapStruct(struct cfstring64_t &cfs) {
1122 sys::swapByteOrder(cfs.isa);
1123 sys::swapByteOrder(cfs.flags);
1124 sys::swapByteOrder(cfs.characters);
1125 sys::swapByteOrder(cfs.length);
1126}
1127
1128inline void swapStruct(struct class64_t &c) {
1129 sys::swapByteOrder(c.isa);
1130 sys::swapByteOrder(c.superclass);
1131 sys::swapByteOrder(c.cache);
1132 sys::swapByteOrder(c.vtable);
1133 sys::swapByteOrder(c.data);
1134}
1135
1136inline void swapStruct(struct class_ro64_t &cro) {
1137 sys::swapByteOrder(cro.flags);
1138 sys::swapByteOrder(cro.instanceStart);
1139 sys::swapByteOrder(cro.instanceSize);
1140 sys::swapByteOrder(cro.reserved);
1141 sys::swapByteOrder(cro.ivarLayout);
1142 sys::swapByteOrder(cro.name);
1143 sys::swapByteOrder(cro.baseMethods);
1144 sys::swapByteOrder(cro.baseProtocols);
1145 sys::swapByteOrder(cro.ivars);
1146 sys::swapByteOrder(cro.weakIvarLayout);
1147 sys::swapByteOrder(cro.baseProperties);
1148}
1149
1150static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1151 struct DisassembleInfo *info);
1152
1153// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1154// to an Objective-C class and returns the class name. It is also passed the
1155// address of the pointer, so when the pointer is zero as it can be in an .o
1156// file, that is used to look for an external relocation entry with a symbol
1157// name.
1158const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1159 uint64_t ReferenceValue,
1160 struct DisassembleInfo *info) {
1161 const char *r;
1162 uint32_t offset, left;
1163 SectionRef S;
1164
1165 // The pointer_value can be 0 in an object file and have a relocation
1166 // entry for the class symbol at the ReferenceValue (the address of the
1167 // pointer).
1168 if (pointer_value == 0) {
1169 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1170 if (r == nullptr || left < sizeof(uint64_t))
1171 return nullptr;
1172 uint64_t n_value;
1173 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1174 if (symbol_name == nullptr)
1175 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001176 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001177 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1178 return class_name + 2;
1179 else
1180 return nullptr;
1181 }
1182
1183 // The case were the pointer_value is non-zero and points to a class defined
1184 // in this Mach-O file.
1185 r = get_pointer_64(pointer_value, offset, left, S, info);
1186 if (r == nullptr || left < sizeof(struct class64_t))
1187 return nullptr;
1188 struct class64_t c;
1189 memcpy(&c, r, sizeof(struct class64_t));
1190 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1191 swapStruct(c);
1192 if (c.data == 0)
1193 return nullptr;
1194 r = get_pointer_64(c.data, offset, left, S, info);
1195 if (r == nullptr || left < sizeof(struct class_ro64_t))
1196 return nullptr;
1197 struct class_ro64_t cro;
1198 memcpy(&cro, r, sizeof(struct class_ro64_t));
1199 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1200 swapStruct(cro);
1201 if (cro.name == 0)
1202 return nullptr;
1203 const char *name = get_pointer_64(cro.name, offset, left, S, info);
1204 return name;
1205}
1206
1207// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1208// pointer to a cfstring and returns its name or nullptr.
1209const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1210 struct DisassembleInfo *info) {
1211 const char *r, *name;
1212 uint32_t offset, left;
1213 SectionRef S;
1214 struct cfstring64_t cfs;
1215 uint64_t cfs_characters;
1216
1217 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1218 if (r == nullptr || left < sizeof(struct cfstring64_t))
1219 return nullptr;
1220 memcpy(&cfs, r, sizeof(struct cfstring64_t));
1221 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1222 swapStruct(cfs);
1223 if (cfs.characters == 0) {
1224 uint64_t n_value;
1225 const char *symbol_name = get_symbol_64(
1226 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1227 if (symbol_name == nullptr)
1228 return nullptr;
1229 cfs_characters = n_value;
1230 } else
1231 cfs_characters = cfs.characters;
1232 name = get_pointer_64(cfs_characters, offset, left, S, info);
1233
1234 return name;
1235}
1236
1237// get_objc2_64bit_selref() is used for disassembly and is passed a the address
1238// of a pointer to an Objective-C selector reference when the pointer value is
1239// zero as in a .o file and is likely to have a external relocation entry with
1240// who's symbol's n_value is the real pointer to the selector name. If that is
1241// the case the real pointer to the selector name is returned else 0 is
1242// returned
1243uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1244 struct DisassembleInfo *info) {
1245 uint32_t offset, left;
1246 SectionRef S;
1247
1248 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1249 if (r == nullptr || left < sizeof(uint64_t))
1250 return 0;
1251 uint64_t n_value;
1252 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1253 if (symbol_name == nullptr)
1254 return 0;
1255 return n_value;
1256}
1257
Kevin Enderbybf246f52014-09-24 23:08:22 +00001258// GuessLiteralPointer returns a string which for the item in the Mach-O file
1259// for the address passed in as ReferenceValue for printing as a comment with
1260// the instruction and also returns the corresponding type of that item
1261// indirectly through ReferenceType.
1262//
1263// If ReferenceValue is an address of literal cstring then a pointer to the
1264// cstring is returned and ReferenceType is set to
1265// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1266//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001267// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1268// Class ref that name is returned and the ReferenceType is set accordingly.
1269//
1270// Lastly, literals which are Symbol address in a literal pool are looked for
1271// and if found the symbol name is returned and ReferenceType is set to
1272// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1273//
1274// If there is no item in the Mach-O file for the address passed in as
1275// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Kevin Enderbybf246f52014-09-24 23:08:22 +00001276const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1277 uint64_t *ReferenceType,
1278 struct DisassembleInfo *info) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001279 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00001280 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00001281 uint64_t sect_offset = ReferencePC - sect_addr;
1282 bool reloc_found = false;
1283 DataRefImpl Rel;
1284 MachO::any_relocation_info RE;
1285 bool isExtern = false;
1286 SymbolRef Symbol;
1287 for (const RelocationRef &Reloc : info->S.relocations()) {
1288 uint64_t RelocOffset;
1289 Reloc.getOffset(RelocOffset);
1290 if (RelocOffset == sect_offset) {
1291 Rel = Reloc.getRawDataRefImpl();
1292 RE = info->O->getRelocation(Rel);
1293 if (info->O->isRelocationScattered(RE))
1294 continue;
1295 isExtern = info->O->getPlainRelocationExternal(RE);
1296 if (isExtern) {
1297 symbol_iterator RelocSym = Reloc.getSymbol();
1298 Symbol = *RelocSym;
1299 }
1300 reloc_found = true;
1301 break;
1302 }
1303 }
1304 // If there is an external relocation entry for a symbol in a section
1305 // then used that symbol's value for the value of the reference.
1306 if (reloc_found && isExtern) {
1307 if (info->O->getAnyRelocationPCRel(RE)) {
1308 unsigned Type = info->O->getAnyRelocationType(RE);
1309 if (Type == MachO::X86_64_RELOC_SIGNED) {
1310 Symbol.getAddress(ReferenceValue);
1311 }
1312 }
1313 }
1314
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001315 // Look for literals such as Objective-C CFStrings refs, Selector refs,
1316 // Message refs and Class refs.
1317 bool classref, selref, msgref, cfstring;
1318 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1319 selref, msgref, cfstring);
1320 if (classref == true && pointer_value == 0) {
1321 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1322 // And the pointer_value in that section is typically zero as it will be
1323 // set by dyld as part of the "bind information".
1324 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1325 if (name != nullptr) {
1326 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001327 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001328 if (class_name != nullptr && class_name[1] == '_' &&
1329 class_name[2] != '\0') {
1330 info->class_name = class_name + 2;
1331 return name;
1332 }
1333 }
1334 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001335
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001336 if (classref == true) {
1337 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1338 const char *name =
1339 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1340 if (name != nullptr)
1341 info->class_name = name;
1342 else
1343 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00001344 return name;
1345 }
1346
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001347 if (cfstring == true) {
1348 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1349 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1350 return name;
1351 }
1352
1353 if (selref == true && pointer_value == 0)
1354 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1355
1356 if (pointer_value != 0)
1357 ReferenceValue = pointer_value;
1358
1359 const char *name = GuessCstringPointer(ReferenceValue, info);
1360 if (name) {
1361 if (pointer_value != 0 && selref == true) {
1362 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1363 info->selector_name = name;
1364 } else if (pointer_value != 0 && msgref == true) {
1365 info->class_name = nullptr;
1366 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1367 info->selector_name = name;
1368 } else
1369 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1370 return name;
1371 }
1372
1373 // Lastly look for an indirect symbol with this ReferenceValue which is in
1374 // a literal pool. If found return that symbol name.
1375 name = GuessIndirectSymbol(ReferenceValue, info);
1376 if (name) {
1377 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1378 return name;
1379 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001380
1381 return nullptr;
1382}
1383
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001384// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00001385// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001386// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1387// is created and returns the symbol name that matches the ReferenceValue or
1388// nullptr if none. The ReferenceType is passed in for the IN type of
1389// reference the instruction is making from the values in defined in the header
1390// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1391// Out type and the ReferenceName will also be set which is added as a comment
1392// to the disassembled instruction.
1393//
Kevin Enderby04bf6932014-10-28 23:39:46 +00001394#if HAVE_CXXABI_H
1395// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001396// returned through ReferenceName and ReferenceType is set to
1397// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00001398#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001399//
1400// When this is called to get a symbol name for a branch target then the
1401// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1402// SymbolValue will be looked for in the indirect symbol table to determine if
1403// it is an address for a symbol stub. If so then the symbol name for that
1404// stub is returned indirectly through ReferenceName and then ReferenceType is
1405// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1406//
Kevin Enderbybf246f52014-09-24 23:08:22 +00001407// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001408// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1409// SymbolValue is checked to be an address of literal pointer, symbol pointer,
1410// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001411// set to correspond to that as well as setting the ReferenceName.
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001412const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1413 uint64_t *ReferenceType,
1414 uint64_t ReferencePC,
1415 const char **ReferenceName) {
1416 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001417 // If no verbose symbolic information is wanted then just return nullptr.
1418 if (info->verbose == false) {
1419 *ReferenceName = nullptr;
1420 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001421 return nullptr;
1422 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001423
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001424 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
Kevin Enderbybf246f52014-09-24 23:08:22 +00001425
Kevin Enderby85974882014-09-26 22:20:44 +00001426 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1427 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001428 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001429 method_reference(info, ReferenceType, ReferenceName);
1430 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1431 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1432 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00001433#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001434 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00001435 if (info->demangled_name != nullptr)
1436 free(info->demangled_name);
1437 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001438 info->demangled_name =
1439 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001440 if (info->demangled_name != nullptr) {
1441 *ReferenceName = info->demangled_name;
1442 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1443 } else
1444 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1445 } else
1446#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001447 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1448 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1449 *ReferenceName =
1450 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00001451 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001452 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00001453 else
1454 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001455 // If this is arm64 and the reference is an adrp instruction save the
1456 // instruction, passed in ReferenceValue and the address of the instruction
1457 // for use later if we see and add immediate instruction.
1458 } else if (info->O->getArch() == Triple::aarch64 &&
1459 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
1460 info->adrp_inst = ReferenceValue;
1461 info->adrp_addr = ReferencePC;
1462 SymbolName = nullptr;
1463 *ReferenceName = nullptr;
1464 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1465 // If this is arm64 and reference is an add immediate instruction and we
1466 // have
1467 // seen an adrp instruction just before it and the adrp's Xd register
1468 // matches
1469 // this add's Xn register reconstruct the value being referenced and look to
1470 // see if it is a literal pointer. Note the add immediate instruction is
1471 // passed in ReferenceValue.
1472 } else if (info->O->getArch() == Triple::aarch64 &&
1473 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
1474 ReferencePC - 4 == info->adrp_addr &&
1475 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
1476 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
1477 uint32_t addxri_inst;
1478 uint64_t adrp_imm, addxri_imm;
1479
1480 adrp_imm =
1481 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
1482 if (info->adrp_inst & 0x0200000)
1483 adrp_imm |= 0xfffffffffc000000LL;
1484
1485 addxri_inst = ReferenceValue;
1486 addxri_imm = (addxri_inst >> 10) & 0xfff;
1487 if (((addxri_inst >> 22) & 0x3) == 1)
1488 addxri_imm <<= 12;
1489
1490 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
1491 (adrp_imm << 12) + addxri_imm;
1492
1493 *ReferenceName =
1494 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1495 if (*ReferenceName == nullptr)
1496 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1497 // If this is arm64 and the reference is a load register instruction and we
1498 // have seen an adrp instruction just before it and the adrp's Xd register
1499 // matches this add's Xn register reconstruct the value being referenced and
1500 // look to see if it is a literal pointer. Note the load register
1501 // instruction is passed in ReferenceValue.
1502 } else if (info->O->getArch() == Triple::aarch64 &&
1503 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
1504 ReferencePC - 4 == info->adrp_addr &&
1505 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
1506 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
1507 uint32_t ldrxui_inst;
1508 uint64_t adrp_imm, ldrxui_imm;
1509
1510 adrp_imm =
1511 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
1512 if (info->adrp_inst & 0x0200000)
1513 adrp_imm |= 0xfffffffffc000000LL;
1514
1515 ldrxui_inst = ReferenceValue;
1516 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
1517
1518 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
1519 (adrp_imm << 12) + (ldrxui_imm << 3);
1520
1521 *ReferenceName =
1522 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1523 if (*ReferenceName == nullptr)
1524 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1525 }
1526 // If this arm64 and is an load register (PC-relative) instruction the
1527 // ReferenceValue is the PC plus the immediate value.
1528 else if (info->O->getArch() == Triple::aarch64 &&
1529 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
1530 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
1531 *ReferenceName =
1532 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1533 if (*ReferenceName == nullptr)
1534 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby85974882014-09-26 22:20:44 +00001535 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00001536#if HAVE_CXXABI_H
1537 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1538 if (info->demangled_name != nullptr)
1539 free(info->demangled_name);
1540 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001541 info->demangled_name =
1542 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001543 if (info->demangled_name != nullptr) {
1544 *ReferenceName = info->demangled_name;
1545 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1546 }
1547 }
1548#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001549 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001550 *ReferenceName = nullptr;
1551 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1552 }
1553
1554 return SymbolName;
1555}
1556
Kevin Enderbybf246f52014-09-24 23:08:22 +00001557/// \brief Emits the comments that are stored in the CommentStream.
1558/// Each comment in the CommentStream must end with a newline.
1559static void emitComments(raw_svector_ostream &CommentStream,
1560 SmallString<128> &CommentsToEmit,
1561 formatted_raw_ostream &FormattedOS,
1562 const MCAsmInfo &MAI) {
1563 // Flush the stream before taking its content.
1564 CommentStream.flush();
1565 StringRef Comments = CommentsToEmit.str();
1566 // Get the default information for printing a comment.
1567 const char *CommentBegin = MAI.getCommentString();
1568 unsigned CommentColumn = MAI.getCommentColumn();
1569 bool IsFirst = true;
1570 while (!Comments.empty()) {
1571 if (!IsFirst)
1572 FormattedOS << '\n';
1573 // Emit a line of comments.
1574 FormattedOS.PadToColumn(CommentColumn);
1575 size_t Position = Comments.find('\n');
1576 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
1577 // Move after the newline character.
1578 Comments = Comments.substr(Position + 1);
1579 IsFirst = false;
1580 }
1581 FormattedOS.flush();
1582
1583 // Tell the comment stream that the vector changed underneath it.
1584 CommentsToEmit.clear();
1585 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001586}
1587
Rafael Espindola9b709252013-04-13 01:45:40 +00001588static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindola56f976f2013-04-18 18:08:55 +00001589 MachOObjectFile *MachOOF) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001590 const char *McpuDefault = nullptr;
1591 const Target *ThumbTarget = nullptr;
1592 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001593 if (!TheTarget) {
1594 // GetTarget prints out stuff.
1595 return;
1596 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001597 if (MCPU.empty() && McpuDefault)
1598 MCPU = McpuDefault;
1599
Ahmed Charles56440fd2014-03-06 05:51:42 +00001600 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001601 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001602 if (ThumbTarget)
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001603 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001604
Kevin Enderbyc9595622014-08-06 23:24:41 +00001605 // Package up features to be passed to target/subtarget
1606 std::string FeaturesStr;
1607 if (MAttrs.size()) {
1608 SubtargetFeatures Features;
1609 for (unsigned i = 0; i != MAttrs.size(); ++i)
1610 Features.AddFeature(MAttrs[i]);
1611 FeaturesStr = Features.getString();
1612 }
1613
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001614 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001615 std::unique_ptr<const MCRegisterInfo> MRI(
1616 TheTarget->createMCRegInfo(TripleName));
1617 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00001618 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00001619 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00001620 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00001621 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001622 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001623 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001624 std::unique_ptr<MCSymbolizer> Symbolizer;
1625 struct DisassembleInfo SymbolizerInfo;
1626 std::unique_ptr<MCRelocationInfo> RelInfo(
1627 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1628 if (RelInfo) {
1629 Symbolizer.reset(TheTarget->createMCSymbolizer(
1630 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1631 &SymbolizerInfo, &Ctx, RelInfo.release()));
1632 DisAsm->setSymbolizer(std::move(Symbolizer));
1633 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001634 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00001635 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1636 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001637 // Set the display preference for hex vs. decimal immediates.
1638 IP->setPrintImmHex(PrintImmHex);
1639 // Comment stream and backing vector.
1640 SmallString<128> CommentsToEmit;
1641 raw_svector_ostream CommentStream(CommentsToEmit);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001642
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001643 if (!AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00001644 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001645 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001646 return;
1647 }
1648
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001649 // Set up thumb disassembler.
1650 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
1651 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
1652 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001653 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001654 std::unique_ptr<MCInstPrinter> ThumbIP;
1655 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001656 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
1657 struct DisassembleInfo ThumbSymbolizerInfo;
1658 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001659 if (ThumbTarget) {
1660 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
1661 ThumbAsmInfo.reset(
1662 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
1663 ThumbSTI.reset(
1664 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
1665 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
1666 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00001667 MCContext *PtrThumbCtx = ThumbCtx.get();
1668 ThumbRelInfo.reset(
1669 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
1670 if (ThumbRelInfo) {
1671 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
1672 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1673 &ThumbSymbolizerInfo, PtrThumbCtx, ThumbRelInfo.release()));
1674 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
1675 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001676 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
1677 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
1678 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
1679 *ThumbSTI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001680 // Set the display preference for hex vs. decimal immediates.
1681 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001682 }
1683
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001684 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001685 errs() << "error: couldn't initialize disassembler for target "
1686 << ThumbTripleName << '\n';
1687 return;
1688 }
1689
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001690 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001691
Charles Davis8bdfafd2013-09-01 04:28:48 +00001692 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001693
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001694 // FIXME: Using the -cfg command line option, this code used to be able to
1695 // annotate relocations with the referenced symbol's name, and if this was
1696 // inside a __[cf]string section, the data it points to. This is now replaced
1697 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00001698 std::vector<SectionRef> Sections;
1699 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001700 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00001701 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001702
Kevin Enderby273ae012013-06-06 17:20:50 +00001703 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
1704 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001705
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001706 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00001707 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001708
Kevin Enderby273ae012013-06-06 17:20:50 +00001709 // Build a data in code table that is sorted on by the address of each entry.
1710 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00001711 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00001712 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00001713 else
1714 BaseAddress = BaseSegmentAddress;
1715 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00001716 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00001717 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00001718 uint32_t Offset;
1719 DI->getOffset(Offset);
1720 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
1721 }
1722 array_pod_sort(Dices.begin(), Dices.end());
1723
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001724#ifndef NDEBUG
1725 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1726#else
1727 raw_ostream &DebugOut = nulls();
1728#endif
1729
Ahmed Charles56440fd2014-03-06 05:51:42 +00001730 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00001731 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00001732 // Try to find debug info and set up the DIContext for it.
1733 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00001734 // A separate DSym file path was specified, parse it as a macho file,
1735 // get the sections and supply it to the section name parsing machinery.
1736 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00001737 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00001738 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00001739 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00001740 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00001741 return;
1742 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001743 DbgObj =
1744 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
1745 .get()
1746 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00001747 }
1748
Eric Christopher7370b552012-11-12 21:40:38 +00001749 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00001750 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00001751 }
1752
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001753 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001754
Rafael Espindola80291272014-10-08 15:28:58 +00001755 bool SectIsText = Sections[SectIdx].isText();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001756 if (SectIsText == false)
1757 continue;
1758
Owen Andersond9243c42011-10-17 21:37:35 +00001759 StringRef SectName;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001760 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001761 continue; // Skip non-text sections
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001762
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001763 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001764
Rafael Espindolab0f76a42013-04-05 15:15:22 +00001765 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
1766 if (SegmentName != "__TEXT")
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001767 continue;
1768
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001769 StringRef BytesStr;
1770 Sections[SectIdx].getContents(BytesStr);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001771 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1772 BytesStr.size());
Rafael Espindola80291272014-10-08 15:28:58 +00001773 uint64_t SectAddress = Sections[SectIdx].getAddress();
Rafael Espindolabd604f22014-11-07 00:52:15 +00001774
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001775 bool symbolTableWorked = false;
1776
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001777 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001778 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1779 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00001780 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001781 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00001782 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00001783 RelocOffset -= SectionAddress;
1784
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001785 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00001786
Rafael Espindola806f0062013-06-05 01:33:53 +00001787 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001788 }
1789 array_pod_sort(Relocs.begin(), Relocs.end());
1790
Kevin Enderbybf246f52014-09-24 23:08:22 +00001791 // Create a map of symbol addresses to symbol names for use by
1792 // the SymbolizerSymbolLookUp() routine.
1793 SymbolAddressMap AddrMap;
1794 for (const SymbolRef &Symbol : MachOOF->symbols()) {
1795 SymbolRef::Type ST;
1796 Symbol.getType(ST);
1797 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1798 ST == SymbolRef::ST_Other) {
1799 uint64_t Address;
1800 Symbol.getAddress(Address);
1801 StringRef SymName;
1802 Symbol.getName(SymName);
1803 AddrMap[Address] = SymName;
1804 }
1805 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001806 // Set up the block of info used by the Symbolizer call backs.
1807 SymbolizerInfo.verbose = true;
1808 SymbolizerInfo.O = MachOOF;
1809 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00001810 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001811 SymbolizerInfo.Sections = &Sections;
1812 SymbolizerInfo.class_name = nullptr;
1813 SymbolizerInfo.selector_name = nullptr;
1814 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001815 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00001816 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00001817 SymbolizerInfo.adrp_addr = 0;
1818 SymbolizerInfo.adrp_inst = 0;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001819 // Same for the ThumbSymbolizer
1820 ThumbSymbolizerInfo.verbose = true;
1821 ThumbSymbolizerInfo.O = MachOOF;
1822 ThumbSymbolizerInfo.S = Sections[SectIdx];
1823 ThumbSymbolizerInfo.AddrMap = &AddrMap;
1824 ThumbSymbolizerInfo.Sections = &Sections;
1825 ThumbSymbolizerInfo.class_name = nullptr;
1826 ThumbSymbolizerInfo.selector_name = nullptr;
1827 ThumbSymbolizerInfo.method = nullptr;
1828 ThumbSymbolizerInfo.demangled_name = nullptr;
1829 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby10738222014-11-19 20:20:16 +00001830 ThumbSymbolizerInfo.adrp_addr = 0;
1831 ThumbSymbolizerInfo.adrp_inst = 0;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001832
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001833 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001834 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00001835 StringRef SymName;
1836 Symbols[SymIdx].getName(SymName);
1837
1838 SymbolRef::Type ST;
1839 Symbols[SymIdx].getType(ST);
1840 if (ST != SymbolRef::ST_Function)
1841 continue;
1842
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001843 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00001844 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00001845 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001846 continue;
1847
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001848 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00001849 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00001850 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00001851 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00001852 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00001853
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001854 // Stop disassembling either at the beginning of the next symbol or at
1855 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00001856 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00001857 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001858 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00001859 while (Symbols.size() > NextSymIdx) {
1860 SymbolRef::Type NextSymType;
1861 Symbols[NextSymIdx].getType(NextSymType);
1862 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00001863 containsNextSym =
1864 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00001865 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00001866 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00001867 break;
1868 }
1869 ++NextSymIdx;
1870 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001871
Rafael Espindola80291272014-10-08 15:28:58 +00001872 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001873 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00001874 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001875
1876 symbolTableWorked = true;
Rafael Espindolabd604f22014-11-07 00:52:15 +00001877
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001878 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
1879 bool isThumb =
1880 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
1881
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001882 outs() << SymName << ":\n";
1883 DILineInfo lastLine;
1884 for (uint64_t Index = Start; Index < End; Index += Size) {
1885 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00001886
Kevin Enderbybf246f52014-09-24 23:08:22 +00001887 uint64_t PC = SectAddress + Index;
1888 if (FullLeadingAddr) {
1889 if (MachOOF->is64Bit())
1890 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001891 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001892 outs() << format("%08" PRIx64, PC);
1893 } else {
1894 outs() << format("%8" PRIx64 ":", PC);
1895 }
1896 if (!NoShowRawInsn)
1897 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00001898
1899 // Check the data in code table here to see if this is data not an
1900 // instruction to be disassembled.
1901 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001902 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001903 dice_table_iterator DTI =
1904 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
1905 compareDiceTableEntries);
1906 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00001907 uint16_t Length;
1908 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00001909 uint16_t Kind;
1910 DTI->second.getKind(Kind);
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001911 Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
1912 Index,
1913 Length, Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001914 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
1915 (PC == (DTI->first + Length - 1)) && (Length & 1))
1916 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00001917 continue;
1918 }
1919
Kevin Enderbybf246f52014-09-24 23:08:22 +00001920 SmallVector<char, 64> AnnotationsBytes;
1921 raw_svector_ostream Annotations(AnnotationsBytes);
1922
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001923 bool gotInst;
1924 if (isThumb)
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001925 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001926 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001927 else
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001928 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00001929 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001930 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001931 if (!NoShowRawInsn) {
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001932 DumpBytes(StringRef(
1933 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001934 }
1935 formatted_raw_ostream FormattedOS(outs());
1936 Annotations.flush();
1937 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001938 if (isThumb)
Kevin Enderbybf246f52014-09-24 23:08:22 +00001939 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001940 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001941 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
1942 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00001943
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001944 // Print debug info.
1945 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001946 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001947 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00001948 if (dli != lastLine && dli.Line != 0)
1949 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
1950 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001951 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001952 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001953 outs() << "\n";
1954 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001955 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001956 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001957 outs() << format("\t.byte 0x%02x #bad opcode\n",
1958 *(Bytes.data() + Index) & 0xff);
1959 Size = 1; // skip exactly one illegible byte and move on.
Kevin Enderbyae3c1262014-11-14 21:52:18 +00001960 } else if (Arch == Triple::aarch64) {
1961 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
1962 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
1963 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
1964 (*(Bytes.data() + Index + 3) & 0xff) << 24;
1965 outs() << format("\t.long\t0x%08x\n", opcode);
1966 Size = 4;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001967 } else {
1968 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1969 if (Size == 0)
1970 Size = 1; // skip illegible bytes
1971 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001972 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001973 }
1974 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001975 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00001976 // Reading the symbol table didn't work, disassemble the whole section.
1977 uint64_t SectAddress = Sections[SectIdx].getAddress();
1978 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00001979 uint64_t InstSize;
1980 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00001981 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00001982
Kevin Enderbybf246f52014-09-24 23:08:22 +00001983 uint64_t PC = SectAddress + Index;
Rafael Espindola7fc5b872014-11-12 02:04:27 +00001984 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
1985 DebugOut, nulls())) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001986 if (FullLeadingAddr) {
1987 if (MachOOF->is64Bit())
1988 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001989 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001990 outs() << format("%08" PRIx64, PC);
1991 } else {
1992 outs() << format("%8" PRIx64 ":", PC);
1993 }
1994 if (!NoShowRawInsn) {
1995 outs() << "\t";
Aaron Ballman106fd7b2014-11-12 14:01:17 +00001996 DumpBytes(
1997 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
1998 InstSize));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001999 }
Bill Wendling4e68e062012-07-19 00:17:40 +00002000 IP->printInst(&Inst, outs(), "");
2001 outs() << "\n";
2002 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002003 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002004 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002005 outs() << format("\t.byte 0x%02x #bad opcode\n",
2006 *(Bytes.data() + Index) & 0xff);
2007 InstSize = 1; // skip exactly one illegible byte and move on.
2008 } else {
2009 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2010 if (InstSize == 0)
2011 InstSize = 1; // skip illegible bytes
2012 }
Bill Wendling4e68e062012-07-19 00:17:40 +00002013 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00002014 }
2015 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00002016 if (SymbolizerInfo.method != nullptr)
2017 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00002018 if (SymbolizerInfo.demangled_name != nullptr)
2019 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00002020 if (SymbolizerInfo.bindtable != nullptr)
2021 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00002022 if (ThumbSymbolizerInfo.method != nullptr)
2023 free(ThumbSymbolizerInfo.method);
2024 if (ThumbSymbolizerInfo.demangled_name != nullptr)
2025 free(ThumbSymbolizerInfo.demangled_name);
2026 if (ThumbSymbolizerInfo.bindtable != nullptr)
2027 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00002028 }
2029}
Tim Northover4bd286a2014-08-01 13:07:19 +00002030
Tim Northover39c70bb2014-08-12 11:52:59 +00002031//===----------------------------------------------------------------------===//
2032// __compact_unwind section dumping
2033//===----------------------------------------------------------------------===//
2034
Tim Northover4bd286a2014-08-01 13:07:19 +00002035namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00002036
2037template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002038 using llvm::support::little;
2039 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00002040
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002041 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2042 Buf += sizeof(T);
2043 return Val;
2044}
Tim Northover39c70bb2014-08-12 11:52:59 +00002045
Tim Northover4bd286a2014-08-01 13:07:19 +00002046struct CompactUnwindEntry {
2047 uint32_t OffsetInSection;
2048
2049 uint64_t FunctionAddr;
2050 uint32_t Length;
2051 uint32_t CompactEncoding;
2052 uint64_t PersonalityAddr;
2053 uint64_t LSDAAddr;
2054
2055 RelocationRef FunctionReloc;
2056 RelocationRef PersonalityReloc;
2057 RelocationRef LSDAReloc;
2058
2059 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002060 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002061 if (Is64)
2062 read<uint64_t>(Contents.data() + Offset);
2063 else
2064 read<uint32_t>(Contents.data() + Offset);
2065 }
2066
2067private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002068 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002069 FunctionAddr = readNext<UIntPtr>(Buf);
2070 Length = readNext<uint32_t>(Buf);
2071 CompactEncoding = readNext<uint32_t>(Buf);
2072 PersonalityAddr = readNext<UIntPtr>(Buf);
2073 LSDAAddr = readNext<UIntPtr>(Buf);
2074 }
2075};
2076}
2077
2078/// Given a relocation from __compact_unwind, consisting of the RelocationRef
2079/// and data being relocated, determine the best base Name and Addend to use for
2080/// display purposes.
2081///
2082/// 1. An Extern relocation will directly reference a symbol (and the data is
2083/// then already an addend), so use that.
2084/// 2. Otherwise the data is an offset in the object file's layout; try to find
2085// a symbol before it in the same section, and use the offset from there.
2086/// 3. Finally, if all that fails, fall back to an offset from the start of the
2087/// referenced section.
2088static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2089 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002090 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00002091 StringRef &Name, uint64_t &Addend) {
2092 if (Reloc.getSymbol() != Obj->symbol_end()) {
2093 Reloc.getSymbol()->getName(Name);
2094 Addend = Addr;
2095 return;
2096 }
2097
2098 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2099 SectionRef RelocSection = Obj->getRelocationSection(RE);
2100
Rafael Espindola80291272014-10-08 15:28:58 +00002101 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00002102
2103 auto Sym = Symbols.upper_bound(Addr);
2104 if (Sym == Symbols.begin()) {
2105 // The first symbol in the object is after this reference, the best we can
2106 // do is section-relative notation.
2107 RelocSection.getName(Name);
2108 Addend = Addr - SectionAddr;
2109 return;
2110 }
2111
2112 // Go back one so that SymbolAddress <= Addr.
2113 --Sym;
2114
2115 section_iterator SymSection = Obj->section_end();
2116 Sym->second.getSection(SymSection);
2117 if (RelocSection == *SymSection) {
2118 // There's a valid symbol in the same section before this reference.
2119 Sym->second.getName(Name);
2120 Addend = Addr - Sym->first;
2121 return;
2122 }
2123
2124 // There is a symbol before this reference, but it's in a different
2125 // section. Probably not helpful to mention it, so use the section name.
2126 RelocSection.getName(Name);
2127 Addend = Addr - SectionAddr;
2128}
2129
2130static void printUnwindRelocDest(const MachOObjectFile *Obj,
2131 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002132 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00002133 StringRef Name;
2134 uint64_t Addend;
2135
Tim Northover0b0add52014-09-09 10:45:06 +00002136 if (!Reloc.getObjectFile())
2137 return;
2138
Tim Northover4bd286a2014-08-01 13:07:19 +00002139 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2140
2141 outs() << Name;
2142 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00002143 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00002144}
2145
2146static void
2147printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2148 std::map<uint64_t, SymbolRef> &Symbols,
2149 const SectionRef &CompactUnwind) {
2150
2151 assert(Obj->isLittleEndian() &&
2152 "There should not be a big-endian .o with __compact_unwind");
2153
2154 bool Is64 = Obj->is64Bit();
2155 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2156 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2157
2158 StringRef Contents;
2159 CompactUnwind.getContents(Contents);
2160
2161 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2162
2163 // First populate the initial raw offsets, encodings and so on from the entry.
2164 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2165 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2166 CompactUnwinds.push_back(Entry);
2167 }
2168
2169 // Next we need to look at the relocations to find out what objects are
2170 // actually being referred to.
2171 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2172 uint64_t RelocAddress;
2173 Reloc.getOffset(RelocAddress);
2174
2175 uint32_t EntryIdx = RelocAddress / EntrySize;
2176 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2177 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2178
2179 if (OffsetInEntry == 0)
2180 Entry.FunctionReloc = Reloc;
2181 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2182 Entry.PersonalityReloc = Reloc;
2183 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2184 Entry.LSDAReloc = Reloc;
2185 else
2186 llvm_unreachable("Unexpected relocation in __compact_unwind section");
2187 }
2188
2189 // Finally, we're ready to print the data we've gathered.
2190 outs() << "Contents of __compact_unwind section:\n";
2191 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00002192 outs() << " Entry at offset "
2193 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00002194
2195 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002196 outs() << " start: " << format("0x%" PRIx64,
2197 Entry.FunctionAddr) << ' ';
2198 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00002199 outs() << '\n';
2200
2201 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002202 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
2203 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00002204 // 3. The 32-bit compact encoding.
2205 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00002206 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00002207
2208 // 4. The personality function, if present.
2209 if (Entry.PersonalityReloc.getObjectFile()) {
2210 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00002211 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00002212 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2213 Entry.PersonalityAddr);
2214 outs() << '\n';
2215 }
2216
2217 // 5. This entry's language-specific data area.
2218 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002219 outs() << " LSDA: " << format("0x%" PRIx64,
2220 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00002221 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2222 outs() << '\n';
2223 }
2224 }
2225}
2226
Tim Northover39c70bb2014-08-12 11:52:59 +00002227//===----------------------------------------------------------------------===//
2228// __unwind_info section dumping
2229//===----------------------------------------------------------------------===//
2230
2231static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2232 const char *Pos = PageStart;
2233 uint32_t Kind = readNext<uint32_t>(Pos);
2234 (void)Kind;
2235 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2236
2237 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2238 uint16_t NumEntries = readNext<uint16_t>(Pos);
2239
2240 Pos = PageStart + EntriesStart;
2241 for (unsigned i = 0; i < NumEntries; ++i) {
2242 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2243 uint32_t Encoding = readNext<uint32_t>(Pos);
2244
2245 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002246 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2247 << ", "
2248 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002249 }
2250}
2251
2252static void printCompressedSecondLevelUnwindPage(
2253 const char *PageStart, uint32_t FunctionBase,
2254 const SmallVectorImpl<uint32_t> &CommonEncodings) {
2255 const char *Pos = PageStart;
2256 uint32_t Kind = readNext<uint32_t>(Pos);
2257 (void)Kind;
2258 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2259
2260 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2261 uint16_t NumEntries = readNext<uint16_t>(Pos);
2262
2263 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
2264 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00002265 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
2266 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00002267
2268 Pos = PageStart + EntriesStart;
2269 for (unsigned i = 0; i < NumEntries; ++i) {
2270 uint32_t Entry = readNext<uint32_t>(Pos);
2271 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
2272 uint32_t EncodingIdx = Entry >> 24;
2273
2274 uint32_t Encoding;
2275 if (EncodingIdx < CommonEncodings.size())
2276 Encoding = CommonEncodings[EncodingIdx];
2277 else
2278 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
2279
2280 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002281 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2282 << ", "
2283 << "encoding[" << EncodingIdx
2284 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002285 }
2286}
2287
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002288static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
2289 std::map<uint64_t, SymbolRef> &Symbols,
2290 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00002291
2292 assert(Obj->isLittleEndian() &&
2293 "There should not be a big-endian .o with __unwind_info");
2294
2295 outs() << "Contents of __unwind_info section:\n";
2296
2297 StringRef Contents;
2298 UnwindInfo.getContents(Contents);
2299 const char *Pos = Contents.data();
2300
2301 //===----------------------------------
2302 // Section header
2303 //===----------------------------------
2304
2305 uint32_t Version = readNext<uint32_t>(Pos);
2306 outs() << " Version: "
2307 << format("0x%" PRIx32, Version) << '\n';
2308 assert(Version == 1 && "only understand version 1");
2309
2310 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
2311 outs() << " Common encodings array section offset: "
2312 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
2313 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
2314 outs() << " Number of common encodings in array: "
2315 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
2316
2317 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
2318 outs() << " Personality function array section offset: "
2319 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
2320 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
2321 outs() << " Number of personality functions in array: "
2322 << format("0x%" PRIx32, NumPersonalities) << '\n';
2323
2324 uint32_t IndicesStart = readNext<uint32_t>(Pos);
2325 outs() << " Index array section offset: "
2326 << format("0x%" PRIx32, IndicesStart) << '\n';
2327 uint32_t NumIndices = readNext<uint32_t>(Pos);
2328 outs() << " Number of indices in array: "
2329 << format("0x%" PRIx32, NumIndices) << '\n';
2330
2331 //===----------------------------------
2332 // A shared list of common encodings
2333 //===----------------------------------
2334
2335 // These occupy indices in the range [0, N] whenever an encoding is referenced
2336 // from a compressed 2nd level index table. In practice the linker only
2337 // creates ~128 of these, so that indices are available to embed encodings in
2338 // the 2nd level index.
2339
2340 SmallVector<uint32_t, 64> CommonEncodings;
2341 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
2342 Pos = Contents.data() + CommonEncodingsStart;
2343 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
2344 uint32_t Encoding = readNext<uint32_t>(Pos);
2345 CommonEncodings.push_back(Encoding);
2346
2347 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
2348 << '\n';
2349 }
2350
Tim Northover39c70bb2014-08-12 11:52:59 +00002351 //===----------------------------------
2352 // Personality functions used in this executable
2353 //===----------------------------------
2354
2355 // There should be only a handful of these (one per source language,
2356 // roughly). Particularly since they only get 2 bits in the compact encoding.
2357
2358 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
2359 Pos = Contents.data() + PersonalitiesStart;
2360 for (unsigned i = 0; i < NumPersonalities; ++i) {
2361 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
2362 outs() << " personality[" << i + 1
2363 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
2364 }
2365
2366 //===----------------------------------
2367 // The level 1 index entries
2368 //===----------------------------------
2369
2370 // These specify an approximate place to start searching for the more detailed
2371 // information, sorted by PC.
2372
2373 struct IndexEntry {
2374 uint32_t FunctionOffset;
2375 uint32_t SecondLevelPageStart;
2376 uint32_t LSDAStart;
2377 };
2378
2379 SmallVector<IndexEntry, 4> IndexEntries;
2380
2381 outs() << " Top level indices: (count = " << NumIndices << ")\n";
2382 Pos = Contents.data() + IndicesStart;
2383 for (unsigned i = 0; i < NumIndices; ++i) {
2384 IndexEntry Entry;
2385
2386 Entry.FunctionOffset = readNext<uint32_t>(Pos);
2387 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
2388 Entry.LSDAStart = readNext<uint32_t>(Pos);
2389 IndexEntries.push_back(Entry);
2390
2391 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002392 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
2393 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00002394 << "2nd level page offset="
2395 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002396 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002397 }
2398
Tim Northover39c70bb2014-08-12 11:52:59 +00002399 //===----------------------------------
2400 // Next come the LSDA tables
2401 //===----------------------------------
2402
2403 // The LSDA layout is rather implicit: it's a contiguous array of entries from
2404 // the first top-level index's LSDAOffset to the last (sentinel).
2405
2406 outs() << " LSDA descriptors:\n";
2407 Pos = Contents.data() + IndexEntries[0].LSDAStart;
2408 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2409 (2 * sizeof(uint32_t));
2410 for (int i = 0; i < NumLSDAs; ++i) {
2411 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2412 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2413 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002414 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2415 << ", "
2416 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002417 }
2418
2419 //===----------------------------------
2420 // Finally, the 2nd level indices
2421 //===----------------------------------
2422
2423 // Generally these are 4K in size, and have 2 possible forms:
2424 // + Regular stores up to 511 entries with disparate encodings
2425 // + Compressed stores up to 1021 entries if few enough compact encoding
2426 // values are used.
2427 outs() << " Second level indices:\n";
2428 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2429 // The final sentinel top-level index has no associated 2nd level page
2430 if (IndexEntries[i].SecondLevelPageStart == 0)
2431 break;
2432
2433 outs() << " Second level index[" << i << "]: "
2434 << "offset in section="
2435 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2436 << ", "
2437 << "base function offset="
2438 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2439
2440 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00002441 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00002442 if (Kind == 2)
2443 printRegularSecondLevelUnwindPage(Pos);
2444 else if (Kind == 3)
2445 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2446 CommonEncodings);
2447 else
2448 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00002449 }
2450}
2451
Tim Northover4bd286a2014-08-01 13:07:19 +00002452void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2453 std::map<uint64_t, SymbolRef> Symbols;
2454 for (const SymbolRef &SymRef : Obj->symbols()) {
2455 // Discard any undefined or absolute symbols. They're not going to take part
2456 // in the convenience lookup for unwind info and just take up resources.
2457 section_iterator Section = Obj->section_end();
2458 SymRef.getSection(Section);
2459 if (Section == Obj->section_end())
2460 continue;
2461
2462 uint64_t Addr;
2463 SymRef.getAddress(Addr);
2464 Symbols.insert(std::make_pair(Addr, SymRef));
2465 }
2466
2467 for (const SectionRef &Section : Obj->sections()) {
2468 StringRef SectName;
2469 Section.getName(SectName);
2470 if (SectName == "__compact_unwind")
2471 printMachOCompactUnwindSection(Obj, Symbols, Section);
2472 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00002473 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00002474 else if (SectName == "__eh_frame")
2475 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00002476 }
2477}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002478
2479static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2480 uint32_t cpusubtype, uint32_t filetype,
2481 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2482 bool verbose) {
2483 outs() << "Mach header\n";
2484 outs() << " magic cputype cpusubtype caps filetype ncmds "
2485 "sizeofcmds flags\n";
2486 if (verbose) {
2487 if (magic == MachO::MH_MAGIC)
2488 outs() << " MH_MAGIC";
2489 else if (magic == MachO::MH_MAGIC_64)
2490 outs() << "MH_MAGIC_64";
2491 else
2492 outs() << format(" 0x%08" PRIx32, magic);
2493 switch (cputype) {
2494 case MachO::CPU_TYPE_I386:
2495 outs() << " I386";
2496 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2497 case MachO::CPU_SUBTYPE_I386_ALL:
2498 outs() << " ALL";
2499 break;
2500 default:
2501 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2502 break;
2503 }
2504 break;
2505 case MachO::CPU_TYPE_X86_64:
2506 outs() << " X86_64";
2507 case MachO::CPU_SUBTYPE_X86_64_ALL:
2508 outs() << " ALL";
2509 break;
2510 case MachO::CPU_SUBTYPE_X86_64_H:
2511 outs() << " Haswell";
Aaron Ballman9d515ff2014-08-24 13:25:16 +00002512 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002513 break;
2514 case MachO::CPU_TYPE_ARM:
2515 outs() << " ARM";
2516 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2517 case MachO::CPU_SUBTYPE_ARM_ALL:
2518 outs() << " ALL";
2519 break;
2520 case MachO::CPU_SUBTYPE_ARM_V4T:
2521 outs() << " V4T";
2522 break;
2523 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2524 outs() << " V5TEJ";
2525 break;
2526 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2527 outs() << " XSCALE";
2528 break;
2529 case MachO::CPU_SUBTYPE_ARM_V6:
2530 outs() << " V6";
2531 break;
2532 case MachO::CPU_SUBTYPE_ARM_V6M:
2533 outs() << " V6M";
2534 break;
2535 case MachO::CPU_SUBTYPE_ARM_V7:
2536 outs() << " V7";
2537 break;
2538 case MachO::CPU_SUBTYPE_ARM_V7EM:
2539 outs() << " V7EM";
2540 break;
2541 case MachO::CPU_SUBTYPE_ARM_V7K:
2542 outs() << " V7K";
2543 break;
2544 case MachO::CPU_SUBTYPE_ARM_V7M:
2545 outs() << " V7M";
2546 break;
2547 case MachO::CPU_SUBTYPE_ARM_V7S:
2548 outs() << " V7S";
2549 break;
2550 default:
2551 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2552 break;
2553 }
2554 break;
2555 case MachO::CPU_TYPE_ARM64:
2556 outs() << " ARM64";
2557 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2558 case MachO::CPU_SUBTYPE_ARM64_ALL:
2559 outs() << " ALL";
2560 break;
2561 default:
2562 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2563 break;
2564 }
2565 break;
2566 case MachO::CPU_TYPE_POWERPC:
2567 outs() << " PPC";
2568 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2569 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2570 outs() << " ALL";
2571 break;
2572 default:
2573 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2574 break;
2575 }
2576 break;
2577 case MachO::CPU_TYPE_POWERPC64:
2578 outs() << " PPC64";
2579 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2580 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2581 outs() << " ALL";
2582 break;
2583 default:
2584 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2585 break;
2586 }
2587 break;
2588 }
2589 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002590 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002591 } else {
2592 outs() << format(" 0x%02" PRIx32,
2593 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2594 }
2595 switch (filetype) {
2596 case MachO::MH_OBJECT:
2597 outs() << " OBJECT";
2598 break;
2599 case MachO::MH_EXECUTE:
2600 outs() << " EXECUTE";
2601 break;
2602 case MachO::MH_FVMLIB:
2603 outs() << " FVMLIB";
2604 break;
2605 case MachO::MH_CORE:
2606 outs() << " CORE";
2607 break;
2608 case MachO::MH_PRELOAD:
2609 outs() << " PRELOAD";
2610 break;
2611 case MachO::MH_DYLIB:
2612 outs() << " DYLIB";
2613 break;
2614 case MachO::MH_DYLIB_STUB:
2615 outs() << " DYLIB_STUB";
2616 break;
2617 case MachO::MH_DYLINKER:
2618 outs() << " DYLINKER";
2619 break;
2620 case MachO::MH_BUNDLE:
2621 outs() << " BUNDLE";
2622 break;
2623 case MachO::MH_DSYM:
2624 outs() << " DSYM";
2625 break;
2626 case MachO::MH_KEXT_BUNDLE:
2627 outs() << " KEXTBUNDLE";
2628 break;
2629 default:
2630 outs() << format(" %10u", filetype);
2631 break;
2632 }
2633 outs() << format(" %5u", ncmds);
2634 outs() << format(" %10u", sizeofcmds);
2635 uint32_t f = flags;
2636 if (f & MachO::MH_NOUNDEFS) {
2637 outs() << " NOUNDEFS";
2638 f &= ~MachO::MH_NOUNDEFS;
2639 }
2640 if (f & MachO::MH_INCRLINK) {
2641 outs() << " INCRLINK";
2642 f &= ~MachO::MH_INCRLINK;
2643 }
2644 if (f & MachO::MH_DYLDLINK) {
2645 outs() << " DYLDLINK";
2646 f &= ~MachO::MH_DYLDLINK;
2647 }
2648 if (f & MachO::MH_BINDATLOAD) {
2649 outs() << " BINDATLOAD";
2650 f &= ~MachO::MH_BINDATLOAD;
2651 }
2652 if (f & MachO::MH_PREBOUND) {
2653 outs() << " PREBOUND";
2654 f &= ~MachO::MH_PREBOUND;
2655 }
2656 if (f & MachO::MH_SPLIT_SEGS) {
2657 outs() << " SPLIT_SEGS";
2658 f &= ~MachO::MH_SPLIT_SEGS;
2659 }
2660 if (f & MachO::MH_LAZY_INIT) {
2661 outs() << " LAZY_INIT";
2662 f &= ~MachO::MH_LAZY_INIT;
2663 }
2664 if (f & MachO::MH_TWOLEVEL) {
2665 outs() << " TWOLEVEL";
2666 f &= ~MachO::MH_TWOLEVEL;
2667 }
2668 if (f & MachO::MH_FORCE_FLAT) {
2669 outs() << " FORCE_FLAT";
2670 f &= ~MachO::MH_FORCE_FLAT;
2671 }
2672 if (f & MachO::MH_NOMULTIDEFS) {
2673 outs() << " NOMULTIDEFS";
2674 f &= ~MachO::MH_NOMULTIDEFS;
2675 }
2676 if (f & MachO::MH_NOFIXPREBINDING) {
2677 outs() << " NOFIXPREBINDING";
2678 f &= ~MachO::MH_NOFIXPREBINDING;
2679 }
2680 if (f & MachO::MH_PREBINDABLE) {
2681 outs() << " PREBINDABLE";
2682 f &= ~MachO::MH_PREBINDABLE;
2683 }
2684 if (f & MachO::MH_ALLMODSBOUND) {
2685 outs() << " ALLMODSBOUND";
2686 f &= ~MachO::MH_ALLMODSBOUND;
2687 }
2688 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
2689 outs() << " SUBSECTIONS_VIA_SYMBOLS";
2690 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
2691 }
2692 if (f & MachO::MH_CANONICAL) {
2693 outs() << " CANONICAL";
2694 f &= ~MachO::MH_CANONICAL;
2695 }
2696 if (f & MachO::MH_WEAK_DEFINES) {
2697 outs() << " WEAK_DEFINES";
2698 f &= ~MachO::MH_WEAK_DEFINES;
2699 }
2700 if (f & MachO::MH_BINDS_TO_WEAK) {
2701 outs() << " BINDS_TO_WEAK";
2702 f &= ~MachO::MH_BINDS_TO_WEAK;
2703 }
2704 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
2705 outs() << " ALLOW_STACK_EXECUTION";
2706 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
2707 }
2708 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
2709 outs() << " DEAD_STRIPPABLE_DYLIB";
2710 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
2711 }
2712 if (f & MachO::MH_PIE) {
2713 outs() << " PIE";
2714 f &= ~MachO::MH_PIE;
2715 }
2716 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
2717 outs() << " NO_REEXPORTED_DYLIBS";
2718 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
2719 }
2720 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
2721 outs() << " MH_HAS_TLV_DESCRIPTORS";
2722 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
2723 }
2724 if (f & MachO::MH_NO_HEAP_EXECUTION) {
2725 outs() << " MH_NO_HEAP_EXECUTION";
2726 f &= ~MachO::MH_NO_HEAP_EXECUTION;
2727 }
2728 if (f & MachO::MH_APP_EXTENSION_SAFE) {
2729 outs() << " APP_EXTENSION_SAFE";
2730 f &= ~MachO::MH_APP_EXTENSION_SAFE;
2731 }
2732 if (f != 0 || flags == 0)
2733 outs() << format(" 0x%08" PRIx32, f);
2734 } else {
2735 outs() << format(" 0x%08" PRIx32, magic);
2736 outs() << format(" %7d", cputype);
2737 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2738 outs() << format(" 0x%02" PRIx32,
2739 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2740 outs() << format(" %10u", filetype);
2741 outs() << format(" %5u", ncmds);
2742 outs() << format(" %10u", sizeofcmds);
2743 outs() << format(" 0x%08" PRIx32, flags);
2744 }
2745 outs() << "\n";
2746}
2747
Kevin Enderby956366c2014-08-29 22:30:52 +00002748static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
2749 StringRef SegName, uint64_t vmaddr,
2750 uint64_t vmsize, uint64_t fileoff,
2751 uint64_t filesize, uint32_t maxprot,
2752 uint32_t initprot, uint32_t nsects,
2753 uint32_t flags, uint32_t object_size,
2754 bool verbose) {
2755 uint64_t expected_cmdsize;
2756 if (cmd == MachO::LC_SEGMENT) {
2757 outs() << " cmd LC_SEGMENT\n";
2758 expected_cmdsize = nsects;
2759 expected_cmdsize *= sizeof(struct MachO::section);
2760 expected_cmdsize += sizeof(struct MachO::segment_command);
2761 } else {
2762 outs() << " cmd LC_SEGMENT_64\n";
2763 expected_cmdsize = nsects;
2764 expected_cmdsize *= sizeof(struct MachO::section_64);
2765 expected_cmdsize += sizeof(struct MachO::segment_command_64);
2766 }
2767 outs() << " cmdsize " << cmdsize;
2768 if (cmdsize != expected_cmdsize)
2769 outs() << " Inconsistent size\n";
2770 else
2771 outs() << "\n";
2772 outs() << " segname " << SegName << "\n";
2773 if (cmd == MachO::LC_SEGMENT_64) {
2774 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
2775 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
2776 } else {
2777 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
2778 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
2779 }
2780 outs() << " fileoff " << fileoff;
2781 if (fileoff > object_size)
2782 outs() << " (past end of file)\n";
2783 else
2784 outs() << "\n";
2785 outs() << " filesize " << filesize;
2786 if (fileoff + filesize > object_size)
2787 outs() << " (past end of file)\n";
2788 else
2789 outs() << "\n";
2790 if (verbose) {
2791 if ((maxprot &
2792 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2793 MachO::VM_PROT_EXECUTE)) != 0)
2794 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
2795 else {
2796 if (maxprot & MachO::VM_PROT_READ)
2797 outs() << " maxprot r";
2798 else
2799 outs() << " maxprot -";
2800 if (maxprot & MachO::VM_PROT_WRITE)
2801 outs() << "w";
2802 else
2803 outs() << "-";
2804 if (maxprot & MachO::VM_PROT_EXECUTE)
2805 outs() << "x\n";
2806 else
2807 outs() << "-\n";
2808 }
2809 if ((initprot &
2810 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2811 MachO::VM_PROT_EXECUTE)) != 0)
2812 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
2813 else {
2814 if (initprot & MachO::VM_PROT_READ)
2815 outs() << " initprot r";
2816 else
2817 outs() << " initprot -";
2818 if (initprot & MachO::VM_PROT_WRITE)
2819 outs() << "w";
2820 else
2821 outs() << "-";
2822 if (initprot & MachO::VM_PROT_EXECUTE)
2823 outs() << "x\n";
2824 else
2825 outs() << "-\n";
2826 }
2827 } else {
2828 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
2829 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
2830 }
2831 outs() << " nsects " << nsects << "\n";
2832 if (verbose) {
2833 outs() << " flags";
2834 if (flags == 0)
2835 outs() << " (none)\n";
2836 else {
2837 if (flags & MachO::SG_HIGHVM) {
2838 outs() << " HIGHVM";
2839 flags &= ~MachO::SG_HIGHVM;
2840 }
2841 if (flags & MachO::SG_FVMLIB) {
2842 outs() << " FVMLIB";
2843 flags &= ~MachO::SG_FVMLIB;
2844 }
2845 if (flags & MachO::SG_NORELOC) {
2846 outs() << " NORELOC";
2847 flags &= ~MachO::SG_NORELOC;
2848 }
2849 if (flags & MachO::SG_PROTECTED_VERSION_1) {
2850 outs() << " PROTECTED_VERSION_1";
2851 flags &= ~MachO::SG_PROTECTED_VERSION_1;
2852 }
2853 if (flags)
2854 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
2855 else
2856 outs() << "\n";
2857 }
2858 } else {
2859 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
2860 }
2861}
2862
2863static void PrintSection(const char *sectname, const char *segname,
2864 uint64_t addr, uint64_t size, uint32_t offset,
2865 uint32_t align, uint32_t reloff, uint32_t nreloc,
2866 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
2867 uint32_t cmd, const char *sg_segname,
2868 uint32_t filetype, uint32_t object_size,
2869 bool verbose) {
2870 outs() << "Section\n";
2871 outs() << " sectname " << format("%.16s\n", sectname);
2872 outs() << " segname " << format("%.16s", segname);
2873 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
2874 outs() << " (does not match segment)\n";
2875 else
2876 outs() << "\n";
2877 if (cmd == MachO::LC_SEGMENT_64) {
2878 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
2879 outs() << " size " << format("0x%016" PRIx64, size);
2880 } else {
2881 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
2882 outs() << " size " << format("0x%08" PRIx32, size);
2883 }
2884 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
2885 outs() << " (past end of file)\n";
2886 else
2887 outs() << "\n";
2888 outs() << " offset " << offset;
2889 if (offset > object_size)
2890 outs() << " (past end of file)\n";
2891 else
2892 outs() << "\n";
2893 uint32_t align_shifted = 1 << align;
2894 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
2895 outs() << " reloff " << reloff;
2896 if (reloff > object_size)
2897 outs() << " (past end of file)\n";
2898 else
2899 outs() << "\n";
2900 outs() << " nreloc " << nreloc;
2901 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
2902 outs() << " (past end of file)\n";
2903 else
2904 outs() << "\n";
2905 uint32_t section_type = flags & MachO::SECTION_TYPE;
2906 if (verbose) {
2907 outs() << " type";
2908 if (section_type == MachO::S_REGULAR)
2909 outs() << " S_REGULAR\n";
2910 else if (section_type == MachO::S_ZEROFILL)
2911 outs() << " S_ZEROFILL\n";
2912 else if (section_type == MachO::S_CSTRING_LITERALS)
2913 outs() << " S_CSTRING_LITERALS\n";
2914 else if (section_type == MachO::S_4BYTE_LITERALS)
2915 outs() << " S_4BYTE_LITERALS\n";
2916 else if (section_type == MachO::S_8BYTE_LITERALS)
2917 outs() << " S_8BYTE_LITERALS\n";
2918 else if (section_type == MachO::S_16BYTE_LITERALS)
2919 outs() << " S_16BYTE_LITERALS\n";
2920 else if (section_type == MachO::S_LITERAL_POINTERS)
2921 outs() << " S_LITERAL_POINTERS\n";
2922 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
2923 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
2924 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
2925 outs() << " S_LAZY_SYMBOL_POINTERS\n";
2926 else if (section_type == MachO::S_SYMBOL_STUBS)
2927 outs() << " S_SYMBOL_STUBS\n";
2928 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
2929 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
2930 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
2931 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
2932 else if (section_type == MachO::S_COALESCED)
2933 outs() << " S_COALESCED\n";
2934 else if (section_type == MachO::S_INTERPOSING)
2935 outs() << " S_INTERPOSING\n";
2936 else if (section_type == MachO::S_DTRACE_DOF)
2937 outs() << " S_DTRACE_DOF\n";
2938 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
2939 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
2940 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
2941 outs() << " S_THREAD_LOCAL_REGULAR\n";
2942 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
2943 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
2944 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
2945 outs() << " S_THREAD_LOCAL_VARIABLES\n";
2946 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2947 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
2948 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
2949 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
2950 else
2951 outs() << format("0x%08" PRIx32, section_type) << "\n";
2952 outs() << "attributes";
2953 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
2954 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
2955 outs() << " PURE_INSTRUCTIONS";
2956 if (section_attributes & MachO::S_ATTR_NO_TOC)
2957 outs() << " NO_TOC";
2958 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
2959 outs() << " STRIP_STATIC_SYMS";
2960 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
2961 outs() << " NO_DEAD_STRIP";
2962 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
2963 outs() << " LIVE_SUPPORT";
2964 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
2965 outs() << " SELF_MODIFYING_CODE";
2966 if (section_attributes & MachO::S_ATTR_DEBUG)
2967 outs() << " DEBUG";
2968 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
2969 outs() << " SOME_INSTRUCTIONS";
2970 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
2971 outs() << " EXT_RELOC";
2972 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
2973 outs() << " LOC_RELOC";
2974 if (section_attributes == 0)
2975 outs() << " (none)";
2976 outs() << "\n";
2977 } else
2978 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
2979 outs() << " reserved1 " << reserved1;
2980 if (section_type == MachO::S_SYMBOL_STUBS ||
2981 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2982 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2983 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2984 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2985 outs() << " (index into indirect symbol table)\n";
2986 else
2987 outs() << "\n";
2988 outs() << " reserved2 " << reserved2;
2989 if (section_type == MachO::S_SYMBOL_STUBS)
2990 outs() << " (size of stubs)\n";
2991 else
2992 outs() << "\n";
2993}
2994
David Majnemer73cc6ff2014-11-13 19:48:56 +00002995static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
Kevin Enderby956366c2014-08-29 22:30:52 +00002996 uint32_t object_size) {
2997 outs() << " cmd LC_SYMTAB\n";
2998 outs() << " cmdsize " << st.cmdsize;
2999 if (st.cmdsize != sizeof(struct MachO::symtab_command))
3000 outs() << " Incorrect size\n";
3001 else
3002 outs() << "\n";
3003 outs() << " symoff " << st.symoff;
3004 if (st.symoff > object_size)
3005 outs() << " (past end of file)\n";
3006 else
3007 outs() << "\n";
3008 outs() << " nsyms " << st.nsyms;
3009 uint64_t big_size;
David Majnemer73cc6ff2014-11-13 19:48:56 +00003010 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003011 big_size = st.nsyms;
3012 big_size *= sizeof(struct MachO::nlist_64);
3013 big_size += st.symoff;
3014 if (big_size > object_size)
3015 outs() << " (past end of file)\n";
3016 else
3017 outs() << "\n";
3018 } else {
3019 big_size = st.nsyms;
3020 big_size *= sizeof(struct MachO::nlist);
3021 big_size += st.symoff;
3022 if (big_size > object_size)
3023 outs() << " (past end of file)\n";
3024 else
3025 outs() << "\n";
3026 }
3027 outs() << " stroff " << st.stroff;
3028 if (st.stroff > object_size)
3029 outs() << " (past end of file)\n";
3030 else
3031 outs() << "\n";
3032 outs() << " strsize " << st.strsize;
3033 big_size = st.stroff;
3034 big_size += st.strsize;
3035 if (big_size > object_size)
3036 outs() << " (past end of file)\n";
3037 else
3038 outs() << "\n";
3039}
3040
3041static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3042 uint32_t nsyms, uint32_t object_size,
David Majnemer73cc6ff2014-11-13 19:48:56 +00003043 bool Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003044 outs() << " cmd LC_DYSYMTAB\n";
3045 outs() << " cmdsize " << dyst.cmdsize;
3046 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3047 outs() << " Incorrect size\n";
3048 else
3049 outs() << "\n";
3050 outs() << " ilocalsym " << dyst.ilocalsym;
3051 if (dyst.ilocalsym > nsyms)
3052 outs() << " (greater than the number of symbols)\n";
3053 else
3054 outs() << "\n";
3055 outs() << " nlocalsym " << dyst.nlocalsym;
3056 uint64_t big_size;
3057 big_size = dyst.ilocalsym;
3058 big_size += dyst.nlocalsym;
3059 if (big_size > nsyms)
3060 outs() << " (past the end of the symbol table)\n";
3061 else
3062 outs() << "\n";
3063 outs() << " iextdefsym " << dyst.iextdefsym;
3064 if (dyst.iextdefsym > nsyms)
3065 outs() << " (greater than the number of symbols)\n";
3066 else
3067 outs() << "\n";
3068 outs() << " nextdefsym " << dyst.nextdefsym;
3069 big_size = dyst.iextdefsym;
3070 big_size += dyst.nextdefsym;
3071 if (big_size > nsyms)
3072 outs() << " (past the end of the symbol table)\n";
3073 else
3074 outs() << "\n";
3075 outs() << " iundefsym " << dyst.iundefsym;
3076 if (dyst.iundefsym > nsyms)
3077 outs() << " (greater than the number of symbols)\n";
3078 else
3079 outs() << "\n";
3080 outs() << " nundefsym " << dyst.nundefsym;
3081 big_size = dyst.iundefsym;
3082 big_size += dyst.nundefsym;
3083 if (big_size > nsyms)
3084 outs() << " (past the end of the symbol table)\n";
3085 else
3086 outs() << "\n";
3087 outs() << " tocoff " << dyst.tocoff;
3088 if (dyst.tocoff > object_size)
3089 outs() << " (past end of file)\n";
3090 else
3091 outs() << "\n";
3092 outs() << " ntoc " << dyst.ntoc;
3093 big_size = dyst.ntoc;
3094 big_size *= sizeof(struct MachO::dylib_table_of_contents);
3095 big_size += dyst.tocoff;
3096 if (big_size > object_size)
3097 outs() << " (past end of file)\n";
3098 else
3099 outs() << "\n";
3100 outs() << " modtaboff " << dyst.modtaboff;
3101 if (dyst.modtaboff > object_size)
3102 outs() << " (past end of file)\n";
3103 else
3104 outs() << "\n";
3105 outs() << " nmodtab " << dyst.nmodtab;
3106 uint64_t modtabend;
David Majnemer73cc6ff2014-11-13 19:48:56 +00003107 if (Is64Bit) {
Kevin Enderby956366c2014-08-29 22:30:52 +00003108 modtabend = dyst.nmodtab;
3109 modtabend *= sizeof(struct MachO::dylib_module_64);
3110 modtabend += dyst.modtaboff;
3111 } else {
3112 modtabend = dyst.nmodtab;
3113 modtabend *= sizeof(struct MachO::dylib_module);
3114 modtabend += dyst.modtaboff;
3115 }
3116 if (modtabend > object_size)
3117 outs() << " (past end of file)\n";
3118 else
3119 outs() << "\n";
3120 outs() << " extrefsymoff " << dyst.extrefsymoff;
3121 if (dyst.extrefsymoff > object_size)
3122 outs() << " (past end of file)\n";
3123 else
3124 outs() << "\n";
3125 outs() << " nextrefsyms " << dyst.nextrefsyms;
3126 big_size = dyst.nextrefsyms;
3127 big_size *= sizeof(struct MachO::dylib_reference);
3128 big_size += dyst.extrefsymoff;
3129 if (big_size > object_size)
3130 outs() << " (past end of file)\n";
3131 else
3132 outs() << "\n";
3133 outs() << " indirectsymoff " << dyst.indirectsymoff;
3134 if (dyst.indirectsymoff > object_size)
3135 outs() << " (past end of file)\n";
3136 else
3137 outs() << "\n";
3138 outs() << " nindirectsyms " << dyst.nindirectsyms;
3139 big_size = dyst.nindirectsyms;
3140 big_size *= sizeof(uint32_t);
3141 big_size += dyst.indirectsymoff;
3142 if (big_size > object_size)
3143 outs() << " (past end of file)\n";
3144 else
3145 outs() << "\n";
3146 outs() << " extreloff " << dyst.extreloff;
3147 if (dyst.extreloff > object_size)
3148 outs() << " (past end of file)\n";
3149 else
3150 outs() << "\n";
3151 outs() << " nextrel " << dyst.nextrel;
3152 big_size = dyst.nextrel;
3153 big_size *= sizeof(struct MachO::relocation_info);
3154 big_size += dyst.extreloff;
3155 if (big_size > object_size)
3156 outs() << " (past end of file)\n";
3157 else
3158 outs() << "\n";
3159 outs() << " locreloff " << dyst.locreloff;
3160 if (dyst.locreloff > object_size)
3161 outs() << " (past end of file)\n";
3162 else
3163 outs() << "\n";
3164 outs() << " nlocrel " << dyst.nlocrel;
3165 big_size = dyst.nlocrel;
3166 big_size *= sizeof(struct MachO::relocation_info);
3167 big_size += dyst.locreloff;
3168 if (big_size > object_size)
3169 outs() << " (past end of file)\n";
3170 else
3171 outs() << "\n";
3172}
3173
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003174static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3175 uint32_t object_size) {
3176 if (dc.cmd == MachO::LC_DYLD_INFO)
3177 outs() << " cmd LC_DYLD_INFO\n";
3178 else
3179 outs() << " cmd LC_DYLD_INFO_ONLY\n";
3180 outs() << " cmdsize " << dc.cmdsize;
3181 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3182 outs() << " Incorrect size\n";
3183 else
3184 outs() << "\n";
3185 outs() << " rebase_off " << dc.rebase_off;
3186 if (dc.rebase_off > object_size)
3187 outs() << " (past end of file)\n";
3188 else
3189 outs() << "\n";
3190 outs() << " rebase_size " << dc.rebase_size;
3191 uint64_t big_size;
3192 big_size = dc.rebase_off;
3193 big_size += dc.rebase_size;
3194 if (big_size > object_size)
3195 outs() << " (past end of file)\n";
3196 else
3197 outs() << "\n";
3198 outs() << " bind_off " << dc.bind_off;
3199 if (dc.bind_off > object_size)
3200 outs() << " (past end of file)\n";
3201 else
3202 outs() << "\n";
3203 outs() << " bind_size " << dc.bind_size;
3204 big_size = dc.bind_off;
3205 big_size += dc.bind_size;
3206 if (big_size > object_size)
3207 outs() << " (past end of file)\n";
3208 else
3209 outs() << "\n";
3210 outs() << " weak_bind_off " << dc.weak_bind_off;
3211 if (dc.weak_bind_off > object_size)
3212 outs() << " (past end of file)\n";
3213 else
3214 outs() << "\n";
3215 outs() << " weak_bind_size " << dc.weak_bind_size;
3216 big_size = dc.weak_bind_off;
3217 big_size += dc.weak_bind_size;
3218 if (big_size > object_size)
3219 outs() << " (past end of file)\n";
3220 else
3221 outs() << "\n";
3222 outs() << " lazy_bind_off " << dc.lazy_bind_off;
3223 if (dc.lazy_bind_off > object_size)
3224 outs() << " (past end of file)\n";
3225 else
3226 outs() << "\n";
3227 outs() << " lazy_bind_size " << dc.lazy_bind_size;
3228 big_size = dc.lazy_bind_off;
3229 big_size += dc.lazy_bind_size;
3230 if (big_size > object_size)
3231 outs() << " (past end of file)\n";
3232 else
3233 outs() << "\n";
3234 outs() << " export_off " << dc.export_off;
3235 if (dc.export_off > object_size)
3236 outs() << " (past end of file)\n";
3237 else
3238 outs() << "\n";
3239 outs() << " export_size " << dc.export_size;
3240 big_size = dc.export_off;
3241 big_size += dc.export_size;
3242 if (big_size > object_size)
3243 outs() << " (past end of file)\n";
3244 else
3245 outs() << "\n";
3246}
3247
3248static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3249 const char *Ptr) {
3250 if (dyld.cmd == MachO::LC_ID_DYLINKER)
3251 outs() << " cmd LC_ID_DYLINKER\n";
3252 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3253 outs() << " cmd LC_LOAD_DYLINKER\n";
3254 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3255 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
3256 else
3257 outs() << " cmd ?(" << dyld.cmd << ")\n";
3258 outs() << " cmdsize " << dyld.cmdsize;
3259 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
3260 outs() << " Incorrect size\n";
3261 else
3262 outs() << "\n";
3263 if (dyld.name >= dyld.cmdsize)
3264 outs() << " name ?(bad offset " << dyld.name << ")\n";
3265 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003266 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003267 outs() << " name " << P << " (offset " << dyld.name << ")\n";
3268 }
3269}
3270
3271static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
3272 outs() << " cmd LC_UUID\n";
3273 outs() << " cmdsize " << uuid.cmdsize;
3274 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
3275 outs() << " Incorrect size\n";
3276 else
3277 outs() << "\n";
3278 outs() << " uuid ";
3279 outs() << format("%02" PRIX32, uuid.uuid[0]);
3280 outs() << format("%02" PRIX32, uuid.uuid[1]);
3281 outs() << format("%02" PRIX32, uuid.uuid[2]);
3282 outs() << format("%02" PRIX32, uuid.uuid[3]);
3283 outs() << "-";
3284 outs() << format("%02" PRIX32, uuid.uuid[4]);
3285 outs() << format("%02" PRIX32, uuid.uuid[5]);
3286 outs() << "-";
3287 outs() << format("%02" PRIX32, uuid.uuid[6]);
3288 outs() << format("%02" PRIX32, uuid.uuid[7]);
3289 outs() << "-";
3290 outs() << format("%02" PRIX32, uuid.uuid[8]);
3291 outs() << format("%02" PRIX32, uuid.uuid[9]);
3292 outs() << "-";
3293 outs() << format("%02" PRIX32, uuid.uuid[10]);
3294 outs() << format("%02" PRIX32, uuid.uuid[11]);
3295 outs() << format("%02" PRIX32, uuid.uuid[12]);
3296 outs() << format("%02" PRIX32, uuid.uuid[13]);
3297 outs() << format("%02" PRIX32, uuid.uuid[14]);
3298 outs() << format("%02" PRIX32, uuid.uuid[15]);
3299 outs() << "\n";
3300}
3301
3302static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
3303 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
3304 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
3305 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
3306 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
3307 else
3308 outs() << " cmd " << vd.cmd << " (?)\n";
3309 outs() << " cmdsize " << vd.cmdsize;
3310 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
3311 outs() << " Incorrect size\n";
3312 else
3313 outs() << "\n";
3314 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
3315 << ((vd.version >> 8) & 0xff);
3316 if ((vd.version & 0xff) != 0)
3317 outs() << "." << (vd.version & 0xff);
3318 outs() << "\n";
3319 if (vd.sdk == 0)
3320 outs() << " sdk n/a\n";
3321 else {
3322 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
3323 << ((vd.sdk >> 8) & 0xff);
3324 }
3325 if ((vd.sdk & 0xff) != 0)
3326 outs() << "." << (vd.sdk & 0xff);
3327 outs() << "\n";
3328}
3329
3330static void PrintSourceVersionCommand(MachO::source_version_command sd) {
3331 outs() << " cmd LC_SOURCE_VERSION\n";
3332 outs() << " cmdsize " << sd.cmdsize;
3333 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
3334 outs() << " Incorrect size\n";
3335 else
3336 outs() << "\n";
3337 uint64_t a = (sd.version >> 40) & 0xffffff;
3338 uint64_t b = (sd.version >> 30) & 0x3ff;
3339 uint64_t c = (sd.version >> 20) & 0x3ff;
3340 uint64_t d = (sd.version >> 10) & 0x3ff;
3341 uint64_t e = sd.version & 0x3ff;
3342 outs() << " version " << a << "." << b;
3343 if (e != 0)
3344 outs() << "." << c << "." << d << "." << e;
3345 else if (d != 0)
3346 outs() << "." << c << "." << d;
3347 else if (c != 0)
3348 outs() << "." << c;
3349 outs() << "\n";
3350}
3351
3352static void PrintEntryPointCommand(MachO::entry_point_command ep) {
3353 outs() << " cmd LC_MAIN\n";
3354 outs() << " cmdsize " << ep.cmdsize;
3355 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
3356 outs() << " Incorrect size\n";
3357 else
3358 outs() << "\n";
3359 outs() << " entryoff " << ep.entryoff << "\n";
3360 outs() << " stacksize " << ep.stacksize << "\n";
3361}
3362
3363static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
3364 if (dl.cmd == MachO::LC_ID_DYLIB)
3365 outs() << " cmd LC_ID_DYLIB\n";
3366 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
3367 outs() << " cmd LC_LOAD_DYLIB\n";
3368 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
3369 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
3370 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
3371 outs() << " cmd LC_REEXPORT_DYLIB\n";
3372 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
3373 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
3374 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
3375 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
3376 else
3377 outs() << " cmd " << dl.cmd << " (unknown)\n";
3378 outs() << " cmdsize " << dl.cmdsize;
3379 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
3380 outs() << " Incorrect size\n";
3381 else
3382 outs() << "\n";
3383 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003384 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003385 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
3386 } else {
3387 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
3388 }
3389 outs() << " time stamp " << dl.dylib.timestamp << " ";
3390 time_t t = dl.dylib.timestamp;
3391 outs() << ctime(&t);
3392 outs() << " current version ";
3393 if (dl.dylib.current_version == 0xffffffff)
3394 outs() << "n/a\n";
3395 else
3396 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
3397 << ((dl.dylib.current_version >> 8) & 0xff) << "."
3398 << (dl.dylib.current_version & 0xff) << "\n";
3399 outs() << "compatibility version ";
3400 if (dl.dylib.compatibility_version == 0xffffffff)
3401 outs() << "n/a\n";
3402 else
3403 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
3404 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
3405 << (dl.dylib.compatibility_version & 0xff) << "\n";
3406}
3407
3408static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
3409 uint32_t object_size) {
3410 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
3411 outs() << " cmd LC_FUNCTION_STARTS\n";
3412 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
3413 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
3414 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
3415 outs() << " cmd LC_FUNCTION_STARTS\n";
3416 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
3417 outs() << " cmd LC_DATA_IN_CODE\n";
3418 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
3419 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
3420 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
3421 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
3422 else
3423 outs() << " cmd " << ld.cmd << " (?)\n";
3424 outs() << " cmdsize " << ld.cmdsize;
3425 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
3426 outs() << " Incorrect size\n";
3427 else
3428 outs() << "\n";
3429 outs() << " dataoff " << ld.dataoff;
3430 if (ld.dataoff > object_size)
3431 outs() << " (past end of file)\n";
3432 else
3433 outs() << "\n";
3434 outs() << " datasize " << ld.datasize;
3435 uint64_t big_size = ld.dataoff;
3436 big_size += ld.datasize;
3437 if (big_size > object_size)
3438 outs() << " (past end of file)\n";
3439 else
3440 outs() << "\n";
3441}
3442
Kevin Enderby956366c2014-08-29 22:30:52 +00003443static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
3444 uint32_t filetype, uint32_t cputype,
3445 bool verbose) {
3446 StringRef Buf = Obj->getData();
3447 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
3448 for (unsigned i = 0;; ++i) {
3449 outs() << "Load command " << i << "\n";
3450 if (Command.C.cmd == MachO::LC_SEGMENT) {
3451 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
3452 const char *sg_segname = SLC.segname;
3453 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
3454 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
3455 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
3456 verbose);
3457 for (unsigned j = 0; j < SLC.nsects; j++) {
3458 MachO::section_64 S = Obj->getSection64(Command, j);
3459 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
3460 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
3461 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
3462 }
3463 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3464 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
3465 const char *sg_segname = SLC_64.segname;
3466 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
3467 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
3468 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
3469 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
3470 for (unsigned j = 0; j < SLC_64.nsects; j++) {
3471 MachO::section_64 S_64 = Obj->getSection64(Command, j);
3472 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
3473 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
3474 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
3475 sg_segname, filetype, Buf.size(), verbose);
3476 }
3477 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
3478 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00003479 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00003480 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
3481 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
3482 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
David Majnemer73cc6ff2014-11-13 19:48:56 +00003483 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
3484 Obj->is64Bit());
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003485 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
3486 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
3487 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
3488 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
3489 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
3490 Command.C.cmd == MachO::LC_ID_DYLINKER ||
3491 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
3492 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
3493 PrintDyldLoadCommand(Dyld, Command.Ptr);
3494 } else if (Command.C.cmd == MachO::LC_UUID) {
3495 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
3496 PrintUuidLoadCommand(Uuid);
3497 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
3498 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
3499 PrintVersionMinLoadCommand(Vd);
3500 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
3501 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
3502 PrintSourceVersionCommand(Sd);
3503 } else if (Command.C.cmd == MachO::LC_MAIN) {
3504 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
3505 PrintEntryPointCommand(Ep);
Nick Kledzik15558912014-10-16 18:58:20 +00003506 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
3507 Command.C.cmd == MachO::LC_ID_DYLIB ||
3508 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
3509 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
3510 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
3511 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003512 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
3513 PrintDylibCommand(Dl, Command.Ptr);
3514 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
3515 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
3516 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
3517 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
3518 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
3519 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
3520 MachO::linkedit_data_command Ld =
3521 Obj->getLinkeditDataLoadCommand(Command);
3522 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00003523 } else {
3524 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
3525 << ")\n";
3526 outs() << " cmdsize " << Command.C.cmdsize << "\n";
3527 // TODO: get and print the raw bytes of the load command.
3528 }
3529 // TODO: print all the other kinds of load commands.
3530 if (i == ncmds - 1)
3531 break;
3532 else
3533 Command = Obj->getNextLoadCommandInfo(Command);
3534 }
3535}
3536
3537static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
3538 uint32_t &filetype, uint32_t &cputype,
3539 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003540 if (Obj->is64Bit()) {
3541 MachO::mach_header_64 H_64;
3542 H_64 = Obj->getHeader64();
3543 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
3544 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00003545 ncmds = H_64.ncmds;
3546 filetype = H_64.filetype;
3547 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003548 } else {
3549 MachO::mach_header H;
3550 H = Obj->getHeader();
3551 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
3552 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00003553 ncmds = H.ncmds;
3554 filetype = H.filetype;
3555 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003556 }
3557}
3558
3559void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
3560 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00003561 uint32_t ncmds = 0;
3562 uint32_t filetype = 0;
3563 uint32_t cputype = 0;
3564 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
3565 PrintLoadCommands(file, ncmds, filetype, cputype, true);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003566}
Nick Kledzikd04bc352014-08-30 00:20:14 +00003567
3568//===----------------------------------------------------------------------===//
3569// export trie dumping
3570//===----------------------------------------------------------------------===//
3571
3572void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003573 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
3574 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00003575 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
3576 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
3577 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3578 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
3579 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3580 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
3581 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
3582 if (ReExport)
3583 outs() << "[re-export] ";
3584 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003585 outs() << format("0x%08llX ",
3586 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003587 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00003588 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003589 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00003590 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00003591 if (WeakDef) {
3592 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003593 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003594 }
3595 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003596 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003597 outs() << ", ";
3598 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003599 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003600 }
3601 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003602 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003603 outs() << ", ";
3604 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003605 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003606 }
3607 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003608 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003609 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003610 outs() << format("resolver=0x%08llX", Entry.other());
3611 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003612 }
3613 outs() << "]";
3614 }
3615 if (ReExport) {
3616 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003617 int Ordinal = Entry.other() - 1;
3618 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
3619 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00003620 outs() << " (from " << DylibName << ")";
3621 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003622 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00003623 }
3624 outs() << "\n";
3625 }
3626}
Nick Kledzikac431442014-09-12 21:34:15 +00003627
Nick Kledzikac431442014-09-12 21:34:15 +00003628//===----------------------------------------------------------------------===//
3629// rebase table dumping
3630//===----------------------------------------------------------------------===//
3631
3632namespace {
3633class SegInfo {
3634public:
3635 SegInfo(const object::MachOObjectFile *Obj);
3636
3637 StringRef segmentName(uint32_t SegIndex);
3638 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
3639 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
3640
3641private:
3642 struct SectionInfo {
3643 uint64_t Address;
3644 uint64_t Size;
3645 StringRef SectionName;
3646 StringRef SegmentName;
3647 uint64_t OffsetInSegment;
3648 uint64_t SegmentStartAddress;
3649 uint32_t SegmentIndex;
3650 };
3651 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
3652 SmallVector<SectionInfo, 32> Sections;
3653};
3654}
3655
3656SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
3657 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00003658 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00003659 StringRef CurSegName;
3660 uint64_t CurSegAddress;
3661 for (const SectionRef &Section : Obj->sections()) {
3662 SectionInfo Info;
3663 if (error(Section.getName(Info.SectionName)))
3664 return;
Rafael Espindola80291272014-10-08 15:28:58 +00003665 Info.Address = Section.getAddress();
3666 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00003667 Info.SegmentName =
3668 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3669 if (!Info.SegmentName.equals(CurSegName)) {
3670 ++CurSegIndex;
3671 CurSegName = Info.SegmentName;
3672 CurSegAddress = Info.Address;
3673 }
3674 Info.SegmentIndex = CurSegIndex - 1;
3675 Info.OffsetInSegment = Info.Address - CurSegAddress;
3676 Info.SegmentStartAddress = CurSegAddress;
3677 Sections.push_back(Info);
3678 }
3679}
3680
3681StringRef SegInfo::segmentName(uint32_t SegIndex) {
3682 for (const SectionInfo &SI : Sections) {
3683 if (SI.SegmentIndex == SegIndex)
3684 return SI.SegmentName;
3685 }
3686 llvm_unreachable("invalid segIndex");
3687}
3688
3689const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
3690 uint64_t OffsetInSeg) {
3691 for (const SectionInfo &SI : Sections) {
3692 if (SI.SegmentIndex != SegIndex)
3693 continue;
3694 if (SI.OffsetInSegment > OffsetInSeg)
3695 continue;
3696 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
3697 continue;
3698 return SI;
3699 }
3700 llvm_unreachable("segIndex and offset not in any section");
3701}
3702
3703StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
3704 return findSection(SegIndex, OffsetInSeg).SectionName;
3705}
3706
3707uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3708 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3709 return SI.SegmentStartAddress + OffsetInSeg;
3710}
3711
3712void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
3713 // Build table of sections so names can used in final output.
3714 SegInfo sectionTable(Obj);
3715
3716 outs() << "segment section address type\n";
3717 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
3718 uint32_t SegIndex = Entry.segmentIndex();
3719 uint64_t OffsetInSeg = Entry.segmentOffset();
3720 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3721 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3722 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3723
3724 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003725 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
3726 SegmentName.str().c_str(), SectionName.str().c_str(),
3727 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00003728 }
3729}
Nick Kledzik56ebef42014-09-16 01:41:51 +00003730
3731static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
3732 StringRef DylibName;
3733 switch (Ordinal) {
3734 case MachO::BIND_SPECIAL_DYLIB_SELF:
3735 return "this-image";
3736 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
3737 return "main-executable";
3738 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
3739 return "flat-namespace";
3740 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00003741 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003742 std::error_code EC =
3743 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00003744 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00003745 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00003746 return DylibName;
3747 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003748 }
Nick Kledzikabd29872014-09-16 22:03:13 +00003749 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003750}
3751
3752//===----------------------------------------------------------------------===//
3753// bind table dumping
3754//===----------------------------------------------------------------------===//
3755
3756void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
3757 // Build table of sections so names can used in final output.
3758 SegInfo sectionTable(Obj);
3759
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003760 outs() << "segment section address type "
3761 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003762 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
3763 uint32_t SegIndex = Entry.segmentIndex();
3764 uint64_t OffsetInSeg = Entry.segmentOffset();
3765 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3766 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3767 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3768
3769 // Table lines look like:
3770 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003771 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003772 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003773 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003774 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003775 << left_justify(SectionName, 18) << " "
3776 << format_hex(Address, 10, true) << " "
3777 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003778 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003779 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003780 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003781 }
3782}
3783
3784//===----------------------------------------------------------------------===//
3785// lazy bind table dumping
3786//===----------------------------------------------------------------------===//
3787
3788void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
3789 // Build table of sections so names can used in final output.
3790 SegInfo sectionTable(Obj);
3791
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003792 outs() << "segment section address "
3793 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003794 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
3795 uint32_t SegIndex = Entry.segmentIndex();
3796 uint64_t OffsetInSeg = Entry.segmentOffset();
3797 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3798 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3799 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3800
3801 // Table lines look like:
3802 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003803 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003804 << left_justify(SectionName, 18) << " "
3805 << format_hex(Address, 10, true) << " "
3806 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00003807 << Entry.symbolName() << "\n";
3808 }
3809}
3810
Nick Kledzik56ebef42014-09-16 01:41:51 +00003811//===----------------------------------------------------------------------===//
3812// weak bind table dumping
3813//===----------------------------------------------------------------------===//
3814
3815void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
3816 // Build table of sections so names can used in final output.
3817 SegInfo sectionTable(Obj);
3818
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003819 outs() << "segment section address "
3820 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003821 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
3822 // Strong symbols don't have a location to update.
3823 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003824 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00003825 << Entry.symbolName() << "\n";
3826 continue;
3827 }
3828 uint32_t SegIndex = Entry.segmentIndex();
3829 uint64_t OffsetInSeg = Entry.segmentOffset();
3830 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3831 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3832 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3833
3834 // Table lines look like:
3835 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003836 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003837 << left_justify(SectionName, 18) << " "
3838 << format_hex(Address, 10, true) << " "
3839 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003840 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
3841 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003842 }
3843}
3844
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003845// get_dyld_bind_info_symbolname() is used for disassembly and passed an
3846// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
3847// information for that address. If the address is found its binding symbol
3848// name is returned. If not nullptr is returned.
3849static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3850 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00003851 if (info->bindtable == nullptr) {
3852 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003853 SegInfo sectionTable(info->O);
3854 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
3855 uint32_t SegIndex = Entry.segmentIndex();
3856 uint64_t OffsetInSeg = Entry.segmentOffset();
3857 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3858 const char *SymbolName = nullptr;
3859 StringRef name = Entry.symbolName();
3860 if (!name.empty())
3861 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00003862 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003863 }
3864 }
Kevin Enderby078be602014-10-23 19:53:12 +00003865 for (bind_table_iterator BI = info->bindtable->begin(),
3866 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003867 BI != BE; ++BI) {
3868 uint64_t Address = BI->first;
3869 if (ReferenceValue == Address) {
3870 const char *SymbolName = BI->second;
3871 return SymbolName;
3872 }
3873 }
3874 return nullptr;
3875}