blob: 566a59769a80e2e58ed5b81651974b27cff952e6 [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"
26#include "llvm/MC/MCInstrAnalysis.h"
27#include "llvm/MC/MCInstrDesc.h"
28#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000029#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000030#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000031#include "llvm/Object/MachO.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000032#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000035#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000036#include "llvm/Support/Format.h"
37#include "llvm/Support/GraphWriter.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000038#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000039#include "llvm/Support/MemoryBuffer.h"
Kevin Enderbybf246f52014-09-24 23:08:22 +000040#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include "llvm/Support/TargetRegistry.h"
42#include "llvm/Support/TargetSelect.h"
43#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000044#include <algorithm>
45#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000046#include <system_error>
Kevin Enderby04bf6932014-10-28 23:39:46 +000047
48#if HAVE_CXXABI_H
49#include <cxxabi.h>
50#endif
51
Benjamin Kramer43a772e2011-09-19 17:56:04 +000052using namespace llvm;
53using namespace object;
54
55static cl::opt<bool>
Kevin Enderbyb28ed012014-10-29 21:28:24 +000056 UseDbg("g",
57 cl::desc("Print line information from debug info if available"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000058
Kevin Enderbyb28ed012014-10-29 21:28:24 +000059static cl::opt<std::string> DSYMFile("dsym",
60 cl::desc("Use .dSYM file for debug info"));
Benjamin Kramer699128e2011-09-21 01:13:19 +000061
Kevin Enderbyb28ed012014-10-29 21:28:24 +000062static cl::opt<bool> FullLeadingAddr("full-leading-addr",
63 cl::desc("Print full leading address"));
Kevin Enderbybf246f52014-09-24 23:08:22 +000064
65static cl::opt<bool>
66 PrintImmHex("print-imm-hex",
67 cl::desc("Use hex format for immediate values"));
68
Kevin Enderbyec5ca032014-08-18 20:21:02 +000069static std::string ThumbTripleName;
70
71static const Target *GetTarget(const MachOObjectFile *MachOObj,
72 const char **McpuDefault,
73 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +000074 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000075 if (TripleName.empty()) {
76 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +000077 llvm::Triple ThumbTriple = Triple();
78 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000079 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +000080 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +000081 }
82
Benjamin Kramer43a772e2011-09-19 17:56:04 +000083 // Get the target specific parser.
84 std::string Error;
85 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +000086 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +000087 return TheTarget;
88
Kevin Enderbyec5ca032014-08-18 20:21:02 +000089 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
90 if (*ThumbTarget)
91 return TheTarget;
92
93 errs() << "llvm-objdump: error: unable to get target for '";
94 if (!TheTarget)
95 errs() << TripleName;
96 else
97 errs() << ThumbTripleName;
98 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +000099 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000100}
101
Owen Andersond9243c42011-10-17 21:37:35 +0000102struct SymbolSorter {
103 bool operator()(const SymbolRef &A, const SymbolRef &B) {
104 SymbolRef::Type AType, BType;
105 A.getType(AType);
106 B.getType(BType);
107
108 uint64_t AAddr, BAddr;
109 if (AType != SymbolRef::ST_Function)
110 AAddr = 0;
111 else
112 A.getAddress(AAddr);
113 if (BType != SymbolRef::ST_Function)
114 BAddr = 0;
115 else
116 B.getAddress(BAddr);
117 return AAddr < BAddr;
118 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000119};
120
Kevin Enderby273ae012013-06-06 17:20:50 +0000121// Types for the storted data in code table that is built before disassembly
122// and the predicate function to sort them.
123typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
124typedef std::vector<DiceTableEntry> DiceTable;
125typedef DiceTable::iterator dice_table_iterator;
126
Kevin Enderby930fdc72014-11-06 19:00:13 +0000127// This is used to search for a data in code table entry for the PC being
128// disassembled. The j parameter has the PC in j.first. A single data in code
129// table entry can cover many bytes for each of its Kind's. So if the offset,
130// aka the i.first value, of the data in code table entry plus its Length
131// covers the PC being searched for this will return true. If not it will
132// return false.
David Majnemerea9b8ee2014-11-04 08:41:48 +0000133static bool compareDiceTableEntries(const DiceTableEntry &i,
134 const DiceTableEntry &j) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000135 uint16_t Length;
136 i.second.getLength(Length);
137
138 return j.first >= i.first && j.first < i.first + Length;
Kevin Enderby273ae012013-06-06 17:20:50 +0000139}
140
Kevin Enderby930fdc72014-11-06 19:00:13 +0000141static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
142 unsigned short Kind) {
143 uint32_t Value, Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000144
145 switch (Kind) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000146 default:
Charles Davis8bdfafd2013-09-01 04:28:48 +0000147 case MachO::DICE_KIND_DATA:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000148 if (Length >= 4) {
149 if (!NoShowRawInsn)
150 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000151 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000152 outs() << "\t.long " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000153 Size = 4;
154 } else if (Length >= 2) {
155 if (!NoShowRawInsn)
156 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000157 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby273ae012013-06-06 17:20:50 +0000158 outs() << "\t.short " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000159 Size = 2;
160 } else {
161 if (!NoShowRawInsn)
162 DumpBytes(StringRef(bytes, 2));
Kevin Enderby273ae012013-06-06 17:20:50 +0000163 Value = bytes[0];
164 outs() << "\t.byte " << Value;
Kevin Enderby930fdc72014-11-06 19:00:13 +0000165 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000166 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000167 if (Kind == MachO::DICE_KIND_DATA)
168 outs() << "\t@ KIND_DATA\n";
169 else
170 outs() << "\t@ data in code kind = " << Kind << "\n";
Kevin Enderby273ae012013-06-06 17:20:50 +0000171 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000172 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000173 if (!NoShowRawInsn)
174 DumpBytes(StringRef(bytes, 1));
Kevin Enderby273ae012013-06-06 17:20:50 +0000175 Value = bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000176 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
177 Size = 1;
Kevin Enderby273ae012013-06-06 17:20:50 +0000178 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000179 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000180 if (!NoShowRawInsn)
181 DumpBytes(StringRef(bytes, 2));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000182 Value = bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000183 outs() << "\t.short " << format("%5u", Value & 0xffff)
184 << "\t@ KIND_JUMP_TABLE16\n";
185 Size = 2;
Kevin Enderby273ae012013-06-06 17:20:50 +0000186 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000187 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby930fdc72014-11-06 19:00:13 +0000188 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
189 if (!NoShowRawInsn)
190 DumpBytes(StringRef(bytes, 4));
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000191 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
Kevin Enderby930fdc72014-11-06 19:00:13 +0000192 outs() << "\t.long " << Value;
193 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
194 outs() << "\t@ KIND_JUMP_TABLE32\n";
195 else
196 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
197 Size = 4;
Kevin Enderby273ae012013-06-06 17:20:50 +0000198 break;
199 }
Kevin Enderby930fdc72014-11-06 19:00:13 +0000200 return Size;
Kevin Enderby273ae012013-06-06 17:20:50 +0000201}
202
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000203static void getSectionsAndSymbols(const MachO::mach_header Header,
204 MachOObjectFile *MachOObj,
205 std::vector<SectionRef> &Sections,
206 std::vector<SymbolRef> &Symbols,
207 SmallVectorImpl<uint64_t> &FoundFns,
208 uint64_t &BaseSegmentAddress) {
209 for (const SymbolRef &Symbol : MachOObj->symbols())
210 Symbols.push_back(Symbol);
Owen Andersond9243c42011-10-17 21:37:35 +0000211
Alexey Samsonov48803e52014-03-13 14:37:36 +0000212 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000213 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000214 Section.getName(SectName);
215 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000216 }
217
Rafael Espindola56f976f2013-04-18 18:08:55 +0000218 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000219 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000220 bool BaseSegmentAddressSet = false;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000221 for (unsigned i = 0;; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000222 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000223 // We found a function starts segment, parse the addresses for later
224 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000225 MachO::linkedit_data_command LLC =
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000226 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000227
Charles Davis8bdfafd2013-09-01 04:28:48 +0000228 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000229 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
230 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000231 StringRef SegName = SLC.segname;
Kevin Enderbyb28ed012014-10-29 21:28:24 +0000232 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
Kevin Enderby273ae012013-06-06 17:20:50 +0000233 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000234 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000235 }
236 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000237
Charles Davis8bdfafd2013-09-01 04:28:48 +0000238 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000239 break;
240 else
241 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000242 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000243}
244
Rafael Espindola9b709252013-04-13 01:45:40 +0000245static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindola56f976f2013-04-18 18:08:55 +0000246 MachOObjectFile *MachOOF);
Rafael Espindola9b709252013-04-13 01:45:40 +0000247
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000248void llvm::DisassembleInputMachO(StringRef Filename) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000249 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000250 MemoryBuffer::getFileOrSTDIN(Filename);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000251 if (std::error_code EC = BuffOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000252 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000253 return;
254 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000255 std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000256
Rafael Espindola48af1c22014-08-19 18:44:46 +0000257 std::unique_ptr<MachOObjectFile> MachOOF = std::move(
258 ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000259
Rafael Espindola56f976f2013-04-18 18:08:55 +0000260 DisassembleInputMachO2(Filename, MachOOF.get());
Rafael Espindola9b709252013-04-13 01:45:40 +0000261}
262
Kevin Enderbybf246f52014-09-24 23:08:22 +0000263typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000264typedef std::pair<uint64_t, const char *> BindInfoEntry;
265typedef std::vector<BindInfoEntry> BindTable;
266typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000267
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000268// The block of info used by the Symbolizer call backs.
269struct DisassembleInfo {
270 bool verbose;
271 MachOObjectFile *O;
272 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000273 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000274 std::vector<SectionRef> *Sections;
275 const char *class_name;
276 const char *selector_name;
277 char *method;
Kevin Enderby04bf6932014-10-28 23:39:46 +0000278 char *demangled_name;
Kevin Enderby078be602014-10-23 19:53:12 +0000279 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000280};
281
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000282// GuessSymbolName is passed the address of what might be a symbol and a
283// pointer to the DisassembleInfo struct. It returns the name of a symbol
284// with that address or nullptr if no symbol is found with that address.
285static const char *GuessSymbolName(uint64_t value,
286 struct DisassembleInfo *info) {
287 const char *SymbolName = nullptr;
288 // A DenseMap can't lookup up some values.
289 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
290 StringRef name = info->AddrMap->lookup(value);
291 if (!name.empty())
292 SymbolName = name.data();
293 }
294 return SymbolName;
295}
296
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000297// SymbolizerGetOpInfo() is the operand information call back function.
298// This is called to get the symbolic information for operand(s) of an
299// instruction when it is being done. This routine does this from
300// the relocation information, symbol table, etc. That block of information
301// is a pointer to the struct DisassembleInfo that was passed when the
302// disassembler context was created and passed to back to here when
303// called back by the disassembler for instruction operands that could have
304// relocation information. The address of the instruction containing operand is
305// at the Pc parameter. The immediate value the operand has is passed in
306// op_info->Value and is at Offset past the start of the instruction and has a
307// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
308// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
309// names and addends of the symbolic expression to add for the operand. The
310// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
311// information is returned then this function returns 1 else it returns 0.
312int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
313 uint64_t Size, int TagType, void *TagBuf) {
314 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
315 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
316 unsigned int value = op_info->Value;
317
318 // Make sure all fields returned are zero if we don't set them.
319 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
320 op_info->Value = value;
321
322 // If the TagType is not the value 1 which it code knows about or if no
323 // verbose symbolic information is wanted then just return 0, indicating no
324 // information is being returned.
325 if (TagType != 1 || info->verbose == false)
326 return 0;
327
328 unsigned int Arch = info->O->getArch();
329 if (Arch == Triple::x86) {
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000330 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
331 return 0;
332 // First search the section's relocation entries (if any) for an entry
333 // for this section offset.
334 uint32_t sect_addr = info->S.getAddress();
335 uint32_t sect_offset = (Pc + Offset) - sect_addr;
336 bool reloc_found = false;
337 DataRefImpl Rel;
338 MachO::any_relocation_info RE;
339 bool isExtern = false;
340 SymbolRef Symbol;
341 bool r_scattered = false;
342 uint32_t r_value, pair_r_value, r_type;
343 for (const RelocationRef &Reloc : info->S.relocations()) {
344 uint64_t RelocOffset;
345 Reloc.getOffset(RelocOffset);
346 if (RelocOffset == sect_offset) {
347 Rel = Reloc.getRawDataRefImpl();
348 RE = info->O->getRelocation(Rel);
349 r_scattered = info->O->isRelocationScattered(RE);
350 if (r_scattered) {
351 r_value = info->O->getScatteredRelocationValue(RE);
352 r_type = info->O->getScatteredRelocationType(RE);
353 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
354 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
355 DataRefImpl RelNext = Rel;
356 info->O->moveRelocationNext(RelNext);
357 MachO::any_relocation_info RENext;
358 RENext = info->O->getRelocation(RelNext);
359 if (info->O->isRelocationScattered(RENext))
Kevin Enderby930fdc72014-11-06 19:00:13 +0000360 pair_r_value = info->O->getScatteredRelocationValue(RENext);
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000361 else
362 return 0;
363 }
364 } else {
365 isExtern = info->O->getPlainRelocationExternal(RE);
366 if (isExtern) {
367 symbol_iterator RelocSym = Reloc.getSymbol();
368 Symbol = *RelocSym;
369 }
370 }
371 reloc_found = true;
372 break;
373 }
374 }
375 if (reloc_found && isExtern) {
376 StringRef SymName;
377 Symbol.getName(SymName);
378 const char *name = SymName.data();
379 op_info->AddSymbol.Present = 1;
380 op_info->AddSymbol.Name = name;
381 // For i386 extern relocation entries the value in the instruction is
382 // the offset from the symbol, and value is already set in op_info->Value.
383 return 1;
384 }
385 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
386 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
387 const char *add = GuessSymbolName(r_value, info);
388 const char *sub = GuessSymbolName(pair_r_value, info);
389 uint32_t offset = value - (r_value - pair_r_value);
390 op_info->AddSymbol.Present = 1;
391 if (add != nullptr)
392 op_info->AddSymbol.Name = add;
393 else
394 op_info->AddSymbol.Value = r_value;
395 op_info->SubtractSymbol.Present = 1;
396 if (sub != nullptr)
397 op_info->SubtractSymbol.Name = sub;
398 else
399 op_info->SubtractSymbol.Value = pair_r_value;
400 op_info->Value = offset;
401 return 1;
402 }
403 // TODO:
404 // Second search the external relocation entries of a fully linked image
405 // (if any) for an entry that matches this segment offset.
406 // uint32_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000407 return 0;
408 } else if (Arch == Triple::x86_64) {
409 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
410 return 0;
411 // First search the section's relocation entries (if any) for an entry
412 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +0000413 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000414 uint64_t sect_offset = (Pc + Offset) - sect_addr;
415 bool reloc_found = false;
416 DataRefImpl Rel;
417 MachO::any_relocation_info RE;
418 bool isExtern = false;
419 SymbolRef Symbol;
420 for (const RelocationRef &Reloc : info->S.relocations()) {
421 uint64_t RelocOffset;
422 Reloc.getOffset(RelocOffset);
423 if (RelocOffset == sect_offset) {
424 Rel = Reloc.getRawDataRefImpl();
425 RE = info->O->getRelocation(Rel);
426 // NOTE: Scattered relocations don't exist on x86_64.
427 isExtern = info->O->getPlainRelocationExternal(RE);
428 if (isExtern) {
429 symbol_iterator RelocSym = Reloc.getSymbol();
430 Symbol = *RelocSym;
431 }
432 reloc_found = true;
433 break;
434 }
435 }
436 if (reloc_found && isExtern) {
437 // The Value passed in will be adjusted by the Pc if the instruction
438 // adds the Pc. But for x86_64 external relocation entries the Value
439 // is the offset from the external symbol.
440 if (info->O->getAnyRelocationPCRel(RE))
441 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000442 StringRef SymName;
443 Symbol.getName(SymName);
444 const char *name = SymName.data();
445 unsigned Type = info->O->getAnyRelocationType(RE);
446 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
447 DataRefImpl RelNext = Rel;
448 info->O->moveRelocationNext(RelNext);
449 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
450 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
451 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
452 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
453 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
454 op_info->SubtractSymbol.Present = 1;
455 op_info->SubtractSymbol.Name = name;
456 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
457 Symbol = *RelocSymNext;
458 StringRef SymNameNext;
459 Symbol.getName(SymNameNext);
460 name = SymNameNext.data();
461 }
462 }
463 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
464 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
465 op_info->AddSymbol.Present = 1;
466 op_info->AddSymbol.Name = name;
467 return 1;
468 }
469 // TODO:
470 // Second search the external relocation entries of a fully linked image
471 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000472 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000473 return 0;
474 } else if (Arch == Triple::arm) {
Kevin Enderby930fdc72014-11-06 19:00:13 +0000475 if (Offset != 0 || (Size != 4 && Size != 2))
476 return 0;
477 // First search the section's relocation entries (if any) for an entry
478 // for this section offset.
479 uint32_t sect_addr = info->S.getAddress();
480 uint32_t sect_offset = (Pc + Offset) - sect_addr;
481 bool reloc_found = false;
482 DataRefImpl Rel;
483 MachO::any_relocation_info RE;
484 bool isExtern = false;
485 SymbolRef Symbol;
486 bool r_scattered = false;
487 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
488 for (const RelocationRef &Reloc : info->S.relocations()) {
489 uint64_t RelocOffset;
490 Reloc.getOffset(RelocOffset);
491 if (RelocOffset == sect_offset) {
492 Rel = Reloc.getRawDataRefImpl();
493 RE = info->O->getRelocation(Rel);
494 r_length = info->O->getAnyRelocationLength(RE);
495 r_scattered = info->O->isRelocationScattered(RE);
496 if (r_scattered) {
497 r_value = info->O->getScatteredRelocationValue(RE);
498 r_type = info->O->getScatteredRelocationType(RE);
499 } else {
500 r_type = info->O->getAnyRelocationType(RE);
501 isExtern = info->O->getPlainRelocationExternal(RE);
502 if (isExtern) {
503 symbol_iterator RelocSym = Reloc.getSymbol();
504 Symbol = *RelocSym;
505 }
506 }
507 if (r_type == MachO::ARM_RELOC_HALF ||
508 r_type == MachO::ARM_RELOC_SECTDIFF ||
509 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
510 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
511 DataRefImpl RelNext = Rel;
512 info->O->moveRelocationNext(RelNext);
513 MachO::any_relocation_info RENext;
514 RENext = info->O->getRelocation(RelNext);
515 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
516 if (info->O->isRelocationScattered(RENext))
517 pair_r_value = info->O->getScatteredRelocationValue(RENext);
518 }
519 reloc_found = true;
520 break;
521 }
522 }
523 if (reloc_found && isExtern) {
524 StringRef SymName;
525 Symbol.getName(SymName);
526 const char *name = SymName.data();
527 op_info->AddSymbol.Present = 1;
528 op_info->AddSymbol.Name = name;
529 if (value != 0) {
530 switch (r_type) {
531 case MachO::ARM_RELOC_HALF:
532 if ((r_length & 0x1) == 1) {
533 op_info->Value = value << 16 | other_half;
534 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
535 } else {
536 op_info->Value = other_half << 16 | value;
537 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
538 }
539 break;
540 default:
541 break;
542 }
543 } else {
544 switch (r_type) {
545 case MachO::ARM_RELOC_HALF:
546 if ((r_length & 0x1) == 1) {
547 op_info->Value = value << 16 | other_half;
548 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
549 } else {
550 op_info->Value = other_half << 16 | value;
551 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
552 }
553 break;
554 default:
555 break;
556 }
557 }
558 return 1;
559 }
560 // If we have a branch that is not an external relocation entry then
561 // return 0 so the code in tryAddingSymbolicOperand() can use the
562 // SymbolLookUp call back with the branch target address to look up the
563 // symbol and possiblity add an annotation for a symbol stub.
564 if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
565 r_type == MachO::ARM_THUMB_RELOC_BR22))
566 return 0;
567
568 uint32_t offset = 0;
569 if (reloc_found) {
570 if (r_type == MachO::ARM_RELOC_HALF ||
571 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
572 if ((r_length & 0x1) == 1)
573 value = value << 16 | other_half;
574 else
575 value = other_half << 16 | value;
576 }
577 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
578 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
579 offset = value - r_value;
580 value = r_value;
581 }
582 }
583
584 if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
585 if ((r_length & 0x1) == 1)
586 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
587 else
588 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
589 const char *add = GuessSymbolName(r_value, info);
590 const char *sub = GuessSymbolName(pair_r_value, info);
591 int32_t offset = value - (r_value - pair_r_value);
592 op_info->AddSymbol.Present = 1;
593 if (add != nullptr)
594 op_info->AddSymbol.Name = add;
595 else
596 op_info->AddSymbol.Value = r_value;
597 op_info->SubtractSymbol.Present = 1;
598 if (sub != nullptr)
599 op_info->SubtractSymbol.Name = sub;
600 else
601 op_info->SubtractSymbol.Value = pair_r_value;
602 op_info->Value = offset;
603 return 1;
604 }
605
606 if (reloc_found == false)
607 return 0;
608
609 op_info->AddSymbol.Present = 1;
610 op_info->Value = offset;
611 if (reloc_found) {
612 if (r_type == MachO::ARM_RELOC_HALF) {
613 if ((r_length & 0x1) == 1)
614 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
615 else
616 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
617 }
618 }
619 const char *add = GuessSymbolName(value, info);
620 if (add != nullptr) {
621 op_info->AddSymbol.Name = add;
622 return 1;
623 }
624 op_info->AddSymbol.Value = value;
625 return 1;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000626 } else if (Arch == Triple::aarch64) {
627 return 0;
628 } else {
629 return 0;
630 }
631}
632
Kevin Enderbybf246f52014-09-24 23:08:22 +0000633// GuessCstringPointer is passed the address of what might be a pointer to a
634// literal string in a cstring section. If that address is in a cstring section
635// it returns a pointer to that string. Else it returns nullptr.
636const char *GuessCstringPointer(uint64_t ReferenceValue,
637 struct DisassembleInfo *info) {
638 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
639 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
640 for (unsigned I = 0;; ++I) {
641 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
642 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
643 for (unsigned J = 0; J < Seg.nsects; ++J) {
644 MachO::section_64 Sec = info->O->getSection64(Load, J);
645 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
646 if (section_type == MachO::S_CSTRING_LITERALS &&
647 ReferenceValue >= Sec.addr &&
648 ReferenceValue < Sec.addr + Sec.size) {
649 uint64_t sect_offset = ReferenceValue - Sec.addr;
650 uint64_t object_offset = Sec.offset + sect_offset;
651 StringRef MachOContents = info->O->getData();
652 uint64_t object_size = MachOContents.size();
653 const char *object_addr = (const char *)MachOContents.data();
654 if (object_offset < object_size) {
655 const char *name = object_addr + object_offset;
656 return name;
657 } else {
658 return nullptr;
659 }
660 }
661 }
662 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
663 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
664 for (unsigned J = 0; J < Seg.nsects; ++J) {
665 MachO::section Sec = info->O->getSection(Load, J);
666 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
667 if (section_type == MachO::S_CSTRING_LITERALS &&
668 ReferenceValue >= Sec.addr &&
669 ReferenceValue < Sec.addr + Sec.size) {
670 uint64_t sect_offset = ReferenceValue - Sec.addr;
671 uint64_t object_offset = Sec.offset + sect_offset;
672 StringRef MachOContents = info->O->getData();
673 uint64_t object_size = MachOContents.size();
674 const char *object_addr = (const char *)MachOContents.data();
675 if (object_offset < object_size) {
676 const char *name = object_addr + object_offset;
677 return name;
678 } else {
679 return nullptr;
680 }
681 }
682 }
683 }
684 if (I == LoadCommandCount - 1)
685 break;
686 else
687 Load = info->O->getNextLoadCommandInfo(Load);
688 }
689 return nullptr;
690}
691
Kevin Enderby85974882014-09-26 22:20:44 +0000692// GuessIndirectSymbol returns the name of the indirect symbol for the
693// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
694// an address of a symbol stub or a lazy or non-lazy pointer to associate the
695// symbol name being referenced by the stub or pointer.
696static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
697 struct DisassembleInfo *info) {
698 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
699 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
700 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
701 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
702 for (unsigned I = 0;; ++I) {
703 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
704 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
705 for (unsigned J = 0; J < Seg.nsects; ++J) {
706 MachO::section_64 Sec = info->O->getSection64(Load, J);
707 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
708 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
709 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
710 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
711 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
712 section_type == MachO::S_SYMBOL_STUBS) &&
713 ReferenceValue >= Sec.addr &&
714 ReferenceValue < Sec.addr + Sec.size) {
715 uint32_t stride;
716 if (section_type == MachO::S_SYMBOL_STUBS)
717 stride = Sec.reserved2;
718 else
719 stride = 8;
720 if (stride == 0)
721 return nullptr;
722 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
723 if (index < Dysymtab.nindirectsyms) {
724 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000725 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +0000726 if (indirect_symbol < Symtab.nsyms) {
727 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
728 SymbolRef Symbol = *Sym;
729 StringRef SymName;
730 Symbol.getName(SymName);
731 const char *name = SymName.data();
732 return name;
733 }
734 }
735 }
736 }
737 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
738 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
739 for (unsigned J = 0; J < Seg.nsects; ++J) {
740 MachO::section Sec = info->O->getSection(Load, J);
741 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
742 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
743 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
744 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
745 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
746 section_type == MachO::S_SYMBOL_STUBS) &&
747 ReferenceValue >= Sec.addr &&
748 ReferenceValue < Sec.addr + Sec.size) {
749 uint32_t stride;
750 if (section_type == MachO::S_SYMBOL_STUBS)
751 stride = Sec.reserved2;
752 else
753 stride = 4;
754 if (stride == 0)
755 return nullptr;
756 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
757 if (index < Dysymtab.nindirectsyms) {
758 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000759 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +0000760 if (indirect_symbol < Symtab.nsyms) {
761 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
762 SymbolRef Symbol = *Sym;
763 StringRef SymName;
764 Symbol.getName(SymName);
765 const char *name = SymName.data();
766 return name;
767 }
768 }
769 }
770 }
771 }
772 if (I == LoadCommandCount - 1)
773 break;
774 else
775 Load = info->O->getNextLoadCommandInfo(Load);
776 }
777 return nullptr;
778}
779
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000780// method_reference() is called passing it the ReferenceName that might be
781// a reference it to an Objective-C method call. If so then it allocates and
782// assembles a method call string with the values last seen and saved in
783// the DisassembleInfo's class_name and selector_name fields. This is saved
784// into the method field of the info and any previous string is free'ed.
785// Then the class_name field in the info is set to nullptr. The method call
786// string is set into ReferenceName and ReferenceType is set to
787// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
788// then both ReferenceType and ReferenceName are left unchanged.
789static void method_reference(struct DisassembleInfo *info,
790 uint64_t *ReferenceType,
791 const char **ReferenceName) {
792 if (*ReferenceName != nullptr) {
793 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
794 if (info->selector_name != NULL) {
795 if (info->method != nullptr)
796 free(info->method);
797 if (info->class_name != nullptr) {
798 info->method = (char *)malloc(5 + strlen(info->class_name) +
799 strlen(info->selector_name));
800 if (info->method != nullptr) {
801 strcpy(info->method, "+[");
802 strcat(info->method, info->class_name);
803 strcat(info->method, " ");
804 strcat(info->method, info->selector_name);
805 strcat(info->method, "]");
806 *ReferenceName = info->method;
807 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
808 }
809 } else {
810 info->method = (char *)malloc(9 + strlen(info->selector_name));
811 if (info->method != nullptr) {
812 strcpy(info->method, "-[%rdi ");
813 strcat(info->method, info->selector_name);
814 strcat(info->method, "]");
815 *ReferenceName = info->method;
816 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
817 }
818 }
819 info->class_name = nullptr;
820 }
821 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
822 if (info->selector_name != NULL) {
823 if (info->method != nullptr)
824 free(info->method);
825 info->method = (char *)malloc(17 + strlen(info->selector_name));
826 if (info->method != nullptr) {
827 strcpy(info->method, "-[[%rdi super] ");
828 strcat(info->method, info->selector_name);
829 strcat(info->method, "]");
830 *ReferenceName = info->method;
831 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
832 }
833 info->class_name = nullptr;
834 }
835 }
836 }
837}
838
839// GuessPointerPointer() is passed the address of what might be a pointer to
840// a reference to an Objective-C class, selector, message ref or cfstring.
841// If so the value of the pointer is returned and one of the booleans are set
842// to true. If not zero is returned and all the booleans are set to false.
843static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
844 struct DisassembleInfo *info,
845 bool &classref, bool &selref, bool &msgref,
846 bool &cfstring) {
847 classref = false;
848 selref = false;
849 msgref = false;
850 cfstring = false;
851 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
852 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
853 for (unsigned I = 0;; ++I) {
854 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
855 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
856 for (unsigned J = 0; J < Seg.nsects; ++J) {
857 MachO::section_64 Sec = info->O->getSection64(Load, J);
858 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
859 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
860 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
861 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
862 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
863 ReferenceValue >= Sec.addr &&
864 ReferenceValue < Sec.addr + Sec.size) {
865 uint64_t sect_offset = ReferenceValue - Sec.addr;
866 uint64_t object_offset = Sec.offset + sect_offset;
867 StringRef MachOContents = info->O->getData();
868 uint64_t object_size = MachOContents.size();
869 const char *object_addr = (const char *)MachOContents.data();
870 if (object_offset < object_size) {
871 uint64_t pointer_value;
872 memcpy(&pointer_value, object_addr + object_offset,
873 sizeof(uint64_t));
874 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
875 sys::swapByteOrder(pointer_value);
876 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
877 selref = true;
878 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
879 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
880 classref = true;
881 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
882 ReferenceValue + 8 < Sec.addr + Sec.size) {
883 msgref = true;
884 memcpy(&pointer_value, object_addr + object_offset + 8,
885 sizeof(uint64_t));
886 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
887 sys::swapByteOrder(pointer_value);
888 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
889 cfstring = true;
890 return pointer_value;
891 } else {
892 return 0;
893 }
894 }
895 }
896 }
897 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
898 if (I == LoadCommandCount - 1)
899 break;
900 else
901 Load = info->O->getNextLoadCommandInfo(Load);
902 }
903 return 0;
904}
905
906// get_pointer_64 returns a pointer to the bytes in the object file at the
907// Address from a section in the Mach-O file. And indirectly returns the
908// offset into the section, number of bytes left in the section past the offset
909// and which section is was being referenced. If the Address is not in a
910// section nullptr is returned.
911const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
912 SectionRef &S, DisassembleInfo *info) {
913 offset = 0;
914 left = 0;
915 S = SectionRef();
916 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
917 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
918 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
919 if (Address >= SectAddress && Address < SectAddress + SectSize) {
920 S = (*(info->Sections))[SectIdx];
921 offset = Address - SectAddress;
922 left = SectSize - offset;
923 StringRef SectContents;
924 ((*(info->Sections))[SectIdx]).getContents(SectContents);
925 return SectContents.data() + offset;
926 }
927 }
928 return nullptr;
929}
930
931// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
932// the symbol indirectly through n_value. Based on the relocation information
933// for the specified section offset in the specified section reference.
934const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
935 DisassembleInfo *info, uint64_t &n_value) {
936 n_value = 0;
937 if (info->verbose == false)
938 return nullptr;
939
940 // See if there is an external relocation entry at the sect_offset.
941 bool reloc_found = false;
942 DataRefImpl Rel;
943 MachO::any_relocation_info RE;
944 bool isExtern = false;
945 SymbolRef Symbol;
946 for (const RelocationRef &Reloc : S.relocations()) {
947 uint64_t RelocOffset;
948 Reloc.getOffset(RelocOffset);
949 if (RelocOffset == sect_offset) {
950 Rel = Reloc.getRawDataRefImpl();
951 RE = info->O->getRelocation(Rel);
952 if (info->O->isRelocationScattered(RE))
953 continue;
954 isExtern = info->O->getPlainRelocationExternal(RE);
955 if (isExtern) {
956 symbol_iterator RelocSym = Reloc.getSymbol();
957 Symbol = *RelocSym;
958 }
959 reloc_found = true;
960 break;
961 }
962 }
963 // If there is an external relocation entry for a symbol in this section
964 // at this section_offset then use that symbol's value for the n_value
965 // and return its name.
966 const char *SymbolName = nullptr;
967 if (reloc_found && isExtern) {
968 Symbol.getAddress(n_value);
969 StringRef name;
970 Symbol.getName(name);
971 if (!name.empty()) {
972 SymbolName = name.data();
973 return SymbolName;
974 }
975 }
976
977 // TODO: For fully linked images, look through the external relocation
978 // entries off the dynamic symtab command. For these the r_offset is from the
979 // start of the first writeable segment in the Mach-O file. So the offset
980 // to this section from that segment is passed to this routine by the caller,
981 // as the database_offset. Which is the difference of the section's starting
982 // address and the first writable segment.
983 //
984 // NOTE: need add passing the database_offset to this routine.
985
986 // TODO: We did not find an external relocation entry so look up the
987 // ReferenceValue as an address of a symbol and if found return that symbol's
988 // name.
989 //
990 // NOTE: need add passing the ReferenceValue to this routine. Then that code
991 // would simply be this:
Kevin Enderby9907d0a2014-11-04 00:43:16 +0000992 // SymbolName = GuessSymbolName(ReferenceValue, info);
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000993
994 return SymbolName;
995}
996
997// These are structs in the Objective-C meta data and read to produce the
998// comments for disassembly. While these are part of the ABI they are no
999// public defintions. So the are here not in include/llvm/Support/MachO.h .
1000
1001// The cfstring object in a 64-bit Mach-O file.
1002struct cfstring64_t {
1003 uint64_t isa; // class64_t * (64-bit pointer)
1004 uint64_t flags; // flag bits
1005 uint64_t characters; // char * (64-bit pointer)
1006 uint64_t length; // number of non-NULL characters in above
1007};
1008
1009// The class object in a 64-bit Mach-O file.
1010struct class64_t {
1011 uint64_t isa; // class64_t * (64-bit pointer)
1012 uint64_t superclass; // class64_t * (64-bit pointer)
1013 uint64_t cache; // Cache (64-bit pointer)
1014 uint64_t vtable; // IMP * (64-bit pointer)
1015 uint64_t data; // class_ro64_t * (64-bit pointer)
1016};
1017
1018struct class_ro64_t {
1019 uint32_t flags;
1020 uint32_t instanceStart;
1021 uint32_t instanceSize;
1022 uint32_t reserved;
1023 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
1024 uint64_t name; // const char * (64-bit pointer)
1025 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
1026 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
1027 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
1028 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1029 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1030};
1031
1032inline void swapStruct(struct cfstring64_t &cfs) {
1033 sys::swapByteOrder(cfs.isa);
1034 sys::swapByteOrder(cfs.flags);
1035 sys::swapByteOrder(cfs.characters);
1036 sys::swapByteOrder(cfs.length);
1037}
1038
1039inline void swapStruct(struct class64_t &c) {
1040 sys::swapByteOrder(c.isa);
1041 sys::swapByteOrder(c.superclass);
1042 sys::swapByteOrder(c.cache);
1043 sys::swapByteOrder(c.vtable);
1044 sys::swapByteOrder(c.data);
1045}
1046
1047inline void swapStruct(struct class_ro64_t &cro) {
1048 sys::swapByteOrder(cro.flags);
1049 sys::swapByteOrder(cro.instanceStart);
1050 sys::swapByteOrder(cro.instanceSize);
1051 sys::swapByteOrder(cro.reserved);
1052 sys::swapByteOrder(cro.ivarLayout);
1053 sys::swapByteOrder(cro.name);
1054 sys::swapByteOrder(cro.baseMethods);
1055 sys::swapByteOrder(cro.baseProtocols);
1056 sys::swapByteOrder(cro.ivars);
1057 sys::swapByteOrder(cro.weakIvarLayout);
1058 sys::swapByteOrder(cro.baseProperties);
1059}
1060
1061static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1062 struct DisassembleInfo *info);
1063
1064// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1065// to an Objective-C class and returns the class name. It is also passed the
1066// address of the pointer, so when the pointer is zero as it can be in an .o
1067// file, that is used to look for an external relocation entry with a symbol
1068// name.
1069const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1070 uint64_t ReferenceValue,
1071 struct DisassembleInfo *info) {
1072 const char *r;
1073 uint32_t offset, left;
1074 SectionRef S;
1075
1076 // The pointer_value can be 0 in an object file and have a relocation
1077 // entry for the class symbol at the ReferenceValue (the address of the
1078 // pointer).
1079 if (pointer_value == 0) {
1080 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1081 if (r == nullptr || left < sizeof(uint64_t))
1082 return nullptr;
1083 uint64_t n_value;
1084 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1085 if (symbol_name == nullptr)
1086 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001087 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001088 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1089 return class_name + 2;
1090 else
1091 return nullptr;
1092 }
1093
1094 // The case were the pointer_value is non-zero and points to a class defined
1095 // in this Mach-O file.
1096 r = get_pointer_64(pointer_value, offset, left, S, info);
1097 if (r == nullptr || left < sizeof(struct class64_t))
1098 return nullptr;
1099 struct class64_t c;
1100 memcpy(&c, r, sizeof(struct class64_t));
1101 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1102 swapStruct(c);
1103 if (c.data == 0)
1104 return nullptr;
1105 r = get_pointer_64(c.data, offset, left, S, info);
1106 if (r == nullptr || left < sizeof(struct class_ro64_t))
1107 return nullptr;
1108 struct class_ro64_t cro;
1109 memcpy(&cro, r, sizeof(struct class_ro64_t));
1110 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1111 swapStruct(cro);
1112 if (cro.name == 0)
1113 return nullptr;
1114 const char *name = get_pointer_64(cro.name, offset, left, S, info);
1115 return name;
1116}
1117
1118// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1119// pointer to a cfstring and returns its name or nullptr.
1120const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1121 struct DisassembleInfo *info) {
1122 const char *r, *name;
1123 uint32_t offset, left;
1124 SectionRef S;
1125 struct cfstring64_t cfs;
1126 uint64_t cfs_characters;
1127
1128 r = get_pointer_64(ReferenceValue, offset, left, S, info);
1129 if (r == nullptr || left < sizeof(struct cfstring64_t))
1130 return nullptr;
1131 memcpy(&cfs, r, sizeof(struct cfstring64_t));
1132 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1133 swapStruct(cfs);
1134 if (cfs.characters == 0) {
1135 uint64_t n_value;
1136 const char *symbol_name = get_symbol_64(
1137 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1138 if (symbol_name == nullptr)
1139 return nullptr;
1140 cfs_characters = n_value;
1141 } else
1142 cfs_characters = cfs.characters;
1143 name = get_pointer_64(cfs_characters, offset, left, S, info);
1144
1145 return name;
1146}
1147
1148// get_objc2_64bit_selref() is used for disassembly and is passed a the address
1149// of a pointer to an Objective-C selector reference when the pointer value is
1150// zero as in a .o file and is likely to have a external relocation entry with
1151// who's symbol's n_value is the real pointer to the selector name. If that is
1152// the case the real pointer to the selector name is returned else 0 is
1153// returned
1154uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1155 struct DisassembleInfo *info) {
1156 uint32_t offset, left;
1157 SectionRef S;
1158
1159 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1160 if (r == nullptr || left < sizeof(uint64_t))
1161 return 0;
1162 uint64_t n_value;
1163 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1164 if (symbol_name == nullptr)
1165 return 0;
1166 return n_value;
1167}
1168
Kevin Enderbybf246f52014-09-24 23:08:22 +00001169// GuessLiteralPointer returns a string which for the item in the Mach-O file
1170// for the address passed in as ReferenceValue for printing as a comment with
1171// the instruction and also returns the corresponding type of that item
1172// indirectly through ReferenceType.
1173//
1174// If ReferenceValue is an address of literal cstring then a pointer to the
1175// cstring is returned and ReferenceType is set to
1176// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1177//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001178// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1179// Class ref that name is returned and the ReferenceType is set accordingly.
1180//
1181// Lastly, literals which are Symbol address in a literal pool are looked for
1182// and if found the symbol name is returned and ReferenceType is set to
1183// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1184//
1185// If there is no item in the Mach-O file for the address passed in as
1186// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Kevin Enderbybf246f52014-09-24 23:08:22 +00001187const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1188 uint64_t *ReferenceType,
1189 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001190 // TODO: This rouine's code and the routines it calls are only work with
1191 // x86_64 Mach-O files for now.
Kevin Enderbybf246f52014-09-24 23:08:22 +00001192 unsigned int Arch = info->O->getArch();
1193 if (Arch != Triple::x86_64)
1194 return nullptr;
1195
1196 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +00001197 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +00001198 uint64_t sect_offset = ReferencePC - sect_addr;
1199 bool reloc_found = false;
1200 DataRefImpl Rel;
1201 MachO::any_relocation_info RE;
1202 bool isExtern = false;
1203 SymbolRef Symbol;
1204 for (const RelocationRef &Reloc : info->S.relocations()) {
1205 uint64_t RelocOffset;
1206 Reloc.getOffset(RelocOffset);
1207 if (RelocOffset == sect_offset) {
1208 Rel = Reloc.getRawDataRefImpl();
1209 RE = info->O->getRelocation(Rel);
1210 if (info->O->isRelocationScattered(RE))
1211 continue;
1212 isExtern = info->O->getPlainRelocationExternal(RE);
1213 if (isExtern) {
1214 symbol_iterator RelocSym = Reloc.getSymbol();
1215 Symbol = *RelocSym;
1216 }
1217 reloc_found = true;
1218 break;
1219 }
1220 }
1221 // If there is an external relocation entry for a symbol in a section
1222 // then used that symbol's value for the value of the reference.
1223 if (reloc_found && isExtern) {
1224 if (info->O->getAnyRelocationPCRel(RE)) {
1225 unsigned Type = info->O->getAnyRelocationType(RE);
1226 if (Type == MachO::X86_64_RELOC_SIGNED) {
1227 Symbol.getAddress(ReferenceValue);
1228 }
1229 }
1230 }
1231
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001232 // Look for literals such as Objective-C CFStrings refs, Selector refs,
1233 // Message refs and Class refs.
1234 bool classref, selref, msgref, cfstring;
1235 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1236 selref, msgref, cfstring);
1237 if (classref == true && pointer_value == 0) {
1238 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1239 // And the pointer_value in that section is typically zero as it will be
1240 // set by dyld as part of the "bind information".
1241 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1242 if (name != nullptr) {
1243 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001244 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001245 if (class_name != nullptr && class_name[1] == '_' &&
1246 class_name[2] != '\0') {
1247 info->class_name = class_name + 2;
1248 return name;
1249 }
1250 }
1251 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001252
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001253 if (classref == true) {
1254 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1255 const char *name =
1256 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1257 if (name != nullptr)
1258 info->class_name = name;
1259 else
1260 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +00001261 return name;
1262 }
1263
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001264 if (cfstring == true) {
1265 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1266 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1267 return name;
1268 }
1269
1270 if (selref == true && pointer_value == 0)
1271 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1272
1273 if (pointer_value != 0)
1274 ReferenceValue = pointer_value;
1275
1276 const char *name = GuessCstringPointer(ReferenceValue, info);
1277 if (name) {
1278 if (pointer_value != 0 && selref == true) {
1279 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1280 info->selector_name = name;
1281 } else if (pointer_value != 0 && msgref == true) {
1282 info->class_name = nullptr;
1283 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1284 info->selector_name = name;
1285 } else
1286 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1287 return name;
1288 }
1289
1290 // Lastly look for an indirect symbol with this ReferenceValue which is in
1291 // a literal pool. If found return that symbol name.
1292 name = GuessIndirectSymbol(ReferenceValue, info);
1293 if (name) {
1294 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1295 return name;
1296 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001297
1298 return nullptr;
1299}
1300
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001301// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00001302// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001303// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1304// is created and returns the symbol name that matches the ReferenceValue or
1305// nullptr if none. The ReferenceType is passed in for the IN type of
1306// reference the instruction is making from the values in defined in the header
1307// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1308// Out type and the ReferenceName will also be set which is added as a comment
1309// to the disassembled instruction.
1310//
Kevin Enderby04bf6932014-10-28 23:39:46 +00001311#if HAVE_CXXABI_H
1312// If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001313// returned through ReferenceName and ReferenceType is set to
1314// LLVMDisassembler_ReferenceType_DeMangled_Name .
Kevin Enderby04bf6932014-10-28 23:39:46 +00001315#endif
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001316//
1317// When this is called to get a symbol name for a branch target then the
1318// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1319// SymbolValue will be looked for in the indirect symbol table to determine if
1320// it is an address for a symbol stub. If so then the symbol name for that
1321// stub is returned indirectly through ReferenceName and then ReferenceType is
1322// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1323//
Kevin Enderbybf246f52014-09-24 23:08:22 +00001324// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001325// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1326// SymbolValue is checked to be an address of literal pointer, symbol pointer,
1327// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001328// set to correspond to that as well as setting the ReferenceName.
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001329const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1330 uint64_t *ReferenceType,
1331 uint64_t ReferencePC,
1332 const char **ReferenceName) {
1333 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001334 // If no verbose symbolic information is wanted then just return nullptr.
1335 if (info->verbose == false) {
1336 *ReferenceName = nullptr;
1337 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001338 return nullptr;
1339 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001340
Kevin Enderby9907d0a2014-11-04 00:43:16 +00001341 const char *SymbolName = GuessSymbolName(ReferenceValue, info);
Kevin Enderbybf246f52014-09-24 23:08:22 +00001342
Kevin Enderby85974882014-09-26 22:20:44 +00001343 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1344 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001345 if (*ReferenceName != nullptr) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001346 method_reference(info, ReferenceType, ReferenceName);
1347 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1348 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1349 } else
Kevin Enderby04bf6932014-10-28 23:39:46 +00001350#if HAVE_CXXABI_H
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001351 if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
Kevin Enderby04bf6932014-10-28 23:39:46 +00001352 if (info->demangled_name != nullptr)
1353 free(info->demangled_name);
1354 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001355 info->demangled_name =
1356 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001357 if (info->demangled_name != nullptr) {
1358 *ReferenceName = info->demangled_name;
1359 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1360 } else
1361 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1362 } else
1363#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001364 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1365 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1366 *ReferenceName =
1367 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00001368 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001369 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00001370 else
1371 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1372 }
Kevin Enderby04bf6932014-10-28 23:39:46 +00001373#if HAVE_CXXABI_H
1374 else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1375 if (info->demangled_name != nullptr)
1376 free(info->demangled_name);
1377 int status;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001378 info->demangled_name =
1379 abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001380 if (info->demangled_name != nullptr) {
1381 *ReferenceName = info->demangled_name;
1382 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1383 }
1384 }
1385#endif
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001386 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001387 *ReferenceName = nullptr;
1388 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1389 }
1390
1391 return SymbolName;
1392}
1393
1394//
1395// This is the memory object used by DisAsm->getInstruction() which has its
1396// BasePC. This then allows the 'address' parameter to getInstruction() to
1397// be the actual PC of the instruction. Then when a branch dispacement is
1398// added to the PC of an instruction, the 'ReferenceValue' passed to the
1399// SymbolizerSymbolLookUp() routine is the correct target addresses. As in
1400// the case of a fully linked Mach-O file where a section being disassembled
1401// generally not linked at address zero.
1402//
1403class DisasmMemoryObject : public MemoryObject {
Aaron Ballman8cb2cae2014-09-25 14:02:43 +00001404 const uint8_t *Bytes;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001405 uint64_t Size;
1406 uint64_t BasePC;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001407
Kevin Enderbybf246f52014-09-24 23:08:22 +00001408public:
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001409 DisasmMemoryObject(const uint8_t *bytes, uint64_t size, uint64_t basePC)
1410 : Bytes(bytes), Size(size), BasePC(basePC) {}
Kevin Enderbybf246f52014-09-24 23:08:22 +00001411
1412 uint64_t getBase() const override { return BasePC; }
1413 uint64_t getExtent() const override { return Size; }
1414
1415 int readByte(uint64_t Addr, uint8_t *Byte) const override {
1416 if (Addr - BasePC >= Size)
1417 return -1;
1418 *Byte = Bytes[Addr - BasePC];
1419 return 0;
1420 }
1421};
1422
1423/// \brief Emits the comments that are stored in the CommentStream.
1424/// Each comment in the CommentStream must end with a newline.
1425static void emitComments(raw_svector_ostream &CommentStream,
1426 SmallString<128> &CommentsToEmit,
1427 formatted_raw_ostream &FormattedOS,
1428 const MCAsmInfo &MAI) {
1429 // Flush the stream before taking its content.
1430 CommentStream.flush();
1431 StringRef Comments = CommentsToEmit.str();
1432 // Get the default information for printing a comment.
1433 const char *CommentBegin = MAI.getCommentString();
1434 unsigned CommentColumn = MAI.getCommentColumn();
1435 bool IsFirst = true;
1436 while (!Comments.empty()) {
1437 if (!IsFirst)
1438 FormattedOS << '\n';
1439 // Emit a line of comments.
1440 FormattedOS.PadToColumn(CommentColumn);
1441 size_t Position = Comments.find('\n');
1442 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
1443 // Move after the newline character.
1444 Comments = Comments.substr(Position + 1);
1445 IsFirst = false;
1446 }
1447 FormattedOS.flush();
1448
1449 // Tell the comment stream that the vector changed underneath it.
1450 CommentsToEmit.clear();
1451 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001452}
1453
Rafael Espindola9b709252013-04-13 01:45:40 +00001454static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindola56f976f2013-04-18 18:08:55 +00001455 MachOObjectFile *MachOOF) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001456 const char *McpuDefault = nullptr;
1457 const Target *ThumbTarget = nullptr;
1458 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001459 if (!TheTarget) {
1460 // GetTarget prints out stuff.
1461 return;
1462 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001463 if (MCPU.empty() && McpuDefault)
1464 MCPU = McpuDefault;
1465
Ahmed Charles56440fd2014-03-06 05:51:42 +00001466 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
1467 std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
1468 TheTarget->createMCInstrAnalysis(InstrInfo.get()));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001469 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
1470 std::unique_ptr<MCInstrAnalysis> ThumbInstrAnalysis;
1471 if (ThumbTarget) {
1472 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
1473 ThumbInstrAnalysis.reset(
1474 ThumbTarget->createMCInstrAnalysis(ThumbInstrInfo.get()));
1475 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001476
Kevin Enderbyc9595622014-08-06 23:24:41 +00001477 // Package up features to be passed to target/subtarget
1478 std::string FeaturesStr;
1479 if (MAttrs.size()) {
1480 SubtargetFeatures Features;
1481 for (unsigned i = 0; i != MAttrs.size(); ++i)
1482 Features.AddFeature(MAttrs[i]);
1483 FeaturesStr = Features.getString();
1484 }
1485
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001486 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001487 std::unique_ptr<const MCRegisterInfo> MRI(
1488 TheTarget->createMCRegInfo(TripleName));
1489 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00001490 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00001491 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00001492 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00001493 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001494 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001495 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001496 std::unique_ptr<MCSymbolizer> Symbolizer;
1497 struct DisassembleInfo SymbolizerInfo;
1498 std::unique_ptr<MCRelocationInfo> RelInfo(
1499 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1500 if (RelInfo) {
1501 Symbolizer.reset(TheTarget->createMCSymbolizer(
1502 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1503 &SymbolizerInfo, &Ctx, RelInfo.release()));
1504 DisAsm->setSymbolizer(std::move(Symbolizer));
1505 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001506 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00001507 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1508 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001509 // Set the display preference for hex vs. decimal immediates.
1510 IP->setPrintImmHex(PrintImmHex);
1511 // Comment stream and backing vector.
1512 SmallString<128> CommentsToEmit;
1513 raw_svector_ostream CommentStream(CommentsToEmit);
1514 IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001515
1516 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00001517 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001518 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001519 return;
1520 }
1521
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001522 // Set up thumb disassembler.
1523 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
1524 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
1525 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001526 std::unique_ptr<MCDisassembler> ThumbDisAsm;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001527 std::unique_ptr<MCInstPrinter> ThumbIP;
1528 std::unique_ptr<MCContext> ThumbCtx;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001529 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
1530 struct DisassembleInfo ThumbSymbolizerInfo;
1531 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001532 if (ThumbTarget) {
1533 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
1534 ThumbAsmInfo.reset(
1535 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
1536 ThumbSTI.reset(
1537 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
1538 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
1539 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderby930fdc72014-11-06 19:00:13 +00001540 MCContext *PtrThumbCtx = ThumbCtx.get();
1541 ThumbRelInfo.reset(
1542 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
1543 if (ThumbRelInfo) {
1544 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
1545 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1546 &ThumbSymbolizerInfo, PtrThumbCtx, ThumbRelInfo.release()));
1547 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
1548 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001549 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
1550 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
1551 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
1552 *ThumbSTI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001553 // Set the display preference for hex vs. decimal immediates.
1554 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001555 }
1556
1557 if (ThumbTarget && (!ThumbInstrAnalysis || !ThumbAsmInfo || !ThumbSTI ||
1558 !ThumbDisAsm || !ThumbIP)) {
1559 errs() << "error: couldn't initialize disassembler for target "
1560 << ThumbTripleName << '\n';
1561 return;
1562 }
1563
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001564 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001565
Charles Davis8bdfafd2013-09-01 04:28:48 +00001566 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001567
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001568 // FIXME: Using the -cfg command line option, this code used to be able to
1569 // annotate relocations with the referenced symbol's name, and if this was
1570 // inside a __[cf]string section, the data it points to. This is now replaced
1571 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00001572 std::vector<SectionRef> Sections;
1573 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001574 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00001575 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001576
Kevin Enderby273ae012013-06-06 17:20:50 +00001577 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
1578 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001579
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001580 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00001581 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001582
Kevin Enderby273ae012013-06-06 17:20:50 +00001583 // Build a data in code table that is sorted on by the address of each entry.
1584 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00001585 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00001586 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00001587 else
1588 BaseAddress = BaseSegmentAddress;
1589 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00001590 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00001591 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00001592 uint32_t Offset;
1593 DI->getOffset(Offset);
1594 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
1595 }
1596 array_pod_sort(Dices.begin(), Dices.end());
1597
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001598#ifndef NDEBUG
1599 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1600#else
1601 raw_ostream &DebugOut = nulls();
1602#endif
1603
Ahmed Charles56440fd2014-03-06 05:51:42 +00001604 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00001605 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00001606 // Try to find debug info and set up the DIContext for it.
1607 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00001608 // A separate DSym file path was specified, parse it as a macho file,
1609 // get the sections and supply it to the section name parsing machinery.
1610 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00001611 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00001612 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00001613 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00001614 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00001615 return;
1616 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001617 DbgObj =
1618 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
1619 .get()
1620 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00001621 }
1622
Eric Christopher7370b552012-11-12 21:40:38 +00001623 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00001624 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00001625 }
1626
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001627 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001628
Rafael Espindola80291272014-10-08 15:28:58 +00001629 bool SectIsText = Sections[SectIdx].isText();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001630 if (SectIsText == false)
1631 continue;
1632
Owen Andersond9243c42011-10-17 21:37:35 +00001633 StringRef SectName;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001634 if (Sections[SectIdx].getName(SectName) || SectName != "__text")
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001635 continue; // Skip non-text sections
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001636
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001637 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001638
Rafael Espindolab0f76a42013-04-05 15:15:22 +00001639 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
1640 if (SegmentName != "__TEXT")
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001641 continue;
1642
Owen Andersond9243c42011-10-17 21:37:35 +00001643 StringRef Bytes;
1644 Sections[SectIdx].getContents(Bytes);
Rafael Espindola80291272014-10-08 15:28:58 +00001645 uint64_t SectAddress = Sections[SectIdx].getAddress();
Aaron Ballman8cb2cae2014-09-25 14:02:43 +00001646 DisasmMemoryObject MemoryObject((const uint8_t *)Bytes.data(), Bytes.size(),
Kevin Enderbybf246f52014-09-24 23:08:22 +00001647 SectAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001648 bool symbolTableWorked = false;
1649
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001650 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001651 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1652 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00001653 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001654 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00001655 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00001656 RelocOffset -= SectionAddress;
1657
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001658 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00001659
Rafael Espindola806f0062013-06-05 01:33:53 +00001660 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001661 }
1662 array_pod_sort(Relocs.begin(), Relocs.end());
1663
Kevin Enderbybf246f52014-09-24 23:08:22 +00001664 // Create a map of symbol addresses to symbol names for use by
1665 // the SymbolizerSymbolLookUp() routine.
1666 SymbolAddressMap AddrMap;
1667 for (const SymbolRef &Symbol : MachOOF->symbols()) {
1668 SymbolRef::Type ST;
1669 Symbol.getType(ST);
1670 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1671 ST == SymbolRef::ST_Other) {
1672 uint64_t Address;
1673 Symbol.getAddress(Address);
1674 StringRef SymName;
1675 Symbol.getName(SymName);
1676 AddrMap[Address] = SymName;
1677 }
1678 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001679 // Set up the block of info used by the Symbolizer call backs.
1680 SymbolizerInfo.verbose = true;
1681 SymbolizerInfo.O = MachOOF;
1682 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00001683 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001684 SymbolizerInfo.Sections = &Sections;
1685 SymbolizerInfo.class_name = nullptr;
1686 SymbolizerInfo.selector_name = nullptr;
1687 SymbolizerInfo.method = nullptr;
Kevin Enderby04bf6932014-10-28 23:39:46 +00001688 SymbolizerInfo.demangled_name = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00001689 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001690 // Same for the ThumbSymbolizer
1691 ThumbSymbolizerInfo.verbose = true;
1692 ThumbSymbolizerInfo.O = MachOOF;
1693 ThumbSymbolizerInfo.S = Sections[SectIdx];
1694 ThumbSymbolizerInfo.AddrMap = &AddrMap;
1695 ThumbSymbolizerInfo.Sections = &Sections;
1696 ThumbSymbolizerInfo.class_name = nullptr;
1697 ThumbSymbolizerInfo.selector_name = nullptr;
1698 ThumbSymbolizerInfo.method = nullptr;
1699 ThumbSymbolizerInfo.demangled_name = nullptr;
1700 ThumbSymbolizerInfo.bindtable = nullptr;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001701
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001702 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001703 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00001704 StringRef SymName;
1705 Symbols[SymIdx].getName(SymName);
1706
1707 SymbolRef::Type ST;
1708 Symbols[SymIdx].getType(ST);
1709 if (ST != SymbolRef::ST_Function)
1710 continue;
1711
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001712 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00001713 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00001714 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001715 continue;
1716
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001717 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00001718 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00001719 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00001720 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00001721 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00001722
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001723 // Stop disassembling either at the beginning of the next symbol or at
1724 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00001725 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00001726 uint64_t NextSym = 0;
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001727 uint64_t NextSymIdx = SymIdx + 1;
Owen Andersond9243c42011-10-17 21:37:35 +00001728 while (Symbols.size() > NextSymIdx) {
1729 SymbolRef::Type NextSymType;
1730 Symbols[NextSymIdx].getType(NextSymType);
1731 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00001732 containsNextSym =
1733 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00001734 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00001735 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00001736 break;
1737 }
1738 ++NextSymIdx;
1739 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001740
Rafael Espindola80291272014-10-08 15:28:58 +00001741 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001742 uint64_t End = containsNextSym ? NextSym : SectSize;
Owen Andersond9243c42011-10-17 21:37:35 +00001743 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001744
1745 symbolTableWorked = true;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001746 DisasmMemoryObject SectionMemoryObject((const uint8_t *)Bytes.data() +
1747 Start,
1748 End - Start, SectAddress + Start);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001749
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001750 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
1751 bool isThumb =
1752 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
1753
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001754 outs() << SymName << ":\n";
1755 DILineInfo lastLine;
1756 for (uint64_t Index = Start; Index < End; Index += Size) {
1757 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00001758
Kevin Enderbybf246f52014-09-24 23:08:22 +00001759 uint64_t PC = SectAddress + Index;
1760 if (FullLeadingAddr) {
1761 if (MachOOF->is64Bit())
1762 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001763 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001764 outs() << format("%08" PRIx64, PC);
1765 } else {
1766 outs() << format("%8" PRIx64 ":", PC);
1767 }
1768 if (!NoShowRawInsn)
1769 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00001770
1771 // Check the data in code table here to see if this is data not an
1772 // instruction to be disassembled.
1773 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001774 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001775 dice_table_iterator DTI =
1776 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
1777 compareDiceTableEntries);
1778 if (DTI != Dices.end()) {
Kevin Enderby273ae012013-06-06 17:20:50 +00001779 uint16_t Length;
1780 DTI->second.getLength(Length);
Kevin Enderby273ae012013-06-06 17:20:50 +00001781 uint16_t Kind;
1782 DTI->second.getKind(Kind);
Kevin Enderby930fdc72014-11-06 19:00:13 +00001783 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
1784 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
1785 (PC == (DTI->first + Length - 1)) && (Length & 1))
1786 Size++;
Kevin Enderby273ae012013-06-06 17:20:50 +00001787 continue;
1788 }
1789
Kevin Enderbybf246f52014-09-24 23:08:22 +00001790 SmallVector<char, 64> AnnotationsBytes;
1791 raw_svector_ostream Annotations(AnnotationsBytes);
1792
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001793 bool gotInst;
1794 if (isThumb)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001795 gotInst = ThumbDisAsm->getInstruction(Inst, Size, SectionMemoryObject,
1796 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001797 else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001798 gotInst = DisAsm->getInstruction(Inst, Size, SectionMemoryObject, PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00001799 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001800 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001801 if (!NoShowRawInsn) {
1802 DumpBytes(StringRef(Bytes.data() + Index, Size));
1803 }
1804 formatted_raw_ostream FormattedOS(outs());
1805 Annotations.flush();
1806 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001807 if (isThumb)
Kevin Enderbybf246f52014-09-24 23:08:22 +00001808 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001809 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001810 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
1811 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00001812
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001813 // Print debug info.
1814 if (diContext) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001815 DILineInfo dli = diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001816 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00001817 if (dli != lastLine && dli.Line != 0)
1818 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
1819 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001820 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001821 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001822 outs() << "\n";
1823 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001824 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001825 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001826 outs() << format("\t.byte 0x%02x #bad opcode\n",
1827 *(Bytes.data() + Index) & 0xff);
1828 Size = 1; // skip exactly one illegible byte and move on.
1829 } else {
1830 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1831 if (Size == 0)
1832 Size = 1; // skip illegible bytes
1833 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001834 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001835 }
1836 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001837 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00001838 // Reading the symbol table didn't work, disassemble the whole section.
1839 uint64_t SectAddress = Sections[SectIdx].getAddress();
1840 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00001841 uint64_t InstSize;
1842 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00001843 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00001844
Kevin Enderbybf246f52014-09-24 23:08:22 +00001845 uint64_t PC = SectAddress + Index;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001846 if (DisAsm->getInstruction(Inst, InstSize, MemoryObject, PC, DebugOut,
1847 nulls())) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001848 if (FullLeadingAddr) {
1849 if (MachOOF->is64Bit())
1850 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001851 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001852 outs() << format("%08" PRIx64, PC);
1853 } else {
1854 outs() << format("%8" PRIx64 ":", PC);
1855 }
1856 if (!NoShowRawInsn) {
1857 outs() << "\t";
1858 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
1859 }
Bill Wendling4e68e062012-07-19 00:17:40 +00001860 IP->printInst(&Inst, outs(), "");
1861 outs() << "\n";
1862 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001863 unsigned int Arch = MachOOF->getArch();
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001864 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001865 outs() << format("\t.byte 0x%02x #bad opcode\n",
1866 *(Bytes.data() + Index) & 0xff);
1867 InstSize = 1; // skip exactly one illegible byte and move on.
1868 } else {
1869 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1870 if (InstSize == 0)
1871 InstSize = 1; // skip illegible bytes
1872 }
Bill Wendling4e68e062012-07-19 00:17:40 +00001873 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00001874 }
1875 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001876 if (SymbolizerInfo.method != nullptr)
1877 free(SymbolizerInfo.method);
Kevin Enderby04bf6932014-10-28 23:39:46 +00001878 if (SymbolizerInfo.demangled_name != nullptr)
1879 free(SymbolizerInfo.demangled_name);
Kevin Enderby078be602014-10-23 19:53:12 +00001880 if (SymbolizerInfo.bindtable != nullptr)
1881 delete SymbolizerInfo.bindtable;
Kevin Enderby930fdc72014-11-06 19:00:13 +00001882 if (ThumbSymbolizerInfo.method != nullptr)
1883 free(ThumbSymbolizerInfo.method);
1884 if (ThumbSymbolizerInfo.demangled_name != nullptr)
1885 free(ThumbSymbolizerInfo.demangled_name);
1886 if (ThumbSymbolizerInfo.bindtable != nullptr)
1887 delete ThumbSymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001888 }
1889}
Tim Northover4bd286a2014-08-01 13:07:19 +00001890
Tim Northover39c70bb2014-08-12 11:52:59 +00001891//===----------------------------------------------------------------------===//
1892// __compact_unwind section dumping
1893//===----------------------------------------------------------------------===//
1894
Tim Northover4bd286a2014-08-01 13:07:19 +00001895namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00001896
1897template <typename T> static uint64_t readNext(const char *&Buf) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001898 using llvm::support::little;
1899 using llvm::support::unaligned;
Tim Northover39c70bb2014-08-12 11:52:59 +00001900
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001901 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
1902 Buf += sizeof(T);
1903 return Val;
1904}
Tim Northover39c70bb2014-08-12 11:52:59 +00001905
Tim Northover4bd286a2014-08-01 13:07:19 +00001906struct CompactUnwindEntry {
1907 uint32_t OffsetInSection;
1908
1909 uint64_t FunctionAddr;
1910 uint32_t Length;
1911 uint32_t CompactEncoding;
1912 uint64_t PersonalityAddr;
1913 uint64_t LSDAAddr;
1914
1915 RelocationRef FunctionReloc;
1916 RelocationRef PersonalityReloc;
1917 RelocationRef LSDAReloc;
1918
1919 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001920 : OffsetInSection(Offset) {
Tim Northover4bd286a2014-08-01 13:07:19 +00001921 if (Is64)
1922 read<uint64_t>(Contents.data() + Offset);
1923 else
1924 read<uint32_t>(Contents.data() + Offset);
1925 }
1926
1927private:
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001928 template <typename UIntPtr> void read(const char *Buf) {
Tim Northover4bd286a2014-08-01 13:07:19 +00001929 FunctionAddr = readNext<UIntPtr>(Buf);
1930 Length = readNext<uint32_t>(Buf);
1931 CompactEncoding = readNext<uint32_t>(Buf);
1932 PersonalityAddr = readNext<UIntPtr>(Buf);
1933 LSDAAddr = readNext<UIntPtr>(Buf);
1934 }
1935};
1936}
1937
1938/// Given a relocation from __compact_unwind, consisting of the RelocationRef
1939/// and data being relocated, determine the best base Name and Addend to use for
1940/// display purposes.
1941///
1942/// 1. An Extern relocation will directly reference a symbol (and the data is
1943/// then already an addend), so use that.
1944/// 2. Otherwise the data is an offset in the object file's layout; try to find
1945// a symbol before it in the same section, and use the offset from there.
1946/// 3. Finally, if all that fails, fall back to an offset from the start of the
1947/// referenced section.
1948static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
1949 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001950 const RelocationRef &Reloc, uint64_t Addr,
Tim Northover4bd286a2014-08-01 13:07:19 +00001951 StringRef &Name, uint64_t &Addend) {
1952 if (Reloc.getSymbol() != Obj->symbol_end()) {
1953 Reloc.getSymbol()->getName(Name);
1954 Addend = Addr;
1955 return;
1956 }
1957
1958 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
1959 SectionRef RelocSection = Obj->getRelocationSection(RE);
1960
Rafael Espindola80291272014-10-08 15:28:58 +00001961 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00001962
1963 auto Sym = Symbols.upper_bound(Addr);
1964 if (Sym == Symbols.begin()) {
1965 // The first symbol in the object is after this reference, the best we can
1966 // do is section-relative notation.
1967 RelocSection.getName(Name);
1968 Addend = Addr - SectionAddr;
1969 return;
1970 }
1971
1972 // Go back one so that SymbolAddress <= Addr.
1973 --Sym;
1974
1975 section_iterator SymSection = Obj->section_end();
1976 Sym->second.getSection(SymSection);
1977 if (RelocSection == *SymSection) {
1978 // There's a valid symbol in the same section before this reference.
1979 Sym->second.getName(Name);
1980 Addend = Addr - Sym->first;
1981 return;
1982 }
1983
1984 // There is a symbol before this reference, but it's in a different
1985 // section. Probably not helpful to mention it, so use the section name.
1986 RelocSection.getName(Name);
1987 Addend = Addr - SectionAddr;
1988}
1989
1990static void printUnwindRelocDest(const MachOObjectFile *Obj,
1991 std::map<uint64_t, SymbolRef> &Symbols,
Kevin Enderbyb28ed012014-10-29 21:28:24 +00001992 const RelocationRef &Reloc, uint64_t Addr) {
Tim Northover4bd286a2014-08-01 13:07:19 +00001993 StringRef Name;
1994 uint64_t Addend;
1995
Tim Northover0b0add52014-09-09 10:45:06 +00001996 if (!Reloc.getObjectFile())
1997 return;
1998
Tim Northover4bd286a2014-08-01 13:07:19 +00001999 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2000
2001 outs() << Name;
2002 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00002003 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00002004}
2005
2006static void
2007printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2008 std::map<uint64_t, SymbolRef> &Symbols,
2009 const SectionRef &CompactUnwind) {
2010
2011 assert(Obj->isLittleEndian() &&
2012 "There should not be a big-endian .o with __compact_unwind");
2013
2014 bool Is64 = Obj->is64Bit();
2015 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2016 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2017
2018 StringRef Contents;
2019 CompactUnwind.getContents(Contents);
2020
2021 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2022
2023 // First populate the initial raw offsets, encodings and so on from the entry.
2024 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2025 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2026 CompactUnwinds.push_back(Entry);
2027 }
2028
2029 // Next we need to look at the relocations to find out what objects are
2030 // actually being referred to.
2031 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2032 uint64_t RelocAddress;
2033 Reloc.getOffset(RelocAddress);
2034
2035 uint32_t EntryIdx = RelocAddress / EntrySize;
2036 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2037 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2038
2039 if (OffsetInEntry == 0)
2040 Entry.FunctionReloc = Reloc;
2041 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2042 Entry.PersonalityReloc = Reloc;
2043 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2044 Entry.LSDAReloc = Reloc;
2045 else
2046 llvm_unreachable("Unexpected relocation in __compact_unwind section");
2047 }
2048
2049 // Finally, we're ready to print the data we've gathered.
2050 outs() << "Contents of __compact_unwind section:\n";
2051 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00002052 outs() << " Entry at offset "
2053 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00002054
2055 // 1. Start of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002056 outs() << " start: " << format("0x%" PRIx64,
2057 Entry.FunctionAddr) << ' ';
2058 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
Tim Northover4bd286a2014-08-01 13:07:19 +00002059 outs() << '\n';
2060
2061 // 2. Length of the region this entry applies to.
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002062 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
2063 << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00002064 // 3. The 32-bit compact encoding.
2065 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00002066 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00002067
2068 // 4. The personality function, if present.
2069 if (Entry.PersonalityReloc.getObjectFile()) {
2070 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00002071 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00002072 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2073 Entry.PersonalityAddr);
2074 outs() << '\n';
2075 }
2076
2077 // 5. This entry's language-specific data area.
2078 if (Entry.LSDAReloc.getObjectFile()) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002079 outs() << " LSDA: " << format("0x%" PRIx64,
2080 Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00002081 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2082 outs() << '\n';
2083 }
2084 }
2085}
2086
Tim Northover39c70bb2014-08-12 11:52:59 +00002087//===----------------------------------------------------------------------===//
2088// __unwind_info section dumping
2089//===----------------------------------------------------------------------===//
2090
2091static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2092 const char *Pos = PageStart;
2093 uint32_t Kind = readNext<uint32_t>(Pos);
2094 (void)Kind;
2095 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2096
2097 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2098 uint16_t NumEntries = readNext<uint16_t>(Pos);
2099
2100 Pos = PageStart + EntriesStart;
2101 for (unsigned i = 0; i < NumEntries; ++i) {
2102 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2103 uint32_t Encoding = readNext<uint32_t>(Pos);
2104
2105 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002106 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2107 << ", "
2108 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002109 }
2110}
2111
2112static void printCompressedSecondLevelUnwindPage(
2113 const char *PageStart, uint32_t FunctionBase,
2114 const SmallVectorImpl<uint32_t> &CommonEncodings) {
2115 const char *Pos = PageStart;
2116 uint32_t Kind = readNext<uint32_t>(Pos);
2117 (void)Kind;
2118 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2119
2120 uint16_t EntriesStart = readNext<uint16_t>(Pos);
2121 uint16_t NumEntries = readNext<uint16_t>(Pos);
2122
2123 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
2124 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00002125 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
2126 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00002127
2128 Pos = PageStart + EntriesStart;
2129 for (unsigned i = 0; i < NumEntries; ++i) {
2130 uint32_t Entry = readNext<uint32_t>(Pos);
2131 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
2132 uint32_t EncodingIdx = Entry >> 24;
2133
2134 uint32_t Encoding;
2135 if (EncodingIdx < CommonEncodings.size())
2136 Encoding = CommonEncodings[EncodingIdx];
2137 else
2138 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
2139
2140 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002141 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2142 << ", "
2143 << "encoding[" << EncodingIdx
2144 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002145 }
2146}
2147
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002148static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
2149 std::map<uint64_t, SymbolRef> &Symbols,
2150 const SectionRef &UnwindInfo) {
Tim Northover39c70bb2014-08-12 11:52:59 +00002151
2152 assert(Obj->isLittleEndian() &&
2153 "There should not be a big-endian .o with __unwind_info");
2154
2155 outs() << "Contents of __unwind_info section:\n";
2156
2157 StringRef Contents;
2158 UnwindInfo.getContents(Contents);
2159 const char *Pos = Contents.data();
2160
2161 //===----------------------------------
2162 // Section header
2163 //===----------------------------------
2164
2165 uint32_t Version = readNext<uint32_t>(Pos);
2166 outs() << " Version: "
2167 << format("0x%" PRIx32, Version) << '\n';
2168 assert(Version == 1 && "only understand version 1");
2169
2170 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
2171 outs() << " Common encodings array section offset: "
2172 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
2173 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
2174 outs() << " Number of common encodings in array: "
2175 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
2176
2177 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
2178 outs() << " Personality function array section offset: "
2179 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
2180 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
2181 outs() << " Number of personality functions in array: "
2182 << format("0x%" PRIx32, NumPersonalities) << '\n';
2183
2184 uint32_t IndicesStart = readNext<uint32_t>(Pos);
2185 outs() << " Index array section offset: "
2186 << format("0x%" PRIx32, IndicesStart) << '\n';
2187 uint32_t NumIndices = readNext<uint32_t>(Pos);
2188 outs() << " Number of indices in array: "
2189 << format("0x%" PRIx32, NumIndices) << '\n';
2190
2191 //===----------------------------------
2192 // A shared list of common encodings
2193 //===----------------------------------
2194
2195 // These occupy indices in the range [0, N] whenever an encoding is referenced
2196 // from a compressed 2nd level index table. In practice the linker only
2197 // creates ~128 of these, so that indices are available to embed encodings in
2198 // the 2nd level index.
2199
2200 SmallVector<uint32_t, 64> CommonEncodings;
2201 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
2202 Pos = Contents.data() + CommonEncodingsStart;
2203 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
2204 uint32_t Encoding = readNext<uint32_t>(Pos);
2205 CommonEncodings.push_back(Encoding);
2206
2207 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
2208 << '\n';
2209 }
2210
Tim Northover39c70bb2014-08-12 11:52:59 +00002211 //===----------------------------------
2212 // Personality functions used in this executable
2213 //===----------------------------------
2214
2215 // There should be only a handful of these (one per source language,
2216 // roughly). Particularly since they only get 2 bits in the compact encoding.
2217
2218 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
2219 Pos = Contents.data() + PersonalitiesStart;
2220 for (unsigned i = 0; i < NumPersonalities; ++i) {
2221 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
2222 outs() << " personality[" << i + 1
2223 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
2224 }
2225
2226 //===----------------------------------
2227 // The level 1 index entries
2228 //===----------------------------------
2229
2230 // These specify an approximate place to start searching for the more detailed
2231 // information, sorted by PC.
2232
2233 struct IndexEntry {
2234 uint32_t FunctionOffset;
2235 uint32_t SecondLevelPageStart;
2236 uint32_t LSDAStart;
2237 };
2238
2239 SmallVector<IndexEntry, 4> IndexEntries;
2240
2241 outs() << " Top level indices: (count = " << NumIndices << ")\n";
2242 Pos = Contents.data() + IndicesStart;
2243 for (unsigned i = 0; i < NumIndices; ++i) {
2244 IndexEntry Entry;
2245
2246 Entry.FunctionOffset = readNext<uint32_t>(Pos);
2247 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
2248 Entry.LSDAStart = readNext<uint32_t>(Pos);
2249 IndexEntries.push_back(Entry);
2250
2251 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002252 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
2253 << ", "
Tim Northover39c70bb2014-08-12 11:52:59 +00002254 << "2nd level page offset="
2255 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002256 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002257 }
2258
Tim Northover39c70bb2014-08-12 11:52:59 +00002259 //===----------------------------------
2260 // Next come the LSDA tables
2261 //===----------------------------------
2262
2263 // The LSDA layout is rather implicit: it's a contiguous array of entries from
2264 // the first top-level index's LSDAOffset to the last (sentinel).
2265
2266 outs() << " LSDA descriptors:\n";
2267 Pos = Contents.data() + IndexEntries[0].LSDAStart;
2268 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2269 (2 * sizeof(uint32_t));
2270 for (int i = 0; i < NumLSDAs; ++i) {
2271 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2272 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2273 outs() << " [" << i << "]: "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00002274 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2275 << ", "
2276 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
Tim Northover39c70bb2014-08-12 11:52:59 +00002277 }
2278
2279 //===----------------------------------
2280 // Finally, the 2nd level indices
2281 //===----------------------------------
2282
2283 // Generally these are 4K in size, and have 2 possible forms:
2284 // + Regular stores up to 511 entries with disparate encodings
2285 // + Compressed stores up to 1021 entries if few enough compact encoding
2286 // values are used.
2287 outs() << " Second level indices:\n";
2288 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2289 // The final sentinel top-level index has no associated 2nd level page
2290 if (IndexEntries[i].SecondLevelPageStart == 0)
2291 break;
2292
2293 outs() << " Second level index[" << i << "]: "
2294 << "offset in section="
2295 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2296 << ", "
2297 << "base function offset="
2298 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2299
2300 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00002301 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00002302 if (Kind == 2)
2303 printRegularSecondLevelUnwindPage(Pos);
2304 else if (Kind == 3)
2305 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2306 CommonEncodings);
2307 else
2308 llvm_unreachable("Do not know how to print this kind of 2nd level page");
Tim Northover39c70bb2014-08-12 11:52:59 +00002309 }
2310}
2311
Tim Northover4bd286a2014-08-01 13:07:19 +00002312void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2313 std::map<uint64_t, SymbolRef> Symbols;
2314 for (const SymbolRef &SymRef : Obj->symbols()) {
2315 // Discard any undefined or absolute symbols. They're not going to take part
2316 // in the convenience lookup for unwind info and just take up resources.
2317 section_iterator Section = Obj->section_end();
2318 SymRef.getSection(Section);
2319 if (Section == Obj->section_end())
2320 continue;
2321
2322 uint64_t Addr;
2323 SymRef.getAddress(Addr);
2324 Symbols.insert(std::make_pair(Addr, SymRef));
2325 }
2326
2327 for (const SectionRef &Section : Obj->sections()) {
2328 StringRef SectName;
2329 Section.getName(SectName);
2330 if (SectName == "__compact_unwind")
2331 printMachOCompactUnwindSection(Obj, Symbols, Section);
2332 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00002333 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00002334 else if (SectName == "__eh_frame")
2335 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00002336 }
2337}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002338
2339static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2340 uint32_t cpusubtype, uint32_t filetype,
2341 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2342 bool verbose) {
2343 outs() << "Mach header\n";
2344 outs() << " magic cputype cpusubtype caps filetype ncmds "
2345 "sizeofcmds flags\n";
2346 if (verbose) {
2347 if (magic == MachO::MH_MAGIC)
2348 outs() << " MH_MAGIC";
2349 else if (magic == MachO::MH_MAGIC_64)
2350 outs() << "MH_MAGIC_64";
2351 else
2352 outs() << format(" 0x%08" PRIx32, magic);
2353 switch (cputype) {
2354 case MachO::CPU_TYPE_I386:
2355 outs() << " I386";
2356 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2357 case MachO::CPU_SUBTYPE_I386_ALL:
2358 outs() << " ALL";
2359 break;
2360 default:
2361 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2362 break;
2363 }
2364 break;
2365 case MachO::CPU_TYPE_X86_64:
2366 outs() << " X86_64";
2367 case MachO::CPU_SUBTYPE_X86_64_ALL:
2368 outs() << " ALL";
2369 break;
2370 case MachO::CPU_SUBTYPE_X86_64_H:
2371 outs() << " Haswell";
Aaron Ballman9d515ff2014-08-24 13:25:16 +00002372 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002373 break;
2374 case MachO::CPU_TYPE_ARM:
2375 outs() << " ARM";
2376 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2377 case MachO::CPU_SUBTYPE_ARM_ALL:
2378 outs() << " ALL";
2379 break;
2380 case MachO::CPU_SUBTYPE_ARM_V4T:
2381 outs() << " V4T";
2382 break;
2383 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2384 outs() << " V5TEJ";
2385 break;
2386 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2387 outs() << " XSCALE";
2388 break;
2389 case MachO::CPU_SUBTYPE_ARM_V6:
2390 outs() << " V6";
2391 break;
2392 case MachO::CPU_SUBTYPE_ARM_V6M:
2393 outs() << " V6M";
2394 break;
2395 case MachO::CPU_SUBTYPE_ARM_V7:
2396 outs() << " V7";
2397 break;
2398 case MachO::CPU_SUBTYPE_ARM_V7EM:
2399 outs() << " V7EM";
2400 break;
2401 case MachO::CPU_SUBTYPE_ARM_V7K:
2402 outs() << " V7K";
2403 break;
2404 case MachO::CPU_SUBTYPE_ARM_V7M:
2405 outs() << " V7M";
2406 break;
2407 case MachO::CPU_SUBTYPE_ARM_V7S:
2408 outs() << " V7S";
2409 break;
2410 default:
2411 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2412 break;
2413 }
2414 break;
2415 case MachO::CPU_TYPE_ARM64:
2416 outs() << " ARM64";
2417 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2418 case MachO::CPU_SUBTYPE_ARM64_ALL:
2419 outs() << " ALL";
2420 break;
2421 default:
2422 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2423 break;
2424 }
2425 break;
2426 case MachO::CPU_TYPE_POWERPC:
2427 outs() << " PPC";
2428 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2429 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2430 outs() << " ALL";
2431 break;
2432 default:
2433 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2434 break;
2435 }
2436 break;
2437 case MachO::CPU_TYPE_POWERPC64:
2438 outs() << " PPC64";
2439 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2440 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2441 outs() << " ALL";
2442 break;
2443 default:
2444 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2445 break;
2446 }
2447 break;
2448 }
2449 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002450 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002451 } else {
2452 outs() << format(" 0x%02" PRIx32,
2453 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2454 }
2455 switch (filetype) {
2456 case MachO::MH_OBJECT:
2457 outs() << " OBJECT";
2458 break;
2459 case MachO::MH_EXECUTE:
2460 outs() << " EXECUTE";
2461 break;
2462 case MachO::MH_FVMLIB:
2463 outs() << " FVMLIB";
2464 break;
2465 case MachO::MH_CORE:
2466 outs() << " CORE";
2467 break;
2468 case MachO::MH_PRELOAD:
2469 outs() << " PRELOAD";
2470 break;
2471 case MachO::MH_DYLIB:
2472 outs() << " DYLIB";
2473 break;
2474 case MachO::MH_DYLIB_STUB:
2475 outs() << " DYLIB_STUB";
2476 break;
2477 case MachO::MH_DYLINKER:
2478 outs() << " DYLINKER";
2479 break;
2480 case MachO::MH_BUNDLE:
2481 outs() << " BUNDLE";
2482 break;
2483 case MachO::MH_DSYM:
2484 outs() << " DSYM";
2485 break;
2486 case MachO::MH_KEXT_BUNDLE:
2487 outs() << " KEXTBUNDLE";
2488 break;
2489 default:
2490 outs() << format(" %10u", filetype);
2491 break;
2492 }
2493 outs() << format(" %5u", ncmds);
2494 outs() << format(" %10u", sizeofcmds);
2495 uint32_t f = flags;
2496 if (f & MachO::MH_NOUNDEFS) {
2497 outs() << " NOUNDEFS";
2498 f &= ~MachO::MH_NOUNDEFS;
2499 }
2500 if (f & MachO::MH_INCRLINK) {
2501 outs() << " INCRLINK";
2502 f &= ~MachO::MH_INCRLINK;
2503 }
2504 if (f & MachO::MH_DYLDLINK) {
2505 outs() << " DYLDLINK";
2506 f &= ~MachO::MH_DYLDLINK;
2507 }
2508 if (f & MachO::MH_BINDATLOAD) {
2509 outs() << " BINDATLOAD";
2510 f &= ~MachO::MH_BINDATLOAD;
2511 }
2512 if (f & MachO::MH_PREBOUND) {
2513 outs() << " PREBOUND";
2514 f &= ~MachO::MH_PREBOUND;
2515 }
2516 if (f & MachO::MH_SPLIT_SEGS) {
2517 outs() << " SPLIT_SEGS";
2518 f &= ~MachO::MH_SPLIT_SEGS;
2519 }
2520 if (f & MachO::MH_LAZY_INIT) {
2521 outs() << " LAZY_INIT";
2522 f &= ~MachO::MH_LAZY_INIT;
2523 }
2524 if (f & MachO::MH_TWOLEVEL) {
2525 outs() << " TWOLEVEL";
2526 f &= ~MachO::MH_TWOLEVEL;
2527 }
2528 if (f & MachO::MH_FORCE_FLAT) {
2529 outs() << " FORCE_FLAT";
2530 f &= ~MachO::MH_FORCE_FLAT;
2531 }
2532 if (f & MachO::MH_NOMULTIDEFS) {
2533 outs() << " NOMULTIDEFS";
2534 f &= ~MachO::MH_NOMULTIDEFS;
2535 }
2536 if (f & MachO::MH_NOFIXPREBINDING) {
2537 outs() << " NOFIXPREBINDING";
2538 f &= ~MachO::MH_NOFIXPREBINDING;
2539 }
2540 if (f & MachO::MH_PREBINDABLE) {
2541 outs() << " PREBINDABLE";
2542 f &= ~MachO::MH_PREBINDABLE;
2543 }
2544 if (f & MachO::MH_ALLMODSBOUND) {
2545 outs() << " ALLMODSBOUND";
2546 f &= ~MachO::MH_ALLMODSBOUND;
2547 }
2548 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
2549 outs() << " SUBSECTIONS_VIA_SYMBOLS";
2550 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
2551 }
2552 if (f & MachO::MH_CANONICAL) {
2553 outs() << " CANONICAL";
2554 f &= ~MachO::MH_CANONICAL;
2555 }
2556 if (f & MachO::MH_WEAK_DEFINES) {
2557 outs() << " WEAK_DEFINES";
2558 f &= ~MachO::MH_WEAK_DEFINES;
2559 }
2560 if (f & MachO::MH_BINDS_TO_WEAK) {
2561 outs() << " BINDS_TO_WEAK";
2562 f &= ~MachO::MH_BINDS_TO_WEAK;
2563 }
2564 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
2565 outs() << " ALLOW_STACK_EXECUTION";
2566 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
2567 }
2568 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
2569 outs() << " DEAD_STRIPPABLE_DYLIB";
2570 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
2571 }
2572 if (f & MachO::MH_PIE) {
2573 outs() << " PIE";
2574 f &= ~MachO::MH_PIE;
2575 }
2576 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
2577 outs() << " NO_REEXPORTED_DYLIBS";
2578 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
2579 }
2580 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
2581 outs() << " MH_HAS_TLV_DESCRIPTORS";
2582 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
2583 }
2584 if (f & MachO::MH_NO_HEAP_EXECUTION) {
2585 outs() << " MH_NO_HEAP_EXECUTION";
2586 f &= ~MachO::MH_NO_HEAP_EXECUTION;
2587 }
2588 if (f & MachO::MH_APP_EXTENSION_SAFE) {
2589 outs() << " APP_EXTENSION_SAFE";
2590 f &= ~MachO::MH_APP_EXTENSION_SAFE;
2591 }
2592 if (f != 0 || flags == 0)
2593 outs() << format(" 0x%08" PRIx32, f);
2594 } else {
2595 outs() << format(" 0x%08" PRIx32, magic);
2596 outs() << format(" %7d", cputype);
2597 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2598 outs() << format(" 0x%02" PRIx32,
2599 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2600 outs() << format(" %10u", filetype);
2601 outs() << format(" %5u", ncmds);
2602 outs() << format(" %10u", sizeofcmds);
2603 outs() << format(" 0x%08" PRIx32, flags);
2604 }
2605 outs() << "\n";
2606}
2607
Kevin Enderby956366c2014-08-29 22:30:52 +00002608static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
2609 StringRef SegName, uint64_t vmaddr,
2610 uint64_t vmsize, uint64_t fileoff,
2611 uint64_t filesize, uint32_t maxprot,
2612 uint32_t initprot, uint32_t nsects,
2613 uint32_t flags, uint32_t object_size,
2614 bool verbose) {
2615 uint64_t expected_cmdsize;
2616 if (cmd == MachO::LC_SEGMENT) {
2617 outs() << " cmd LC_SEGMENT\n";
2618 expected_cmdsize = nsects;
2619 expected_cmdsize *= sizeof(struct MachO::section);
2620 expected_cmdsize += sizeof(struct MachO::segment_command);
2621 } else {
2622 outs() << " cmd LC_SEGMENT_64\n";
2623 expected_cmdsize = nsects;
2624 expected_cmdsize *= sizeof(struct MachO::section_64);
2625 expected_cmdsize += sizeof(struct MachO::segment_command_64);
2626 }
2627 outs() << " cmdsize " << cmdsize;
2628 if (cmdsize != expected_cmdsize)
2629 outs() << " Inconsistent size\n";
2630 else
2631 outs() << "\n";
2632 outs() << " segname " << SegName << "\n";
2633 if (cmd == MachO::LC_SEGMENT_64) {
2634 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
2635 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
2636 } else {
2637 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
2638 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
2639 }
2640 outs() << " fileoff " << fileoff;
2641 if (fileoff > object_size)
2642 outs() << " (past end of file)\n";
2643 else
2644 outs() << "\n";
2645 outs() << " filesize " << filesize;
2646 if (fileoff + filesize > object_size)
2647 outs() << " (past end of file)\n";
2648 else
2649 outs() << "\n";
2650 if (verbose) {
2651 if ((maxprot &
2652 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2653 MachO::VM_PROT_EXECUTE)) != 0)
2654 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
2655 else {
2656 if (maxprot & MachO::VM_PROT_READ)
2657 outs() << " maxprot r";
2658 else
2659 outs() << " maxprot -";
2660 if (maxprot & MachO::VM_PROT_WRITE)
2661 outs() << "w";
2662 else
2663 outs() << "-";
2664 if (maxprot & MachO::VM_PROT_EXECUTE)
2665 outs() << "x\n";
2666 else
2667 outs() << "-\n";
2668 }
2669 if ((initprot &
2670 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2671 MachO::VM_PROT_EXECUTE)) != 0)
2672 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
2673 else {
2674 if (initprot & MachO::VM_PROT_READ)
2675 outs() << " initprot r";
2676 else
2677 outs() << " initprot -";
2678 if (initprot & MachO::VM_PROT_WRITE)
2679 outs() << "w";
2680 else
2681 outs() << "-";
2682 if (initprot & MachO::VM_PROT_EXECUTE)
2683 outs() << "x\n";
2684 else
2685 outs() << "-\n";
2686 }
2687 } else {
2688 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
2689 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
2690 }
2691 outs() << " nsects " << nsects << "\n";
2692 if (verbose) {
2693 outs() << " flags";
2694 if (flags == 0)
2695 outs() << " (none)\n";
2696 else {
2697 if (flags & MachO::SG_HIGHVM) {
2698 outs() << " HIGHVM";
2699 flags &= ~MachO::SG_HIGHVM;
2700 }
2701 if (flags & MachO::SG_FVMLIB) {
2702 outs() << " FVMLIB";
2703 flags &= ~MachO::SG_FVMLIB;
2704 }
2705 if (flags & MachO::SG_NORELOC) {
2706 outs() << " NORELOC";
2707 flags &= ~MachO::SG_NORELOC;
2708 }
2709 if (flags & MachO::SG_PROTECTED_VERSION_1) {
2710 outs() << " PROTECTED_VERSION_1";
2711 flags &= ~MachO::SG_PROTECTED_VERSION_1;
2712 }
2713 if (flags)
2714 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
2715 else
2716 outs() << "\n";
2717 }
2718 } else {
2719 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
2720 }
2721}
2722
2723static void PrintSection(const char *sectname, const char *segname,
2724 uint64_t addr, uint64_t size, uint32_t offset,
2725 uint32_t align, uint32_t reloff, uint32_t nreloc,
2726 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
2727 uint32_t cmd, const char *sg_segname,
2728 uint32_t filetype, uint32_t object_size,
2729 bool verbose) {
2730 outs() << "Section\n";
2731 outs() << " sectname " << format("%.16s\n", sectname);
2732 outs() << " segname " << format("%.16s", segname);
2733 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
2734 outs() << " (does not match segment)\n";
2735 else
2736 outs() << "\n";
2737 if (cmd == MachO::LC_SEGMENT_64) {
2738 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
2739 outs() << " size " << format("0x%016" PRIx64, size);
2740 } else {
2741 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
2742 outs() << " size " << format("0x%08" PRIx32, size);
2743 }
2744 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
2745 outs() << " (past end of file)\n";
2746 else
2747 outs() << "\n";
2748 outs() << " offset " << offset;
2749 if (offset > object_size)
2750 outs() << " (past end of file)\n";
2751 else
2752 outs() << "\n";
2753 uint32_t align_shifted = 1 << align;
2754 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
2755 outs() << " reloff " << reloff;
2756 if (reloff > object_size)
2757 outs() << " (past end of file)\n";
2758 else
2759 outs() << "\n";
2760 outs() << " nreloc " << nreloc;
2761 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
2762 outs() << " (past end of file)\n";
2763 else
2764 outs() << "\n";
2765 uint32_t section_type = flags & MachO::SECTION_TYPE;
2766 if (verbose) {
2767 outs() << " type";
2768 if (section_type == MachO::S_REGULAR)
2769 outs() << " S_REGULAR\n";
2770 else if (section_type == MachO::S_ZEROFILL)
2771 outs() << " S_ZEROFILL\n";
2772 else if (section_type == MachO::S_CSTRING_LITERALS)
2773 outs() << " S_CSTRING_LITERALS\n";
2774 else if (section_type == MachO::S_4BYTE_LITERALS)
2775 outs() << " S_4BYTE_LITERALS\n";
2776 else if (section_type == MachO::S_8BYTE_LITERALS)
2777 outs() << " S_8BYTE_LITERALS\n";
2778 else if (section_type == MachO::S_16BYTE_LITERALS)
2779 outs() << " S_16BYTE_LITERALS\n";
2780 else if (section_type == MachO::S_LITERAL_POINTERS)
2781 outs() << " S_LITERAL_POINTERS\n";
2782 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
2783 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
2784 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
2785 outs() << " S_LAZY_SYMBOL_POINTERS\n";
2786 else if (section_type == MachO::S_SYMBOL_STUBS)
2787 outs() << " S_SYMBOL_STUBS\n";
2788 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
2789 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
2790 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
2791 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
2792 else if (section_type == MachO::S_COALESCED)
2793 outs() << " S_COALESCED\n";
2794 else if (section_type == MachO::S_INTERPOSING)
2795 outs() << " S_INTERPOSING\n";
2796 else if (section_type == MachO::S_DTRACE_DOF)
2797 outs() << " S_DTRACE_DOF\n";
2798 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
2799 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
2800 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
2801 outs() << " S_THREAD_LOCAL_REGULAR\n";
2802 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
2803 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
2804 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
2805 outs() << " S_THREAD_LOCAL_VARIABLES\n";
2806 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2807 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
2808 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
2809 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
2810 else
2811 outs() << format("0x%08" PRIx32, section_type) << "\n";
2812 outs() << "attributes";
2813 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
2814 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
2815 outs() << " PURE_INSTRUCTIONS";
2816 if (section_attributes & MachO::S_ATTR_NO_TOC)
2817 outs() << " NO_TOC";
2818 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
2819 outs() << " STRIP_STATIC_SYMS";
2820 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
2821 outs() << " NO_DEAD_STRIP";
2822 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
2823 outs() << " LIVE_SUPPORT";
2824 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
2825 outs() << " SELF_MODIFYING_CODE";
2826 if (section_attributes & MachO::S_ATTR_DEBUG)
2827 outs() << " DEBUG";
2828 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
2829 outs() << " SOME_INSTRUCTIONS";
2830 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
2831 outs() << " EXT_RELOC";
2832 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
2833 outs() << " LOC_RELOC";
2834 if (section_attributes == 0)
2835 outs() << " (none)";
2836 outs() << "\n";
2837 } else
2838 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
2839 outs() << " reserved1 " << reserved1;
2840 if (section_type == MachO::S_SYMBOL_STUBS ||
2841 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2842 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2843 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2844 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2845 outs() << " (index into indirect symbol table)\n";
2846 else
2847 outs() << "\n";
2848 outs() << " reserved2 " << reserved2;
2849 if (section_type == MachO::S_SYMBOL_STUBS)
2850 outs() << " (size of stubs)\n";
2851 else
2852 outs() << "\n";
2853}
2854
2855static void PrintSymtabLoadCommand(MachO::symtab_command st, uint32_t cputype,
2856 uint32_t object_size) {
2857 outs() << " cmd LC_SYMTAB\n";
2858 outs() << " cmdsize " << st.cmdsize;
2859 if (st.cmdsize != sizeof(struct MachO::symtab_command))
2860 outs() << " Incorrect size\n";
2861 else
2862 outs() << "\n";
2863 outs() << " symoff " << st.symoff;
2864 if (st.symoff > object_size)
2865 outs() << " (past end of file)\n";
2866 else
2867 outs() << "\n";
2868 outs() << " nsyms " << st.nsyms;
2869 uint64_t big_size;
2870 if (cputype & MachO::CPU_ARCH_ABI64) {
2871 big_size = st.nsyms;
2872 big_size *= sizeof(struct MachO::nlist_64);
2873 big_size += st.symoff;
2874 if (big_size > object_size)
2875 outs() << " (past end of file)\n";
2876 else
2877 outs() << "\n";
2878 } else {
2879 big_size = st.nsyms;
2880 big_size *= sizeof(struct MachO::nlist);
2881 big_size += st.symoff;
2882 if (big_size > object_size)
2883 outs() << " (past end of file)\n";
2884 else
2885 outs() << "\n";
2886 }
2887 outs() << " stroff " << st.stroff;
2888 if (st.stroff > object_size)
2889 outs() << " (past end of file)\n";
2890 else
2891 outs() << "\n";
2892 outs() << " strsize " << st.strsize;
2893 big_size = st.stroff;
2894 big_size += st.strsize;
2895 if (big_size > object_size)
2896 outs() << " (past end of file)\n";
2897 else
2898 outs() << "\n";
2899}
2900
2901static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
2902 uint32_t nsyms, uint32_t object_size,
2903 uint32_t cputype) {
2904 outs() << " cmd LC_DYSYMTAB\n";
2905 outs() << " cmdsize " << dyst.cmdsize;
2906 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
2907 outs() << " Incorrect size\n";
2908 else
2909 outs() << "\n";
2910 outs() << " ilocalsym " << dyst.ilocalsym;
2911 if (dyst.ilocalsym > nsyms)
2912 outs() << " (greater than the number of symbols)\n";
2913 else
2914 outs() << "\n";
2915 outs() << " nlocalsym " << dyst.nlocalsym;
2916 uint64_t big_size;
2917 big_size = dyst.ilocalsym;
2918 big_size += dyst.nlocalsym;
2919 if (big_size > nsyms)
2920 outs() << " (past the end of the symbol table)\n";
2921 else
2922 outs() << "\n";
2923 outs() << " iextdefsym " << dyst.iextdefsym;
2924 if (dyst.iextdefsym > nsyms)
2925 outs() << " (greater than the number of symbols)\n";
2926 else
2927 outs() << "\n";
2928 outs() << " nextdefsym " << dyst.nextdefsym;
2929 big_size = dyst.iextdefsym;
2930 big_size += dyst.nextdefsym;
2931 if (big_size > nsyms)
2932 outs() << " (past the end of the symbol table)\n";
2933 else
2934 outs() << "\n";
2935 outs() << " iundefsym " << dyst.iundefsym;
2936 if (dyst.iundefsym > nsyms)
2937 outs() << " (greater than the number of symbols)\n";
2938 else
2939 outs() << "\n";
2940 outs() << " nundefsym " << dyst.nundefsym;
2941 big_size = dyst.iundefsym;
2942 big_size += dyst.nundefsym;
2943 if (big_size > nsyms)
2944 outs() << " (past the end of the symbol table)\n";
2945 else
2946 outs() << "\n";
2947 outs() << " tocoff " << dyst.tocoff;
2948 if (dyst.tocoff > object_size)
2949 outs() << " (past end of file)\n";
2950 else
2951 outs() << "\n";
2952 outs() << " ntoc " << dyst.ntoc;
2953 big_size = dyst.ntoc;
2954 big_size *= sizeof(struct MachO::dylib_table_of_contents);
2955 big_size += dyst.tocoff;
2956 if (big_size > object_size)
2957 outs() << " (past end of file)\n";
2958 else
2959 outs() << "\n";
2960 outs() << " modtaboff " << dyst.modtaboff;
2961 if (dyst.modtaboff > object_size)
2962 outs() << " (past end of file)\n";
2963 else
2964 outs() << "\n";
2965 outs() << " nmodtab " << dyst.nmodtab;
2966 uint64_t modtabend;
2967 if (cputype & MachO::CPU_ARCH_ABI64) {
2968 modtabend = dyst.nmodtab;
2969 modtabend *= sizeof(struct MachO::dylib_module_64);
2970 modtabend += dyst.modtaboff;
2971 } else {
2972 modtabend = dyst.nmodtab;
2973 modtabend *= sizeof(struct MachO::dylib_module);
2974 modtabend += dyst.modtaboff;
2975 }
2976 if (modtabend > object_size)
2977 outs() << " (past end of file)\n";
2978 else
2979 outs() << "\n";
2980 outs() << " extrefsymoff " << dyst.extrefsymoff;
2981 if (dyst.extrefsymoff > object_size)
2982 outs() << " (past end of file)\n";
2983 else
2984 outs() << "\n";
2985 outs() << " nextrefsyms " << dyst.nextrefsyms;
2986 big_size = dyst.nextrefsyms;
2987 big_size *= sizeof(struct MachO::dylib_reference);
2988 big_size += dyst.extrefsymoff;
2989 if (big_size > object_size)
2990 outs() << " (past end of file)\n";
2991 else
2992 outs() << "\n";
2993 outs() << " indirectsymoff " << dyst.indirectsymoff;
2994 if (dyst.indirectsymoff > object_size)
2995 outs() << " (past end of file)\n";
2996 else
2997 outs() << "\n";
2998 outs() << " nindirectsyms " << dyst.nindirectsyms;
2999 big_size = dyst.nindirectsyms;
3000 big_size *= sizeof(uint32_t);
3001 big_size += dyst.indirectsymoff;
3002 if (big_size > object_size)
3003 outs() << " (past end of file)\n";
3004 else
3005 outs() << "\n";
3006 outs() << " extreloff " << dyst.extreloff;
3007 if (dyst.extreloff > object_size)
3008 outs() << " (past end of file)\n";
3009 else
3010 outs() << "\n";
3011 outs() << " nextrel " << dyst.nextrel;
3012 big_size = dyst.nextrel;
3013 big_size *= sizeof(struct MachO::relocation_info);
3014 big_size += dyst.extreloff;
3015 if (big_size > object_size)
3016 outs() << " (past end of file)\n";
3017 else
3018 outs() << "\n";
3019 outs() << " locreloff " << dyst.locreloff;
3020 if (dyst.locreloff > object_size)
3021 outs() << " (past end of file)\n";
3022 else
3023 outs() << "\n";
3024 outs() << " nlocrel " << dyst.nlocrel;
3025 big_size = dyst.nlocrel;
3026 big_size *= sizeof(struct MachO::relocation_info);
3027 big_size += dyst.locreloff;
3028 if (big_size > object_size)
3029 outs() << " (past end of file)\n";
3030 else
3031 outs() << "\n";
3032}
3033
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003034static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3035 uint32_t object_size) {
3036 if (dc.cmd == MachO::LC_DYLD_INFO)
3037 outs() << " cmd LC_DYLD_INFO\n";
3038 else
3039 outs() << " cmd LC_DYLD_INFO_ONLY\n";
3040 outs() << " cmdsize " << dc.cmdsize;
3041 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3042 outs() << " Incorrect size\n";
3043 else
3044 outs() << "\n";
3045 outs() << " rebase_off " << dc.rebase_off;
3046 if (dc.rebase_off > object_size)
3047 outs() << " (past end of file)\n";
3048 else
3049 outs() << "\n";
3050 outs() << " rebase_size " << dc.rebase_size;
3051 uint64_t big_size;
3052 big_size = dc.rebase_off;
3053 big_size += dc.rebase_size;
3054 if (big_size > object_size)
3055 outs() << " (past end of file)\n";
3056 else
3057 outs() << "\n";
3058 outs() << " bind_off " << dc.bind_off;
3059 if (dc.bind_off > object_size)
3060 outs() << " (past end of file)\n";
3061 else
3062 outs() << "\n";
3063 outs() << " bind_size " << dc.bind_size;
3064 big_size = dc.bind_off;
3065 big_size += dc.bind_size;
3066 if (big_size > object_size)
3067 outs() << " (past end of file)\n";
3068 else
3069 outs() << "\n";
3070 outs() << " weak_bind_off " << dc.weak_bind_off;
3071 if (dc.weak_bind_off > object_size)
3072 outs() << " (past end of file)\n";
3073 else
3074 outs() << "\n";
3075 outs() << " weak_bind_size " << dc.weak_bind_size;
3076 big_size = dc.weak_bind_off;
3077 big_size += dc.weak_bind_size;
3078 if (big_size > object_size)
3079 outs() << " (past end of file)\n";
3080 else
3081 outs() << "\n";
3082 outs() << " lazy_bind_off " << dc.lazy_bind_off;
3083 if (dc.lazy_bind_off > object_size)
3084 outs() << " (past end of file)\n";
3085 else
3086 outs() << "\n";
3087 outs() << " lazy_bind_size " << dc.lazy_bind_size;
3088 big_size = dc.lazy_bind_off;
3089 big_size += dc.lazy_bind_size;
3090 if (big_size > object_size)
3091 outs() << " (past end of file)\n";
3092 else
3093 outs() << "\n";
3094 outs() << " export_off " << dc.export_off;
3095 if (dc.export_off > object_size)
3096 outs() << " (past end of file)\n";
3097 else
3098 outs() << "\n";
3099 outs() << " export_size " << dc.export_size;
3100 big_size = dc.export_off;
3101 big_size += dc.export_size;
3102 if (big_size > object_size)
3103 outs() << " (past end of file)\n";
3104 else
3105 outs() << "\n";
3106}
3107
3108static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3109 const char *Ptr) {
3110 if (dyld.cmd == MachO::LC_ID_DYLINKER)
3111 outs() << " cmd LC_ID_DYLINKER\n";
3112 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3113 outs() << " cmd LC_LOAD_DYLINKER\n";
3114 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3115 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
3116 else
3117 outs() << " cmd ?(" << dyld.cmd << ")\n";
3118 outs() << " cmdsize " << dyld.cmdsize;
3119 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
3120 outs() << " Incorrect size\n";
3121 else
3122 outs() << "\n";
3123 if (dyld.name >= dyld.cmdsize)
3124 outs() << " name ?(bad offset " << dyld.name << ")\n";
3125 else {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003126 const char *P = (const char *)(Ptr) + dyld.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003127 outs() << " name " << P << " (offset " << dyld.name << ")\n";
3128 }
3129}
3130
3131static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
3132 outs() << " cmd LC_UUID\n";
3133 outs() << " cmdsize " << uuid.cmdsize;
3134 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
3135 outs() << " Incorrect size\n";
3136 else
3137 outs() << "\n";
3138 outs() << " uuid ";
3139 outs() << format("%02" PRIX32, uuid.uuid[0]);
3140 outs() << format("%02" PRIX32, uuid.uuid[1]);
3141 outs() << format("%02" PRIX32, uuid.uuid[2]);
3142 outs() << format("%02" PRIX32, uuid.uuid[3]);
3143 outs() << "-";
3144 outs() << format("%02" PRIX32, uuid.uuid[4]);
3145 outs() << format("%02" PRIX32, uuid.uuid[5]);
3146 outs() << "-";
3147 outs() << format("%02" PRIX32, uuid.uuid[6]);
3148 outs() << format("%02" PRIX32, uuid.uuid[7]);
3149 outs() << "-";
3150 outs() << format("%02" PRIX32, uuid.uuid[8]);
3151 outs() << format("%02" PRIX32, uuid.uuid[9]);
3152 outs() << "-";
3153 outs() << format("%02" PRIX32, uuid.uuid[10]);
3154 outs() << format("%02" PRIX32, uuid.uuid[11]);
3155 outs() << format("%02" PRIX32, uuid.uuid[12]);
3156 outs() << format("%02" PRIX32, uuid.uuid[13]);
3157 outs() << format("%02" PRIX32, uuid.uuid[14]);
3158 outs() << format("%02" PRIX32, uuid.uuid[15]);
3159 outs() << "\n";
3160}
3161
3162static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
3163 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
3164 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
3165 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
3166 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
3167 else
3168 outs() << " cmd " << vd.cmd << " (?)\n";
3169 outs() << " cmdsize " << vd.cmdsize;
3170 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
3171 outs() << " Incorrect size\n";
3172 else
3173 outs() << "\n";
3174 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
3175 << ((vd.version >> 8) & 0xff);
3176 if ((vd.version & 0xff) != 0)
3177 outs() << "." << (vd.version & 0xff);
3178 outs() << "\n";
3179 if (vd.sdk == 0)
3180 outs() << " sdk n/a\n";
3181 else {
3182 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
3183 << ((vd.sdk >> 8) & 0xff);
3184 }
3185 if ((vd.sdk & 0xff) != 0)
3186 outs() << "." << (vd.sdk & 0xff);
3187 outs() << "\n";
3188}
3189
3190static void PrintSourceVersionCommand(MachO::source_version_command sd) {
3191 outs() << " cmd LC_SOURCE_VERSION\n";
3192 outs() << " cmdsize " << sd.cmdsize;
3193 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
3194 outs() << " Incorrect size\n";
3195 else
3196 outs() << "\n";
3197 uint64_t a = (sd.version >> 40) & 0xffffff;
3198 uint64_t b = (sd.version >> 30) & 0x3ff;
3199 uint64_t c = (sd.version >> 20) & 0x3ff;
3200 uint64_t d = (sd.version >> 10) & 0x3ff;
3201 uint64_t e = sd.version & 0x3ff;
3202 outs() << " version " << a << "." << b;
3203 if (e != 0)
3204 outs() << "." << c << "." << d << "." << e;
3205 else if (d != 0)
3206 outs() << "." << c << "." << d;
3207 else if (c != 0)
3208 outs() << "." << c;
3209 outs() << "\n";
3210}
3211
3212static void PrintEntryPointCommand(MachO::entry_point_command ep) {
3213 outs() << " cmd LC_MAIN\n";
3214 outs() << " cmdsize " << ep.cmdsize;
3215 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
3216 outs() << " Incorrect size\n";
3217 else
3218 outs() << "\n";
3219 outs() << " entryoff " << ep.entryoff << "\n";
3220 outs() << " stacksize " << ep.stacksize << "\n";
3221}
3222
3223static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
3224 if (dl.cmd == MachO::LC_ID_DYLIB)
3225 outs() << " cmd LC_ID_DYLIB\n";
3226 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
3227 outs() << " cmd LC_LOAD_DYLIB\n";
3228 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
3229 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
3230 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
3231 outs() << " cmd LC_REEXPORT_DYLIB\n";
3232 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
3233 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
3234 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
3235 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
3236 else
3237 outs() << " cmd " << dl.cmd << " (unknown)\n";
3238 outs() << " cmdsize " << dl.cmdsize;
3239 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
3240 outs() << " Incorrect size\n";
3241 else
3242 outs() << "\n";
3243 if (dl.dylib.name < dl.cmdsize) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003244 const char *P = (const char *)(Ptr) + dl.dylib.name;
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003245 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
3246 } else {
3247 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
3248 }
3249 outs() << " time stamp " << dl.dylib.timestamp << " ";
3250 time_t t = dl.dylib.timestamp;
3251 outs() << ctime(&t);
3252 outs() << " current version ";
3253 if (dl.dylib.current_version == 0xffffffff)
3254 outs() << "n/a\n";
3255 else
3256 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
3257 << ((dl.dylib.current_version >> 8) & 0xff) << "."
3258 << (dl.dylib.current_version & 0xff) << "\n";
3259 outs() << "compatibility version ";
3260 if (dl.dylib.compatibility_version == 0xffffffff)
3261 outs() << "n/a\n";
3262 else
3263 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
3264 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
3265 << (dl.dylib.compatibility_version & 0xff) << "\n";
3266}
3267
3268static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
3269 uint32_t object_size) {
3270 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
3271 outs() << " cmd LC_FUNCTION_STARTS\n";
3272 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
3273 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
3274 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
3275 outs() << " cmd LC_FUNCTION_STARTS\n";
3276 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
3277 outs() << " cmd LC_DATA_IN_CODE\n";
3278 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
3279 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
3280 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
3281 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
3282 else
3283 outs() << " cmd " << ld.cmd << " (?)\n";
3284 outs() << " cmdsize " << ld.cmdsize;
3285 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
3286 outs() << " Incorrect size\n";
3287 else
3288 outs() << "\n";
3289 outs() << " dataoff " << ld.dataoff;
3290 if (ld.dataoff > object_size)
3291 outs() << " (past end of file)\n";
3292 else
3293 outs() << "\n";
3294 outs() << " datasize " << ld.datasize;
3295 uint64_t big_size = ld.dataoff;
3296 big_size += ld.datasize;
3297 if (big_size > object_size)
3298 outs() << " (past end of file)\n";
3299 else
3300 outs() << "\n";
3301}
3302
Kevin Enderby956366c2014-08-29 22:30:52 +00003303static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
3304 uint32_t filetype, uint32_t cputype,
3305 bool verbose) {
3306 StringRef Buf = Obj->getData();
3307 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
3308 for (unsigned i = 0;; ++i) {
3309 outs() << "Load command " << i << "\n";
3310 if (Command.C.cmd == MachO::LC_SEGMENT) {
3311 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
3312 const char *sg_segname = SLC.segname;
3313 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
3314 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
3315 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
3316 verbose);
3317 for (unsigned j = 0; j < SLC.nsects; j++) {
3318 MachO::section_64 S = Obj->getSection64(Command, j);
3319 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
3320 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
3321 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
3322 }
3323 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3324 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
3325 const char *sg_segname = SLC_64.segname;
3326 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
3327 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
3328 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
3329 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
3330 for (unsigned j = 0; j < SLC_64.nsects; j++) {
3331 MachO::section_64 S_64 = Obj->getSection64(Command, j);
3332 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
3333 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
3334 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
3335 sg_segname, filetype, Buf.size(), verbose);
3336 }
3337 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
3338 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3339 PrintSymtabLoadCommand(Symtab, cputype, Buf.size());
3340 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
3341 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
3342 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3343 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), cputype);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003344 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
3345 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
3346 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
3347 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
3348 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
3349 Command.C.cmd == MachO::LC_ID_DYLINKER ||
3350 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
3351 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
3352 PrintDyldLoadCommand(Dyld, Command.Ptr);
3353 } else if (Command.C.cmd == MachO::LC_UUID) {
3354 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
3355 PrintUuidLoadCommand(Uuid);
3356 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
3357 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
3358 PrintVersionMinLoadCommand(Vd);
3359 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
3360 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
3361 PrintSourceVersionCommand(Sd);
3362 } else if (Command.C.cmd == MachO::LC_MAIN) {
3363 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
3364 PrintEntryPointCommand(Ep);
Nick Kledzik15558912014-10-16 18:58:20 +00003365 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
3366 Command.C.cmd == MachO::LC_ID_DYLIB ||
3367 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
3368 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
3369 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
3370 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003371 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
3372 PrintDylibCommand(Dl, Command.Ptr);
3373 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
3374 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
3375 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
3376 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
3377 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
3378 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
3379 MachO::linkedit_data_command Ld =
3380 Obj->getLinkeditDataLoadCommand(Command);
3381 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00003382 } else {
3383 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
3384 << ")\n";
3385 outs() << " cmdsize " << Command.C.cmdsize << "\n";
3386 // TODO: get and print the raw bytes of the load command.
3387 }
3388 // TODO: print all the other kinds of load commands.
3389 if (i == ncmds - 1)
3390 break;
3391 else
3392 Command = Obj->getNextLoadCommandInfo(Command);
3393 }
3394}
3395
3396static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
3397 uint32_t &filetype, uint32_t &cputype,
3398 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003399 if (Obj->is64Bit()) {
3400 MachO::mach_header_64 H_64;
3401 H_64 = Obj->getHeader64();
3402 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
3403 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00003404 ncmds = H_64.ncmds;
3405 filetype = H_64.filetype;
3406 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003407 } else {
3408 MachO::mach_header H;
3409 H = Obj->getHeader();
3410 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
3411 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00003412 ncmds = H.ncmds;
3413 filetype = H.filetype;
3414 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003415 }
3416}
3417
3418void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
3419 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00003420 uint32_t ncmds = 0;
3421 uint32_t filetype = 0;
3422 uint32_t cputype = 0;
3423 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
3424 PrintLoadCommands(file, ncmds, filetype, cputype, true);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003425}
Nick Kledzikd04bc352014-08-30 00:20:14 +00003426
3427//===----------------------------------------------------------------------===//
3428// export trie dumping
3429//===----------------------------------------------------------------------===//
3430
3431void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003432 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
3433 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00003434 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
3435 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
3436 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3437 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
3438 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3439 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
3440 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
3441 if (ReExport)
3442 outs() << "[re-export] ";
3443 else
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003444 outs() << format("0x%08llX ",
3445 Entry.address()); // FIXME:add in base address
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003446 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00003447 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003448 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00003449 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00003450 if (WeakDef) {
3451 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003452 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003453 }
3454 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003455 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003456 outs() << ", ";
3457 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003458 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003459 }
3460 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003461 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003462 outs() << ", ";
3463 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003464 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003465 }
3466 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003467 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003468 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003469 outs() << format("resolver=0x%08llX", Entry.other());
3470 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003471 }
3472 outs() << "]";
3473 }
3474 if (ReExport) {
3475 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003476 int Ordinal = Entry.other() - 1;
3477 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
3478 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00003479 outs() << " (from " << DylibName << ")";
3480 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003481 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00003482 }
3483 outs() << "\n";
3484 }
3485}
Nick Kledzikac431442014-09-12 21:34:15 +00003486
Nick Kledzikac431442014-09-12 21:34:15 +00003487//===----------------------------------------------------------------------===//
3488// rebase table dumping
3489//===----------------------------------------------------------------------===//
3490
3491namespace {
3492class SegInfo {
3493public:
3494 SegInfo(const object::MachOObjectFile *Obj);
3495
3496 StringRef segmentName(uint32_t SegIndex);
3497 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
3498 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
3499
3500private:
3501 struct SectionInfo {
3502 uint64_t Address;
3503 uint64_t Size;
3504 StringRef SectionName;
3505 StringRef SegmentName;
3506 uint64_t OffsetInSegment;
3507 uint64_t SegmentStartAddress;
3508 uint32_t SegmentIndex;
3509 };
3510 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
3511 SmallVector<SectionInfo, 32> Sections;
3512};
3513}
3514
3515SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
3516 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00003517 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00003518 StringRef CurSegName;
3519 uint64_t CurSegAddress;
3520 for (const SectionRef &Section : Obj->sections()) {
3521 SectionInfo Info;
3522 if (error(Section.getName(Info.SectionName)))
3523 return;
Rafael Espindola80291272014-10-08 15:28:58 +00003524 Info.Address = Section.getAddress();
3525 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00003526 Info.SegmentName =
3527 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3528 if (!Info.SegmentName.equals(CurSegName)) {
3529 ++CurSegIndex;
3530 CurSegName = Info.SegmentName;
3531 CurSegAddress = Info.Address;
3532 }
3533 Info.SegmentIndex = CurSegIndex - 1;
3534 Info.OffsetInSegment = Info.Address - CurSegAddress;
3535 Info.SegmentStartAddress = CurSegAddress;
3536 Sections.push_back(Info);
3537 }
3538}
3539
3540StringRef SegInfo::segmentName(uint32_t SegIndex) {
3541 for (const SectionInfo &SI : Sections) {
3542 if (SI.SegmentIndex == SegIndex)
3543 return SI.SegmentName;
3544 }
3545 llvm_unreachable("invalid segIndex");
3546}
3547
3548const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
3549 uint64_t OffsetInSeg) {
3550 for (const SectionInfo &SI : Sections) {
3551 if (SI.SegmentIndex != SegIndex)
3552 continue;
3553 if (SI.OffsetInSegment > OffsetInSeg)
3554 continue;
3555 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
3556 continue;
3557 return SI;
3558 }
3559 llvm_unreachable("segIndex and offset not in any section");
3560}
3561
3562StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
3563 return findSection(SegIndex, OffsetInSeg).SectionName;
3564}
3565
3566uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3567 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3568 return SI.SegmentStartAddress + OffsetInSeg;
3569}
3570
3571void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
3572 // Build table of sections so names can used in final output.
3573 SegInfo sectionTable(Obj);
3574
3575 outs() << "segment section address type\n";
3576 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
3577 uint32_t SegIndex = Entry.segmentIndex();
3578 uint64_t OffsetInSeg = Entry.segmentOffset();
3579 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3580 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3581 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3582
3583 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003584 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
3585 SegmentName.str().c_str(), SectionName.str().c_str(),
3586 Address, Entry.typeName().str().c_str());
Nick Kledzikac431442014-09-12 21:34:15 +00003587 }
3588}
Nick Kledzik56ebef42014-09-16 01:41:51 +00003589
3590static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
3591 StringRef DylibName;
3592 switch (Ordinal) {
3593 case MachO::BIND_SPECIAL_DYLIB_SELF:
3594 return "this-image";
3595 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
3596 return "main-executable";
3597 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
3598 return "flat-namespace";
3599 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00003600 if (Ordinal > 0) {
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003601 std::error_code EC =
3602 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
Nick Kledzikabd29872014-09-16 22:03:13 +00003603 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00003604 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00003605 return DylibName;
3606 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003607 }
Nick Kledzikabd29872014-09-16 22:03:13 +00003608 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003609}
3610
3611//===----------------------------------------------------------------------===//
3612// bind table dumping
3613//===----------------------------------------------------------------------===//
3614
3615void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
3616 // Build table of sections so names can used in final output.
3617 SegInfo sectionTable(Obj);
3618
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003619 outs() << "segment section address type "
3620 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003621 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
3622 uint32_t SegIndex = Entry.segmentIndex();
3623 uint64_t OffsetInSeg = Entry.segmentOffset();
3624 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3625 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3626 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3627
3628 // Table lines look like:
3629 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003630 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003631 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003632 Attr = " (weak_import)";
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003633 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003634 << left_justify(SectionName, 18) << " "
3635 << format_hex(Address, 10, true) << " "
3636 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003637 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003638 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003639 << Entry.symbolName() << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003640 }
3641}
3642
3643//===----------------------------------------------------------------------===//
3644// lazy bind table dumping
3645//===----------------------------------------------------------------------===//
3646
3647void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
3648 // Build table of sections so names can used in final output.
3649 SegInfo sectionTable(Obj);
3650
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003651 outs() << "segment section address "
3652 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003653 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
3654 uint32_t SegIndex = Entry.segmentIndex();
3655 uint64_t OffsetInSeg = Entry.segmentOffset();
3656 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3657 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3658 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3659
3660 // Table lines look like:
3661 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003662 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003663 << left_justify(SectionName, 18) << " "
3664 << format_hex(Address, 10, true) << " "
3665 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00003666 << Entry.symbolName() << "\n";
3667 }
3668}
3669
Nick Kledzik56ebef42014-09-16 01:41:51 +00003670//===----------------------------------------------------------------------===//
3671// weak bind table dumping
3672//===----------------------------------------------------------------------===//
3673
3674void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
3675 // Build table of sections so names can used in final output.
3676 SegInfo sectionTable(Obj);
3677
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003678 outs() << "segment section address "
3679 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003680 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
3681 // Strong symbols don't have a location to update.
3682 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003683 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00003684 << Entry.symbolName() << "\n";
3685 continue;
3686 }
3687 uint32_t SegIndex = Entry.segmentIndex();
3688 uint64_t OffsetInSeg = Entry.segmentOffset();
3689 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3690 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3691 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3692
3693 // Table lines look like:
3694 // __DATA __data 0x00001000 pointer 0 _foo
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003695 outs() << left_justify(SegmentName, 8) << " "
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003696 << left_justify(SectionName, 18) << " "
3697 << format_hex(Address, 10, true) << " "
3698 << left_justify(Entry.typeName(), 8) << " "
Kevin Enderbyb28ed012014-10-29 21:28:24 +00003699 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
3700 << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003701 }
3702}
3703
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003704// get_dyld_bind_info_symbolname() is used for disassembly and passed an
3705// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
3706// information for that address. If the address is found its binding symbol
3707// name is returned. If not nullptr is returned.
3708static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3709 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00003710 if (info->bindtable == nullptr) {
3711 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003712 SegInfo sectionTable(info->O);
3713 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
3714 uint32_t SegIndex = Entry.segmentIndex();
3715 uint64_t OffsetInSeg = Entry.segmentOffset();
3716 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3717 const char *SymbolName = nullptr;
3718 StringRef name = Entry.symbolName();
3719 if (!name.empty())
3720 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00003721 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003722 }
3723 }
Kevin Enderby078be602014-10-23 19:53:12 +00003724 for (bind_table_iterator BI = info->bindtable->begin(),
3725 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003726 BI != BE; ++BI) {
3727 uint64_t Address = BI->first;
3728 if (ReferenceValue == Address) {
3729 const char *SymbolName = BI->second;
3730 return SymbolName;
3731 }
3732 }
3733 return nullptr;
3734}