blob: 9c3dfec92e4606f167c96da4152815025efa23d4 [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"
Benjamin Kramer699128e2011-09-21 01:13:19 +000019#include "llvm/DebugInfo/DIContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000020#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000021#include "llvm/MC/MCContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000022#include "llvm/MC/MCDisassembler.h"
23#include "llvm/MC/MCInst.h"
24#include "llvm/MC/MCInstPrinter.h"
25#include "llvm/MC/MCInstrAnalysis.h"
26#include "llvm/MC/MCInstrDesc.h"
27#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000028#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000029#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000030#include "llvm/Object/MachO.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000031#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000032#include "llvm/Support/CommandLine.h"
33#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000034#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000035#include "llvm/Support/Format.h"
36#include "llvm/Support/GraphWriter.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000037#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000038#include "llvm/Support/MemoryBuffer.h"
Kevin Enderbybf246f52014-09-24 23:08:22 +000039#include "llvm/Support/FormattedStream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000040#include "llvm/Support/TargetRegistry.h"
41#include "llvm/Support/TargetSelect.h"
42#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000043#include <algorithm>
44#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000045#include <system_error>
Benjamin Kramer43a772e2011-09-19 17:56:04 +000046using namespace llvm;
47using namespace object;
48
49static cl::opt<bool>
Benjamin Kramer699128e2011-09-21 01:13:19 +000050 UseDbg("g", cl::desc("Print line information from debug info if available"));
51
52static cl::opt<std::string>
53 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
54
Kevin Enderbybf246f52014-09-24 23:08:22 +000055static cl::opt<bool>
56 FullLeadingAddr("full-leading-addr",
57 cl::desc("Print full leading address"));
58
59static cl::opt<bool>
60 PrintImmHex("print-imm-hex",
61 cl::desc("Use hex format for immediate values"));
62
Kevin Enderbyec5ca032014-08-18 20:21:02 +000063static std::string ThumbTripleName;
64
65static const Target *GetTarget(const MachOObjectFile *MachOObj,
66 const char **McpuDefault,
67 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +000068 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000069 if (TripleName.empty()) {
70 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +000071 llvm::Triple ThumbTriple = Triple();
72 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000073 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +000074 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +000075 }
76
Benjamin Kramer43a772e2011-09-19 17:56:04 +000077 // Get the target specific parser.
78 std::string Error;
79 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +000080 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +000081 return TheTarget;
82
Kevin Enderbyec5ca032014-08-18 20:21:02 +000083 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
84 if (*ThumbTarget)
85 return TheTarget;
86
87 errs() << "llvm-objdump: error: unable to get target for '";
88 if (!TheTarget)
89 errs() << TripleName;
90 else
91 errs() << ThumbTripleName;
92 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +000093 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +000094}
95
Owen Andersond9243c42011-10-17 21:37:35 +000096struct SymbolSorter {
97 bool operator()(const SymbolRef &A, const SymbolRef &B) {
98 SymbolRef::Type AType, BType;
99 A.getType(AType);
100 B.getType(BType);
101
102 uint64_t AAddr, BAddr;
103 if (AType != SymbolRef::ST_Function)
104 AAddr = 0;
105 else
106 A.getAddress(AAddr);
107 if (BType != SymbolRef::ST_Function)
108 BAddr = 0;
109 else
110 B.getAddress(BAddr);
111 return AAddr < BAddr;
112 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000113};
114
Kevin Enderby273ae012013-06-06 17:20:50 +0000115// Types for the storted data in code table that is built before disassembly
116// and the predicate function to sort them.
117typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
118typedef std::vector<DiceTableEntry> DiceTable;
119typedef DiceTable::iterator dice_table_iterator;
120
121static bool
122compareDiceTableEntries(const DiceTableEntry i,
123 const DiceTableEntry j) {
124 return i.first == j.first;
125}
126
127static void DumpDataInCode(const char *bytes, uint64_t Size,
128 unsigned short Kind) {
129 uint64_t Value;
130
131 switch (Kind) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000132 case MachO::DICE_KIND_DATA:
Kevin Enderby273ae012013-06-06 17:20:50 +0000133 switch (Size) {
134 case 4:
135 Value = bytes[3] << 24 |
136 bytes[2] << 16 |
137 bytes[1] << 8 |
138 bytes[0];
139 outs() << "\t.long " << Value;
140 break;
141 case 2:
142 Value = bytes[1] << 8 |
143 bytes[0];
144 outs() << "\t.short " << Value;
145 break;
146 case 1:
147 Value = bytes[0];
148 outs() << "\t.byte " << Value;
149 break;
150 }
151 outs() << "\t@ KIND_DATA\n";
152 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000153 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby273ae012013-06-06 17:20:50 +0000154 Value = bytes[0];
155 outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
156 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000157 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby273ae012013-06-06 17:20:50 +0000158 Value = bytes[1] << 8 |
159 bytes[0];
160 outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
161 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000162 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby273ae012013-06-06 17:20:50 +0000163 Value = bytes[3] << 24 |
164 bytes[2] << 16 |
165 bytes[1] << 8 |
166 bytes[0];
167 outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
168 break;
169 default:
170 outs() << "\t@ data in code kind = " << Kind << "\n";
171 break;
172 }
173}
174
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000175static void getSectionsAndSymbols(const MachO::mach_header Header,
176 MachOObjectFile *MachOObj,
177 std::vector<SectionRef> &Sections,
178 std::vector<SymbolRef> &Symbols,
179 SmallVectorImpl<uint64_t> &FoundFns,
180 uint64_t &BaseSegmentAddress) {
181 for (const SymbolRef &Symbol : MachOObj->symbols())
182 Symbols.push_back(Symbol);
Owen Andersond9243c42011-10-17 21:37:35 +0000183
Alexey Samsonov48803e52014-03-13 14:37:36 +0000184 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000185 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000186 Section.getName(SectName);
187 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000188 }
189
Rafael Espindola56f976f2013-04-18 18:08:55 +0000190 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000191 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000192 bool BaseSegmentAddressSet = false;
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000193 for (unsigned i = 0; ; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000194 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000195 // We found a function starts segment, parse the addresses for later
196 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000197 MachO::linkedit_data_command LLC =
Rafael Espindola56f976f2013-04-18 18:08:55 +0000198 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000199
Charles Davis8bdfafd2013-09-01 04:28:48 +0000200 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000201 }
Charles Davis8bdfafd2013-09-01 04:28:48 +0000202 else if (Command.C.cmd == MachO::LC_SEGMENT) {
203 MachO::segment_command SLC =
Kevin Enderby273ae012013-06-06 17:20:50 +0000204 MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000205 StringRef SegName = SLC.segname;
Kevin Enderby273ae012013-06-06 17:20:50 +0000206 if(!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
207 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000208 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000209 }
210 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000211
Charles Davis8bdfafd2013-09-01 04:28:48 +0000212 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000213 break;
214 else
215 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000216 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000217}
218
Rafael Espindola9b709252013-04-13 01:45:40 +0000219static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindola56f976f2013-04-18 18:08:55 +0000220 MachOObjectFile *MachOOF);
Rafael Espindola9b709252013-04-13 01:45:40 +0000221
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000222void llvm::DisassembleInputMachO(StringRef Filename) {
Rafael Espindola48af1c22014-08-19 18:44:46 +0000223 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000224 MemoryBuffer::getFileOrSTDIN(Filename);
Rafael Espindola48af1c22014-08-19 18:44:46 +0000225 if (std::error_code EC = BuffOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000226 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000227 return;
228 }
Rafael Espindola48af1c22014-08-19 18:44:46 +0000229 std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000230
Rafael Espindola48af1c22014-08-19 18:44:46 +0000231 std::unique_ptr<MachOObjectFile> MachOOF = std::move(
232 ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000233
Rafael Espindola56f976f2013-04-18 18:08:55 +0000234 DisassembleInputMachO2(Filename, MachOOF.get());
Rafael Espindola9b709252013-04-13 01:45:40 +0000235}
236
Kevin Enderbybf246f52014-09-24 23:08:22 +0000237typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000238typedef std::pair<uint64_t, const char *> BindInfoEntry;
239typedef std::vector<BindInfoEntry> BindTable;
240typedef BindTable::iterator bind_table_iterator;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000241
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000242// The block of info used by the Symbolizer call backs.
243struct DisassembleInfo {
244 bool verbose;
245 MachOObjectFile *O;
246 SectionRef S;
Kevin Enderbybf246f52014-09-24 23:08:22 +0000247 SymbolAddressMap *AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000248 std::vector<SectionRef> *Sections;
249 const char *class_name;
250 const char *selector_name;
251 char *method;
Kevin Enderby078be602014-10-23 19:53:12 +0000252 BindTable *bindtable;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000253};
254
255// SymbolizerGetOpInfo() is the operand information call back function.
256// This is called to get the symbolic information for operand(s) of an
257// instruction when it is being done. This routine does this from
258// the relocation information, symbol table, etc. That block of information
259// is a pointer to the struct DisassembleInfo that was passed when the
260// disassembler context was created and passed to back to here when
261// called back by the disassembler for instruction operands that could have
262// relocation information. The address of the instruction containing operand is
263// at the Pc parameter. The immediate value the operand has is passed in
264// op_info->Value and is at Offset past the start of the instruction and has a
265// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
266// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
267// names and addends of the symbolic expression to add for the operand. The
268// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
269// information is returned then this function returns 1 else it returns 0.
270int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
271 uint64_t Size, int TagType, void *TagBuf) {
272 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
273 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
274 unsigned int value = op_info->Value;
275
276 // Make sure all fields returned are zero if we don't set them.
277 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
278 op_info->Value = value;
279
280 // If the TagType is not the value 1 which it code knows about or if no
281 // verbose symbolic information is wanted then just return 0, indicating no
282 // information is being returned.
283 if (TagType != 1 || info->verbose == false)
284 return 0;
285
286 unsigned int Arch = info->O->getArch();
287 if (Arch == Triple::x86) {
288 return 0;
289 } else if (Arch == Triple::x86_64) {
290 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
291 return 0;
292 // First search the section's relocation entries (if any) for an entry
293 // for this section offset.
Rafael Espindola80291272014-10-08 15:28:58 +0000294 uint64_t sect_addr = info->S.getAddress();
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000295 uint64_t sect_offset = (Pc + Offset) - sect_addr;
296 bool reloc_found = false;
297 DataRefImpl Rel;
298 MachO::any_relocation_info RE;
299 bool isExtern = false;
300 SymbolRef Symbol;
301 for (const RelocationRef &Reloc : info->S.relocations()) {
302 uint64_t RelocOffset;
303 Reloc.getOffset(RelocOffset);
304 if (RelocOffset == sect_offset) {
305 Rel = Reloc.getRawDataRefImpl();
306 RE = info->O->getRelocation(Rel);
307 // NOTE: Scattered relocations don't exist on x86_64.
308 isExtern = info->O->getPlainRelocationExternal(RE);
309 if (isExtern) {
310 symbol_iterator RelocSym = Reloc.getSymbol();
311 Symbol = *RelocSym;
312 }
313 reloc_found = true;
314 break;
315 }
316 }
317 if (reloc_found && isExtern) {
318 // The Value passed in will be adjusted by the Pc if the instruction
319 // adds the Pc. But for x86_64 external relocation entries the Value
320 // is the offset from the external symbol.
321 if (info->O->getAnyRelocationPCRel(RE))
322 op_info->Value -= Pc + Offset + Size;
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000323 StringRef SymName;
324 Symbol.getName(SymName);
325 const char *name = SymName.data();
326 unsigned Type = info->O->getAnyRelocationType(RE);
327 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
328 DataRefImpl RelNext = Rel;
329 info->O->moveRelocationNext(RelNext);
330 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
331 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
332 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
333 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
334 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
335 op_info->SubtractSymbol.Present = 1;
336 op_info->SubtractSymbol.Name = name;
337 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
338 Symbol = *RelocSymNext;
339 StringRef SymNameNext;
340 Symbol.getName(SymNameNext);
341 name = SymNameNext.data();
342 }
343 }
344 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
345 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
346 op_info->AddSymbol.Present = 1;
347 op_info->AddSymbol.Name = name;
348 return 1;
349 }
350 // TODO:
351 // Second search the external relocation entries of a fully linked image
352 // (if any) for an entry that matches this segment offset.
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000353 // uint64_t seg_offset = (Pc + Offset);
Kevin Enderby98c9acc2014-09-16 18:00:57 +0000354 return 0;
355 } else if (Arch == Triple::arm) {
356 return 0;
357 } else if (Arch == Triple::aarch64) {
358 return 0;
359 } else {
360 return 0;
361 }
362}
363
Kevin Enderbybf246f52014-09-24 23:08:22 +0000364// GuessCstringPointer is passed the address of what might be a pointer to a
365// literal string in a cstring section. If that address is in a cstring section
366// it returns a pointer to that string. Else it returns nullptr.
367const char *GuessCstringPointer(uint64_t ReferenceValue,
368 struct DisassembleInfo *info) {
369 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
370 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
371 for (unsigned I = 0;; ++I) {
372 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
373 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
374 for (unsigned J = 0; J < Seg.nsects; ++J) {
375 MachO::section_64 Sec = info->O->getSection64(Load, J);
376 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
377 if (section_type == MachO::S_CSTRING_LITERALS &&
378 ReferenceValue >= Sec.addr &&
379 ReferenceValue < Sec.addr + Sec.size) {
380 uint64_t sect_offset = ReferenceValue - Sec.addr;
381 uint64_t object_offset = Sec.offset + sect_offset;
382 StringRef MachOContents = info->O->getData();
383 uint64_t object_size = MachOContents.size();
384 const char *object_addr = (const char *)MachOContents.data();
385 if (object_offset < object_size) {
386 const char *name = object_addr + object_offset;
387 return name;
388 } else {
389 return nullptr;
390 }
391 }
392 }
393 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
394 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
395 for (unsigned J = 0; J < Seg.nsects; ++J) {
396 MachO::section Sec = info->O->getSection(Load, J);
397 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
398 if (section_type == MachO::S_CSTRING_LITERALS &&
399 ReferenceValue >= Sec.addr &&
400 ReferenceValue < Sec.addr + Sec.size) {
401 uint64_t sect_offset = ReferenceValue - Sec.addr;
402 uint64_t object_offset = Sec.offset + sect_offset;
403 StringRef MachOContents = info->O->getData();
404 uint64_t object_size = MachOContents.size();
405 const char *object_addr = (const char *)MachOContents.data();
406 if (object_offset < object_size) {
407 const char *name = object_addr + object_offset;
408 return name;
409 } else {
410 return nullptr;
411 }
412 }
413 }
414 }
415 if (I == LoadCommandCount - 1)
416 break;
417 else
418 Load = info->O->getNextLoadCommandInfo(Load);
419 }
420 return nullptr;
421}
422
Kevin Enderby85974882014-09-26 22:20:44 +0000423// GuessIndirectSymbol returns the name of the indirect symbol for the
424// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
425// an address of a symbol stub or a lazy or non-lazy pointer to associate the
426// symbol name being referenced by the stub or pointer.
427static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
428 struct DisassembleInfo *info) {
429 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
430 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
431 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
432 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
433 for (unsigned I = 0;; ++I) {
434 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
435 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
436 for (unsigned J = 0; J < Seg.nsects; ++J) {
437 MachO::section_64 Sec = info->O->getSection64(Load, J);
438 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
439 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
440 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
441 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
442 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
443 section_type == MachO::S_SYMBOL_STUBS) &&
444 ReferenceValue >= Sec.addr &&
445 ReferenceValue < Sec.addr + Sec.size) {
446 uint32_t stride;
447 if (section_type == MachO::S_SYMBOL_STUBS)
448 stride = Sec.reserved2;
449 else
450 stride = 8;
451 if (stride == 0)
452 return nullptr;
453 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
454 if (index < Dysymtab.nindirectsyms) {
455 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000456 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +0000457 if (indirect_symbol < Symtab.nsyms) {
458 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
459 SymbolRef Symbol = *Sym;
460 StringRef SymName;
461 Symbol.getName(SymName);
462 const char *name = SymName.data();
463 return name;
464 }
465 }
466 }
467 }
468 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
469 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
470 for (unsigned J = 0; J < Seg.nsects; ++J) {
471 MachO::section Sec = info->O->getSection(Load, J);
472 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
473 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
474 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
475 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
476 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
477 section_type == MachO::S_SYMBOL_STUBS) &&
478 ReferenceValue >= Sec.addr &&
479 ReferenceValue < Sec.addr + Sec.size) {
480 uint32_t stride;
481 if (section_type == MachO::S_SYMBOL_STUBS)
482 stride = Sec.reserved2;
483 else
484 stride = 4;
485 if (stride == 0)
486 return nullptr;
487 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
488 if (index < Dysymtab.nindirectsyms) {
489 uint32_t indirect_symbol =
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000490 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
Kevin Enderby85974882014-09-26 22:20:44 +0000491 if (indirect_symbol < Symtab.nsyms) {
492 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
493 SymbolRef Symbol = *Sym;
494 StringRef SymName;
495 Symbol.getName(SymName);
496 const char *name = SymName.data();
497 return name;
498 }
499 }
500 }
501 }
502 }
503 if (I == LoadCommandCount - 1)
504 break;
505 else
506 Load = info->O->getNextLoadCommandInfo(Load);
507 }
508 return nullptr;
509}
510
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000511// method_reference() is called passing it the ReferenceName that might be
512// a reference it to an Objective-C method call. If so then it allocates and
513// assembles a method call string with the values last seen and saved in
514// the DisassembleInfo's class_name and selector_name fields. This is saved
515// into the method field of the info and any previous string is free'ed.
516// Then the class_name field in the info is set to nullptr. The method call
517// string is set into ReferenceName and ReferenceType is set to
518// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
519// then both ReferenceType and ReferenceName are left unchanged.
520static void method_reference(struct DisassembleInfo *info,
521 uint64_t *ReferenceType,
522 const char **ReferenceName) {
523 if (*ReferenceName != nullptr) {
524 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
525 if (info->selector_name != NULL) {
526 if (info->method != nullptr)
527 free(info->method);
528 if (info->class_name != nullptr) {
529 info->method = (char *)malloc(5 + strlen(info->class_name) +
530 strlen(info->selector_name));
531 if (info->method != nullptr) {
532 strcpy(info->method, "+[");
533 strcat(info->method, info->class_name);
534 strcat(info->method, " ");
535 strcat(info->method, info->selector_name);
536 strcat(info->method, "]");
537 *ReferenceName = info->method;
538 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
539 }
540 } else {
541 info->method = (char *)malloc(9 + strlen(info->selector_name));
542 if (info->method != nullptr) {
543 strcpy(info->method, "-[%rdi ");
544 strcat(info->method, info->selector_name);
545 strcat(info->method, "]");
546 *ReferenceName = info->method;
547 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
548 }
549 }
550 info->class_name = nullptr;
551 }
552 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
553 if (info->selector_name != NULL) {
554 if (info->method != nullptr)
555 free(info->method);
556 info->method = (char *)malloc(17 + strlen(info->selector_name));
557 if (info->method != nullptr) {
558 strcpy(info->method, "-[[%rdi super] ");
559 strcat(info->method, info->selector_name);
560 strcat(info->method, "]");
561 *ReferenceName = info->method;
562 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
563 }
564 info->class_name = nullptr;
565 }
566 }
567 }
568}
569
570// GuessPointerPointer() is passed the address of what might be a pointer to
571// a reference to an Objective-C class, selector, message ref or cfstring.
572// If so the value of the pointer is returned and one of the booleans are set
573// to true. If not zero is returned and all the booleans are set to false.
574static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
575 struct DisassembleInfo *info,
576 bool &classref, bool &selref, bool &msgref,
577 bool &cfstring) {
578 classref = false;
579 selref = false;
580 msgref = false;
581 cfstring = false;
582 uint32_t LoadCommandCount = info->O->getHeader().ncmds;
583 MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
584 for (unsigned I = 0;; ++I) {
585 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
586 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
587 for (unsigned J = 0; J < Seg.nsects; ++J) {
588 MachO::section_64 Sec = info->O->getSection64(Load, J);
589 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
590 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
591 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
592 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
593 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
594 ReferenceValue >= Sec.addr &&
595 ReferenceValue < Sec.addr + Sec.size) {
596 uint64_t sect_offset = ReferenceValue - Sec.addr;
597 uint64_t object_offset = Sec.offset + sect_offset;
598 StringRef MachOContents = info->O->getData();
599 uint64_t object_size = MachOContents.size();
600 const char *object_addr = (const char *)MachOContents.data();
601 if (object_offset < object_size) {
602 uint64_t pointer_value;
603 memcpy(&pointer_value, object_addr + object_offset,
604 sizeof(uint64_t));
605 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
606 sys::swapByteOrder(pointer_value);
607 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
608 selref = true;
609 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
610 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
611 classref = true;
612 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
613 ReferenceValue + 8 < Sec.addr + Sec.size) {
614 msgref = true;
615 memcpy(&pointer_value, object_addr + object_offset + 8,
616 sizeof(uint64_t));
617 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
618 sys::swapByteOrder(pointer_value);
619 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
620 cfstring = true;
621 return pointer_value;
622 } else {
623 return 0;
624 }
625 }
626 }
627 }
628 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
629 if (I == LoadCommandCount - 1)
630 break;
631 else
632 Load = info->O->getNextLoadCommandInfo(Load);
633 }
634 return 0;
635}
636
637// get_pointer_64 returns a pointer to the bytes in the object file at the
638// Address from a section in the Mach-O file. And indirectly returns the
639// offset into the section, number of bytes left in the section past the offset
640// and which section is was being referenced. If the Address is not in a
641// section nullptr is returned.
642const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
643 SectionRef &S, DisassembleInfo *info) {
644 offset = 0;
645 left = 0;
646 S = SectionRef();
647 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
648 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
649 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
650 if (Address >= SectAddress && Address < SectAddress + SectSize) {
651 S = (*(info->Sections))[SectIdx];
652 offset = Address - SectAddress;
653 left = SectSize - offset;
654 StringRef SectContents;
655 ((*(info->Sections))[SectIdx]).getContents(SectContents);
656 return SectContents.data() + offset;
657 }
658 }
659 return nullptr;
660}
661
662// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
663// the symbol indirectly through n_value. Based on the relocation information
664// for the specified section offset in the specified section reference.
665const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
666 DisassembleInfo *info, uint64_t &n_value) {
667 n_value = 0;
668 if (info->verbose == false)
669 return nullptr;
670
671 // See if there is an external relocation entry at the sect_offset.
672 bool reloc_found = false;
673 DataRefImpl Rel;
674 MachO::any_relocation_info RE;
675 bool isExtern = false;
676 SymbolRef Symbol;
677 for (const RelocationRef &Reloc : S.relocations()) {
678 uint64_t RelocOffset;
679 Reloc.getOffset(RelocOffset);
680 if (RelocOffset == sect_offset) {
681 Rel = Reloc.getRawDataRefImpl();
682 RE = info->O->getRelocation(Rel);
683 if (info->O->isRelocationScattered(RE))
684 continue;
685 isExtern = info->O->getPlainRelocationExternal(RE);
686 if (isExtern) {
687 symbol_iterator RelocSym = Reloc.getSymbol();
688 Symbol = *RelocSym;
689 }
690 reloc_found = true;
691 break;
692 }
693 }
694 // If there is an external relocation entry for a symbol in this section
695 // at this section_offset then use that symbol's value for the n_value
696 // and return its name.
697 const char *SymbolName = nullptr;
698 if (reloc_found && isExtern) {
699 Symbol.getAddress(n_value);
700 StringRef name;
701 Symbol.getName(name);
702 if (!name.empty()) {
703 SymbolName = name.data();
704 return SymbolName;
705 }
706 }
707
708 // TODO: For fully linked images, look through the external relocation
709 // entries off the dynamic symtab command. For these the r_offset is from the
710 // start of the first writeable segment in the Mach-O file. So the offset
711 // to this section from that segment is passed to this routine by the caller,
712 // as the database_offset. Which is the difference of the section's starting
713 // address and the first writable segment.
714 //
715 // NOTE: need add passing the database_offset to this routine.
716
717 // TODO: We did not find an external relocation entry so look up the
718 // ReferenceValue as an address of a symbol and if found return that symbol's
719 // name.
720 //
721 // NOTE: need add passing the ReferenceValue to this routine. Then that code
722 // would simply be this:
723 //
724 // if (ReferenceValue != 0xffffffffffffffffLLU &&
725 // ReferenceValue != 0xfffffffffffffffeLLU) {
726 // StringRef name = info->AddrMap->lookup(ReferenceValue);
727 // if (!name.empty())
728 // SymbolName = name.data();
729 // }
730
731 return SymbolName;
732}
733
734// These are structs in the Objective-C meta data and read to produce the
735// comments for disassembly. While these are part of the ABI they are no
736// public defintions. So the are here not in include/llvm/Support/MachO.h .
737
738// The cfstring object in a 64-bit Mach-O file.
739struct cfstring64_t {
740 uint64_t isa; // class64_t * (64-bit pointer)
741 uint64_t flags; // flag bits
742 uint64_t characters; // char * (64-bit pointer)
743 uint64_t length; // number of non-NULL characters in above
744};
745
746// The class object in a 64-bit Mach-O file.
747struct class64_t {
748 uint64_t isa; // class64_t * (64-bit pointer)
749 uint64_t superclass; // class64_t * (64-bit pointer)
750 uint64_t cache; // Cache (64-bit pointer)
751 uint64_t vtable; // IMP * (64-bit pointer)
752 uint64_t data; // class_ro64_t * (64-bit pointer)
753};
754
755struct class_ro64_t {
756 uint32_t flags;
757 uint32_t instanceStart;
758 uint32_t instanceSize;
759 uint32_t reserved;
760 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
761 uint64_t name; // const char * (64-bit pointer)
762 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
763 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
764 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
765 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
766 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
767};
768
769inline void swapStruct(struct cfstring64_t &cfs) {
770 sys::swapByteOrder(cfs.isa);
771 sys::swapByteOrder(cfs.flags);
772 sys::swapByteOrder(cfs.characters);
773 sys::swapByteOrder(cfs.length);
774}
775
776inline void swapStruct(struct class64_t &c) {
777 sys::swapByteOrder(c.isa);
778 sys::swapByteOrder(c.superclass);
779 sys::swapByteOrder(c.cache);
780 sys::swapByteOrder(c.vtable);
781 sys::swapByteOrder(c.data);
782}
783
784inline void swapStruct(struct class_ro64_t &cro) {
785 sys::swapByteOrder(cro.flags);
786 sys::swapByteOrder(cro.instanceStart);
787 sys::swapByteOrder(cro.instanceSize);
788 sys::swapByteOrder(cro.reserved);
789 sys::swapByteOrder(cro.ivarLayout);
790 sys::swapByteOrder(cro.name);
791 sys::swapByteOrder(cro.baseMethods);
792 sys::swapByteOrder(cro.baseProtocols);
793 sys::swapByteOrder(cro.ivars);
794 sys::swapByteOrder(cro.weakIvarLayout);
795 sys::swapByteOrder(cro.baseProperties);
796}
797
798static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
799 struct DisassembleInfo *info);
800
801// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
802// to an Objective-C class and returns the class name. It is also passed the
803// address of the pointer, so when the pointer is zero as it can be in an .o
804// file, that is used to look for an external relocation entry with a symbol
805// name.
806const char *get_objc2_64bit_class_name(uint64_t pointer_value,
807 uint64_t ReferenceValue,
808 struct DisassembleInfo *info) {
809 const char *r;
810 uint32_t offset, left;
811 SectionRef S;
812
813 // The pointer_value can be 0 in an object file and have a relocation
814 // entry for the class symbol at the ReferenceValue (the address of the
815 // pointer).
816 if (pointer_value == 0) {
817 r = get_pointer_64(ReferenceValue, offset, left, S, info);
818 if (r == nullptr || left < sizeof(uint64_t))
819 return nullptr;
820 uint64_t n_value;
821 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
822 if (symbol_name == nullptr)
823 return nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +0000824 const char *class_name = strrchr(symbol_name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000825 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
826 return class_name + 2;
827 else
828 return nullptr;
829 }
830
831 // The case were the pointer_value is non-zero and points to a class defined
832 // in this Mach-O file.
833 r = get_pointer_64(pointer_value, offset, left, S, info);
834 if (r == nullptr || left < sizeof(struct class64_t))
835 return nullptr;
836 struct class64_t c;
837 memcpy(&c, r, sizeof(struct class64_t));
838 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
839 swapStruct(c);
840 if (c.data == 0)
841 return nullptr;
842 r = get_pointer_64(c.data, offset, left, S, info);
843 if (r == nullptr || left < sizeof(struct class_ro64_t))
844 return nullptr;
845 struct class_ro64_t cro;
846 memcpy(&cro, r, sizeof(struct class_ro64_t));
847 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
848 swapStruct(cro);
849 if (cro.name == 0)
850 return nullptr;
851 const char *name = get_pointer_64(cro.name, offset, left, S, info);
852 return name;
853}
854
855// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
856// pointer to a cfstring and returns its name or nullptr.
857const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
858 struct DisassembleInfo *info) {
859 const char *r, *name;
860 uint32_t offset, left;
861 SectionRef S;
862 struct cfstring64_t cfs;
863 uint64_t cfs_characters;
864
865 r = get_pointer_64(ReferenceValue, offset, left, S, info);
866 if (r == nullptr || left < sizeof(struct cfstring64_t))
867 return nullptr;
868 memcpy(&cfs, r, sizeof(struct cfstring64_t));
869 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
870 swapStruct(cfs);
871 if (cfs.characters == 0) {
872 uint64_t n_value;
873 const char *symbol_name = get_symbol_64(
874 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
875 if (symbol_name == nullptr)
876 return nullptr;
877 cfs_characters = n_value;
878 } else
879 cfs_characters = cfs.characters;
880 name = get_pointer_64(cfs_characters, offset, left, S, info);
881
882 return name;
883}
884
885// get_objc2_64bit_selref() is used for disassembly and is passed a the address
886// of a pointer to an Objective-C selector reference when the pointer value is
887// zero as in a .o file and is likely to have a external relocation entry with
888// who's symbol's n_value is the real pointer to the selector name. If that is
889// the case the real pointer to the selector name is returned else 0 is
890// returned
891uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
892 struct DisassembleInfo *info) {
893 uint32_t offset, left;
894 SectionRef S;
895
896 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
897 if (r == nullptr || left < sizeof(uint64_t))
898 return 0;
899 uint64_t n_value;
900 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
901 if (symbol_name == nullptr)
902 return 0;
903 return n_value;
904}
905
Kevin Enderbybf246f52014-09-24 23:08:22 +0000906// GuessLiteralPointer returns a string which for the item in the Mach-O file
907// for the address passed in as ReferenceValue for printing as a comment with
908// the instruction and also returns the corresponding type of that item
909// indirectly through ReferenceType.
910//
911// If ReferenceValue is an address of literal cstring then a pointer to the
912// cstring is returned and ReferenceType is set to
913// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
914//
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000915// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
916// Class ref that name is returned and the ReferenceType is set accordingly.
917//
918// Lastly, literals which are Symbol address in a literal pool are looked for
919// and if found the symbol name is returned and ReferenceType is set to
920// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
921//
922// If there is no item in the Mach-O file for the address passed in as
923// ReferenceValue nullptr is returned and ReferenceType is unchanged.
Kevin Enderbybf246f52014-09-24 23:08:22 +0000924const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
925 uint64_t *ReferenceType,
926 struct DisassembleInfo *info) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000927 // TODO: This rouine's code and the routines it calls are only work with
928 // x86_64 Mach-O files for now.
Kevin Enderbybf246f52014-09-24 23:08:22 +0000929 unsigned int Arch = info->O->getArch();
930 if (Arch != Triple::x86_64)
931 return nullptr;
932
933 // First see if there is an external relocation entry at the ReferencePC.
Rafael Espindola80291272014-10-08 15:28:58 +0000934 uint64_t sect_addr = info->S.getAddress();
Kevin Enderbybf246f52014-09-24 23:08:22 +0000935 uint64_t sect_offset = ReferencePC - sect_addr;
936 bool reloc_found = false;
937 DataRefImpl Rel;
938 MachO::any_relocation_info RE;
939 bool isExtern = false;
940 SymbolRef Symbol;
941 for (const RelocationRef &Reloc : info->S.relocations()) {
942 uint64_t RelocOffset;
943 Reloc.getOffset(RelocOffset);
944 if (RelocOffset == sect_offset) {
945 Rel = Reloc.getRawDataRefImpl();
946 RE = info->O->getRelocation(Rel);
947 if (info->O->isRelocationScattered(RE))
948 continue;
949 isExtern = info->O->getPlainRelocationExternal(RE);
950 if (isExtern) {
951 symbol_iterator RelocSym = Reloc.getSymbol();
952 Symbol = *RelocSym;
953 }
954 reloc_found = true;
955 break;
956 }
957 }
958 // If there is an external relocation entry for a symbol in a section
959 // then used that symbol's value for the value of the reference.
960 if (reloc_found && isExtern) {
961 if (info->O->getAnyRelocationPCRel(RE)) {
962 unsigned Type = info->O->getAnyRelocationType(RE);
963 if (Type == MachO::X86_64_RELOC_SIGNED) {
964 Symbol.getAddress(ReferenceValue);
965 }
966 }
967 }
968
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000969 // Look for literals such as Objective-C CFStrings refs, Selector refs,
970 // Message refs and Class refs.
971 bool classref, selref, msgref, cfstring;
972 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
973 selref, msgref, cfstring);
974 if (classref == true && pointer_value == 0) {
975 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
976 // And the pointer_value in that section is typically zero as it will be
977 // set by dyld as part of the "bind information".
978 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
979 if (name != nullptr) {
980 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
Hans Wennborgdb53e302014-10-23 21:59:17 +0000981 const char *class_name = strrchr(name, '$');
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000982 if (class_name != nullptr && class_name[1] == '_' &&
983 class_name[2] != '\0') {
984 info->class_name = class_name + 2;
985 return name;
986 }
987 }
988 }
Kevin Enderbybf246f52014-09-24 23:08:22 +0000989
Kevin Enderby6f326ce2014-10-23 19:37:31 +0000990 if (classref == true) {
991 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
992 const char *name =
993 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
994 if (name != nullptr)
995 info->class_name = name;
996 else
997 name = "bad class ref";
Kevin Enderbybf246f52014-09-24 23:08:22 +0000998 return name;
999 }
1000
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001001 if (cfstring == true) {
1002 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1003 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1004 return name;
1005 }
1006
1007 if (selref == true && pointer_value == 0)
1008 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1009
1010 if (pointer_value != 0)
1011 ReferenceValue = pointer_value;
1012
1013 const char *name = GuessCstringPointer(ReferenceValue, info);
1014 if (name) {
1015 if (pointer_value != 0 && selref == true) {
1016 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1017 info->selector_name = name;
1018 } else if (pointer_value != 0 && msgref == true) {
1019 info->class_name = nullptr;
1020 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1021 info->selector_name = name;
1022 } else
1023 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1024 return name;
1025 }
1026
1027 // Lastly look for an indirect symbol with this ReferenceValue which is in
1028 // a literal pool. If found return that symbol name.
1029 name = GuessIndirectSymbol(ReferenceValue, info);
1030 if (name) {
1031 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1032 return name;
1033 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001034
1035 return nullptr;
1036}
1037
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001038// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
Kevin Enderbybf246f52014-09-24 23:08:22 +00001039// the Symbolizer. It looks up the ReferenceValue using the info passed via the
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001040// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1041// is created and returns the symbol name that matches the ReferenceValue or
1042// nullptr if none. The ReferenceType is passed in for the IN type of
1043// reference the instruction is making from the values in defined in the header
1044// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
1045// Out type and the ReferenceName will also be set which is added as a comment
1046// to the disassembled instruction.
1047//
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001048// TODO: If the symbol name is a C++ mangled name then the demangled name is
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001049// returned through ReferenceName and ReferenceType is set to
1050// LLVMDisassembler_ReferenceType_DeMangled_Name .
1051//
1052// When this is called to get a symbol name for a branch target then the
1053// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1054// SymbolValue will be looked for in the indirect symbol table to determine if
1055// it is an address for a symbol stub. If so then the symbol name for that
1056// stub is returned indirectly through ReferenceName and then ReferenceType is
1057// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1058//
Kevin Enderbybf246f52014-09-24 23:08:22 +00001059// When this is called with an value loaded via a PC relative load then
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001060// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1061// SymbolValue is checked to be an address of literal pointer, symbol pointer,
1062// or an Objective-C meta data reference. If so the output ReferenceType is
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001063// set to correspond to that as well as setting the ReferenceName.
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001064const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1065 uint64_t *ReferenceType,
1066 uint64_t ReferencePC,
1067 const char **ReferenceName) {
1068 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001069 // If no verbose symbolic information is wanted then just return nullptr.
1070 if (info->verbose == false) {
1071 *ReferenceName = nullptr;
1072 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001073 return nullptr;
1074 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001075
1076 const char *SymbolName = nullptr;
Hans Wennborgdb53e302014-10-23 21:59:17 +00001077 if (ReferenceValue != 0xffffffffffffffffULL &&
1078 ReferenceValue != 0xfffffffffffffffeULL) {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001079 StringRef name = info->AddrMap->lookup(ReferenceValue);
1080 if (!name.empty())
1081 SymbolName = name.data();
1082 }
Kevin Enderbybf246f52014-09-24 23:08:22 +00001083
Kevin Enderby85974882014-09-26 22:20:44 +00001084 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1085 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001086 if (*ReferenceName) {
1087 method_reference(info, ReferenceType, ReferenceName);
1088 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1089 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1090 } else
1091 // TODO: if SymbolName is not nullptr see if it is a C++ name
1092 // and demangle it.
1093 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1094 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1095 *ReferenceName =
1096 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
Kevin Enderby85974882014-09-26 22:20:44 +00001097 if (*ReferenceName)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001098 method_reference(info, ReferenceType, ReferenceName);
Kevin Enderby85974882014-09-26 22:20:44 +00001099 else
1100 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1101 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001102 // TODO: if SymbolName is not nullptr see if it is a C++ name
1103 // and demangle it.
1104 else {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001105 *ReferenceName = nullptr;
1106 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1107 }
1108
1109 return SymbolName;
1110}
1111
1112//
1113// This is the memory object used by DisAsm->getInstruction() which has its
1114// BasePC. This then allows the 'address' parameter to getInstruction() to
1115// be the actual PC of the instruction. Then when a branch dispacement is
1116// added to the PC of an instruction, the 'ReferenceValue' passed to the
1117// SymbolizerSymbolLookUp() routine is the correct target addresses. As in
1118// the case of a fully linked Mach-O file where a section being disassembled
1119// generally not linked at address zero.
1120//
1121class DisasmMemoryObject : public MemoryObject {
Aaron Ballman8cb2cae2014-09-25 14:02:43 +00001122 const uint8_t *Bytes;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001123 uint64_t Size;
1124 uint64_t BasePC;
1125public:
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001126 DisasmMemoryObject(const uint8_t *bytes, uint64_t size, uint64_t basePC)
1127 : Bytes(bytes), Size(size), BasePC(basePC) {}
Kevin Enderbybf246f52014-09-24 23:08:22 +00001128
1129 uint64_t getBase() const override { return BasePC; }
1130 uint64_t getExtent() const override { return Size; }
1131
1132 int readByte(uint64_t Addr, uint8_t *Byte) const override {
1133 if (Addr - BasePC >= Size)
1134 return -1;
1135 *Byte = Bytes[Addr - BasePC];
1136 return 0;
1137 }
1138};
1139
1140/// \brief Emits the comments that are stored in the CommentStream.
1141/// Each comment in the CommentStream must end with a newline.
1142static void emitComments(raw_svector_ostream &CommentStream,
1143 SmallString<128> &CommentsToEmit,
1144 formatted_raw_ostream &FormattedOS,
1145 const MCAsmInfo &MAI) {
1146 // Flush the stream before taking its content.
1147 CommentStream.flush();
1148 StringRef Comments = CommentsToEmit.str();
1149 // Get the default information for printing a comment.
1150 const char *CommentBegin = MAI.getCommentString();
1151 unsigned CommentColumn = MAI.getCommentColumn();
1152 bool IsFirst = true;
1153 while (!Comments.empty()) {
1154 if (!IsFirst)
1155 FormattedOS << '\n';
1156 // Emit a line of comments.
1157 FormattedOS.PadToColumn(CommentColumn);
1158 size_t Position = Comments.find('\n');
1159 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
1160 // Move after the newline character.
1161 Comments = Comments.substr(Position + 1);
1162 IsFirst = false;
1163 }
1164 FormattedOS.flush();
1165
1166 // Tell the comment stream that the vector changed underneath it.
1167 CommentsToEmit.clear();
1168 CommentStream.resync();
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001169}
1170
Rafael Espindola9b709252013-04-13 01:45:40 +00001171static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindola56f976f2013-04-18 18:08:55 +00001172 MachOObjectFile *MachOOF) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001173 const char *McpuDefault = nullptr;
1174 const Target *ThumbTarget = nullptr;
1175 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001176 if (!TheTarget) {
1177 // GetTarget prints out stuff.
1178 return;
1179 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001180 if (MCPU.empty() && McpuDefault)
1181 MCPU = McpuDefault;
1182
Ahmed Charles56440fd2014-03-06 05:51:42 +00001183 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
1184 std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
1185 TheTarget->createMCInstrAnalysis(InstrInfo.get()));
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001186 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
1187 std::unique_ptr<MCInstrAnalysis> ThumbInstrAnalysis;
1188 if (ThumbTarget) {
1189 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
1190 ThumbInstrAnalysis.reset(
1191 ThumbTarget->createMCInstrAnalysis(ThumbInstrInfo.get()));
1192 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001193
Kevin Enderbyc9595622014-08-06 23:24:41 +00001194 // Package up features to be passed to target/subtarget
1195 std::string FeaturesStr;
1196 if (MAttrs.size()) {
1197 SubtargetFeatures Features;
1198 for (unsigned i = 0; i != MAttrs.size(); ++i)
1199 Features.AddFeature(MAttrs[i]);
1200 FeaturesStr = Features.getString();
1201 }
1202
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001203 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +00001204 std::unique_ptr<const MCRegisterInfo> MRI(
1205 TheTarget->createMCRegInfo(TripleName));
1206 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +00001207 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +00001208 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +00001209 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +00001210 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001211 std::unique_ptr<MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001212 TheTarget->createMCDisassembler(*STI, Ctx));
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001213 std::unique_ptr<MCSymbolizer> Symbolizer;
1214 struct DisassembleInfo SymbolizerInfo;
1215 std::unique_ptr<MCRelocationInfo> RelInfo(
1216 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1217 if (RelInfo) {
1218 Symbolizer.reset(TheTarget->createMCSymbolizer(
1219 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1220 &SymbolizerInfo, &Ctx, RelInfo.release()));
1221 DisAsm->setSymbolizer(std::move(Symbolizer));
1222 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001223 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +00001224 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1225 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001226 // Set the display preference for hex vs. decimal immediates.
1227 IP->setPrintImmHex(PrintImmHex);
1228 // Comment stream and backing vector.
1229 SmallString<128> CommentsToEmit;
1230 raw_svector_ostream CommentStream(CommentsToEmit);
1231 IP->setCommentStream(CommentStream);
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001232
1233 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +00001234 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001235 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001236 return;
1237 }
1238
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001239 // Set up thumb disassembler.
1240 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
1241 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
1242 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
1243 std::unique_ptr<const MCDisassembler> ThumbDisAsm;
1244 std::unique_ptr<MCInstPrinter> ThumbIP;
1245 std::unique_ptr<MCContext> ThumbCtx;
1246 if (ThumbTarget) {
1247 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
1248 ThumbAsmInfo.reset(
1249 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
1250 ThumbSTI.reset(
1251 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
1252 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
1253 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001254 // TODO: add MCSymbolizer here for the ThumbTarget like above for TheTarget.
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001255 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
1256 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
1257 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
1258 *ThumbSTI));
Kevin Enderbybf246f52014-09-24 23:08:22 +00001259 // Set the display preference for hex vs. decimal immediates.
1260 ThumbIP->setPrintImmHex(PrintImmHex);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001261 }
1262
1263 if (ThumbTarget && (!ThumbInstrAnalysis || !ThumbAsmInfo || !ThumbSTI ||
1264 !ThumbDisAsm || !ThumbIP)) {
1265 errs() << "error: couldn't initialize disassembler for target "
1266 << ThumbTripleName << '\n';
1267 return;
1268 }
1269
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001270 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001271
Charles Davis8bdfafd2013-09-01 04:28:48 +00001272 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001273
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001274 // FIXME: Using the -cfg command line option, this code used to be able to
1275 // annotate relocations with the referenced symbol's name, and if this was
1276 // inside a __[cf]string section, the data it points to. This is now replaced
1277 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +00001278 std::vector<SectionRef> Sections;
1279 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001280 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +00001281 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001282
Kevin Enderby273ae012013-06-06 17:20:50 +00001283 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
1284 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001285
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001286 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +00001287 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001288
Kevin Enderby273ae012013-06-06 17:20:50 +00001289 // Build a data in code table that is sorted on by the address of each entry.
1290 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +00001291 if (Header.filetype == MachO::MH_OBJECT)
Rafael Espindola80291272014-10-08 15:28:58 +00001292 BaseAddress = Sections[0].getAddress();
Kevin Enderby273ae012013-06-06 17:20:50 +00001293 else
1294 BaseAddress = BaseSegmentAddress;
1295 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +00001296 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +00001297 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +00001298 uint32_t Offset;
1299 DI->getOffset(Offset);
1300 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
1301 }
1302 array_pod_sort(Dices.begin(), Dices.end());
1303
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001304#ifndef NDEBUG
1305 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1306#else
1307 raw_ostream &DebugOut = nulls();
1308#endif
1309
Ahmed Charles56440fd2014-03-06 05:51:42 +00001310 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +00001311 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +00001312 // Try to find debug info and set up the DIContext for it.
1313 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +00001314 // A separate DSym file path was specified, parse it as a macho file,
1315 // get the sections and supply it to the section name parsing machinery.
1316 if (!DSYMFile.empty()) {
Rafael Espindola48af1c22014-08-19 18:44:46 +00001317 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
Rafael Espindolaadf21f22014-07-06 17:43:13 +00001318 MemoryBuffer::getFileOrSTDIN(DSYMFile);
Rafael Espindola48af1c22014-08-19 18:44:46 +00001319 if (std::error_code EC = BufOrErr.getError()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +00001320 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +00001321 return;
1322 }
Rafael Espindola48af1c22014-08-19 18:44:46 +00001323 DbgObj =
1324 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
1325 .get()
1326 .release();
Benjamin Kramer699128e2011-09-21 01:13:19 +00001327 }
1328
Eric Christopher7370b552012-11-12 21:40:38 +00001329 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +00001330 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +00001331 }
1332
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001333 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001334
Rafael Espindola80291272014-10-08 15:28:58 +00001335 bool SectIsText = Sections[SectIdx].isText();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001336 if (SectIsText == false)
1337 continue;
1338
Owen Andersond9243c42011-10-17 21:37:35 +00001339 StringRef SectName;
1340 if (Sections[SectIdx].getName(SectName) ||
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001341 SectName != "__text")
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001342 continue; // Skip non-text sections
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001343
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001344 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001345
Rafael Espindolab0f76a42013-04-05 15:15:22 +00001346 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
1347 if (SegmentName != "__TEXT")
Rafael Espindolaa9f810b2012-12-21 03:47:03 +00001348 continue;
1349
Owen Andersond9243c42011-10-17 21:37:35 +00001350 StringRef Bytes;
1351 Sections[SectIdx].getContents(Bytes);
Rafael Espindola80291272014-10-08 15:28:58 +00001352 uint64_t SectAddress = Sections[SectIdx].getAddress();
Aaron Ballman8cb2cae2014-09-25 14:02:43 +00001353 DisasmMemoryObject MemoryObject((const uint8_t *)Bytes.data(), Bytes.size(),
Kevin Enderbybf246f52014-09-24 23:08:22 +00001354 SectAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001355 bool symbolTableWorked = false;
1356
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001357 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001358 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1359 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Rafael Espindola80291272014-10-08 15:28:58 +00001360 uint64_t RelocOffset;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001361 Reloc.getOffset(RelocOffset);
Rafael Espindola80291272014-10-08 15:28:58 +00001362 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Owen Andersond9243c42011-10-17 21:37:35 +00001363 RelocOffset -= SectionAddress;
1364
Alexey Samsonovaa4d2952014-03-14 14:22:49 +00001365 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +00001366
Rafael Espindola806f0062013-06-05 01:33:53 +00001367 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001368 }
1369 array_pod_sort(Relocs.begin(), Relocs.end());
1370
Kevin Enderbybf246f52014-09-24 23:08:22 +00001371 // Create a map of symbol addresses to symbol names for use by
1372 // the SymbolizerSymbolLookUp() routine.
1373 SymbolAddressMap AddrMap;
1374 for (const SymbolRef &Symbol : MachOOF->symbols()) {
1375 SymbolRef::Type ST;
1376 Symbol.getType(ST);
1377 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1378 ST == SymbolRef::ST_Other) {
1379 uint64_t Address;
1380 Symbol.getAddress(Address);
1381 StringRef SymName;
1382 Symbol.getName(SymName);
1383 AddrMap[Address] = SymName;
1384 }
1385 }
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001386 // Set up the block of info used by the Symbolizer call backs.
1387 SymbolizerInfo.verbose = true;
1388 SymbolizerInfo.O = MachOOF;
1389 SymbolizerInfo.S = Sections[SectIdx];
Kevin Enderbybf246f52014-09-24 23:08:22 +00001390 SymbolizerInfo.AddrMap = &AddrMap;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001391 SymbolizerInfo.Sections = &Sections;
1392 SymbolizerInfo.class_name = nullptr;
1393 SymbolizerInfo.selector_name = nullptr;
1394 SymbolizerInfo.method = nullptr;
Kevin Enderby078be602014-10-23 19:53:12 +00001395 SymbolizerInfo.bindtable = nullptr;
Kevin Enderby98c9acc2014-09-16 18:00:57 +00001396
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001397 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001398 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +00001399 StringRef SymName;
1400 Symbols[SymIdx].getName(SymName);
1401
1402 SymbolRef::Type ST;
1403 Symbols[SymIdx].getType(ST);
1404 if (ST != SymbolRef::ST_Function)
1405 continue;
1406
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001407 // Make sure the symbol is defined in this section.
Rafael Espindola80291272014-10-08 15:28:58 +00001408 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
Owen Andersond9243c42011-10-17 21:37:35 +00001409 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001410 continue;
1411
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001412 // Start at the address of the symbol relative to the section's address.
Owen Andersond9243c42011-10-17 21:37:35 +00001413 uint64_t Start = 0;
Rafael Espindola80291272014-10-08 15:28:58 +00001414 uint64_t SectionAddress = Sections[SectIdx].getAddress();
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00001415 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +00001416 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00001417
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +00001418 // Stop disassembling either at the beginning of the next symbol or at
1419 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +00001420 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +00001421 uint64_t NextSym = 0;
1422 uint64_t NextSymIdx = SymIdx+1;
1423 while (Symbols.size() > NextSymIdx) {
1424 SymbolRef::Type NextSymType;
1425 Symbols[NextSymIdx].getType(NextSymType);
1426 if (NextSymType == SymbolRef::ST_Function) {
Rafael Espindola80291272014-10-08 15:28:58 +00001427 containsNextSym =
1428 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +00001429 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +00001430 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +00001431 break;
1432 }
1433 ++NextSymIdx;
1434 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001435
Rafael Espindola80291272014-10-08 15:28:58 +00001436 uint64_t SectSize = Sections[SectIdx].getSize();
Owen Andersond9243c42011-10-17 21:37:35 +00001437 uint64_t End = containsNextSym ? NextSym : SectSize;
1438 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001439
1440 symbolTableWorked = true;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001441 DisasmMemoryObject SectionMemoryObject((const uint8_t *)Bytes.data() +
1442 Start,
1443 End - Start, SectAddress + Start);
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001444
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001445 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
1446 bool isThumb =
1447 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
1448
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001449 outs() << SymName << ":\n";
1450 DILineInfo lastLine;
1451 for (uint64_t Index = Start; Index < End; Index += Size) {
1452 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +00001453
Kevin Enderbybf246f52014-09-24 23:08:22 +00001454 uint64_t PC = SectAddress + Index;
1455 if (FullLeadingAddr) {
1456 if (MachOOF->is64Bit())
1457 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001458 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001459 outs() << format("%08" PRIx64, PC);
1460 } else {
1461 outs() << format("%8" PRIx64 ":", PC);
1462 }
1463 if (!NoShowRawInsn)
1464 outs() << "\t";
Kevin Enderby273ae012013-06-06 17:20:50 +00001465
1466 // Check the data in code table here to see if this is data not an
1467 // instruction to be disassembled.
1468 DiceTable Dice;
Kevin Enderbybf246f52014-09-24 23:08:22 +00001469 Dice.push_back(std::make_pair(PC, DiceRef()));
Kevin Enderby273ae012013-06-06 17:20:50 +00001470 dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
1471 Dice.begin(), Dice.end(),
1472 compareDiceTableEntries);
1473 if (DTI != Dices.end()){
1474 uint16_t Length;
1475 DTI->second.getLength(Length);
1476 DumpBytes(StringRef(Bytes.data() + Index, Length));
1477 uint16_t Kind;
1478 DTI->second.getKind(Kind);
1479 DumpDataInCode(Bytes.data() + Index, Length, Kind);
1480 continue;
1481 }
1482
Kevin Enderbybf246f52014-09-24 23:08:22 +00001483 SmallVector<char, 64> AnnotationsBytes;
1484 raw_svector_ostream Annotations(AnnotationsBytes);
1485
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001486 bool gotInst;
1487 if (isThumb)
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001488 gotInst = ThumbDisAsm->getInstruction(Inst, Size, SectionMemoryObject,
1489 PC, DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001490 else
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001491 gotInst = DisAsm->getInstruction(Inst, Size, SectionMemoryObject, PC,
Kevin Enderbybf246f52014-09-24 23:08:22 +00001492 DebugOut, Annotations);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001493 if (gotInst) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001494 if (!NoShowRawInsn) {
1495 DumpBytes(StringRef(Bytes.data() + Index, Size));
1496 }
1497 formatted_raw_ostream FormattedOS(outs());
1498 Annotations.flush();
1499 StringRef AnnotationsStr = Annotations.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001500 if (isThumb)
Kevin Enderbybf246f52014-09-24 23:08:22 +00001501 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
Kevin Enderbyec5ca032014-08-18 20:21:02 +00001502 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001503 IP->printInst(&Inst, FormattedOS, AnnotationsStr);
1504 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
Owen Andersond9243c42011-10-17 21:37:35 +00001505
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001506 // Print debug info.
1507 if (diContext) {
1508 DILineInfo dli =
Kevin Enderbybf246f52014-09-24 23:08:22 +00001509 diContext->getLineInfoForAddress(PC);
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001510 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +00001511 if (dli != lastLine && dli.Line != 0)
1512 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
1513 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001514 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001515 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001516 outs() << "\n";
1517 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001518 unsigned int Arch = MachOOF->getArch();
1519 if (Arch == Triple::x86_64 || Arch == Triple::x86){
1520 outs() << format("\t.byte 0x%02x #bad opcode\n",
1521 *(Bytes.data() + Index) & 0xff);
1522 Size = 1; // skip exactly one illegible byte and move on.
1523 } else {
1524 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1525 if (Size == 0)
1526 Size = 1; // skip illegible bytes
1527 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001528 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001529 }
1530 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +00001531 if (!symbolTableWorked) {
Rafael Espindola80291272014-10-08 15:28:58 +00001532 // Reading the symbol table didn't work, disassemble the whole section.
1533 uint64_t SectAddress = Sections[SectIdx].getAddress();
1534 uint64_t SectSize = Sections[SectIdx].getSize();
Kevin Enderbybadd1002012-05-18 00:13:56 +00001535 uint64_t InstSize;
1536 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +00001537 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +00001538
Kevin Enderbybf246f52014-09-24 23:08:22 +00001539 uint64_t PC = SectAddress + Index;
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001540 if (DisAsm->getInstruction(Inst, InstSize, MemoryObject, PC, DebugOut,
1541 nulls())) {
Kevin Enderbybf246f52014-09-24 23:08:22 +00001542 if (FullLeadingAddr) {
1543 if (MachOOF->is64Bit())
1544 outs() << format("%016" PRIx64, PC);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001545 else
Kevin Enderbybf246f52014-09-24 23:08:22 +00001546 outs() << format("%08" PRIx64, PC);
1547 } else {
1548 outs() << format("%8" PRIx64 ":", PC);
1549 }
1550 if (!NoShowRawInsn) {
1551 outs() << "\t";
1552 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
1553 }
Bill Wendling4e68e062012-07-19 00:17:40 +00001554 IP->printInst(&Inst, outs(), "");
1555 outs() << "\n";
1556 } else {
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001557 unsigned int Arch = MachOOF->getArch();
1558 if (Arch == Triple::x86_64 || Arch == Triple::x86){
1559 outs() << format("\t.byte 0x%02x #bad opcode\n",
1560 *(Bytes.data() + Index) & 0xff);
1561 InstSize = 1; // skip exactly one illegible byte and move on.
1562 } else {
1563 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1564 if (InstSize == 0)
1565 InstSize = 1; // skip illegible bytes
1566 }
Bill Wendling4e68e062012-07-19 00:17:40 +00001567 }
Kevin Enderbybadd1002012-05-18 00:13:56 +00001568 }
1569 }
Kevin Enderby6f326ce2014-10-23 19:37:31 +00001570 if (SymbolizerInfo.method != nullptr)
1571 free(SymbolizerInfo.method);
Kevin Enderby078be602014-10-23 19:53:12 +00001572 if (SymbolizerInfo.bindtable != nullptr)
1573 delete SymbolizerInfo.bindtable;
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001574 }
1575}
Tim Northover4bd286a2014-08-01 13:07:19 +00001576
Tim Northover39c70bb2014-08-12 11:52:59 +00001577
1578//===----------------------------------------------------------------------===//
1579// __compact_unwind section dumping
1580//===----------------------------------------------------------------------===//
1581
Tim Northover4bd286a2014-08-01 13:07:19 +00001582namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +00001583
1584template <typename T> static uint64_t readNext(const char *&Buf) {
1585 using llvm::support::little;
1586 using llvm::support::unaligned;
1587
1588 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
1589 Buf += sizeof(T);
1590 return Val;
1591 }
1592
Tim Northover4bd286a2014-08-01 13:07:19 +00001593struct CompactUnwindEntry {
1594 uint32_t OffsetInSection;
1595
1596 uint64_t FunctionAddr;
1597 uint32_t Length;
1598 uint32_t CompactEncoding;
1599 uint64_t PersonalityAddr;
1600 uint64_t LSDAAddr;
1601
1602 RelocationRef FunctionReloc;
1603 RelocationRef PersonalityReloc;
1604 RelocationRef LSDAReloc;
1605
1606 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
1607 : OffsetInSection(Offset) {
1608 if (Is64)
1609 read<uint64_t>(Contents.data() + Offset);
1610 else
1611 read<uint32_t>(Contents.data() + Offset);
1612 }
1613
1614private:
Tim Northover4bd286a2014-08-01 13:07:19 +00001615 template<typename UIntPtr>
1616 void read(const char *Buf) {
1617 FunctionAddr = readNext<UIntPtr>(Buf);
1618 Length = readNext<uint32_t>(Buf);
1619 CompactEncoding = readNext<uint32_t>(Buf);
1620 PersonalityAddr = readNext<UIntPtr>(Buf);
1621 LSDAAddr = readNext<UIntPtr>(Buf);
1622 }
1623};
1624}
1625
1626/// Given a relocation from __compact_unwind, consisting of the RelocationRef
1627/// and data being relocated, determine the best base Name and Addend to use for
1628/// display purposes.
1629///
1630/// 1. An Extern relocation will directly reference a symbol (and the data is
1631/// then already an addend), so use that.
1632/// 2. Otherwise the data is an offset in the object file's layout; try to find
1633// a symbol before it in the same section, and use the offset from there.
1634/// 3. Finally, if all that fails, fall back to an offset from the start of the
1635/// referenced section.
1636static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
1637 std::map<uint64_t, SymbolRef> &Symbols,
1638 const RelocationRef &Reloc,
1639 uint64_t Addr,
1640 StringRef &Name, uint64_t &Addend) {
1641 if (Reloc.getSymbol() != Obj->symbol_end()) {
1642 Reloc.getSymbol()->getName(Name);
1643 Addend = Addr;
1644 return;
1645 }
1646
1647 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
1648 SectionRef RelocSection = Obj->getRelocationSection(RE);
1649
Rafael Espindola80291272014-10-08 15:28:58 +00001650 uint64_t SectionAddr = RelocSection.getAddress();
Tim Northover4bd286a2014-08-01 13:07:19 +00001651
1652 auto Sym = Symbols.upper_bound(Addr);
1653 if (Sym == Symbols.begin()) {
1654 // The first symbol in the object is after this reference, the best we can
1655 // do is section-relative notation.
1656 RelocSection.getName(Name);
1657 Addend = Addr - SectionAddr;
1658 return;
1659 }
1660
1661 // Go back one so that SymbolAddress <= Addr.
1662 --Sym;
1663
1664 section_iterator SymSection = Obj->section_end();
1665 Sym->second.getSection(SymSection);
1666 if (RelocSection == *SymSection) {
1667 // There's a valid symbol in the same section before this reference.
1668 Sym->second.getName(Name);
1669 Addend = Addr - Sym->first;
1670 return;
1671 }
1672
1673 // There is a symbol before this reference, but it's in a different
1674 // section. Probably not helpful to mention it, so use the section name.
1675 RelocSection.getName(Name);
1676 Addend = Addr - SectionAddr;
1677}
1678
1679static void printUnwindRelocDest(const MachOObjectFile *Obj,
1680 std::map<uint64_t, SymbolRef> &Symbols,
1681 const RelocationRef &Reloc,
1682 uint64_t Addr) {
1683 StringRef Name;
1684 uint64_t Addend;
1685
Tim Northover0b0add52014-09-09 10:45:06 +00001686 if (!Reloc.getObjectFile())
1687 return;
1688
Tim Northover4bd286a2014-08-01 13:07:19 +00001689 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
1690
1691 outs() << Name;
1692 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +00001693 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +00001694}
1695
1696static void
1697printMachOCompactUnwindSection(const MachOObjectFile *Obj,
1698 std::map<uint64_t, SymbolRef> &Symbols,
1699 const SectionRef &CompactUnwind) {
1700
1701 assert(Obj->isLittleEndian() &&
1702 "There should not be a big-endian .o with __compact_unwind");
1703
1704 bool Is64 = Obj->is64Bit();
1705 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
1706 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
1707
1708 StringRef Contents;
1709 CompactUnwind.getContents(Contents);
1710
1711 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
1712
1713 // First populate the initial raw offsets, encodings and so on from the entry.
1714 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
1715 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
1716 CompactUnwinds.push_back(Entry);
1717 }
1718
1719 // Next we need to look at the relocations to find out what objects are
1720 // actually being referred to.
1721 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
1722 uint64_t RelocAddress;
1723 Reloc.getOffset(RelocAddress);
1724
1725 uint32_t EntryIdx = RelocAddress / EntrySize;
1726 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
1727 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
1728
1729 if (OffsetInEntry == 0)
1730 Entry.FunctionReloc = Reloc;
1731 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
1732 Entry.PersonalityReloc = Reloc;
1733 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
1734 Entry.LSDAReloc = Reloc;
1735 else
1736 llvm_unreachable("Unexpected relocation in __compact_unwind section");
1737 }
1738
1739 // Finally, we're ready to print the data we've gathered.
1740 outs() << "Contents of __compact_unwind section:\n";
1741 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +00001742 outs() << " Entry at offset "
1743 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +00001744
1745 // 1. Start of the region this entry applies to.
1746 outs() << " start: "
Tim Northoverb911bf82014-08-08 12:00:09 +00001747 << format("0x%" PRIx64, Entry.FunctionAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00001748 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc,
1749 Entry.FunctionAddr);
1750 outs() << '\n';
1751
1752 // 2. Length of the region this entry applies to.
1753 outs() << " length: "
Tim Northoverb911bf82014-08-08 12:00:09 +00001754 << format("0x%" PRIx32, Entry.Length) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00001755 // 3. The 32-bit compact encoding.
1756 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +00001757 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +00001758
1759 // 4. The personality function, if present.
1760 if (Entry.PersonalityReloc.getObjectFile()) {
1761 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +00001762 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00001763 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
1764 Entry.PersonalityAddr);
1765 outs() << '\n';
1766 }
1767
1768 // 5. This entry's language-specific data area.
1769 if (Entry.LSDAReloc.getObjectFile()) {
1770 outs() << " LSDA: "
Tim Northoverb911bf82014-08-08 12:00:09 +00001771 << format("0x%" PRIx64, Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +00001772 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
1773 outs() << '\n';
1774 }
1775 }
1776}
1777
Tim Northover39c70bb2014-08-12 11:52:59 +00001778//===----------------------------------------------------------------------===//
1779// __unwind_info section dumping
1780//===----------------------------------------------------------------------===//
1781
1782static void printRegularSecondLevelUnwindPage(const char *PageStart) {
1783 const char *Pos = PageStart;
1784 uint32_t Kind = readNext<uint32_t>(Pos);
1785 (void)Kind;
1786 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
1787
1788 uint16_t EntriesStart = readNext<uint16_t>(Pos);
1789 uint16_t NumEntries = readNext<uint16_t>(Pos);
1790
1791 Pos = PageStart + EntriesStart;
1792 for (unsigned i = 0; i < NumEntries; ++i) {
1793 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
1794 uint32_t Encoding = readNext<uint32_t>(Pos);
1795
1796 outs() << " [" << i << "]: "
1797 << "function offset="
1798 << format("0x%08" PRIx32, FunctionOffset) << ", "
1799 << "encoding="
1800 << format("0x%08" PRIx32, Encoding)
1801 << '\n';
1802 }
1803}
1804
1805static void printCompressedSecondLevelUnwindPage(
1806 const char *PageStart, uint32_t FunctionBase,
1807 const SmallVectorImpl<uint32_t> &CommonEncodings) {
1808 const char *Pos = PageStart;
1809 uint32_t Kind = readNext<uint32_t>(Pos);
1810 (void)Kind;
1811 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
1812
1813 uint16_t EntriesStart = readNext<uint16_t>(Pos);
1814 uint16_t NumEntries = readNext<uint16_t>(Pos);
1815
1816 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
1817 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +00001818 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
1819 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +00001820
1821 Pos = PageStart + EntriesStart;
1822 for (unsigned i = 0; i < NumEntries; ++i) {
1823 uint32_t Entry = readNext<uint32_t>(Pos);
1824 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
1825 uint32_t EncodingIdx = Entry >> 24;
1826
1827 uint32_t Encoding;
1828 if (EncodingIdx < CommonEncodings.size())
1829 Encoding = CommonEncodings[EncodingIdx];
1830 else
1831 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
1832
1833 outs() << " [" << i << "]: "
1834 << "function offset="
1835 << format("0x%08" PRIx32, FunctionOffset) << ", "
1836 << "encoding[" << EncodingIdx << "]="
1837 << format("0x%08" PRIx32, Encoding)
1838 << '\n';
1839 }
1840}
1841
1842static void
1843printMachOUnwindInfoSection(const MachOObjectFile *Obj,
1844 std::map<uint64_t, SymbolRef> &Symbols,
1845 const SectionRef &UnwindInfo) {
1846
1847 assert(Obj->isLittleEndian() &&
1848 "There should not be a big-endian .o with __unwind_info");
1849
1850 outs() << "Contents of __unwind_info section:\n";
1851
1852 StringRef Contents;
1853 UnwindInfo.getContents(Contents);
1854 const char *Pos = Contents.data();
1855
1856 //===----------------------------------
1857 // Section header
1858 //===----------------------------------
1859
1860 uint32_t Version = readNext<uint32_t>(Pos);
1861 outs() << " Version: "
1862 << format("0x%" PRIx32, Version) << '\n';
1863 assert(Version == 1 && "only understand version 1");
1864
1865 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
1866 outs() << " Common encodings array section offset: "
1867 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
1868 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
1869 outs() << " Number of common encodings in array: "
1870 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
1871
1872 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
1873 outs() << " Personality function array section offset: "
1874 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
1875 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
1876 outs() << " Number of personality functions in array: "
1877 << format("0x%" PRIx32, NumPersonalities) << '\n';
1878
1879 uint32_t IndicesStart = readNext<uint32_t>(Pos);
1880 outs() << " Index array section offset: "
1881 << format("0x%" PRIx32, IndicesStart) << '\n';
1882 uint32_t NumIndices = readNext<uint32_t>(Pos);
1883 outs() << " Number of indices in array: "
1884 << format("0x%" PRIx32, NumIndices) << '\n';
1885
1886 //===----------------------------------
1887 // A shared list of common encodings
1888 //===----------------------------------
1889
1890 // These occupy indices in the range [0, N] whenever an encoding is referenced
1891 // from a compressed 2nd level index table. In practice the linker only
1892 // creates ~128 of these, so that indices are available to embed encodings in
1893 // the 2nd level index.
1894
1895 SmallVector<uint32_t, 64> CommonEncodings;
1896 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
1897 Pos = Contents.data() + CommonEncodingsStart;
1898 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
1899 uint32_t Encoding = readNext<uint32_t>(Pos);
1900 CommonEncodings.push_back(Encoding);
1901
1902 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
1903 << '\n';
1904 }
1905
1906
1907 //===----------------------------------
1908 // Personality functions used in this executable
1909 //===----------------------------------
1910
1911 // There should be only a handful of these (one per source language,
1912 // roughly). Particularly since they only get 2 bits in the compact encoding.
1913
1914 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
1915 Pos = Contents.data() + PersonalitiesStart;
1916 for (unsigned i = 0; i < NumPersonalities; ++i) {
1917 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
1918 outs() << " personality[" << i + 1
1919 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
1920 }
1921
1922 //===----------------------------------
1923 // The level 1 index entries
1924 //===----------------------------------
1925
1926 // These specify an approximate place to start searching for the more detailed
1927 // information, sorted by PC.
1928
1929 struct IndexEntry {
1930 uint32_t FunctionOffset;
1931 uint32_t SecondLevelPageStart;
1932 uint32_t LSDAStart;
1933 };
1934
1935 SmallVector<IndexEntry, 4> IndexEntries;
1936
1937 outs() << " Top level indices: (count = " << NumIndices << ")\n";
1938 Pos = Contents.data() + IndicesStart;
1939 for (unsigned i = 0; i < NumIndices; ++i) {
1940 IndexEntry Entry;
1941
1942 Entry.FunctionOffset = readNext<uint32_t>(Pos);
1943 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
1944 Entry.LSDAStart = readNext<uint32_t>(Pos);
1945 IndexEntries.push_back(Entry);
1946
1947 outs() << " [" << i << "]: "
1948 << "function offset="
1949 << format("0x%08" PRIx32, Entry.FunctionOffset) << ", "
1950 << "2nd level page offset="
1951 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
1952 << "LSDA offset="
1953 << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
1954 }
1955
1956
1957 //===----------------------------------
1958 // Next come the LSDA tables
1959 //===----------------------------------
1960
1961 // The LSDA layout is rather implicit: it's a contiguous array of entries from
1962 // the first top-level index's LSDAOffset to the last (sentinel).
1963
1964 outs() << " LSDA descriptors:\n";
1965 Pos = Contents.data() + IndexEntries[0].LSDAStart;
1966 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
1967 (2 * sizeof(uint32_t));
1968 for (int i = 0; i < NumLSDAs; ++i) {
1969 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
1970 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
1971 outs() << " [" << i << "]: "
1972 << "function offset="
1973 << format("0x%08" PRIx32, FunctionOffset) << ", "
1974 << "LSDA offset="
1975 << format("0x%08" PRIx32, LSDAOffset) << '\n';
1976 }
1977
1978 //===----------------------------------
1979 // Finally, the 2nd level indices
1980 //===----------------------------------
1981
1982 // Generally these are 4K in size, and have 2 possible forms:
1983 // + Regular stores up to 511 entries with disparate encodings
1984 // + Compressed stores up to 1021 entries if few enough compact encoding
1985 // values are used.
1986 outs() << " Second level indices:\n";
1987 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
1988 // The final sentinel top-level index has no associated 2nd level page
1989 if (IndexEntries[i].SecondLevelPageStart == 0)
1990 break;
1991
1992 outs() << " Second level index[" << i << "]: "
1993 << "offset in section="
1994 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
1995 << ", "
1996 << "base function offset="
1997 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
1998
1999 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +00002000 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +00002001 if (Kind == 2)
2002 printRegularSecondLevelUnwindPage(Pos);
2003 else if (Kind == 3)
2004 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2005 CommonEncodings);
2006 else
2007 llvm_unreachable("Do not know how to print this kind of 2nd level page");
2008
2009 }
2010}
2011
Tim Northover4bd286a2014-08-01 13:07:19 +00002012void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2013 std::map<uint64_t, SymbolRef> Symbols;
2014 for (const SymbolRef &SymRef : Obj->symbols()) {
2015 // Discard any undefined or absolute symbols. They're not going to take part
2016 // in the convenience lookup for unwind info and just take up resources.
2017 section_iterator Section = Obj->section_end();
2018 SymRef.getSection(Section);
2019 if (Section == Obj->section_end())
2020 continue;
2021
2022 uint64_t Addr;
2023 SymRef.getAddress(Addr);
2024 Symbols.insert(std::make_pair(Addr, SymRef));
2025 }
2026
2027 for (const SectionRef &Section : Obj->sections()) {
2028 StringRef SectName;
2029 Section.getName(SectName);
2030 if (SectName == "__compact_unwind")
2031 printMachOCompactUnwindSection(Obj, Symbols, Section);
2032 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +00002033 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +00002034 else if (SectName == "__eh_frame")
2035 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
2036
2037 }
2038}
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002039
2040static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2041 uint32_t cpusubtype, uint32_t filetype,
2042 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2043 bool verbose) {
2044 outs() << "Mach header\n";
2045 outs() << " magic cputype cpusubtype caps filetype ncmds "
2046 "sizeofcmds flags\n";
2047 if (verbose) {
2048 if (magic == MachO::MH_MAGIC)
2049 outs() << " MH_MAGIC";
2050 else if (magic == MachO::MH_MAGIC_64)
2051 outs() << "MH_MAGIC_64";
2052 else
2053 outs() << format(" 0x%08" PRIx32, magic);
2054 switch (cputype) {
2055 case MachO::CPU_TYPE_I386:
2056 outs() << " I386";
2057 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2058 case MachO::CPU_SUBTYPE_I386_ALL:
2059 outs() << " ALL";
2060 break;
2061 default:
2062 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2063 break;
2064 }
2065 break;
2066 case MachO::CPU_TYPE_X86_64:
2067 outs() << " X86_64";
2068 case MachO::CPU_SUBTYPE_X86_64_ALL:
2069 outs() << " ALL";
2070 break;
2071 case MachO::CPU_SUBTYPE_X86_64_H:
2072 outs() << " Haswell";
Aaron Ballman9d515ff2014-08-24 13:25:16 +00002073 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002074 break;
2075 case MachO::CPU_TYPE_ARM:
2076 outs() << " ARM";
2077 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2078 case MachO::CPU_SUBTYPE_ARM_ALL:
2079 outs() << " ALL";
2080 break;
2081 case MachO::CPU_SUBTYPE_ARM_V4T:
2082 outs() << " V4T";
2083 break;
2084 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2085 outs() << " V5TEJ";
2086 break;
2087 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2088 outs() << " XSCALE";
2089 break;
2090 case MachO::CPU_SUBTYPE_ARM_V6:
2091 outs() << " V6";
2092 break;
2093 case MachO::CPU_SUBTYPE_ARM_V6M:
2094 outs() << " V6M";
2095 break;
2096 case MachO::CPU_SUBTYPE_ARM_V7:
2097 outs() << " V7";
2098 break;
2099 case MachO::CPU_SUBTYPE_ARM_V7EM:
2100 outs() << " V7EM";
2101 break;
2102 case MachO::CPU_SUBTYPE_ARM_V7K:
2103 outs() << " V7K";
2104 break;
2105 case MachO::CPU_SUBTYPE_ARM_V7M:
2106 outs() << " V7M";
2107 break;
2108 case MachO::CPU_SUBTYPE_ARM_V7S:
2109 outs() << " V7S";
2110 break;
2111 default:
2112 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2113 break;
2114 }
2115 break;
2116 case MachO::CPU_TYPE_ARM64:
2117 outs() << " ARM64";
2118 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2119 case MachO::CPU_SUBTYPE_ARM64_ALL:
2120 outs() << " ALL";
2121 break;
2122 default:
2123 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2124 break;
2125 }
2126 break;
2127 case MachO::CPU_TYPE_POWERPC:
2128 outs() << " PPC";
2129 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2130 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2131 outs() << " ALL";
2132 break;
2133 default:
2134 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2135 break;
2136 }
2137 break;
2138 case MachO::CPU_TYPE_POWERPC64:
2139 outs() << " PPC64";
2140 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2141 case MachO::CPU_SUBTYPE_POWERPC_ALL:
2142 outs() << " ALL";
2143 break;
2144 default:
2145 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2146 break;
2147 }
2148 break;
2149 }
2150 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002151 outs() << " LIB64";
Kevin Enderbyb76d3862014-08-22 20:35:18 +00002152 } else {
2153 outs() << format(" 0x%02" PRIx32,
2154 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2155 }
2156 switch (filetype) {
2157 case MachO::MH_OBJECT:
2158 outs() << " OBJECT";
2159 break;
2160 case MachO::MH_EXECUTE:
2161 outs() << " EXECUTE";
2162 break;
2163 case MachO::MH_FVMLIB:
2164 outs() << " FVMLIB";
2165 break;
2166 case MachO::MH_CORE:
2167 outs() << " CORE";
2168 break;
2169 case MachO::MH_PRELOAD:
2170 outs() << " PRELOAD";
2171 break;
2172 case MachO::MH_DYLIB:
2173 outs() << " DYLIB";
2174 break;
2175 case MachO::MH_DYLIB_STUB:
2176 outs() << " DYLIB_STUB";
2177 break;
2178 case MachO::MH_DYLINKER:
2179 outs() << " DYLINKER";
2180 break;
2181 case MachO::MH_BUNDLE:
2182 outs() << " BUNDLE";
2183 break;
2184 case MachO::MH_DSYM:
2185 outs() << " DSYM";
2186 break;
2187 case MachO::MH_KEXT_BUNDLE:
2188 outs() << " KEXTBUNDLE";
2189 break;
2190 default:
2191 outs() << format(" %10u", filetype);
2192 break;
2193 }
2194 outs() << format(" %5u", ncmds);
2195 outs() << format(" %10u", sizeofcmds);
2196 uint32_t f = flags;
2197 if (f & MachO::MH_NOUNDEFS) {
2198 outs() << " NOUNDEFS";
2199 f &= ~MachO::MH_NOUNDEFS;
2200 }
2201 if (f & MachO::MH_INCRLINK) {
2202 outs() << " INCRLINK";
2203 f &= ~MachO::MH_INCRLINK;
2204 }
2205 if (f & MachO::MH_DYLDLINK) {
2206 outs() << " DYLDLINK";
2207 f &= ~MachO::MH_DYLDLINK;
2208 }
2209 if (f & MachO::MH_BINDATLOAD) {
2210 outs() << " BINDATLOAD";
2211 f &= ~MachO::MH_BINDATLOAD;
2212 }
2213 if (f & MachO::MH_PREBOUND) {
2214 outs() << " PREBOUND";
2215 f &= ~MachO::MH_PREBOUND;
2216 }
2217 if (f & MachO::MH_SPLIT_SEGS) {
2218 outs() << " SPLIT_SEGS";
2219 f &= ~MachO::MH_SPLIT_SEGS;
2220 }
2221 if (f & MachO::MH_LAZY_INIT) {
2222 outs() << " LAZY_INIT";
2223 f &= ~MachO::MH_LAZY_INIT;
2224 }
2225 if (f & MachO::MH_TWOLEVEL) {
2226 outs() << " TWOLEVEL";
2227 f &= ~MachO::MH_TWOLEVEL;
2228 }
2229 if (f & MachO::MH_FORCE_FLAT) {
2230 outs() << " FORCE_FLAT";
2231 f &= ~MachO::MH_FORCE_FLAT;
2232 }
2233 if (f & MachO::MH_NOMULTIDEFS) {
2234 outs() << " NOMULTIDEFS";
2235 f &= ~MachO::MH_NOMULTIDEFS;
2236 }
2237 if (f & MachO::MH_NOFIXPREBINDING) {
2238 outs() << " NOFIXPREBINDING";
2239 f &= ~MachO::MH_NOFIXPREBINDING;
2240 }
2241 if (f & MachO::MH_PREBINDABLE) {
2242 outs() << " PREBINDABLE";
2243 f &= ~MachO::MH_PREBINDABLE;
2244 }
2245 if (f & MachO::MH_ALLMODSBOUND) {
2246 outs() << " ALLMODSBOUND";
2247 f &= ~MachO::MH_ALLMODSBOUND;
2248 }
2249 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
2250 outs() << " SUBSECTIONS_VIA_SYMBOLS";
2251 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
2252 }
2253 if (f & MachO::MH_CANONICAL) {
2254 outs() << " CANONICAL";
2255 f &= ~MachO::MH_CANONICAL;
2256 }
2257 if (f & MachO::MH_WEAK_DEFINES) {
2258 outs() << " WEAK_DEFINES";
2259 f &= ~MachO::MH_WEAK_DEFINES;
2260 }
2261 if (f & MachO::MH_BINDS_TO_WEAK) {
2262 outs() << " BINDS_TO_WEAK";
2263 f &= ~MachO::MH_BINDS_TO_WEAK;
2264 }
2265 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
2266 outs() << " ALLOW_STACK_EXECUTION";
2267 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
2268 }
2269 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
2270 outs() << " DEAD_STRIPPABLE_DYLIB";
2271 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
2272 }
2273 if (f & MachO::MH_PIE) {
2274 outs() << " PIE";
2275 f &= ~MachO::MH_PIE;
2276 }
2277 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
2278 outs() << " NO_REEXPORTED_DYLIBS";
2279 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
2280 }
2281 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
2282 outs() << " MH_HAS_TLV_DESCRIPTORS";
2283 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
2284 }
2285 if (f & MachO::MH_NO_HEAP_EXECUTION) {
2286 outs() << " MH_NO_HEAP_EXECUTION";
2287 f &= ~MachO::MH_NO_HEAP_EXECUTION;
2288 }
2289 if (f & MachO::MH_APP_EXTENSION_SAFE) {
2290 outs() << " APP_EXTENSION_SAFE";
2291 f &= ~MachO::MH_APP_EXTENSION_SAFE;
2292 }
2293 if (f != 0 || flags == 0)
2294 outs() << format(" 0x%08" PRIx32, f);
2295 } else {
2296 outs() << format(" 0x%08" PRIx32, magic);
2297 outs() << format(" %7d", cputype);
2298 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2299 outs() << format(" 0x%02" PRIx32,
2300 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2301 outs() << format(" %10u", filetype);
2302 outs() << format(" %5u", ncmds);
2303 outs() << format(" %10u", sizeofcmds);
2304 outs() << format(" 0x%08" PRIx32, flags);
2305 }
2306 outs() << "\n";
2307}
2308
Kevin Enderby956366c2014-08-29 22:30:52 +00002309static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
2310 StringRef SegName, uint64_t vmaddr,
2311 uint64_t vmsize, uint64_t fileoff,
2312 uint64_t filesize, uint32_t maxprot,
2313 uint32_t initprot, uint32_t nsects,
2314 uint32_t flags, uint32_t object_size,
2315 bool verbose) {
2316 uint64_t expected_cmdsize;
2317 if (cmd == MachO::LC_SEGMENT) {
2318 outs() << " cmd LC_SEGMENT\n";
2319 expected_cmdsize = nsects;
2320 expected_cmdsize *= sizeof(struct MachO::section);
2321 expected_cmdsize += sizeof(struct MachO::segment_command);
2322 } else {
2323 outs() << " cmd LC_SEGMENT_64\n";
2324 expected_cmdsize = nsects;
2325 expected_cmdsize *= sizeof(struct MachO::section_64);
2326 expected_cmdsize += sizeof(struct MachO::segment_command_64);
2327 }
2328 outs() << " cmdsize " << cmdsize;
2329 if (cmdsize != expected_cmdsize)
2330 outs() << " Inconsistent size\n";
2331 else
2332 outs() << "\n";
2333 outs() << " segname " << SegName << "\n";
2334 if (cmd == MachO::LC_SEGMENT_64) {
2335 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
2336 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
2337 } else {
2338 outs() << " vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
2339 outs() << " vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
2340 }
2341 outs() << " fileoff " << fileoff;
2342 if (fileoff > object_size)
2343 outs() << " (past end of file)\n";
2344 else
2345 outs() << "\n";
2346 outs() << " filesize " << filesize;
2347 if (fileoff + filesize > object_size)
2348 outs() << " (past end of file)\n";
2349 else
2350 outs() << "\n";
2351 if (verbose) {
2352 if ((maxprot &
2353 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2354 MachO::VM_PROT_EXECUTE)) != 0)
2355 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
2356 else {
2357 if (maxprot & MachO::VM_PROT_READ)
2358 outs() << " maxprot r";
2359 else
2360 outs() << " maxprot -";
2361 if (maxprot & MachO::VM_PROT_WRITE)
2362 outs() << "w";
2363 else
2364 outs() << "-";
2365 if (maxprot & MachO::VM_PROT_EXECUTE)
2366 outs() << "x\n";
2367 else
2368 outs() << "-\n";
2369 }
2370 if ((initprot &
2371 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2372 MachO::VM_PROT_EXECUTE)) != 0)
2373 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
2374 else {
2375 if (initprot & MachO::VM_PROT_READ)
2376 outs() << " initprot r";
2377 else
2378 outs() << " initprot -";
2379 if (initprot & MachO::VM_PROT_WRITE)
2380 outs() << "w";
2381 else
2382 outs() << "-";
2383 if (initprot & MachO::VM_PROT_EXECUTE)
2384 outs() << "x\n";
2385 else
2386 outs() << "-\n";
2387 }
2388 } else {
2389 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
2390 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
2391 }
2392 outs() << " nsects " << nsects << "\n";
2393 if (verbose) {
2394 outs() << " flags";
2395 if (flags == 0)
2396 outs() << " (none)\n";
2397 else {
2398 if (flags & MachO::SG_HIGHVM) {
2399 outs() << " HIGHVM";
2400 flags &= ~MachO::SG_HIGHVM;
2401 }
2402 if (flags & MachO::SG_FVMLIB) {
2403 outs() << " FVMLIB";
2404 flags &= ~MachO::SG_FVMLIB;
2405 }
2406 if (flags & MachO::SG_NORELOC) {
2407 outs() << " NORELOC";
2408 flags &= ~MachO::SG_NORELOC;
2409 }
2410 if (flags & MachO::SG_PROTECTED_VERSION_1) {
2411 outs() << " PROTECTED_VERSION_1";
2412 flags &= ~MachO::SG_PROTECTED_VERSION_1;
2413 }
2414 if (flags)
2415 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
2416 else
2417 outs() << "\n";
2418 }
2419 } else {
2420 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
2421 }
2422}
2423
2424static void PrintSection(const char *sectname, const char *segname,
2425 uint64_t addr, uint64_t size, uint32_t offset,
2426 uint32_t align, uint32_t reloff, uint32_t nreloc,
2427 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
2428 uint32_t cmd, const char *sg_segname,
2429 uint32_t filetype, uint32_t object_size,
2430 bool verbose) {
2431 outs() << "Section\n";
2432 outs() << " sectname " << format("%.16s\n", sectname);
2433 outs() << " segname " << format("%.16s", segname);
2434 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
2435 outs() << " (does not match segment)\n";
2436 else
2437 outs() << "\n";
2438 if (cmd == MachO::LC_SEGMENT_64) {
2439 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
2440 outs() << " size " << format("0x%016" PRIx64, size);
2441 } else {
2442 outs() << " addr " << format("0x%08" PRIx32, addr) << "\n";
2443 outs() << " size " << format("0x%08" PRIx32, size);
2444 }
2445 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
2446 outs() << " (past end of file)\n";
2447 else
2448 outs() << "\n";
2449 outs() << " offset " << offset;
2450 if (offset > object_size)
2451 outs() << " (past end of file)\n";
2452 else
2453 outs() << "\n";
2454 uint32_t align_shifted = 1 << align;
2455 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
2456 outs() << " reloff " << reloff;
2457 if (reloff > object_size)
2458 outs() << " (past end of file)\n";
2459 else
2460 outs() << "\n";
2461 outs() << " nreloc " << nreloc;
2462 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
2463 outs() << " (past end of file)\n";
2464 else
2465 outs() << "\n";
2466 uint32_t section_type = flags & MachO::SECTION_TYPE;
2467 if (verbose) {
2468 outs() << " type";
2469 if (section_type == MachO::S_REGULAR)
2470 outs() << " S_REGULAR\n";
2471 else if (section_type == MachO::S_ZEROFILL)
2472 outs() << " S_ZEROFILL\n";
2473 else if (section_type == MachO::S_CSTRING_LITERALS)
2474 outs() << " S_CSTRING_LITERALS\n";
2475 else if (section_type == MachO::S_4BYTE_LITERALS)
2476 outs() << " S_4BYTE_LITERALS\n";
2477 else if (section_type == MachO::S_8BYTE_LITERALS)
2478 outs() << " S_8BYTE_LITERALS\n";
2479 else if (section_type == MachO::S_16BYTE_LITERALS)
2480 outs() << " S_16BYTE_LITERALS\n";
2481 else if (section_type == MachO::S_LITERAL_POINTERS)
2482 outs() << " S_LITERAL_POINTERS\n";
2483 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
2484 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
2485 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
2486 outs() << " S_LAZY_SYMBOL_POINTERS\n";
2487 else if (section_type == MachO::S_SYMBOL_STUBS)
2488 outs() << " S_SYMBOL_STUBS\n";
2489 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
2490 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
2491 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
2492 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
2493 else if (section_type == MachO::S_COALESCED)
2494 outs() << " S_COALESCED\n";
2495 else if (section_type == MachO::S_INTERPOSING)
2496 outs() << " S_INTERPOSING\n";
2497 else if (section_type == MachO::S_DTRACE_DOF)
2498 outs() << " S_DTRACE_DOF\n";
2499 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
2500 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
2501 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
2502 outs() << " S_THREAD_LOCAL_REGULAR\n";
2503 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
2504 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
2505 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
2506 outs() << " S_THREAD_LOCAL_VARIABLES\n";
2507 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2508 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
2509 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
2510 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
2511 else
2512 outs() << format("0x%08" PRIx32, section_type) << "\n";
2513 outs() << "attributes";
2514 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
2515 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
2516 outs() << " PURE_INSTRUCTIONS";
2517 if (section_attributes & MachO::S_ATTR_NO_TOC)
2518 outs() << " NO_TOC";
2519 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
2520 outs() << " STRIP_STATIC_SYMS";
2521 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
2522 outs() << " NO_DEAD_STRIP";
2523 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
2524 outs() << " LIVE_SUPPORT";
2525 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
2526 outs() << " SELF_MODIFYING_CODE";
2527 if (section_attributes & MachO::S_ATTR_DEBUG)
2528 outs() << " DEBUG";
2529 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
2530 outs() << " SOME_INSTRUCTIONS";
2531 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
2532 outs() << " EXT_RELOC";
2533 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
2534 outs() << " LOC_RELOC";
2535 if (section_attributes == 0)
2536 outs() << " (none)";
2537 outs() << "\n";
2538 } else
2539 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
2540 outs() << " reserved1 " << reserved1;
2541 if (section_type == MachO::S_SYMBOL_STUBS ||
2542 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2543 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2544 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2545 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2546 outs() << " (index into indirect symbol table)\n";
2547 else
2548 outs() << "\n";
2549 outs() << " reserved2 " << reserved2;
2550 if (section_type == MachO::S_SYMBOL_STUBS)
2551 outs() << " (size of stubs)\n";
2552 else
2553 outs() << "\n";
2554}
2555
2556static void PrintSymtabLoadCommand(MachO::symtab_command st, uint32_t cputype,
2557 uint32_t object_size) {
2558 outs() << " cmd LC_SYMTAB\n";
2559 outs() << " cmdsize " << st.cmdsize;
2560 if (st.cmdsize != sizeof(struct MachO::symtab_command))
2561 outs() << " Incorrect size\n";
2562 else
2563 outs() << "\n";
2564 outs() << " symoff " << st.symoff;
2565 if (st.symoff > object_size)
2566 outs() << " (past end of file)\n";
2567 else
2568 outs() << "\n";
2569 outs() << " nsyms " << st.nsyms;
2570 uint64_t big_size;
2571 if (cputype & MachO::CPU_ARCH_ABI64) {
2572 big_size = st.nsyms;
2573 big_size *= sizeof(struct MachO::nlist_64);
2574 big_size += st.symoff;
2575 if (big_size > object_size)
2576 outs() << " (past end of file)\n";
2577 else
2578 outs() << "\n";
2579 } else {
2580 big_size = st.nsyms;
2581 big_size *= sizeof(struct MachO::nlist);
2582 big_size += st.symoff;
2583 if (big_size > object_size)
2584 outs() << " (past end of file)\n";
2585 else
2586 outs() << "\n";
2587 }
2588 outs() << " stroff " << st.stroff;
2589 if (st.stroff > object_size)
2590 outs() << " (past end of file)\n";
2591 else
2592 outs() << "\n";
2593 outs() << " strsize " << st.strsize;
2594 big_size = st.stroff;
2595 big_size += st.strsize;
2596 if (big_size > object_size)
2597 outs() << " (past end of file)\n";
2598 else
2599 outs() << "\n";
2600}
2601
2602static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
2603 uint32_t nsyms, uint32_t object_size,
2604 uint32_t cputype) {
2605 outs() << " cmd LC_DYSYMTAB\n";
2606 outs() << " cmdsize " << dyst.cmdsize;
2607 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
2608 outs() << " Incorrect size\n";
2609 else
2610 outs() << "\n";
2611 outs() << " ilocalsym " << dyst.ilocalsym;
2612 if (dyst.ilocalsym > nsyms)
2613 outs() << " (greater than the number of symbols)\n";
2614 else
2615 outs() << "\n";
2616 outs() << " nlocalsym " << dyst.nlocalsym;
2617 uint64_t big_size;
2618 big_size = dyst.ilocalsym;
2619 big_size += dyst.nlocalsym;
2620 if (big_size > nsyms)
2621 outs() << " (past the end of the symbol table)\n";
2622 else
2623 outs() << "\n";
2624 outs() << " iextdefsym " << dyst.iextdefsym;
2625 if (dyst.iextdefsym > nsyms)
2626 outs() << " (greater than the number of symbols)\n";
2627 else
2628 outs() << "\n";
2629 outs() << " nextdefsym " << dyst.nextdefsym;
2630 big_size = dyst.iextdefsym;
2631 big_size += dyst.nextdefsym;
2632 if (big_size > nsyms)
2633 outs() << " (past the end of the symbol table)\n";
2634 else
2635 outs() << "\n";
2636 outs() << " iundefsym " << dyst.iundefsym;
2637 if (dyst.iundefsym > nsyms)
2638 outs() << " (greater than the number of symbols)\n";
2639 else
2640 outs() << "\n";
2641 outs() << " nundefsym " << dyst.nundefsym;
2642 big_size = dyst.iundefsym;
2643 big_size += dyst.nundefsym;
2644 if (big_size > nsyms)
2645 outs() << " (past the end of the symbol table)\n";
2646 else
2647 outs() << "\n";
2648 outs() << " tocoff " << dyst.tocoff;
2649 if (dyst.tocoff > object_size)
2650 outs() << " (past end of file)\n";
2651 else
2652 outs() << "\n";
2653 outs() << " ntoc " << dyst.ntoc;
2654 big_size = dyst.ntoc;
2655 big_size *= sizeof(struct MachO::dylib_table_of_contents);
2656 big_size += dyst.tocoff;
2657 if (big_size > object_size)
2658 outs() << " (past end of file)\n";
2659 else
2660 outs() << "\n";
2661 outs() << " modtaboff " << dyst.modtaboff;
2662 if (dyst.modtaboff > object_size)
2663 outs() << " (past end of file)\n";
2664 else
2665 outs() << "\n";
2666 outs() << " nmodtab " << dyst.nmodtab;
2667 uint64_t modtabend;
2668 if (cputype & MachO::CPU_ARCH_ABI64) {
2669 modtabend = dyst.nmodtab;
2670 modtabend *= sizeof(struct MachO::dylib_module_64);
2671 modtabend += dyst.modtaboff;
2672 } else {
2673 modtabend = dyst.nmodtab;
2674 modtabend *= sizeof(struct MachO::dylib_module);
2675 modtabend += dyst.modtaboff;
2676 }
2677 if (modtabend > object_size)
2678 outs() << " (past end of file)\n";
2679 else
2680 outs() << "\n";
2681 outs() << " extrefsymoff " << dyst.extrefsymoff;
2682 if (dyst.extrefsymoff > object_size)
2683 outs() << " (past end of file)\n";
2684 else
2685 outs() << "\n";
2686 outs() << " nextrefsyms " << dyst.nextrefsyms;
2687 big_size = dyst.nextrefsyms;
2688 big_size *= sizeof(struct MachO::dylib_reference);
2689 big_size += dyst.extrefsymoff;
2690 if (big_size > object_size)
2691 outs() << " (past end of file)\n";
2692 else
2693 outs() << "\n";
2694 outs() << " indirectsymoff " << dyst.indirectsymoff;
2695 if (dyst.indirectsymoff > object_size)
2696 outs() << " (past end of file)\n";
2697 else
2698 outs() << "\n";
2699 outs() << " nindirectsyms " << dyst.nindirectsyms;
2700 big_size = dyst.nindirectsyms;
2701 big_size *= sizeof(uint32_t);
2702 big_size += dyst.indirectsymoff;
2703 if (big_size > object_size)
2704 outs() << " (past end of file)\n";
2705 else
2706 outs() << "\n";
2707 outs() << " extreloff " << dyst.extreloff;
2708 if (dyst.extreloff > object_size)
2709 outs() << " (past end of file)\n";
2710 else
2711 outs() << "\n";
2712 outs() << " nextrel " << dyst.nextrel;
2713 big_size = dyst.nextrel;
2714 big_size *= sizeof(struct MachO::relocation_info);
2715 big_size += dyst.extreloff;
2716 if (big_size > object_size)
2717 outs() << " (past end of file)\n";
2718 else
2719 outs() << "\n";
2720 outs() << " locreloff " << dyst.locreloff;
2721 if (dyst.locreloff > object_size)
2722 outs() << " (past end of file)\n";
2723 else
2724 outs() << "\n";
2725 outs() << " nlocrel " << dyst.nlocrel;
2726 big_size = dyst.nlocrel;
2727 big_size *= sizeof(struct MachO::relocation_info);
2728 big_size += dyst.locreloff;
2729 if (big_size > object_size)
2730 outs() << " (past end of file)\n";
2731 else
2732 outs() << "\n";
2733}
2734
Kevin Enderby8ae63c12014-09-04 16:54:47 +00002735static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
2736 uint32_t object_size) {
2737 if (dc.cmd == MachO::LC_DYLD_INFO)
2738 outs() << " cmd LC_DYLD_INFO\n";
2739 else
2740 outs() << " cmd LC_DYLD_INFO_ONLY\n";
2741 outs() << " cmdsize " << dc.cmdsize;
2742 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
2743 outs() << " Incorrect size\n";
2744 else
2745 outs() << "\n";
2746 outs() << " rebase_off " << dc.rebase_off;
2747 if (dc.rebase_off > object_size)
2748 outs() << " (past end of file)\n";
2749 else
2750 outs() << "\n";
2751 outs() << " rebase_size " << dc.rebase_size;
2752 uint64_t big_size;
2753 big_size = dc.rebase_off;
2754 big_size += dc.rebase_size;
2755 if (big_size > object_size)
2756 outs() << " (past end of file)\n";
2757 else
2758 outs() << "\n";
2759 outs() << " bind_off " << dc.bind_off;
2760 if (dc.bind_off > object_size)
2761 outs() << " (past end of file)\n";
2762 else
2763 outs() << "\n";
2764 outs() << " bind_size " << dc.bind_size;
2765 big_size = dc.bind_off;
2766 big_size += dc.bind_size;
2767 if (big_size > object_size)
2768 outs() << " (past end of file)\n";
2769 else
2770 outs() << "\n";
2771 outs() << " weak_bind_off " << dc.weak_bind_off;
2772 if (dc.weak_bind_off > object_size)
2773 outs() << " (past end of file)\n";
2774 else
2775 outs() << "\n";
2776 outs() << " weak_bind_size " << dc.weak_bind_size;
2777 big_size = dc.weak_bind_off;
2778 big_size += dc.weak_bind_size;
2779 if (big_size > object_size)
2780 outs() << " (past end of file)\n";
2781 else
2782 outs() << "\n";
2783 outs() << " lazy_bind_off " << dc.lazy_bind_off;
2784 if (dc.lazy_bind_off > object_size)
2785 outs() << " (past end of file)\n";
2786 else
2787 outs() << "\n";
2788 outs() << " lazy_bind_size " << dc.lazy_bind_size;
2789 big_size = dc.lazy_bind_off;
2790 big_size += dc.lazy_bind_size;
2791 if (big_size > object_size)
2792 outs() << " (past end of file)\n";
2793 else
2794 outs() << "\n";
2795 outs() << " export_off " << dc.export_off;
2796 if (dc.export_off > object_size)
2797 outs() << " (past end of file)\n";
2798 else
2799 outs() << "\n";
2800 outs() << " export_size " << dc.export_size;
2801 big_size = dc.export_off;
2802 big_size += dc.export_size;
2803 if (big_size > object_size)
2804 outs() << " (past end of file)\n";
2805 else
2806 outs() << "\n";
2807}
2808
2809static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
2810 const char *Ptr) {
2811 if (dyld.cmd == MachO::LC_ID_DYLINKER)
2812 outs() << " cmd LC_ID_DYLINKER\n";
2813 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
2814 outs() << " cmd LC_LOAD_DYLINKER\n";
2815 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
2816 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
2817 else
2818 outs() << " cmd ?(" << dyld.cmd << ")\n";
2819 outs() << " cmdsize " << dyld.cmdsize;
2820 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
2821 outs() << " Incorrect size\n";
2822 else
2823 outs() << "\n";
2824 if (dyld.name >= dyld.cmdsize)
2825 outs() << " name ?(bad offset " << dyld.name << ")\n";
2826 else {
2827 const char *P = (const char *)(Ptr)+dyld.name;
2828 outs() << " name " << P << " (offset " << dyld.name << ")\n";
2829 }
2830}
2831
2832static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
2833 outs() << " cmd LC_UUID\n";
2834 outs() << " cmdsize " << uuid.cmdsize;
2835 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
2836 outs() << " Incorrect size\n";
2837 else
2838 outs() << "\n";
2839 outs() << " uuid ";
2840 outs() << format("%02" PRIX32, uuid.uuid[0]);
2841 outs() << format("%02" PRIX32, uuid.uuid[1]);
2842 outs() << format("%02" PRIX32, uuid.uuid[2]);
2843 outs() << format("%02" PRIX32, uuid.uuid[3]);
2844 outs() << "-";
2845 outs() << format("%02" PRIX32, uuid.uuid[4]);
2846 outs() << format("%02" PRIX32, uuid.uuid[5]);
2847 outs() << "-";
2848 outs() << format("%02" PRIX32, uuid.uuid[6]);
2849 outs() << format("%02" PRIX32, uuid.uuid[7]);
2850 outs() << "-";
2851 outs() << format("%02" PRIX32, uuid.uuid[8]);
2852 outs() << format("%02" PRIX32, uuid.uuid[9]);
2853 outs() << "-";
2854 outs() << format("%02" PRIX32, uuid.uuid[10]);
2855 outs() << format("%02" PRIX32, uuid.uuid[11]);
2856 outs() << format("%02" PRIX32, uuid.uuid[12]);
2857 outs() << format("%02" PRIX32, uuid.uuid[13]);
2858 outs() << format("%02" PRIX32, uuid.uuid[14]);
2859 outs() << format("%02" PRIX32, uuid.uuid[15]);
2860 outs() << "\n";
2861}
2862
2863static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
2864 if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
2865 outs() << " cmd LC_VERSION_MIN_MACOSX\n";
2866 else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
2867 outs() << " cmd LC_VERSION_MIN_IPHONEOS\n";
2868 else
2869 outs() << " cmd " << vd.cmd << " (?)\n";
2870 outs() << " cmdsize " << vd.cmdsize;
2871 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
2872 outs() << " Incorrect size\n";
2873 else
2874 outs() << "\n";
2875 outs() << " version " << ((vd.version >> 16) & 0xffff) << "."
2876 << ((vd.version >> 8) & 0xff);
2877 if ((vd.version & 0xff) != 0)
2878 outs() << "." << (vd.version & 0xff);
2879 outs() << "\n";
2880 if (vd.sdk == 0)
2881 outs() << " sdk n/a\n";
2882 else {
2883 outs() << " sdk " << ((vd.sdk >> 16) & 0xffff) << "."
2884 << ((vd.sdk >> 8) & 0xff);
2885 }
2886 if ((vd.sdk & 0xff) != 0)
2887 outs() << "." << (vd.sdk & 0xff);
2888 outs() << "\n";
2889}
2890
2891static void PrintSourceVersionCommand(MachO::source_version_command sd) {
2892 outs() << " cmd LC_SOURCE_VERSION\n";
2893 outs() << " cmdsize " << sd.cmdsize;
2894 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
2895 outs() << " Incorrect size\n";
2896 else
2897 outs() << "\n";
2898 uint64_t a = (sd.version >> 40) & 0xffffff;
2899 uint64_t b = (sd.version >> 30) & 0x3ff;
2900 uint64_t c = (sd.version >> 20) & 0x3ff;
2901 uint64_t d = (sd.version >> 10) & 0x3ff;
2902 uint64_t e = sd.version & 0x3ff;
2903 outs() << " version " << a << "." << b;
2904 if (e != 0)
2905 outs() << "." << c << "." << d << "." << e;
2906 else if (d != 0)
2907 outs() << "." << c << "." << d;
2908 else if (c != 0)
2909 outs() << "." << c;
2910 outs() << "\n";
2911}
2912
2913static void PrintEntryPointCommand(MachO::entry_point_command ep) {
2914 outs() << " cmd LC_MAIN\n";
2915 outs() << " cmdsize " << ep.cmdsize;
2916 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
2917 outs() << " Incorrect size\n";
2918 else
2919 outs() << "\n";
2920 outs() << " entryoff " << ep.entryoff << "\n";
2921 outs() << " stacksize " << ep.stacksize << "\n";
2922}
2923
2924static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
2925 if (dl.cmd == MachO::LC_ID_DYLIB)
2926 outs() << " cmd LC_ID_DYLIB\n";
2927 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
2928 outs() << " cmd LC_LOAD_DYLIB\n";
2929 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
2930 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
2931 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
2932 outs() << " cmd LC_REEXPORT_DYLIB\n";
2933 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
2934 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
2935 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
2936 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
2937 else
2938 outs() << " cmd " << dl.cmd << " (unknown)\n";
2939 outs() << " cmdsize " << dl.cmdsize;
2940 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
2941 outs() << " Incorrect size\n";
2942 else
2943 outs() << "\n";
2944 if (dl.dylib.name < dl.cmdsize) {
2945 const char *P = (const char *)(Ptr)+dl.dylib.name;
2946 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
2947 } else {
2948 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
2949 }
2950 outs() << " time stamp " << dl.dylib.timestamp << " ";
2951 time_t t = dl.dylib.timestamp;
2952 outs() << ctime(&t);
2953 outs() << " current version ";
2954 if (dl.dylib.current_version == 0xffffffff)
2955 outs() << "n/a\n";
2956 else
2957 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
2958 << ((dl.dylib.current_version >> 8) & 0xff) << "."
2959 << (dl.dylib.current_version & 0xff) << "\n";
2960 outs() << "compatibility version ";
2961 if (dl.dylib.compatibility_version == 0xffffffff)
2962 outs() << "n/a\n";
2963 else
2964 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
2965 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
2966 << (dl.dylib.compatibility_version & 0xff) << "\n";
2967}
2968
2969static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
2970 uint32_t object_size) {
2971 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
2972 outs() << " cmd LC_FUNCTION_STARTS\n";
2973 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
2974 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
2975 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
2976 outs() << " cmd LC_FUNCTION_STARTS\n";
2977 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
2978 outs() << " cmd LC_DATA_IN_CODE\n";
2979 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
2980 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
2981 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
2982 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
2983 else
2984 outs() << " cmd " << ld.cmd << " (?)\n";
2985 outs() << " cmdsize " << ld.cmdsize;
2986 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
2987 outs() << " Incorrect size\n";
2988 else
2989 outs() << "\n";
2990 outs() << " dataoff " << ld.dataoff;
2991 if (ld.dataoff > object_size)
2992 outs() << " (past end of file)\n";
2993 else
2994 outs() << "\n";
2995 outs() << " datasize " << ld.datasize;
2996 uint64_t big_size = ld.dataoff;
2997 big_size += ld.datasize;
2998 if (big_size > object_size)
2999 outs() << " (past end of file)\n";
3000 else
3001 outs() << "\n";
3002}
3003
Kevin Enderby956366c2014-08-29 22:30:52 +00003004static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
3005 uint32_t filetype, uint32_t cputype,
3006 bool verbose) {
3007 StringRef Buf = Obj->getData();
3008 MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
3009 for (unsigned i = 0;; ++i) {
3010 outs() << "Load command " << i << "\n";
3011 if (Command.C.cmd == MachO::LC_SEGMENT) {
3012 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
3013 const char *sg_segname = SLC.segname;
3014 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
3015 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
3016 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
3017 verbose);
3018 for (unsigned j = 0; j < SLC.nsects; j++) {
3019 MachO::section_64 S = Obj->getSection64(Command, j);
3020 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
3021 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
3022 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
3023 }
3024 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3025 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
3026 const char *sg_segname = SLC_64.segname;
3027 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
3028 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
3029 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
3030 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
3031 for (unsigned j = 0; j < SLC_64.nsects; j++) {
3032 MachO::section_64 S_64 = Obj->getSection64(Command, j);
3033 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
3034 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
3035 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
3036 sg_segname, filetype, Buf.size(), verbose);
3037 }
3038 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
3039 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3040 PrintSymtabLoadCommand(Symtab, cputype, Buf.size());
3041 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
3042 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
3043 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3044 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), cputype);
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003045 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
3046 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
3047 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
3048 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
3049 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
3050 Command.C.cmd == MachO::LC_ID_DYLINKER ||
3051 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
3052 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
3053 PrintDyldLoadCommand(Dyld, Command.Ptr);
3054 } else if (Command.C.cmd == MachO::LC_UUID) {
3055 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
3056 PrintUuidLoadCommand(Uuid);
3057 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
3058 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
3059 PrintVersionMinLoadCommand(Vd);
3060 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
3061 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
3062 PrintSourceVersionCommand(Sd);
3063 } else if (Command.C.cmd == MachO::LC_MAIN) {
3064 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
3065 PrintEntryPointCommand(Ep);
Nick Kledzik15558912014-10-16 18:58:20 +00003066 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
3067 Command.C.cmd == MachO::LC_ID_DYLIB ||
3068 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
3069 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
3070 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
3071 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
Kevin Enderby8ae63c12014-09-04 16:54:47 +00003072 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
3073 PrintDylibCommand(Dl, Command.Ptr);
3074 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
3075 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
3076 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
3077 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
3078 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
3079 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
3080 MachO::linkedit_data_command Ld =
3081 Obj->getLinkeditDataLoadCommand(Command);
3082 PrintLinkEditDataCommand(Ld, Buf.size());
Kevin Enderby956366c2014-08-29 22:30:52 +00003083 } else {
3084 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
3085 << ")\n";
3086 outs() << " cmdsize " << Command.C.cmdsize << "\n";
3087 // TODO: get and print the raw bytes of the load command.
3088 }
3089 // TODO: print all the other kinds of load commands.
3090 if (i == ncmds - 1)
3091 break;
3092 else
3093 Command = Obj->getNextLoadCommandInfo(Command);
3094 }
3095}
3096
3097static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
3098 uint32_t &filetype, uint32_t &cputype,
3099 bool verbose) {
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003100 if (Obj->is64Bit()) {
3101 MachO::mach_header_64 H_64;
3102 H_64 = Obj->getHeader64();
3103 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
3104 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00003105 ncmds = H_64.ncmds;
3106 filetype = H_64.filetype;
3107 cputype = H_64.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003108 } else {
3109 MachO::mach_header H;
3110 H = Obj->getHeader();
3111 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
3112 H.sizeofcmds, H.flags, verbose);
Kevin Enderby956366c2014-08-29 22:30:52 +00003113 ncmds = H.ncmds;
3114 filetype = H.filetype;
3115 cputype = H.cputype;
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003116 }
3117}
3118
3119void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
3120 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
Kevin Enderby956366c2014-08-29 22:30:52 +00003121 uint32_t ncmds = 0;
3122 uint32_t filetype = 0;
3123 uint32_t cputype = 0;
3124 getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
3125 PrintLoadCommands(file, ncmds, filetype, cputype, true);
Kevin Enderbyb76d3862014-08-22 20:35:18 +00003126}
Nick Kledzikd04bc352014-08-30 00:20:14 +00003127
3128//===----------------------------------------------------------------------===//
3129// export trie dumping
3130//===----------------------------------------------------------------------===//
3131
3132void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003133 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
3134 uint64_t Flags = Entry.flags();
Nick Kledzikd04bc352014-08-30 00:20:14 +00003135 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
3136 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
3137 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3138 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
3139 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3140 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
3141 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
3142 if (ReExport)
3143 outs() << "[re-export] ";
3144 else
3145 outs()
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003146 << format("0x%08llX ", Entry.address()); // FIXME:add in base address
3147 outs() << Entry.name();
Nick Kledzikd04bc352014-08-30 00:20:14 +00003148 if (WeakDef || ThreadLocal || Resolver || Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003149 bool NeedsComma = false;
Nick Kledzik1d1ac4b2014-09-03 01:12:52 +00003150 outs() << " [";
Nick Kledzikd04bc352014-08-30 00:20:14 +00003151 if (WeakDef) {
3152 outs() << "weak_def";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003153 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003154 }
3155 if (ThreadLocal) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003156 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003157 outs() << ", ";
3158 outs() << "per-thread";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003159 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003160 }
3161 if (Abs) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003162 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003163 outs() << ", ";
3164 outs() << "absolute";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003165 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003166 }
3167 if (Resolver) {
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003168 if (NeedsComma)
Nick Kledzikd04bc352014-08-30 00:20:14 +00003169 outs() << ", ";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003170 outs() << format("resolver=0x%08llX", Entry.other());
3171 NeedsComma = true;
Nick Kledzikd04bc352014-08-30 00:20:14 +00003172 }
3173 outs() << "]";
3174 }
3175 if (ReExport) {
3176 StringRef DylibName = "unknown";
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003177 int Ordinal = Entry.other() - 1;
3178 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
3179 if (Entry.otherName().empty())
Nick Kledzikd04bc352014-08-30 00:20:14 +00003180 outs() << " (from " << DylibName << ")";
3181 else
Nick Kledzikac7cbdc2014-09-02 18:50:24 +00003182 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
Nick Kledzikd04bc352014-08-30 00:20:14 +00003183 }
3184 outs() << "\n";
3185 }
3186}
Nick Kledzikac431442014-09-12 21:34:15 +00003187
3188
3189//===----------------------------------------------------------------------===//
3190// rebase table dumping
3191//===----------------------------------------------------------------------===//
3192
3193namespace {
3194class SegInfo {
3195public:
3196 SegInfo(const object::MachOObjectFile *Obj);
3197
3198 StringRef segmentName(uint32_t SegIndex);
3199 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
3200 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
3201
3202private:
3203 struct SectionInfo {
3204 uint64_t Address;
3205 uint64_t Size;
3206 StringRef SectionName;
3207 StringRef SegmentName;
3208 uint64_t OffsetInSegment;
3209 uint64_t SegmentStartAddress;
3210 uint32_t SegmentIndex;
3211 };
3212 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
3213 SmallVector<SectionInfo, 32> Sections;
3214};
3215}
3216
3217SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
3218 // Build table of sections so segIndex/offset pairs can be translated.
Nick Kledzik56ebef42014-09-16 01:41:51 +00003219 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
Nick Kledzikac431442014-09-12 21:34:15 +00003220 StringRef CurSegName;
3221 uint64_t CurSegAddress;
3222 for (const SectionRef &Section : Obj->sections()) {
3223 SectionInfo Info;
3224 if (error(Section.getName(Info.SectionName)))
3225 return;
Rafael Espindola80291272014-10-08 15:28:58 +00003226 Info.Address = Section.getAddress();
3227 Info.Size = Section.getSize();
Nick Kledzikac431442014-09-12 21:34:15 +00003228 Info.SegmentName =
3229 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3230 if (!Info.SegmentName.equals(CurSegName)) {
3231 ++CurSegIndex;
3232 CurSegName = Info.SegmentName;
3233 CurSegAddress = Info.Address;
3234 }
3235 Info.SegmentIndex = CurSegIndex - 1;
3236 Info.OffsetInSegment = Info.Address - CurSegAddress;
3237 Info.SegmentStartAddress = CurSegAddress;
3238 Sections.push_back(Info);
3239 }
3240}
3241
3242StringRef SegInfo::segmentName(uint32_t SegIndex) {
3243 for (const SectionInfo &SI : Sections) {
3244 if (SI.SegmentIndex == SegIndex)
3245 return SI.SegmentName;
3246 }
3247 llvm_unreachable("invalid segIndex");
3248}
3249
3250const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
3251 uint64_t OffsetInSeg) {
3252 for (const SectionInfo &SI : Sections) {
3253 if (SI.SegmentIndex != SegIndex)
3254 continue;
3255 if (SI.OffsetInSegment > OffsetInSeg)
3256 continue;
3257 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
3258 continue;
3259 return SI;
3260 }
3261 llvm_unreachable("segIndex and offset not in any section");
3262}
3263
3264StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
3265 return findSection(SegIndex, OffsetInSeg).SectionName;
3266}
3267
3268uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3269 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3270 return SI.SegmentStartAddress + OffsetInSeg;
3271}
3272
3273void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
3274 // Build table of sections so names can used in final output.
3275 SegInfo sectionTable(Obj);
3276
3277 outs() << "segment section address type\n";
3278 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
3279 uint32_t SegIndex = Entry.segmentIndex();
3280 uint64_t OffsetInSeg = Entry.segmentOffset();
3281 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3282 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3283 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3284
3285 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
Nick Kledzik3df5fb82014-09-13 00:18:40 +00003286 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
3287 SegmentName.str().c_str(),
Nick Kledzikac431442014-09-12 21:34:15 +00003288 SectionName.str().c_str(), Address,
3289 Entry.typeName().str().c_str());
3290 }
3291}
Nick Kledzik56ebef42014-09-16 01:41:51 +00003292
3293static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
3294 StringRef DylibName;
3295 switch (Ordinal) {
3296 case MachO::BIND_SPECIAL_DYLIB_SELF:
3297 return "this-image";
3298 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
3299 return "main-executable";
3300 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
3301 return "flat-namespace";
3302 default:
Nick Kledzikabd29872014-09-16 22:03:13 +00003303 if (Ordinal > 0) {
3304 std::error_code EC = Obj->getLibraryShortNameByIndex(Ordinal-1,
3305 DylibName);
3306 if (EC)
Nick Kledzik51d2c2b2014-10-14 23:29:38 +00003307 return "<<bad library ordinal>>";
Nick Kledzikabd29872014-09-16 22:03:13 +00003308 return DylibName;
3309 }
Nick Kledzik56ebef42014-09-16 01:41:51 +00003310 }
Nick Kledzikabd29872014-09-16 22:03:13 +00003311 return "<<unknown special ordinal>>";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003312}
3313
3314//===----------------------------------------------------------------------===//
3315// bind table dumping
3316//===----------------------------------------------------------------------===//
3317
3318void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
3319 // Build table of sections so names can used in final output.
3320 SegInfo sectionTable(Obj);
3321
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003322 outs() << "segment section address type "
3323 "addend dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003324 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
3325 uint32_t SegIndex = Entry.segmentIndex();
3326 uint64_t OffsetInSeg = Entry.segmentOffset();
3327 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3328 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3329 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3330
3331 // Table lines look like:
3332 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003333 StringRef Attr;
Nick Kledzik56ebef42014-09-16 01:41:51 +00003334 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003335 Attr = " (weak_import)";
3336 outs() << left_justify(SegmentName, 8) << " "
3337 << left_justify(SectionName, 18) << " "
3338 << format_hex(Address, 10, true) << " "
3339 << left_justify(Entry.typeName(), 8) << " "
3340 << format_decimal(Entry.addend(), 8) << " "
3341 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3342 << Entry.symbolName()
3343 << Attr << "\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003344 }
3345}
3346
3347//===----------------------------------------------------------------------===//
3348// lazy bind table dumping
3349//===----------------------------------------------------------------------===//
3350
3351void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
3352 // Build table of sections so names can used in final output.
3353 SegInfo sectionTable(Obj);
3354
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003355 outs() << "segment section address "
3356 "dylib symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003357 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
3358 uint32_t SegIndex = Entry.segmentIndex();
3359 uint64_t OffsetInSeg = Entry.segmentOffset();
3360 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3361 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3362 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3363
3364 // Table lines look like:
3365 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003366 outs() << left_justify(SegmentName, 8) << " "
3367 << left_justify(SectionName, 18) << " "
3368 << format_hex(Address, 10, true) << " "
3369 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00003370 << Entry.symbolName() << "\n";
3371 }
3372}
3373
3374
3375//===----------------------------------------------------------------------===//
3376// weak bind table dumping
3377//===----------------------------------------------------------------------===//
3378
3379void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
3380 // Build table of sections so names can used in final output.
3381 SegInfo sectionTable(Obj);
3382
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003383 outs() << "segment section address "
3384 "type addend symbol\n";
Nick Kledzik56ebef42014-09-16 01:41:51 +00003385 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
3386 // Strong symbols don't have a location to update.
3387 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003388 outs() << " strong "
Nick Kledzik56ebef42014-09-16 01:41:51 +00003389 << Entry.symbolName() << "\n";
3390 continue;
3391 }
3392 uint32_t SegIndex = Entry.segmentIndex();
3393 uint64_t OffsetInSeg = Entry.segmentOffset();
3394 StringRef SegmentName = sectionTable.segmentName(SegIndex);
3395 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3396 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3397
3398 // Table lines look like:
3399 // __DATA __data 0x00001000 pointer 0 _foo
Nick Kledzik5ffacc12014-09-30 00:19:58 +00003400 outs() << left_justify(SegmentName, 8) << " "
3401 << left_justify(SectionName, 18) << " "
3402 << format_hex(Address, 10, true) << " "
3403 << left_justify(Entry.typeName(), 8) << " "
3404 << format_decimal(Entry.addend(), 8) << " "
Nick Kledzik56ebef42014-09-16 01:41:51 +00003405 << Entry.symbolName() << "\n";
3406 }
3407}
3408
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003409// get_dyld_bind_info_symbolname() is used for disassembly and passed an
3410// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
3411// information for that address. If the address is found its binding symbol
3412// name is returned. If not nullptr is returned.
3413static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3414 struct DisassembleInfo *info) {
Kevin Enderby078be602014-10-23 19:53:12 +00003415 if (info->bindtable == nullptr) {
3416 info->bindtable = new (BindTable);
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003417 SegInfo sectionTable(info->O);
3418 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
3419 uint32_t SegIndex = Entry.segmentIndex();
3420 uint64_t OffsetInSeg = Entry.segmentOffset();
3421 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3422 const char *SymbolName = nullptr;
3423 StringRef name = Entry.symbolName();
3424 if (!name.empty())
3425 SymbolName = name.data();
Kevin Enderby078be602014-10-23 19:53:12 +00003426 info->bindtable->push_back(std::make_pair(Address, SymbolName));
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003427 }
3428 }
Kevin Enderby078be602014-10-23 19:53:12 +00003429 for (bind_table_iterator BI = info->bindtable->begin(),
3430 BE = info->bindtable->end();
Kevin Enderby6f326ce2014-10-23 19:37:31 +00003431 BI != BE; ++BI) {
3432 uint64_t Address = BI->first;
3433 if (ReferenceValue == Address) {
3434 const char *SymbolName = BI->second;
3435 return SymbolName;
3436 }
3437 }
3438 return nullptr;
3439}