Add the code and test cases for 64-bit ARM to llvm-objdump’s Mach-O symbolizer.
[oota-llvm.git] / tools / llvm-objdump / MachODump.cpp
1 //===-- 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"
15 #include "llvm-c/Disassembler.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Config/config.h"
20 #include "llvm/DebugInfo/DIContext.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCContext.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstPrinter.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCRegisterInfo.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Object/MachO.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/Endian.h"
35 #include "llvm/Support/Format.h"
36 #include "llvm/Support/GraphWriter.h"
37 #include "llvm/Support/MachO.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/FormattedStream.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <algorithm>
44 #include <cstring>
45 #include <system_error>
46
47 #if HAVE_CXXABI_H
48 #include <cxxabi.h>
49 #endif
50
51 using namespace llvm;
52 using namespace object;
53
54 static cl::opt<bool>
55     UseDbg("g",
56            cl::desc("Print line information from debug info if available"));
57
58 static cl::opt<std::string> DSYMFile("dsym",
59                                      cl::desc("Use .dSYM file for debug info"));
60
61 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
62                                      cl::desc("Print full leading address"));
63
64 static cl::opt<bool>
65     PrintImmHex("print-imm-hex",
66                 cl::desc("Use hex format for immediate values"));
67
68 static std::string ThumbTripleName;
69
70 static const Target *GetTarget(const MachOObjectFile *MachOObj,
71                                const char **McpuDefault,
72                                const Target **ThumbTarget) {
73   // Figure out the target triple.
74   if (TripleName.empty()) {
75     llvm::Triple TT("unknown-unknown-unknown");
76     llvm::Triple ThumbTriple = Triple();
77     TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
78     TripleName = TT.str();
79     ThumbTripleName = ThumbTriple.str();
80   }
81
82   // Get the target specific parser.
83   std::string Error;
84   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
85   if (TheTarget && ThumbTripleName.empty())
86     return TheTarget;
87
88   *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
89   if (*ThumbTarget)
90     return TheTarget;
91
92   errs() << "llvm-objdump: error: unable to get target for '";
93   if (!TheTarget)
94     errs() << TripleName;
95   else
96     errs() << ThumbTripleName;
97   errs() << "', see --version and --triple.\n";
98   return nullptr;
99 }
100
101 struct SymbolSorter {
102   bool operator()(const SymbolRef &A, const SymbolRef &B) {
103     SymbolRef::Type AType, BType;
104     A.getType(AType);
105     B.getType(BType);
106
107     uint64_t AAddr, BAddr;
108     if (AType != SymbolRef::ST_Function)
109       AAddr = 0;
110     else
111       A.getAddress(AAddr);
112     if (BType != SymbolRef::ST_Function)
113       BAddr = 0;
114     else
115       B.getAddress(BAddr);
116     return AAddr < BAddr;
117   }
118 };
119
120 // Types for the storted data in code table that is built before disassembly
121 // and the predicate function to sort them.
122 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
123 typedef std::vector<DiceTableEntry> DiceTable;
124 typedef DiceTable::iterator dice_table_iterator;
125
126 // This is used to search for a data in code table entry for the PC being
127 // disassembled.  The j parameter has the PC in j.first.  A single data in code
128 // table entry can cover many bytes for each of its Kind's.  So if the offset,
129 // aka the i.first value, of the data in code table entry plus its Length
130 // covers the PC being searched for this will return true.  If not it will
131 // return false.
132 static bool compareDiceTableEntries(const DiceTableEntry &i,
133                                     const DiceTableEntry &j) {
134   uint16_t Length;
135   i.second.getLength(Length);
136
137   return j.first >= i.first && j.first < i.first + Length;
138 }
139
140 static uint64_t DumpDataInCode(const char *bytes, uint64_t Length,
141                                unsigned short Kind) {
142   uint32_t Value, Size = 1;
143
144   switch (Kind) {
145   default:
146   case MachO::DICE_KIND_DATA:
147     if (Length >= 4) {
148       if (!NoShowRawInsn)
149         DumpBytes(StringRef(bytes, 4));
150       Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
151       outs() << "\t.long " << Value;
152       Size = 4;
153     } else if (Length >= 2) {
154       if (!NoShowRawInsn)
155         DumpBytes(StringRef(bytes, 2));
156       Value = bytes[1] << 8 | bytes[0];
157       outs() << "\t.short " << Value;
158       Size = 2;
159     } else {
160       if (!NoShowRawInsn)
161         DumpBytes(StringRef(bytes, 2));
162       Value = bytes[0];
163       outs() << "\t.byte " << Value;
164       Size = 1;
165     }
166     if (Kind == MachO::DICE_KIND_DATA)
167       outs() << "\t@ KIND_DATA\n";
168     else
169       outs() << "\t@ data in code kind = " << Kind << "\n";
170     break;
171   case MachO::DICE_KIND_JUMP_TABLE8:
172     if (!NoShowRawInsn)
173       DumpBytes(StringRef(bytes, 1));
174     Value = bytes[0];
175     outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
176     Size = 1;
177     break;
178   case MachO::DICE_KIND_JUMP_TABLE16:
179     if (!NoShowRawInsn)
180       DumpBytes(StringRef(bytes, 2));
181     Value = bytes[1] << 8 | bytes[0];
182     outs() << "\t.short " << format("%5u", Value & 0xffff)
183            << "\t@ KIND_JUMP_TABLE16\n";
184     Size = 2;
185     break;
186   case MachO::DICE_KIND_JUMP_TABLE32:
187   case MachO::DICE_KIND_ABS_JUMP_TABLE32:
188     if (!NoShowRawInsn)
189       DumpBytes(StringRef(bytes, 4));
190     Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
191     outs() << "\t.long " << Value;
192     if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
193       outs() << "\t@ KIND_JUMP_TABLE32\n";
194     else
195       outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
196     Size = 4;
197     break;
198   }
199   return Size;
200 }
201
202 static void getSectionsAndSymbols(const MachO::mach_header Header,
203                                   MachOObjectFile *MachOObj,
204                                   std::vector<SectionRef> &Sections,
205                                   std::vector<SymbolRef> &Symbols,
206                                   SmallVectorImpl<uint64_t> &FoundFns,
207                                   uint64_t &BaseSegmentAddress) {
208   for (const SymbolRef &Symbol : MachOObj->symbols())
209     Symbols.push_back(Symbol);
210
211   for (const SectionRef &Section : MachOObj->sections()) {
212     StringRef SectName;
213     Section.getName(SectName);
214     Sections.push_back(Section);
215   }
216
217   MachOObjectFile::LoadCommandInfo Command =
218       MachOObj->getFirstLoadCommandInfo();
219   bool BaseSegmentAddressSet = false;
220   for (unsigned i = 0;; ++i) {
221     if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
222       // We found a function starts segment, parse the addresses for later
223       // consumption.
224       MachO::linkedit_data_command LLC =
225           MachOObj->getLinkeditDataLoadCommand(Command);
226
227       MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
228     } else if (Command.C.cmd == MachO::LC_SEGMENT) {
229       MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
230       StringRef SegName = SLC.segname;
231       if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
232         BaseSegmentAddressSet = true;
233         BaseSegmentAddress = SLC.vmaddr;
234       }
235     }
236
237     if (i == Header.ncmds - 1)
238       break;
239     else
240       Command = MachOObj->getNextLoadCommandInfo(Command);
241   }
242 }
243
244 static void DisassembleInputMachO2(StringRef Filename,
245                                    MachOObjectFile *MachOOF);
246
247 void llvm::DisassembleInputMachO(StringRef Filename) {
248   ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
249       MemoryBuffer::getFileOrSTDIN(Filename);
250   if (std::error_code EC = BuffOrErr.getError()) {
251     errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
252     return;
253   }
254   std::unique_ptr<MemoryBuffer> Buff = std::move(BuffOrErr.get());
255
256   std::unique_ptr<MachOObjectFile> MachOOF = std::move(
257       ObjectFile::createMachOObjectFile(Buff.get()->getMemBufferRef()).get());
258
259   DisassembleInputMachO2(Filename, MachOOF.get());
260 }
261
262 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
263 typedef std::pair<uint64_t, const char *> BindInfoEntry;
264 typedef std::vector<BindInfoEntry> BindTable;
265 typedef BindTable::iterator bind_table_iterator;
266
267 // The block of info used by the Symbolizer call backs.
268 struct DisassembleInfo {
269   bool verbose;
270   MachOObjectFile *O;
271   SectionRef S;
272   SymbolAddressMap *AddrMap;
273   std::vector<SectionRef> *Sections;
274   const char *class_name;
275   const char *selector_name;
276   char *method;
277   char *demangled_name;
278   uint64_t adrp_addr;
279   uint32_t adrp_inst;
280   BindTable *bindtable;
281 };
282
283 // GuessSymbolName is passed the address of what might be a symbol and a
284 // pointer to the DisassembleInfo struct.  It returns the name of a symbol
285 // with that address or nullptr if no symbol is found with that address.
286 static const char *GuessSymbolName(uint64_t value,
287                                    struct DisassembleInfo *info) {
288   const char *SymbolName = nullptr;
289   // A DenseMap can't lookup up some values.
290   if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
291     StringRef name = info->AddrMap->lookup(value);
292     if (!name.empty())
293       SymbolName = name.data();
294   }
295   return SymbolName;
296 }
297
298 // SymbolizerGetOpInfo() is the operand information call back function.
299 // This is called to get the symbolic information for operand(s) of an
300 // instruction when it is being done.  This routine does this from
301 // the relocation information, symbol table, etc. That block of information
302 // is a pointer to the struct DisassembleInfo that was passed when the
303 // disassembler context was created and passed to back to here when
304 // called back by the disassembler for instruction operands that could have
305 // relocation information. The address of the instruction containing operand is
306 // at the Pc parameter.  The immediate value the operand has is passed in
307 // op_info->Value and is at Offset past the start of the instruction and has a
308 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
309 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
310 // names and addends of the symbolic expression to add for the operand.  The
311 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
312 // information is returned then this function returns 1 else it returns 0.
313 int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
314                         uint64_t Size, int TagType, void *TagBuf) {
315   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
316   struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
317   uint64_t value = op_info->Value;
318
319   // Make sure all fields returned are zero if we don't set them.
320   memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
321   op_info->Value = value;
322
323   // If the TagType is not the value 1 which it code knows about or if no
324   // verbose symbolic information is wanted then just return 0, indicating no
325   // information is being returned.
326   if (TagType != 1 || info->verbose == false)
327     return 0;
328
329   unsigned int Arch = info->O->getArch();
330   if (Arch == Triple::x86) {
331     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
332       return 0;
333     // First search the section's relocation entries (if any) for an entry
334     // for this section offset.
335     uint32_t sect_addr = info->S.getAddress();
336     uint32_t sect_offset = (Pc + Offset) - sect_addr;
337     bool reloc_found = false;
338     DataRefImpl Rel;
339     MachO::any_relocation_info RE;
340     bool isExtern = false;
341     SymbolRef Symbol;
342     bool r_scattered = false;
343     uint32_t r_value, pair_r_value, r_type;
344     for (const RelocationRef &Reloc : info->S.relocations()) {
345       uint64_t RelocOffset;
346       Reloc.getOffset(RelocOffset);
347       if (RelocOffset == sect_offset) {
348         Rel = Reloc.getRawDataRefImpl();
349         RE = info->O->getRelocation(Rel);
350         r_type = info->O->getAnyRelocationType(RE);
351         r_scattered = info->O->isRelocationScattered(RE);
352         if (r_scattered) {
353           r_value = info->O->getScatteredRelocationValue(RE);
354           if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
355               r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
356             DataRefImpl RelNext = Rel;
357             info->O->moveRelocationNext(RelNext);
358             MachO::any_relocation_info RENext;
359             RENext = info->O->getRelocation(RelNext);
360             if (info->O->isRelocationScattered(RENext))
361               pair_r_value = info->O->getScatteredRelocationValue(RENext);
362             else
363               return 0;
364           }
365         } else {
366           isExtern = info->O->getPlainRelocationExternal(RE);
367           if (isExtern) {
368             symbol_iterator RelocSym = Reloc.getSymbol();
369             Symbol = *RelocSym;
370           }
371         }
372         reloc_found = true;
373         break;
374       }
375     }
376     if (reloc_found && isExtern) {
377       StringRef SymName;
378       Symbol.getName(SymName);
379       const char *name = SymName.data();
380       op_info->AddSymbol.Present = 1;
381       op_info->AddSymbol.Name = name;
382       // For i386 extern relocation entries the value in the instruction is
383       // the offset from the symbol, and value is already set in op_info->Value.
384       return 1;
385     }
386     if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
387                         r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
388       const char *add = GuessSymbolName(r_value, info);
389       const char *sub = GuessSymbolName(pair_r_value, info);
390       uint32_t offset = value - (r_value - pair_r_value);
391       op_info->AddSymbol.Present = 1;
392       if (add != nullptr)
393         op_info->AddSymbol.Name = add;
394       else
395         op_info->AddSymbol.Value = r_value;
396       op_info->SubtractSymbol.Present = 1;
397       if (sub != nullptr)
398         op_info->SubtractSymbol.Name = sub;
399       else
400         op_info->SubtractSymbol.Value = pair_r_value;
401       op_info->Value = offset;
402       return 1;
403     }
404     // TODO:
405     // Second search the external relocation entries of a fully linked image
406     // (if any) for an entry that matches this segment offset.
407     // uint32_t seg_offset = (Pc + Offset);
408     return 0;
409   } else if (Arch == Triple::x86_64) {
410     if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
411       return 0;
412     // First search the section's relocation entries (if any) for an entry
413     // for this section offset.
414     uint64_t sect_addr = info->S.getAddress();
415     uint64_t sect_offset = (Pc + Offset) - sect_addr;
416     bool reloc_found = false;
417     DataRefImpl Rel;
418     MachO::any_relocation_info RE;
419     bool isExtern = false;
420     SymbolRef Symbol;
421     for (const RelocationRef &Reloc : info->S.relocations()) {
422       uint64_t RelocOffset;
423       Reloc.getOffset(RelocOffset);
424       if (RelocOffset == sect_offset) {
425         Rel = Reloc.getRawDataRefImpl();
426         RE = info->O->getRelocation(Rel);
427         // NOTE: Scattered relocations don't exist on x86_64.
428         isExtern = info->O->getPlainRelocationExternal(RE);
429         if (isExtern) {
430           symbol_iterator RelocSym = Reloc.getSymbol();
431           Symbol = *RelocSym;
432         }
433         reloc_found = true;
434         break;
435       }
436     }
437     if (reloc_found && isExtern) {
438       // The Value passed in will be adjusted by the Pc if the instruction
439       // adds the Pc.  But for x86_64 external relocation entries the Value
440       // is the offset from the external symbol.
441       if (info->O->getAnyRelocationPCRel(RE))
442         op_info->Value -= Pc + Offset + Size;
443       StringRef SymName;
444       Symbol.getName(SymName);
445       const char *name = SymName.data();
446       unsigned Type = info->O->getAnyRelocationType(RE);
447       if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
448         DataRefImpl RelNext = Rel;
449         info->O->moveRelocationNext(RelNext);
450         MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
451         unsigned TypeNext = info->O->getAnyRelocationType(RENext);
452         bool isExternNext = info->O->getPlainRelocationExternal(RENext);
453         unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
454         if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
455           op_info->SubtractSymbol.Present = 1;
456           op_info->SubtractSymbol.Name = name;
457           symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
458           Symbol = *RelocSymNext;
459           StringRef SymNameNext;
460           Symbol.getName(SymNameNext);
461           name = SymNameNext.data();
462         }
463       }
464       // TODO: add the VariantKinds to op_info->VariantKind for relocation types
465       // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
466       op_info->AddSymbol.Present = 1;
467       op_info->AddSymbol.Name = name;
468       return 1;
469     }
470     // TODO:
471     // Second search the external relocation entries of a fully linked image
472     // (if any) for an entry that matches this segment offset.
473     // uint64_t seg_offset = (Pc + Offset);
474     return 0;
475   } else if (Arch == Triple::arm) {
476     if (Offset != 0 || (Size != 4 && Size != 2))
477       return 0;
478     // First search the section's relocation entries (if any) for an entry
479     // for this section offset.
480     uint32_t sect_addr = info->S.getAddress();
481     uint32_t sect_offset = (Pc + Offset) - sect_addr;
482     bool reloc_found = false;
483     DataRefImpl Rel;
484     MachO::any_relocation_info RE;
485     bool isExtern = false;
486     SymbolRef Symbol;
487     bool r_scattered = false;
488     uint32_t r_value, pair_r_value, r_type, r_length, other_half;
489     for (const RelocationRef &Reloc : info->S.relocations()) {
490       uint64_t RelocOffset;
491       Reloc.getOffset(RelocOffset);
492       if (RelocOffset == sect_offset) {
493         Rel = Reloc.getRawDataRefImpl();
494         RE = info->O->getRelocation(Rel);
495         r_length = info->O->getAnyRelocationLength(RE);
496         r_scattered = info->O->isRelocationScattered(RE);
497         if (r_scattered) {
498           r_value = info->O->getScatteredRelocationValue(RE);
499           r_type = info->O->getScatteredRelocationType(RE);
500         } else {
501           r_type = info->O->getAnyRelocationType(RE);
502           isExtern = info->O->getPlainRelocationExternal(RE);
503           if (isExtern) {
504             symbol_iterator RelocSym = Reloc.getSymbol();
505             Symbol = *RelocSym;
506           }
507         }
508         if (r_type == MachO::ARM_RELOC_HALF ||
509             r_type == MachO::ARM_RELOC_SECTDIFF ||
510             r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
511             r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
512           DataRefImpl RelNext = Rel;
513           info->O->moveRelocationNext(RelNext);
514           MachO::any_relocation_info RENext;
515           RENext = info->O->getRelocation(RelNext);
516           other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
517           if (info->O->isRelocationScattered(RENext))
518             pair_r_value = info->O->getScatteredRelocationValue(RENext);
519         }
520         reloc_found = true;
521         break;
522       }
523     }
524     if (reloc_found && isExtern) {
525       StringRef SymName;
526       Symbol.getName(SymName);
527       const char *name = SymName.data();
528       op_info->AddSymbol.Present = 1;
529       op_info->AddSymbol.Name = name;
530       if (value != 0) {
531         switch (r_type) {
532         case MachO::ARM_RELOC_HALF:
533           if ((r_length & 0x1) == 1) {
534             op_info->Value = value << 16 | other_half;
535             op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
536           } else {
537             op_info->Value = other_half << 16 | value;
538             op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
539           }
540           break;
541         default:
542           break;
543         }
544       } else {
545         switch (r_type) {
546         case MachO::ARM_RELOC_HALF:
547           if ((r_length & 0x1) == 1) {
548             op_info->Value = value << 16 | other_half;
549             op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
550           } else {
551             op_info->Value = other_half << 16 | value;
552             op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
553           }
554           break;
555         default:
556           break;
557         }
558       }
559       return 1;
560     }
561     // If we have a branch that is not an external relocation entry then
562     // return 0 so the code in tryAddingSymbolicOperand() can use the
563     // SymbolLookUp call back with the branch target address to look up the
564     // symbol and possiblity add an annotation for a symbol stub.
565     if (reloc_found && isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
566                                          r_type == MachO::ARM_THUMB_RELOC_BR22))
567       return 0;
568
569     uint32_t offset = 0;
570     if (reloc_found) {
571       if (r_type == MachO::ARM_RELOC_HALF ||
572           r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
573         if ((r_length & 0x1) == 1)
574           value = value << 16 | other_half;
575         else
576           value = other_half << 16 | value;
577       }
578       if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
579                           r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
580         offset = value - r_value;
581         value = r_value;
582       }
583     }
584
585     if (reloc_found && r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
586       if ((r_length & 0x1) == 1)
587         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
588       else
589         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
590       const char *add = GuessSymbolName(r_value, info);
591       const char *sub = GuessSymbolName(pair_r_value, info);
592       int32_t offset = value - (r_value - pair_r_value);
593       op_info->AddSymbol.Present = 1;
594       if (add != nullptr)
595         op_info->AddSymbol.Name = add;
596       else
597         op_info->AddSymbol.Value = r_value;
598       op_info->SubtractSymbol.Present = 1;
599       if (sub != nullptr)
600         op_info->SubtractSymbol.Name = sub;
601       else
602         op_info->SubtractSymbol.Value = pair_r_value;
603       op_info->Value = offset;
604       return 1;
605     }
606
607     if (reloc_found == false)
608       return 0;
609
610     op_info->AddSymbol.Present = 1;
611     op_info->Value = offset;
612     if (reloc_found) {
613       if (r_type == MachO::ARM_RELOC_HALF) {
614         if ((r_length & 0x1) == 1)
615           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
616         else
617           op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
618       }
619     }
620     const char *add = GuessSymbolName(value, info);
621     if (add != nullptr) {
622       op_info->AddSymbol.Name = add;
623       return 1;
624     }
625     op_info->AddSymbol.Value = value;
626     return 1;
627   } else if (Arch == Triple::aarch64) {
628     if (Offset != 0 || Size != 4)
629       return 0;
630     // First search the section's relocation entries (if any) for an entry
631     // for this section offset.
632     uint64_t sect_addr = info->S.getAddress();
633     uint64_t sect_offset = (Pc + Offset) - sect_addr;
634     bool reloc_found = false;
635     DataRefImpl Rel;
636     MachO::any_relocation_info RE;
637     bool isExtern = false;
638     SymbolRef Symbol;
639     uint32_t r_type = 0;
640     for (const RelocationRef &Reloc : info->S.relocations()) {
641       uint64_t RelocOffset;
642       Reloc.getOffset(RelocOffset);
643       if (RelocOffset == sect_offset) {
644         Rel = Reloc.getRawDataRefImpl();
645         RE = info->O->getRelocation(Rel);
646         r_type = info->O->getAnyRelocationType(RE);
647         if (r_type == MachO::ARM64_RELOC_ADDEND) {
648           DataRefImpl RelNext = Rel;
649           info->O->moveRelocationNext(RelNext);
650           MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
651           if (value == 0) {
652             value = info->O->getPlainRelocationSymbolNum(RENext);
653             op_info->Value = value;
654           }
655         }
656         // NOTE: Scattered relocations don't exist on arm64.
657         isExtern = info->O->getPlainRelocationExternal(RE);
658         if (isExtern) {
659           symbol_iterator RelocSym = Reloc.getSymbol();
660           Symbol = *RelocSym;
661         }
662         reloc_found = true;
663         break;
664       }
665     }
666     if (reloc_found && isExtern) {
667       StringRef SymName;
668       Symbol.getName(SymName);
669       const char *name = SymName.data();
670       op_info->AddSymbol.Present = 1;
671       op_info->AddSymbol.Name = name;
672
673       switch (r_type) {
674       case MachO::ARM64_RELOC_PAGE21:
675         /* @page */
676         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
677         break;
678       case MachO::ARM64_RELOC_PAGEOFF12:
679         /* @pageoff */
680         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
681         break;
682       case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
683         /* @gotpage */
684         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
685         break;
686       case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
687         /* @gotpageoff */
688         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
689         break;
690       case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
691         /* @tvlppage is not implemented in llvm-mc */
692         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
693         break;
694       case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
695         /* @tvlppageoff is not implemented in llvm-mc */
696         op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
697         break;
698       default:
699       case MachO::ARM64_RELOC_BRANCH26:
700         op_info->VariantKind = LLVMDisassembler_VariantKind_None;
701         break;
702       }
703       return 1;
704     }
705     return 0;
706   } else {
707     return 0;
708   }
709 }
710
711 // GuessCstringPointer is passed the address of what might be a pointer to a
712 // literal string in a cstring section.  If that address is in a cstring section
713 // it returns a pointer to that string.  Else it returns nullptr.
714 const char *GuessCstringPointer(uint64_t ReferenceValue,
715                                 struct DisassembleInfo *info) {
716   uint32_t LoadCommandCount = info->O->getHeader().ncmds;
717   MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
718   for (unsigned I = 0;; ++I) {
719     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
720       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
721       for (unsigned J = 0; J < Seg.nsects; ++J) {
722         MachO::section_64 Sec = info->O->getSection64(Load, J);
723         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
724         if (section_type == MachO::S_CSTRING_LITERALS &&
725             ReferenceValue >= Sec.addr &&
726             ReferenceValue < Sec.addr + Sec.size) {
727           uint64_t sect_offset = ReferenceValue - Sec.addr;
728           uint64_t object_offset = Sec.offset + sect_offset;
729           StringRef MachOContents = info->O->getData();
730           uint64_t object_size = MachOContents.size();
731           const char *object_addr = (const char *)MachOContents.data();
732           if (object_offset < object_size) {
733             const char *name = object_addr + object_offset;
734             return name;
735           } else {
736             return nullptr;
737           }
738         }
739       }
740     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
741       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
742       for (unsigned J = 0; J < Seg.nsects; ++J) {
743         MachO::section Sec = info->O->getSection(Load, J);
744         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
745         if (section_type == MachO::S_CSTRING_LITERALS &&
746             ReferenceValue >= Sec.addr &&
747             ReferenceValue < Sec.addr + Sec.size) {
748           uint64_t sect_offset = ReferenceValue - Sec.addr;
749           uint64_t object_offset = Sec.offset + sect_offset;
750           StringRef MachOContents = info->O->getData();
751           uint64_t object_size = MachOContents.size();
752           const char *object_addr = (const char *)MachOContents.data();
753           if (object_offset < object_size) {
754             const char *name = object_addr + object_offset;
755             return name;
756           } else {
757             return nullptr;
758           }
759         }
760       }
761     }
762     if (I == LoadCommandCount - 1)
763       break;
764     else
765       Load = info->O->getNextLoadCommandInfo(Load);
766   }
767   return nullptr;
768 }
769
770 // GuessIndirectSymbol returns the name of the indirect symbol for the
771 // ReferenceValue passed in or nullptr.  This is used when ReferenceValue maybe
772 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
773 // symbol name being referenced by the stub or pointer.
774 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
775                                        struct DisassembleInfo *info) {
776   uint32_t LoadCommandCount = info->O->getHeader().ncmds;
777   MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
778   MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
779   MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
780   for (unsigned I = 0;; ++I) {
781     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
782       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
783       for (unsigned J = 0; J < Seg.nsects; ++J) {
784         MachO::section_64 Sec = info->O->getSection64(Load, J);
785         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
786         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
787              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
788              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
789              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
790              section_type == MachO::S_SYMBOL_STUBS) &&
791             ReferenceValue >= Sec.addr &&
792             ReferenceValue < Sec.addr + Sec.size) {
793           uint32_t stride;
794           if (section_type == MachO::S_SYMBOL_STUBS)
795             stride = Sec.reserved2;
796           else
797             stride = 8;
798           if (stride == 0)
799             return nullptr;
800           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
801           if (index < Dysymtab.nindirectsyms) {
802             uint32_t indirect_symbol =
803                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
804             if (indirect_symbol < Symtab.nsyms) {
805               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
806               SymbolRef Symbol = *Sym;
807               StringRef SymName;
808               Symbol.getName(SymName);
809               const char *name = SymName.data();
810               return name;
811             }
812           }
813         }
814       }
815     } else if (Load.C.cmd == MachO::LC_SEGMENT) {
816       MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
817       for (unsigned J = 0; J < Seg.nsects; ++J) {
818         MachO::section Sec = info->O->getSection(Load, J);
819         uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
820         if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
821              section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
822              section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
823              section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
824              section_type == MachO::S_SYMBOL_STUBS) &&
825             ReferenceValue >= Sec.addr &&
826             ReferenceValue < Sec.addr + Sec.size) {
827           uint32_t stride;
828           if (section_type == MachO::S_SYMBOL_STUBS)
829             stride = Sec.reserved2;
830           else
831             stride = 4;
832           if (stride == 0)
833             return nullptr;
834           uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
835           if (index < Dysymtab.nindirectsyms) {
836             uint32_t indirect_symbol =
837                 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
838             if (indirect_symbol < Symtab.nsyms) {
839               symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
840               SymbolRef Symbol = *Sym;
841               StringRef SymName;
842               Symbol.getName(SymName);
843               const char *name = SymName.data();
844               return name;
845             }
846           }
847         }
848       }
849     }
850     if (I == LoadCommandCount - 1)
851       break;
852     else
853       Load = info->O->getNextLoadCommandInfo(Load);
854   }
855   return nullptr;
856 }
857
858 // method_reference() is called passing it the ReferenceName that might be
859 // a reference it to an Objective-C method call.  If so then it allocates and
860 // assembles a method call string with the values last seen and saved in
861 // the DisassembleInfo's class_name and selector_name fields.  This is saved
862 // into the method field of the info and any previous string is free'ed.
863 // Then the class_name field in the info is set to nullptr.  The method call
864 // string is set into ReferenceName and ReferenceType is set to
865 // LLVMDisassembler_ReferenceType_Out_Objc_Message.  If this not a method call
866 // then both ReferenceType and ReferenceName are left unchanged.
867 static void method_reference(struct DisassembleInfo *info,
868                              uint64_t *ReferenceType,
869                              const char **ReferenceName) {
870   unsigned int Arch = info->O->getArch();
871   if (*ReferenceName != nullptr) {
872     if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
873       if (info->selector_name != nullptr) {
874         if (info->method != nullptr)
875           free(info->method);
876         if (info->class_name != nullptr) {
877           info->method = (char *)malloc(5 + strlen(info->class_name) +
878                                         strlen(info->selector_name));
879           if (info->method != nullptr) {
880             strcpy(info->method, "+[");
881             strcat(info->method, info->class_name);
882             strcat(info->method, " ");
883             strcat(info->method, info->selector_name);
884             strcat(info->method, "]");
885             *ReferenceName = info->method;
886             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
887           }
888         } else {
889           info->method = (char *)malloc(9 + strlen(info->selector_name));
890           if (info->method != nullptr) {
891             if (Arch == Triple::x86_64)
892               strcpy(info->method, "-[%rdi ");
893             else if (Arch == Triple::aarch64)
894               strcpy(info->method, "-[x0 ");
895             else
896               strcpy(info->method, "-[r? ");
897             strcat(info->method, info->selector_name);
898             strcat(info->method, "]");
899             *ReferenceName = info->method;
900             *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
901           }
902         }
903         info->class_name = nullptr;
904       }
905     } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
906       if (info->selector_name != nullptr) {
907         if (info->method != nullptr)
908           free(info->method);
909         info->method = (char *)malloc(17 + strlen(info->selector_name));
910         if (info->method != nullptr) {
911           if (Arch == Triple::x86_64)
912             strcpy(info->method, "-[[%rdi super] ");
913           else if (Arch == Triple::aarch64)
914             strcpy(info->method, "-[[x0 super] ");
915           else
916             strcpy(info->method, "-[[r? super] ");
917           strcat(info->method, info->selector_name);
918           strcat(info->method, "]");
919           *ReferenceName = info->method;
920           *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
921         }
922         info->class_name = nullptr;
923       }
924     }
925   }
926 }
927
928 // GuessPointerPointer() is passed the address of what might be a pointer to
929 // a reference to an Objective-C class, selector, message ref or cfstring.
930 // If so the value of the pointer is returned and one of the booleans are set
931 // to true.  If not zero is returned and all the booleans are set to false.
932 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
933                                     struct DisassembleInfo *info,
934                                     bool &classref, bool &selref, bool &msgref,
935                                     bool &cfstring) {
936   classref = false;
937   selref = false;
938   msgref = false;
939   cfstring = false;
940   uint32_t LoadCommandCount = info->O->getHeader().ncmds;
941   MachOObjectFile::LoadCommandInfo Load = info->O->getFirstLoadCommandInfo();
942   for (unsigned I = 0;; ++I) {
943     if (Load.C.cmd == MachO::LC_SEGMENT_64) {
944       MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
945       for (unsigned J = 0; J < Seg.nsects; ++J) {
946         MachO::section_64 Sec = info->O->getSection64(Load, J);
947         if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
948              strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
949              strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
950              strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
951              strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
952             ReferenceValue >= Sec.addr &&
953             ReferenceValue < Sec.addr + Sec.size) {
954           uint64_t sect_offset = ReferenceValue - Sec.addr;
955           uint64_t object_offset = Sec.offset + sect_offset;
956           StringRef MachOContents = info->O->getData();
957           uint64_t object_size = MachOContents.size();
958           const char *object_addr = (const char *)MachOContents.data();
959           if (object_offset < object_size) {
960             uint64_t pointer_value;
961             memcpy(&pointer_value, object_addr + object_offset,
962                    sizeof(uint64_t));
963             if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
964               sys::swapByteOrder(pointer_value);
965             if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
966               selref = true;
967             else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
968                      strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
969               classref = true;
970             else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
971                      ReferenceValue + 8 < Sec.addr + Sec.size) {
972               msgref = true;
973               memcpy(&pointer_value, object_addr + object_offset + 8,
974                      sizeof(uint64_t));
975               if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
976                 sys::swapByteOrder(pointer_value);
977             } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
978               cfstring = true;
979             return pointer_value;
980           } else {
981             return 0;
982           }
983         }
984       }
985     }
986     // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
987     if (I == LoadCommandCount - 1)
988       break;
989     else
990       Load = info->O->getNextLoadCommandInfo(Load);
991   }
992   return 0;
993 }
994
995 // get_pointer_64 returns a pointer to the bytes in the object file at the
996 // Address from a section in the Mach-O file.  And indirectly returns the
997 // offset into the section, number of bytes left in the section past the offset
998 // and which section is was being referenced.  If the Address is not in a
999 // section nullptr is returned.
1000 const char *get_pointer_64(uint64_t Address, uint32_t &offset, uint32_t &left,
1001                            SectionRef &S, DisassembleInfo *info) {
1002   offset = 0;
1003   left = 0;
1004   S = SectionRef();
1005   for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
1006     uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
1007     uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
1008     if (Address >= SectAddress && Address < SectAddress + SectSize) {
1009       S = (*(info->Sections))[SectIdx];
1010       offset = Address - SectAddress;
1011       left = SectSize - offset;
1012       StringRef SectContents;
1013       ((*(info->Sections))[SectIdx]).getContents(SectContents);
1014       return SectContents.data() + offset;
1015     }
1016   }
1017   return nullptr;
1018 }
1019
1020 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
1021 // the symbol indirectly through n_value. Based on the relocation information
1022 // for the specified section offset in the specified section reference.
1023 const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
1024                           DisassembleInfo *info, uint64_t &n_value) {
1025   n_value = 0;
1026   if (info->verbose == false)
1027     return nullptr;
1028
1029   // See if there is an external relocation entry at the sect_offset.
1030   bool reloc_found = false;
1031   DataRefImpl Rel;
1032   MachO::any_relocation_info RE;
1033   bool isExtern = false;
1034   SymbolRef Symbol;
1035   for (const RelocationRef &Reloc : S.relocations()) {
1036     uint64_t RelocOffset;
1037     Reloc.getOffset(RelocOffset);
1038     if (RelocOffset == sect_offset) {
1039       Rel = Reloc.getRawDataRefImpl();
1040       RE = info->O->getRelocation(Rel);
1041       if (info->O->isRelocationScattered(RE))
1042         continue;
1043       isExtern = info->O->getPlainRelocationExternal(RE);
1044       if (isExtern) {
1045         symbol_iterator RelocSym = Reloc.getSymbol();
1046         Symbol = *RelocSym;
1047       }
1048       reloc_found = true;
1049       break;
1050     }
1051   }
1052   // If there is an external relocation entry for a symbol in this section
1053   // at this section_offset then use that symbol's value for the n_value
1054   // and return its name.
1055   const char *SymbolName = nullptr;
1056   if (reloc_found && isExtern) {
1057     Symbol.getAddress(n_value);
1058     StringRef name;
1059     Symbol.getName(name);
1060     if (!name.empty()) {
1061       SymbolName = name.data();
1062       return SymbolName;
1063     }
1064   }
1065
1066   // TODO: For fully linked images, look through the external relocation
1067   // entries off the dynamic symtab command. For these the r_offset is from the
1068   // start of the first writeable segment in the Mach-O file.  So the offset
1069   // to this section from that segment is passed to this routine by the caller,
1070   // as the database_offset. Which is the difference of the section's starting
1071   // address and the first writable segment.
1072   //
1073   // NOTE: need add passing the database_offset to this routine.
1074
1075   // TODO: We did not find an external relocation entry so look up the
1076   // ReferenceValue as an address of a symbol and if found return that symbol's
1077   // name.
1078   //
1079   // NOTE: need add passing the ReferenceValue to this routine.  Then that code
1080   // would simply be this:
1081   // SymbolName = GuessSymbolName(ReferenceValue, info);
1082
1083   return SymbolName;
1084 }
1085
1086 // These are structs in the Objective-C meta data and read to produce the
1087 // comments for disassembly.  While these are part of the ABI they are no
1088 // public defintions.  So the are here not in include/llvm/Support/MachO.h .
1089
1090 // The cfstring object in a 64-bit Mach-O file.
1091 struct cfstring64_t {
1092   uint64_t isa;        // class64_t * (64-bit pointer)
1093   uint64_t flags;      // flag bits
1094   uint64_t characters; // char * (64-bit pointer)
1095   uint64_t length;     // number of non-NULL characters in above
1096 };
1097
1098 // The class object in a 64-bit Mach-O file.
1099 struct class64_t {
1100   uint64_t isa;        // class64_t * (64-bit pointer)
1101   uint64_t superclass; // class64_t * (64-bit pointer)
1102   uint64_t cache;      // Cache (64-bit pointer)
1103   uint64_t vtable;     // IMP * (64-bit pointer)
1104   uint64_t data;       // class_ro64_t * (64-bit pointer)
1105 };
1106
1107 struct class_ro64_t {
1108   uint32_t flags;
1109   uint32_t instanceStart;
1110   uint32_t instanceSize;
1111   uint32_t reserved;
1112   uint64_t ivarLayout;     // const uint8_t * (64-bit pointer)
1113   uint64_t name;           // const char * (64-bit pointer)
1114   uint64_t baseMethods;    // const method_list_t * (64-bit pointer)
1115   uint64_t baseProtocols;  // const protocol_list_t * (64-bit pointer)
1116   uint64_t ivars;          // const ivar_list_t * (64-bit pointer)
1117   uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
1118   uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
1119 };
1120
1121 inline void swapStruct(struct cfstring64_t &cfs) {
1122   sys::swapByteOrder(cfs.isa);
1123   sys::swapByteOrder(cfs.flags);
1124   sys::swapByteOrder(cfs.characters);
1125   sys::swapByteOrder(cfs.length);
1126 }
1127
1128 inline void swapStruct(struct class64_t &c) {
1129   sys::swapByteOrder(c.isa);
1130   sys::swapByteOrder(c.superclass);
1131   sys::swapByteOrder(c.cache);
1132   sys::swapByteOrder(c.vtable);
1133   sys::swapByteOrder(c.data);
1134 }
1135
1136 inline void swapStruct(struct class_ro64_t &cro) {
1137   sys::swapByteOrder(cro.flags);
1138   sys::swapByteOrder(cro.instanceStart);
1139   sys::swapByteOrder(cro.instanceSize);
1140   sys::swapByteOrder(cro.reserved);
1141   sys::swapByteOrder(cro.ivarLayout);
1142   sys::swapByteOrder(cro.name);
1143   sys::swapByteOrder(cro.baseMethods);
1144   sys::swapByteOrder(cro.baseProtocols);
1145   sys::swapByteOrder(cro.ivars);
1146   sys::swapByteOrder(cro.weakIvarLayout);
1147   sys::swapByteOrder(cro.baseProperties);
1148 }
1149
1150 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
1151                                                  struct DisassembleInfo *info);
1152
1153 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
1154 // to an Objective-C class and returns the class name.  It is also passed the
1155 // address of the pointer, so when the pointer is zero as it can be in an .o
1156 // file, that is used to look for an external relocation entry with a symbol
1157 // name.
1158 const char *get_objc2_64bit_class_name(uint64_t pointer_value,
1159                                        uint64_t ReferenceValue,
1160                                        struct DisassembleInfo *info) {
1161   const char *r;
1162   uint32_t offset, left;
1163   SectionRef S;
1164
1165   // The pointer_value can be 0 in an object file and have a relocation
1166   // entry for the class symbol at the ReferenceValue (the address of the
1167   // pointer).
1168   if (pointer_value == 0) {
1169     r = get_pointer_64(ReferenceValue, offset, left, S, info);
1170     if (r == nullptr || left < sizeof(uint64_t))
1171       return nullptr;
1172     uint64_t n_value;
1173     const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1174     if (symbol_name == nullptr)
1175       return nullptr;
1176     const char *class_name = strrchr(symbol_name, '$');
1177     if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
1178       return class_name + 2;
1179     else
1180       return nullptr;
1181   }
1182
1183   // The case were the pointer_value is non-zero and points to a class defined
1184   // in this Mach-O file.
1185   r = get_pointer_64(pointer_value, offset, left, S, info);
1186   if (r == nullptr || left < sizeof(struct class64_t))
1187     return nullptr;
1188   struct class64_t c;
1189   memcpy(&c, r, sizeof(struct class64_t));
1190   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1191     swapStruct(c);
1192   if (c.data == 0)
1193     return nullptr;
1194   r = get_pointer_64(c.data, offset, left, S, info);
1195   if (r == nullptr || left < sizeof(struct class_ro64_t))
1196     return nullptr;
1197   struct class_ro64_t cro;
1198   memcpy(&cro, r, sizeof(struct class_ro64_t));
1199   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1200     swapStruct(cro);
1201   if (cro.name == 0)
1202     return nullptr;
1203   const char *name = get_pointer_64(cro.name, offset, left, S, info);
1204   return name;
1205 }
1206
1207 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
1208 // pointer to a cfstring and returns its name or nullptr.
1209 const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
1210                                           struct DisassembleInfo *info) {
1211   const char *r, *name;
1212   uint32_t offset, left;
1213   SectionRef S;
1214   struct cfstring64_t cfs;
1215   uint64_t cfs_characters;
1216
1217   r = get_pointer_64(ReferenceValue, offset, left, S, info);
1218   if (r == nullptr || left < sizeof(struct cfstring64_t))
1219     return nullptr;
1220   memcpy(&cfs, r, sizeof(struct cfstring64_t));
1221   if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
1222     swapStruct(cfs);
1223   if (cfs.characters == 0) {
1224     uint64_t n_value;
1225     const char *symbol_name = get_symbol_64(
1226         offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
1227     if (symbol_name == nullptr)
1228       return nullptr;
1229     cfs_characters = n_value;
1230   } else
1231     cfs_characters = cfs.characters;
1232   name = get_pointer_64(cfs_characters, offset, left, S, info);
1233
1234   return name;
1235 }
1236
1237 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
1238 // of a pointer to an Objective-C selector reference when the pointer value is
1239 // zero as in a .o file and is likely to have a external relocation entry with
1240 // who's symbol's n_value is the real pointer to the selector name.  If that is
1241 // the case the real pointer to the selector name is returned else 0 is
1242 // returned
1243 uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
1244                                 struct DisassembleInfo *info) {
1245   uint32_t offset, left;
1246   SectionRef S;
1247
1248   const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
1249   if (r == nullptr || left < sizeof(uint64_t))
1250     return 0;
1251   uint64_t n_value;
1252   const char *symbol_name = get_symbol_64(offset, S, info, n_value);
1253   if (symbol_name == nullptr)
1254     return 0;
1255   return n_value;
1256 }
1257
1258 // GuessLiteralPointer returns a string which for the item in the Mach-O file
1259 // for the address passed in as ReferenceValue for printing as a comment with
1260 // the instruction and also returns the corresponding type of that item
1261 // indirectly through ReferenceType.
1262 //
1263 // If ReferenceValue is an address of literal cstring then a pointer to the
1264 // cstring is returned and ReferenceType is set to
1265 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
1266 //
1267 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
1268 // Class ref that name is returned and the ReferenceType is set accordingly.
1269 //
1270 // Lastly, literals which are Symbol address in a literal pool are looked for
1271 // and if found the symbol name is returned and ReferenceType is set to
1272 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
1273 //
1274 // If there is no item in the Mach-O file for the address passed in as
1275 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
1276 const char *GuessLiteralPointer(uint64_t ReferenceValue, uint64_t ReferencePC,
1277                                 uint64_t *ReferenceType,
1278                                 struct DisassembleInfo *info) {
1279   // First see if there is an external relocation entry at the ReferencePC.
1280   uint64_t sect_addr = info->S.getAddress();
1281   uint64_t sect_offset = ReferencePC - sect_addr;
1282   bool reloc_found = false;
1283   DataRefImpl Rel;
1284   MachO::any_relocation_info RE;
1285   bool isExtern = false;
1286   SymbolRef Symbol;
1287   for (const RelocationRef &Reloc : info->S.relocations()) {
1288     uint64_t RelocOffset;
1289     Reloc.getOffset(RelocOffset);
1290     if (RelocOffset == sect_offset) {
1291       Rel = Reloc.getRawDataRefImpl();
1292       RE = info->O->getRelocation(Rel);
1293       if (info->O->isRelocationScattered(RE))
1294         continue;
1295       isExtern = info->O->getPlainRelocationExternal(RE);
1296       if (isExtern) {
1297         symbol_iterator RelocSym = Reloc.getSymbol();
1298         Symbol = *RelocSym;
1299       }
1300       reloc_found = true;
1301       break;
1302     }
1303   }
1304   // If there is an external relocation entry for a symbol in a section
1305   // then used that symbol's value for the value of the reference.
1306   if (reloc_found && isExtern) {
1307     if (info->O->getAnyRelocationPCRel(RE)) {
1308       unsigned Type = info->O->getAnyRelocationType(RE);
1309       if (Type == MachO::X86_64_RELOC_SIGNED) {
1310         Symbol.getAddress(ReferenceValue);
1311       }
1312     }
1313   }
1314
1315   // Look for literals such as Objective-C CFStrings refs, Selector refs,
1316   // Message refs and Class refs.
1317   bool classref, selref, msgref, cfstring;
1318   uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
1319                                                selref, msgref, cfstring);
1320   if (classref == true && pointer_value == 0) {
1321     // Note the ReferenceValue is a pointer into the __objc_classrefs section.
1322     // And the pointer_value in that section is typically zero as it will be
1323     // set by dyld as part of the "bind information".
1324     const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
1325     if (name != nullptr) {
1326       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1327       const char *class_name = strrchr(name, '$');
1328       if (class_name != nullptr && class_name[1] == '_' &&
1329           class_name[2] != '\0') {
1330         info->class_name = class_name + 2;
1331         return name;
1332       }
1333     }
1334   }
1335
1336   if (classref == true) {
1337     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
1338     const char *name =
1339         get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
1340     if (name != nullptr)
1341       info->class_name = name;
1342     else
1343       name = "bad class ref";
1344     return name;
1345   }
1346
1347   if (cfstring == true) {
1348     *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
1349     const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
1350     return name;
1351   }
1352
1353   if (selref == true && pointer_value == 0)
1354     pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
1355
1356   if (pointer_value != 0)
1357     ReferenceValue = pointer_value;
1358
1359   const char *name = GuessCstringPointer(ReferenceValue, info);
1360   if (name) {
1361     if (pointer_value != 0 && selref == true) {
1362       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
1363       info->selector_name = name;
1364     } else if (pointer_value != 0 && msgref == true) {
1365       info->class_name = nullptr;
1366       *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
1367       info->selector_name = name;
1368     } else
1369       *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
1370     return name;
1371   }
1372
1373   // Lastly look for an indirect symbol with this ReferenceValue which is in
1374   // a literal pool.  If found return that symbol name.
1375   name = GuessIndirectSymbol(ReferenceValue, info);
1376   if (name) {
1377     *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
1378     return name;
1379   }
1380
1381   return nullptr;
1382 }
1383
1384 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
1385 // the Symbolizer.  It looks up the ReferenceValue using the info passed via the
1386 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
1387 // is created and returns the symbol name that matches the ReferenceValue or
1388 // nullptr if none.  The ReferenceType is passed in for the IN type of
1389 // reference the instruction is making from the values in defined in the header
1390 // "llvm-c/Disassembler.h".  On return the ReferenceType can set to a specific
1391 // Out type and the ReferenceName will also be set which is added as a comment
1392 // to the disassembled instruction.
1393 //
1394 #if HAVE_CXXABI_H
1395 // If the symbol name is a C++ mangled name then the demangled name is
1396 // returned through ReferenceName and ReferenceType is set to
1397 // LLVMDisassembler_ReferenceType_DeMangled_Name .
1398 #endif
1399 //
1400 // When this is called to get a symbol name for a branch target then the
1401 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
1402 // SymbolValue will be looked for in the indirect symbol table to determine if
1403 // it is an address for a symbol stub.  If so then the symbol name for that
1404 // stub is returned indirectly through ReferenceName and then ReferenceType is
1405 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
1406 //
1407 // When this is called with an value loaded via a PC relative load then
1408 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
1409 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
1410 // or an Objective-C meta data reference.  If so the output ReferenceType is
1411 // set to correspond to that as well as setting the ReferenceName.
1412 const char *SymbolizerSymbolLookUp(void *DisInfo, uint64_t ReferenceValue,
1413                                    uint64_t *ReferenceType,
1414                                    uint64_t ReferencePC,
1415                                    const char **ReferenceName) {
1416   struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1417   // If no verbose symbolic information is wanted then just return nullptr.
1418   if (info->verbose == false) {
1419     *ReferenceName = nullptr;
1420     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1421     return nullptr;
1422   }
1423
1424   const char *SymbolName = GuessSymbolName(ReferenceValue, info);
1425
1426   if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
1427     *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
1428     if (*ReferenceName != nullptr) {
1429       method_reference(info, ReferenceType, ReferenceName);
1430       if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
1431         *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
1432     } else
1433 #if HAVE_CXXABI_H
1434         if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1435       if (info->demangled_name != nullptr)
1436         free(info->demangled_name);
1437       int status;
1438       info->demangled_name =
1439           abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1440       if (info->demangled_name != nullptr) {
1441         *ReferenceName = info->demangled_name;
1442         *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1443       } else
1444         *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1445     } else
1446 #endif
1447       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1448   } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
1449     *ReferenceName =
1450         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1451     if (*ReferenceName)
1452       method_reference(info, ReferenceType, ReferenceName);
1453     else
1454       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1455     // If this is arm64 and the reference is an adrp instruction save the
1456     // instruction, passed in ReferenceValue and the address of the instruction
1457     // for use later if we see and add immediate instruction.
1458   } else if (info->O->getArch() == Triple::aarch64 &&
1459              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
1460     info->adrp_inst = ReferenceValue;
1461     info->adrp_addr = ReferencePC;
1462     SymbolName = nullptr;
1463     *ReferenceName = nullptr;
1464     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1465     // If this is arm64 and reference is an add immediate instruction and we
1466     // have
1467     // seen an adrp instruction just before it and the adrp's Xd register
1468     // matches
1469     // this add's Xn register reconstruct the value being referenced and look to
1470     // see if it is a literal pointer.  Note the add immediate instruction is
1471     // passed in ReferenceValue.
1472   } else if (info->O->getArch() == Triple::aarch64 &&
1473              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
1474              ReferencePC - 4 == info->adrp_addr &&
1475              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
1476              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
1477     uint32_t addxri_inst;
1478     uint64_t adrp_imm, addxri_imm;
1479
1480     adrp_imm =
1481         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
1482     if (info->adrp_inst & 0x0200000)
1483       adrp_imm |= 0xfffffffffc000000LL;
1484
1485     addxri_inst = ReferenceValue;
1486     addxri_imm = (addxri_inst >> 10) & 0xfff;
1487     if (((addxri_inst >> 22) & 0x3) == 1)
1488       addxri_imm <<= 12;
1489
1490     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
1491                      (adrp_imm << 12) + addxri_imm;
1492
1493     *ReferenceName =
1494         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1495     if (*ReferenceName == nullptr)
1496       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1497     // If this is arm64 and the reference is a load register instruction and we
1498     // have seen an adrp instruction just before it and the adrp's Xd register
1499     // matches this add's Xn register reconstruct the value being referenced and
1500     // look to see if it is a literal pointer.  Note the load register
1501     // instruction is passed in ReferenceValue.
1502   } else if (info->O->getArch() == Triple::aarch64 &&
1503              *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
1504              ReferencePC - 4 == info->adrp_addr &&
1505              (info->adrp_inst & 0x9f000000) == 0x90000000 &&
1506              (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
1507     uint32_t ldrxui_inst;
1508     uint64_t adrp_imm, ldrxui_imm;
1509
1510     adrp_imm =
1511         ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
1512     if (info->adrp_inst & 0x0200000)
1513       adrp_imm |= 0xfffffffffc000000LL;
1514
1515     ldrxui_inst = ReferenceValue;
1516     ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
1517
1518     ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
1519                      (adrp_imm << 12) + (ldrxui_imm << 3);
1520
1521     *ReferenceName =
1522         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1523     if (*ReferenceName == nullptr)
1524       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1525   }
1526   // If this arm64 and is an load register (PC-relative) instruction the
1527   // ReferenceValue is the PC plus the immediate value.
1528   else if (info->O->getArch() == Triple::aarch64 &&
1529            (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
1530             *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
1531     *ReferenceName =
1532         GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
1533     if (*ReferenceName == nullptr)
1534       *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1535   }
1536 #if HAVE_CXXABI_H
1537   else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
1538     if (info->demangled_name != nullptr)
1539       free(info->demangled_name);
1540     int status;
1541     info->demangled_name =
1542         abi::__cxa_demangle(SymbolName + 1, nullptr, nullptr, &status);
1543     if (info->demangled_name != nullptr) {
1544       *ReferenceName = info->demangled_name;
1545       *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
1546     }
1547   }
1548 #endif
1549   else {
1550     *ReferenceName = nullptr;
1551     *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
1552   }
1553
1554   return SymbolName;
1555 }
1556
1557 /// \brief Emits the comments that are stored in the CommentStream.
1558 /// Each comment in the CommentStream must end with a newline.
1559 static void emitComments(raw_svector_ostream &CommentStream,
1560                          SmallString<128> &CommentsToEmit,
1561                          formatted_raw_ostream &FormattedOS,
1562                          const MCAsmInfo &MAI) {
1563   // Flush the stream before taking its content.
1564   CommentStream.flush();
1565   StringRef Comments = CommentsToEmit.str();
1566   // Get the default information for printing a comment.
1567   const char *CommentBegin = MAI.getCommentString();
1568   unsigned CommentColumn = MAI.getCommentColumn();
1569   bool IsFirst = true;
1570   while (!Comments.empty()) {
1571     if (!IsFirst)
1572       FormattedOS << '\n';
1573     // Emit a line of comments.
1574     FormattedOS.PadToColumn(CommentColumn);
1575     size_t Position = Comments.find('\n');
1576     FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
1577     // Move after the newline character.
1578     Comments = Comments.substr(Position + 1);
1579     IsFirst = false;
1580   }
1581   FormattedOS.flush();
1582
1583   // Tell the comment stream that the vector changed underneath it.
1584   CommentsToEmit.clear();
1585   CommentStream.resync();
1586 }
1587
1588 static void DisassembleInputMachO2(StringRef Filename,
1589                                    MachOObjectFile *MachOOF) {
1590   const char *McpuDefault = nullptr;
1591   const Target *ThumbTarget = nullptr;
1592   const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
1593   if (!TheTarget) {
1594     // GetTarget prints out stuff.
1595     return;
1596   }
1597   if (MCPU.empty() && McpuDefault)
1598     MCPU = McpuDefault;
1599
1600   std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
1601   std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
1602   if (ThumbTarget)
1603     ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
1604
1605   // Package up features to be passed to target/subtarget
1606   std::string FeaturesStr;
1607   if (MAttrs.size()) {
1608     SubtargetFeatures Features;
1609     for (unsigned i = 0; i != MAttrs.size(); ++i)
1610       Features.AddFeature(MAttrs[i]);
1611     FeaturesStr = Features.getString();
1612   }
1613
1614   // Set up disassembler.
1615   std::unique_ptr<const MCRegisterInfo> MRI(
1616       TheTarget->createMCRegInfo(TripleName));
1617   std::unique_ptr<const MCAsmInfo> AsmInfo(
1618       TheTarget->createMCAsmInfo(*MRI, TripleName));
1619   std::unique_ptr<const MCSubtargetInfo> STI(
1620       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
1621   MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
1622   std::unique_ptr<MCDisassembler> DisAsm(
1623       TheTarget->createMCDisassembler(*STI, Ctx));
1624   std::unique_ptr<MCSymbolizer> Symbolizer;
1625   struct DisassembleInfo SymbolizerInfo;
1626   std::unique_ptr<MCRelocationInfo> RelInfo(
1627       TheTarget->createMCRelocationInfo(TripleName, Ctx));
1628   if (RelInfo) {
1629     Symbolizer.reset(TheTarget->createMCSymbolizer(
1630         TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1631         &SymbolizerInfo, &Ctx, RelInfo.release()));
1632     DisAsm->setSymbolizer(std::move(Symbolizer));
1633   }
1634   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1635   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1636       AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
1637   // Set the display preference for hex vs. decimal immediates.
1638   IP->setPrintImmHex(PrintImmHex);
1639   // Comment stream and backing vector.
1640   SmallString<128> CommentsToEmit;
1641   raw_svector_ostream CommentStream(CommentsToEmit);
1642
1643   if (!AsmInfo || !STI || !DisAsm || !IP) {
1644     errs() << "error: couldn't initialize disassembler for target "
1645            << TripleName << '\n';
1646     return;
1647   }
1648
1649   // Set up thumb disassembler.
1650   std::unique_ptr<const MCRegisterInfo> ThumbMRI;
1651   std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
1652   std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
1653   std::unique_ptr<MCDisassembler> ThumbDisAsm;
1654   std::unique_ptr<MCInstPrinter> ThumbIP;
1655   std::unique_ptr<MCContext> ThumbCtx;
1656   std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
1657   struct DisassembleInfo ThumbSymbolizerInfo;
1658   std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
1659   if (ThumbTarget) {
1660     ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
1661     ThumbAsmInfo.reset(
1662         ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
1663     ThumbSTI.reset(
1664         ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
1665     ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
1666     ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
1667     MCContext *PtrThumbCtx = ThumbCtx.get();
1668     ThumbRelInfo.reset(
1669         ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
1670     if (ThumbRelInfo) {
1671       ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
1672           ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
1673           &ThumbSymbolizerInfo, PtrThumbCtx, ThumbRelInfo.release()));
1674       ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
1675     }
1676     int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
1677     ThumbIP.reset(ThumbTarget->createMCInstPrinter(
1678         ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
1679         *ThumbSTI));
1680     // Set the display preference for hex vs. decimal immediates.
1681     ThumbIP->setPrintImmHex(PrintImmHex);
1682   }
1683
1684   if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
1685     errs() << "error: couldn't initialize disassembler for target "
1686            << ThumbTripleName << '\n';
1687     return;
1688   }
1689
1690   outs() << '\n' << Filename << ":\n\n";
1691
1692   MachO::mach_header Header = MachOOF->getHeader();
1693
1694   // FIXME: Using the -cfg command line option, this code used to be able to
1695   // annotate relocations with the referenced symbol's name, and if this was
1696   // inside a __[cf]string section, the data it points to. This is now replaced
1697   // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
1698   std::vector<SectionRef> Sections;
1699   std::vector<SymbolRef> Symbols;
1700   SmallVector<uint64_t, 8> FoundFns;
1701   uint64_t BaseSegmentAddress;
1702
1703   getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
1704                         BaseSegmentAddress);
1705
1706   // Sort the symbols by address, just in case they didn't come in that way.
1707   std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
1708
1709   // Build a data in code table that is sorted on by the address of each entry.
1710   uint64_t BaseAddress = 0;
1711   if (Header.filetype == MachO::MH_OBJECT)
1712     BaseAddress = Sections[0].getAddress();
1713   else
1714     BaseAddress = BaseSegmentAddress;
1715   DiceTable Dices;
1716   for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
1717        DI != DE; ++DI) {
1718     uint32_t Offset;
1719     DI->getOffset(Offset);
1720     Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
1721   }
1722   array_pod_sort(Dices.begin(), Dices.end());
1723
1724 #ifndef NDEBUG
1725   raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1726 #else
1727   raw_ostream &DebugOut = nulls();
1728 #endif
1729
1730   std::unique_ptr<DIContext> diContext;
1731   ObjectFile *DbgObj = MachOOF;
1732   // Try to find debug info and set up the DIContext for it.
1733   if (UseDbg) {
1734     // A separate DSym file path was specified, parse it as a macho file,
1735     // get the sections and supply it to the section name parsing machinery.
1736     if (!DSYMFile.empty()) {
1737       ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
1738           MemoryBuffer::getFileOrSTDIN(DSYMFile);
1739       if (std::error_code EC = BufOrErr.getError()) {
1740         errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
1741         return;
1742       }
1743       DbgObj =
1744           ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
1745               .get()
1746               .release();
1747     }
1748
1749     // Setup the DIContext
1750     diContext.reset(DIContext::getDWARFContext(*DbgObj));
1751   }
1752
1753   for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
1754
1755     bool SectIsText = Sections[SectIdx].isText();
1756     if (SectIsText == false)
1757       continue;
1758
1759     StringRef SectName;
1760     if (Sections[SectIdx].getName(SectName) || SectName != "__text")
1761       continue; // Skip non-text sections
1762
1763     DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
1764
1765     StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
1766     if (SegmentName != "__TEXT")
1767       continue;
1768
1769     StringRef BytesStr;
1770     Sections[SectIdx].getContents(BytesStr);
1771     ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1772                             BytesStr.size());
1773     uint64_t SectAddress = Sections[SectIdx].getAddress();
1774
1775     bool symbolTableWorked = false;
1776
1777     // Parse relocations.
1778     std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1779     for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
1780       uint64_t RelocOffset;
1781       Reloc.getOffset(RelocOffset);
1782       uint64_t SectionAddress = Sections[SectIdx].getAddress();
1783       RelocOffset -= SectionAddress;
1784
1785       symbol_iterator RelocSym = Reloc.getSymbol();
1786
1787       Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1788     }
1789     array_pod_sort(Relocs.begin(), Relocs.end());
1790
1791     // Create a map of symbol addresses to symbol names for use by
1792     // the SymbolizerSymbolLookUp() routine.
1793     SymbolAddressMap AddrMap;
1794     for (const SymbolRef &Symbol : MachOOF->symbols()) {
1795       SymbolRef::Type ST;
1796       Symbol.getType(ST);
1797       if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1798           ST == SymbolRef::ST_Other) {
1799         uint64_t Address;
1800         Symbol.getAddress(Address);
1801         StringRef SymName;
1802         Symbol.getName(SymName);
1803         AddrMap[Address] = SymName;
1804       }
1805     }
1806     // Set up the block of info used by the Symbolizer call backs.
1807     SymbolizerInfo.verbose = true;
1808     SymbolizerInfo.O = MachOOF;
1809     SymbolizerInfo.S = Sections[SectIdx];
1810     SymbolizerInfo.AddrMap = &AddrMap;
1811     SymbolizerInfo.Sections = &Sections;
1812     SymbolizerInfo.class_name = nullptr;
1813     SymbolizerInfo.selector_name = nullptr;
1814     SymbolizerInfo.method = nullptr;
1815     SymbolizerInfo.demangled_name = nullptr;
1816     SymbolizerInfo.bindtable = nullptr;
1817     // Same for the ThumbSymbolizer
1818     ThumbSymbolizerInfo.verbose = true;
1819     ThumbSymbolizerInfo.O = MachOOF;
1820     ThumbSymbolizerInfo.S = Sections[SectIdx];
1821     ThumbSymbolizerInfo.AddrMap = &AddrMap;
1822     ThumbSymbolizerInfo.Sections = &Sections;
1823     ThumbSymbolizerInfo.class_name = nullptr;
1824     ThumbSymbolizerInfo.selector_name = nullptr;
1825     ThumbSymbolizerInfo.method = nullptr;
1826     ThumbSymbolizerInfo.demangled_name = nullptr;
1827     ThumbSymbolizerInfo.bindtable = nullptr;
1828
1829     // Disassemble symbol by symbol.
1830     for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
1831       StringRef SymName;
1832       Symbols[SymIdx].getName(SymName);
1833
1834       SymbolRef::Type ST;
1835       Symbols[SymIdx].getType(ST);
1836       if (ST != SymbolRef::ST_Function)
1837         continue;
1838
1839       // Make sure the symbol is defined in this section.
1840       bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
1841       if (!containsSym)
1842         continue;
1843
1844       // Start at the address of the symbol relative to the section's address.
1845       uint64_t Start = 0;
1846       uint64_t SectionAddress = Sections[SectIdx].getAddress();
1847       Symbols[SymIdx].getAddress(Start);
1848       Start -= SectionAddress;
1849
1850       // Stop disassembling either at the beginning of the next symbol or at
1851       // the end of the section.
1852       bool containsNextSym = false;
1853       uint64_t NextSym = 0;
1854       uint64_t NextSymIdx = SymIdx + 1;
1855       while (Symbols.size() > NextSymIdx) {
1856         SymbolRef::Type NextSymType;
1857         Symbols[NextSymIdx].getType(NextSymType);
1858         if (NextSymType == SymbolRef::ST_Function) {
1859           containsNextSym =
1860               Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
1861           Symbols[NextSymIdx].getAddress(NextSym);
1862           NextSym -= SectionAddress;
1863           break;
1864         }
1865         ++NextSymIdx;
1866       }
1867
1868       uint64_t SectSize = Sections[SectIdx].getSize();
1869       uint64_t End = containsNextSym ? NextSym : SectSize;
1870       uint64_t Size;
1871
1872       symbolTableWorked = true;
1873
1874       DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
1875       bool isThumb =
1876           (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
1877
1878       outs() << SymName << ":\n";
1879       DILineInfo lastLine;
1880       for (uint64_t Index = Start; Index < End; Index += Size) {
1881         MCInst Inst;
1882
1883         uint64_t PC = SectAddress + Index;
1884         if (FullLeadingAddr) {
1885           if (MachOOF->is64Bit())
1886             outs() << format("%016" PRIx64, PC);
1887           else
1888             outs() << format("%08" PRIx64, PC);
1889         } else {
1890           outs() << format("%8" PRIx64 ":", PC);
1891         }
1892         if (!NoShowRawInsn)
1893           outs() << "\t";
1894
1895         // Check the data in code table here to see if this is data not an
1896         // instruction to be disassembled.
1897         DiceTable Dice;
1898         Dice.push_back(std::make_pair(PC, DiceRef()));
1899         dice_table_iterator DTI =
1900             std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
1901                         compareDiceTableEntries);
1902         if (DTI != Dices.end()) {
1903           uint16_t Length;
1904           DTI->second.getLength(Length);
1905           uint16_t Kind;
1906           DTI->second.getKind(Kind);
1907           Size = DumpDataInCode(reinterpret_cast<const char *>(Bytes.data()) +
1908                                     Index,
1909                                 Length, Kind);
1910           if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
1911               (PC == (DTI->first + Length - 1)) && (Length & 1))
1912             Size++;
1913           continue;
1914         }
1915
1916         SmallVector<char, 64> AnnotationsBytes;
1917         raw_svector_ostream Annotations(AnnotationsBytes);
1918
1919         bool gotInst;
1920         if (isThumb)
1921           gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1922                                                 PC, DebugOut, Annotations);
1923         else
1924           gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
1925                                            DebugOut, Annotations);
1926         if (gotInst) {
1927           if (!NoShowRawInsn) {
1928             DumpBytes(StringRef(
1929                 reinterpret_cast<const char *>(Bytes.data()) + Index, Size));
1930           }
1931           formatted_raw_ostream FormattedOS(outs());
1932           Annotations.flush();
1933           StringRef AnnotationsStr = Annotations.str();
1934           if (isThumb)
1935             ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr);
1936           else
1937             IP->printInst(&Inst, FormattedOS, AnnotationsStr);
1938           emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
1939
1940           // Print debug info.
1941           if (diContext) {
1942             DILineInfo dli = diContext->getLineInfoForAddress(PC);
1943             // Print valid line info if it changed.
1944             if (dli != lastLine && dli.Line != 0)
1945               outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
1946                      << dli.Column;
1947             lastLine = dli;
1948           }
1949           outs() << "\n";
1950         } else {
1951           unsigned int Arch = MachOOF->getArch();
1952           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
1953             outs() << format("\t.byte 0x%02x #bad opcode\n",
1954                              *(Bytes.data() + Index) & 0xff);
1955             Size = 1; // skip exactly one illegible byte and move on.
1956           } else if (Arch == Triple::aarch64) {
1957             uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
1958                               (*(Bytes.data() + Index + 1) & 0xff) << 8 |
1959                               (*(Bytes.data() + Index + 2) & 0xff) << 16 |
1960                               (*(Bytes.data() + Index + 3) & 0xff) << 24;
1961             outs() << format("\t.long\t0x%08x\n", opcode);
1962             Size = 4;
1963           } else {
1964             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
1965             if (Size == 0)
1966               Size = 1; // skip illegible bytes
1967           }
1968         }
1969       }
1970     }
1971     if (!symbolTableWorked) {
1972       // Reading the symbol table didn't work, disassemble the whole section.
1973       uint64_t SectAddress = Sections[SectIdx].getAddress();
1974       uint64_t SectSize = Sections[SectIdx].getSize();
1975       uint64_t InstSize;
1976       for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
1977         MCInst Inst;
1978
1979         uint64_t PC = SectAddress + Index;
1980         if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
1981                                    DebugOut, nulls())) {
1982           if (FullLeadingAddr) {
1983             if (MachOOF->is64Bit())
1984               outs() << format("%016" PRIx64, PC);
1985             else
1986               outs() << format("%08" PRIx64, PC);
1987           } else {
1988             outs() << format("%8" PRIx64 ":", PC);
1989           }
1990           if (!NoShowRawInsn) {
1991             outs() << "\t";
1992             DumpBytes(
1993                 StringRef(reinterpret_cast<const char *>(Bytes.data()) + Index,
1994                           InstSize));
1995           }
1996           IP->printInst(&Inst, outs(), "");
1997           outs() << "\n";
1998         } else {
1999           unsigned int Arch = MachOOF->getArch();
2000           if (Arch == Triple::x86_64 || Arch == Triple::x86) {
2001             outs() << format("\t.byte 0x%02x #bad opcode\n",
2002                              *(Bytes.data() + Index) & 0xff);
2003             InstSize = 1; // skip exactly one illegible byte and move on.
2004           } else {
2005             errs() << "llvm-objdump: warning: invalid instruction encoding\n";
2006             if (InstSize == 0)
2007               InstSize = 1; // skip illegible bytes
2008           }
2009         }
2010       }
2011     }
2012     if (SymbolizerInfo.method != nullptr)
2013       free(SymbolizerInfo.method);
2014     if (SymbolizerInfo.demangled_name != nullptr)
2015       free(SymbolizerInfo.demangled_name);
2016     if (SymbolizerInfo.bindtable != nullptr)
2017       delete SymbolizerInfo.bindtable;
2018     if (ThumbSymbolizerInfo.method != nullptr)
2019       free(ThumbSymbolizerInfo.method);
2020     if (ThumbSymbolizerInfo.demangled_name != nullptr)
2021       free(ThumbSymbolizerInfo.demangled_name);
2022     if (ThumbSymbolizerInfo.bindtable != nullptr)
2023       delete ThumbSymbolizerInfo.bindtable;
2024   }
2025 }
2026
2027 //===----------------------------------------------------------------------===//
2028 // __compact_unwind section dumping
2029 //===----------------------------------------------------------------------===//
2030
2031 namespace {
2032
2033 template <typename T> static uint64_t readNext(const char *&Buf) {
2034   using llvm::support::little;
2035   using llvm::support::unaligned;
2036
2037   uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
2038   Buf += sizeof(T);
2039   return Val;
2040 }
2041
2042 struct CompactUnwindEntry {
2043   uint32_t OffsetInSection;
2044
2045   uint64_t FunctionAddr;
2046   uint32_t Length;
2047   uint32_t CompactEncoding;
2048   uint64_t PersonalityAddr;
2049   uint64_t LSDAAddr;
2050
2051   RelocationRef FunctionReloc;
2052   RelocationRef PersonalityReloc;
2053   RelocationRef LSDAReloc;
2054
2055   CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
2056       : OffsetInSection(Offset) {
2057     if (Is64)
2058       read<uint64_t>(Contents.data() + Offset);
2059     else
2060       read<uint32_t>(Contents.data() + Offset);
2061   }
2062
2063 private:
2064   template <typename UIntPtr> void read(const char *Buf) {
2065     FunctionAddr = readNext<UIntPtr>(Buf);
2066     Length = readNext<uint32_t>(Buf);
2067     CompactEncoding = readNext<uint32_t>(Buf);
2068     PersonalityAddr = readNext<UIntPtr>(Buf);
2069     LSDAAddr = readNext<UIntPtr>(Buf);
2070   }
2071 };
2072 }
2073
2074 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
2075 /// and data being relocated, determine the best base Name and Addend to use for
2076 /// display purposes.
2077 ///
2078 /// 1. An Extern relocation will directly reference a symbol (and the data is
2079 ///    then already an addend), so use that.
2080 /// 2. Otherwise the data is an offset in the object file's layout; try to find
2081 //     a symbol before it in the same section, and use the offset from there.
2082 /// 3. Finally, if all that fails, fall back to an offset from the start of the
2083 ///    referenced section.
2084 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
2085                                       std::map<uint64_t, SymbolRef> &Symbols,
2086                                       const RelocationRef &Reloc, uint64_t Addr,
2087                                       StringRef &Name, uint64_t &Addend) {
2088   if (Reloc.getSymbol() != Obj->symbol_end()) {
2089     Reloc.getSymbol()->getName(Name);
2090     Addend = Addr;
2091     return;
2092   }
2093
2094   auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
2095   SectionRef RelocSection = Obj->getRelocationSection(RE);
2096
2097   uint64_t SectionAddr = RelocSection.getAddress();
2098
2099   auto Sym = Symbols.upper_bound(Addr);
2100   if (Sym == Symbols.begin()) {
2101     // The first symbol in the object is after this reference, the best we can
2102     // do is section-relative notation.
2103     RelocSection.getName(Name);
2104     Addend = Addr - SectionAddr;
2105     return;
2106   }
2107
2108   // Go back one so that SymbolAddress <= Addr.
2109   --Sym;
2110
2111   section_iterator SymSection = Obj->section_end();
2112   Sym->second.getSection(SymSection);
2113   if (RelocSection == *SymSection) {
2114     // There's a valid symbol in the same section before this reference.
2115     Sym->second.getName(Name);
2116     Addend = Addr - Sym->first;
2117     return;
2118   }
2119
2120   // There is a symbol before this reference, but it's in a different
2121   // section. Probably not helpful to mention it, so use the section name.
2122   RelocSection.getName(Name);
2123   Addend = Addr - SectionAddr;
2124 }
2125
2126 static void printUnwindRelocDest(const MachOObjectFile *Obj,
2127                                  std::map<uint64_t, SymbolRef> &Symbols,
2128                                  const RelocationRef &Reloc, uint64_t Addr) {
2129   StringRef Name;
2130   uint64_t Addend;
2131
2132   if (!Reloc.getObjectFile())
2133     return;
2134
2135   findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
2136
2137   outs() << Name;
2138   if (Addend)
2139     outs() << " + " << format("0x%" PRIx64, Addend);
2140 }
2141
2142 static void
2143 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
2144                                std::map<uint64_t, SymbolRef> &Symbols,
2145                                const SectionRef &CompactUnwind) {
2146
2147   assert(Obj->isLittleEndian() &&
2148          "There should not be a big-endian .o with __compact_unwind");
2149
2150   bool Is64 = Obj->is64Bit();
2151   uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
2152   uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
2153
2154   StringRef Contents;
2155   CompactUnwind.getContents(Contents);
2156
2157   SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
2158
2159   // First populate the initial raw offsets, encodings and so on from the entry.
2160   for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
2161     CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
2162     CompactUnwinds.push_back(Entry);
2163   }
2164
2165   // Next we need to look at the relocations to find out what objects are
2166   // actually being referred to.
2167   for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
2168     uint64_t RelocAddress;
2169     Reloc.getOffset(RelocAddress);
2170
2171     uint32_t EntryIdx = RelocAddress / EntrySize;
2172     uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
2173     CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
2174
2175     if (OffsetInEntry == 0)
2176       Entry.FunctionReloc = Reloc;
2177     else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
2178       Entry.PersonalityReloc = Reloc;
2179     else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
2180       Entry.LSDAReloc = Reloc;
2181     else
2182       llvm_unreachable("Unexpected relocation in __compact_unwind section");
2183   }
2184
2185   // Finally, we're ready to print the data we've gathered.
2186   outs() << "Contents of __compact_unwind section:\n";
2187   for (auto &Entry : CompactUnwinds) {
2188     outs() << "  Entry at offset "
2189            << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
2190
2191     // 1. Start of the region this entry applies to.
2192     outs() << "    start:                " << format("0x%" PRIx64,
2193                                                      Entry.FunctionAddr) << ' ';
2194     printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
2195     outs() << '\n';
2196
2197     // 2. Length of the region this entry applies to.
2198     outs() << "    length:               " << format("0x%" PRIx32, Entry.Length)
2199            << '\n';
2200     // 3. The 32-bit compact encoding.
2201     outs() << "    compact encoding:     "
2202            << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
2203
2204     // 4. The personality function, if present.
2205     if (Entry.PersonalityReloc.getObjectFile()) {
2206       outs() << "    personality function: "
2207              << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
2208       printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
2209                            Entry.PersonalityAddr);
2210       outs() << '\n';
2211     }
2212
2213     // 5. This entry's language-specific data area.
2214     if (Entry.LSDAReloc.getObjectFile()) {
2215       outs() << "    LSDA:                 " << format("0x%" PRIx64,
2216                                                        Entry.LSDAAddr) << ' ';
2217       printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
2218       outs() << '\n';
2219     }
2220   }
2221 }
2222
2223 //===----------------------------------------------------------------------===//
2224 // __unwind_info section dumping
2225 //===----------------------------------------------------------------------===//
2226
2227 static void printRegularSecondLevelUnwindPage(const char *PageStart) {
2228   const char *Pos = PageStart;
2229   uint32_t Kind = readNext<uint32_t>(Pos);
2230   (void)Kind;
2231   assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
2232
2233   uint16_t EntriesStart = readNext<uint16_t>(Pos);
2234   uint16_t NumEntries = readNext<uint16_t>(Pos);
2235
2236   Pos = PageStart + EntriesStart;
2237   for (unsigned i = 0; i < NumEntries; ++i) {
2238     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2239     uint32_t Encoding = readNext<uint32_t>(Pos);
2240
2241     outs() << "      [" << i << "]: "
2242            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2243            << ", "
2244            << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
2245   }
2246 }
2247
2248 static void printCompressedSecondLevelUnwindPage(
2249     const char *PageStart, uint32_t FunctionBase,
2250     const SmallVectorImpl<uint32_t> &CommonEncodings) {
2251   const char *Pos = PageStart;
2252   uint32_t Kind = readNext<uint32_t>(Pos);
2253   (void)Kind;
2254   assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
2255
2256   uint16_t EntriesStart = readNext<uint16_t>(Pos);
2257   uint16_t NumEntries = readNext<uint16_t>(Pos);
2258
2259   uint16_t EncodingsStart = readNext<uint16_t>(Pos);
2260   readNext<uint16_t>(Pos);
2261   const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
2262       PageStart + EncodingsStart);
2263
2264   Pos = PageStart + EntriesStart;
2265   for (unsigned i = 0; i < NumEntries; ++i) {
2266     uint32_t Entry = readNext<uint32_t>(Pos);
2267     uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
2268     uint32_t EncodingIdx = Entry >> 24;
2269
2270     uint32_t Encoding;
2271     if (EncodingIdx < CommonEncodings.size())
2272       Encoding = CommonEncodings[EncodingIdx];
2273     else
2274       Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
2275
2276     outs() << "      [" << i << "]: "
2277            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2278            << ", "
2279            << "encoding[" << EncodingIdx
2280            << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
2281   }
2282 }
2283
2284 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
2285                                         std::map<uint64_t, SymbolRef> &Symbols,
2286                                         const SectionRef &UnwindInfo) {
2287
2288   assert(Obj->isLittleEndian() &&
2289          "There should not be a big-endian .o with __unwind_info");
2290
2291   outs() << "Contents of __unwind_info section:\n";
2292
2293   StringRef Contents;
2294   UnwindInfo.getContents(Contents);
2295   const char *Pos = Contents.data();
2296
2297   //===----------------------------------
2298   // Section header
2299   //===----------------------------------
2300
2301   uint32_t Version = readNext<uint32_t>(Pos);
2302   outs() << "  Version:                                   "
2303          << format("0x%" PRIx32, Version) << '\n';
2304   assert(Version == 1 && "only understand version 1");
2305
2306   uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
2307   outs() << "  Common encodings array section offset:     "
2308          << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
2309   uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
2310   outs() << "  Number of common encodings in array:       "
2311          << format("0x%" PRIx32, NumCommonEncodings) << '\n';
2312
2313   uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
2314   outs() << "  Personality function array section offset: "
2315          << format("0x%" PRIx32, PersonalitiesStart) << '\n';
2316   uint32_t NumPersonalities = readNext<uint32_t>(Pos);
2317   outs() << "  Number of personality functions in array:  "
2318          << format("0x%" PRIx32, NumPersonalities) << '\n';
2319
2320   uint32_t IndicesStart = readNext<uint32_t>(Pos);
2321   outs() << "  Index array section offset:                "
2322          << format("0x%" PRIx32, IndicesStart) << '\n';
2323   uint32_t NumIndices = readNext<uint32_t>(Pos);
2324   outs() << "  Number of indices in array:                "
2325          << format("0x%" PRIx32, NumIndices) << '\n';
2326
2327   //===----------------------------------
2328   // A shared list of common encodings
2329   //===----------------------------------
2330
2331   // These occupy indices in the range [0, N] whenever an encoding is referenced
2332   // from a compressed 2nd level index table. In practice the linker only
2333   // creates ~128 of these, so that indices are available to embed encodings in
2334   // the 2nd level index.
2335
2336   SmallVector<uint32_t, 64> CommonEncodings;
2337   outs() << "  Common encodings: (count = " << NumCommonEncodings << ")\n";
2338   Pos = Contents.data() + CommonEncodingsStart;
2339   for (unsigned i = 0; i < NumCommonEncodings; ++i) {
2340     uint32_t Encoding = readNext<uint32_t>(Pos);
2341     CommonEncodings.push_back(Encoding);
2342
2343     outs() << "    encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
2344            << '\n';
2345   }
2346
2347   //===----------------------------------
2348   // Personality functions used in this executable
2349   //===----------------------------------
2350
2351   // There should be only a handful of these (one per source language,
2352   // roughly). Particularly since they only get 2 bits in the compact encoding.
2353
2354   outs() << "  Personality functions: (count = " << NumPersonalities << ")\n";
2355   Pos = Contents.data() + PersonalitiesStart;
2356   for (unsigned i = 0; i < NumPersonalities; ++i) {
2357     uint32_t PersonalityFn = readNext<uint32_t>(Pos);
2358     outs() << "    personality[" << i + 1
2359            << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
2360   }
2361
2362   //===----------------------------------
2363   // The level 1 index entries
2364   //===----------------------------------
2365
2366   // These specify an approximate place to start searching for the more detailed
2367   // information, sorted by PC.
2368
2369   struct IndexEntry {
2370     uint32_t FunctionOffset;
2371     uint32_t SecondLevelPageStart;
2372     uint32_t LSDAStart;
2373   };
2374
2375   SmallVector<IndexEntry, 4> IndexEntries;
2376
2377   outs() << "  Top level indices: (count = " << NumIndices << ")\n";
2378   Pos = Contents.data() + IndicesStart;
2379   for (unsigned i = 0; i < NumIndices; ++i) {
2380     IndexEntry Entry;
2381
2382     Entry.FunctionOffset = readNext<uint32_t>(Pos);
2383     Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
2384     Entry.LSDAStart = readNext<uint32_t>(Pos);
2385     IndexEntries.push_back(Entry);
2386
2387     outs() << "    [" << i << "]: "
2388            << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
2389            << ", "
2390            << "2nd level page offset="
2391            << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
2392            << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
2393   }
2394
2395   //===----------------------------------
2396   // Next come the LSDA tables
2397   //===----------------------------------
2398
2399   // The LSDA layout is rather implicit: it's a contiguous array of entries from
2400   // the first top-level index's LSDAOffset to the last (sentinel).
2401
2402   outs() << "  LSDA descriptors:\n";
2403   Pos = Contents.data() + IndexEntries[0].LSDAStart;
2404   int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
2405                  (2 * sizeof(uint32_t));
2406   for (int i = 0; i < NumLSDAs; ++i) {
2407     uint32_t FunctionOffset = readNext<uint32_t>(Pos);
2408     uint32_t LSDAOffset = readNext<uint32_t>(Pos);
2409     outs() << "    [" << i << "]: "
2410            << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
2411            << ", "
2412            << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
2413   }
2414
2415   //===----------------------------------
2416   // Finally, the 2nd level indices
2417   //===----------------------------------
2418
2419   // Generally these are 4K in size, and have 2 possible forms:
2420   //   + Regular stores up to 511 entries with disparate encodings
2421   //   + Compressed stores up to 1021 entries if few enough compact encoding
2422   //     values are used.
2423   outs() << "  Second level indices:\n";
2424   for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
2425     // The final sentinel top-level index has no associated 2nd level page
2426     if (IndexEntries[i].SecondLevelPageStart == 0)
2427       break;
2428
2429     outs() << "    Second level index[" << i << "]: "
2430            << "offset in section="
2431            << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
2432            << ", "
2433            << "base function offset="
2434            << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
2435
2436     Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
2437     uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
2438     if (Kind == 2)
2439       printRegularSecondLevelUnwindPage(Pos);
2440     else if (Kind == 3)
2441       printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
2442                                            CommonEncodings);
2443     else
2444       llvm_unreachable("Do not know how to print this kind of 2nd level page");
2445   }
2446 }
2447
2448 void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
2449   std::map<uint64_t, SymbolRef> Symbols;
2450   for (const SymbolRef &SymRef : Obj->symbols()) {
2451     // Discard any undefined or absolute symbols. They're not going to take part
2452     // in the convenience lookup for unwind info and just take up resources.
2453     section_iterator Section = Obj->section_end();
2454     SymRef.getSection(Section);
2455     if (Section == Obj->section_end())
2456       continue;
2457
2458     uint64_t Addr;
2459     SymRef.getAddress(Addr);
2460     Symbols.insert(std::make_pair(Addr, SymRef));
2461   }
2462
2463   for (const SectionRef &Section : Obj->sections()) {
2464     StringRef SectName;
2465     Section.getName(SectName);
2466     if (SectName == "__compact_unwind")
2467       printMachOCompactUnwindSection(Obj, Symbols, Section);
2468     else if (SectName == "__unwind_info")
2469       printMachOUnwindInfoSection(Obj, Symbols, Section);
2470     else if (SectName == "__eh_frame")
2471       outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
2472   }
2473 }
2474
2475 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
2476                             uint32_t cpusubtype, uint32_t filetype,
2477                             uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
2478                             bool verbose) {
2479   outs() << "Mach header\n";
2480   outs() << "      magic cputype cpusubtype  caps    filetype ncmds "
2481             "sizeofcmds      flags\n";
2482   if (verbose) {
2483     if (magic == MachO::MH_MAGIC)
2484       outs() << "   MH_MAGIC";
2485     else if (magic == MachO::MH_MAGIC_64)
2486       outs() << "MH_MAGIC_64";
2487     else
2488       outs() << format(" 0x%08" PRIx32, magic);
2489     switch (cputype) {
2490     case MachO::CPU_TYPE_I386:
2491       outs() << "    I386";
2492       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2493       case MachO::CPU_SUBTYPE_I386_ALL:
2494         outs() << "        ALL";
2495         break;
2496       default:
2497         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2498         break;
2499       }
2500       break;
2501     case MachO::CPU_TYPE_X86_64:
2502       outs() << "  X86_64";
2503     case MachO::CPU_SUBTYPE_X86_64_ALL:
2504       outs() << "        ALL";
2505       break;
2506     case MachO::CPU_SUBTYPE_X86_64_H:
2507       outs() << "    Haswell";
2508       outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2509       break;
2510     case MachO::CPU_TYPE_ARM:
2511       outs() << "     ARM";
2512       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2513       case MachO::CPU_SUBTYPE_ARM_ALL:
2514         outs() << "        ALL";
2515         break;
2516       case MachO::CPU_SUBTYPE_ARM_V4T:
2517         outs() << "        V4T";
2518         break;
2519       case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2520         outs() << "      V5TEJ";
2521         break;
2522       case MachO::CPU_SUBTYPE_ARM_XSCALE:
2523         outs() << "     XSCALE";
2524         break;
2525       case MachO::CPU_SUBTYPE_ARM_V6:
2526         outs() << "         V6";
2527         break;
2528       case MachO::CPU_SUBTYPE_ARM_V6M:
2529         outs() << "        V6M";
2530         break;
2531       case MachO::CPU_SUBTYPE_ARM_V7:
2532         outs() << "         V7";
2533         break;
2534       case MachO::CPU_SUBTYPE_ARM_V7EM:
2535         outs() << "       V7EM";
2536         break;
2537       case MachO::CPU_SUBTYPE_ARM_V7K:
2538         outs() << "        V7K";
2539         break;
2540       case MachO::CPU_SUBTYPE_ARM_V7M:
2541         outs() << "        V7M";
2542         break;
2543       case MachO::CPU_SUBTYPE_ARM_V7S:
2544         outs() << "        V7S";
2545         break;
2546       default:
2547         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2548         break;
2549       }
2550       break;
2551     case MachO::CPU_TYPE_ARM64:
2552       outs() << "   ARM64";
2553       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2554       case MachO::CPU_SUBTYPE_ARM64_ALL:
2555         outs() << "        ALL";
2556         break;
2557       default:
2558         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2559         break;
2560       }
2561       break;
2562     case MachO::CPU_TYPE_POWERPC:
2563       outs() << "     PPC";
2564       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2565       case MachO::CPU_SUBTYPE_POWERPC_ALL:
2566         outs() << "        ALL";
2567         break;
2568       default:
2569         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2570         break;
2571       }
2572       break;
2573     case MachO::CPU_TYPE_POWERPC64:
2574       outs() << "   PPC64";
2575       switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2576       case MachO::CPU_SUBTYPE_POWERPC_ALL:
2577         outs() << "        ALL";
2578         break;
2579       default:
2580         outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2581         break;
2582       }
2583       break;
2584     }
2585     if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
2586       outs() << " LIB64";
2587     } else {
2588       outs() << format("  0x%02" PRIx32,
2589                        (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2590     }
2591     switch (filetype) {
2592     case MachO::MH_OBJECT:
2593       outs() << "      OBJECT";
2594       break;
2595     case MachO::MH_EXECUTE:
2596       outs() << "     EXECUTE";
2597       break;
2598     case MachO::MH_FVMLIB:
2599       outs() << "      FVMLIB";
2600       break;
2601     case MachO::MH_CORE:
2602       outs() << "        CORE";
2603       break;
2604     case MachO::MH_PRELOAD:
2605       outs() << "     PRELOAD";
2606       break;
2607     case MachO::MH_DYLIB:
2608       outs() << "       DYLIB";
2609       break;
2610     case MachO::MH_DYLIB_STUB:
2611       outs() << "  DYLIB_STUB";
2612       break;
2613     case MachO::MH_DYLINKER:
2614       outs() << "    DYLINKER";
2615       break;
2616     case MachO::MH_BUNDLE:
2617       outs() << "      BUNDLE";
2618       break;
2619     case MachO::MH_DSYM:
2620       outs() << "        DSYM";
2621       break;
2622     case MachO::MH_KEXT_BUNDLE:
2623       outs() << "  KEXTBUNDLE";
2624       break;
2625     default:
2626       outs() << format("  %10u", filetype);
2627       break;
2628     }
2629     outs() << format(" %5u", ncmds);
2630     outs() << format(" %10u", sizeofcmds);
2631     uint32_t f = flags;
2632     if (f & MachO::MH_NOUNDEFS) {
2633       outs() << "   NOUNDEFS";
2634       f &= ~MachO::MH_NOUNDEFS;
2635     }
2636     if (f & MachO::MH_INCRLINK) {
2637       outs() << " INCRLINK";
2638       f &= ~MachO::MH_INCRLINK;
2639     }
2640     if (f & MachO::MH_DYLDLINK) {
2641       outs() << " DYLDLINK";
2642       f &= ~MachO::MH_DYLDLINK;
2643     }
2644     if (f & MachO::MH_BINDATLOAD) {
2645       outs() << " BINDATLOAD";
2646       f &= ~MachO::MH_BINDATLOAD;
2647     }
2648     if (f & MachO::MH_PREBOUND) {
2649       outs() << " PREBOUND";
2650       f &= ~MachO::MH_PREBOUND;
2651     }
2652     if (f & MachO::MH_SPLIT_SEGS) {
2653       outs() << " SPLIT_SEGS";
2654       f &= ~MachO::MH_SPLIT_SEGS;
2655     }
2656     if (f & MachO::MH_LAZY_INIT) {
2657       outs() << " LAZY_INIT";
2658       f &= ~MachO::MH_LAZY_INIT;
2659     }
2660     if (f & MachO::MH_TWOLEVEL) {
2661       outs() << " TWOLEVEL";
2662       f &= ~MachO::MH_TWOLEVEL;
2663     }
2664     if (f & MachO::MH_FORCE_FLAT) {
2665       outs() << " FORCE_FLAT";
2666       f &= ~MachO::MH_FORCE_FLAT;
2667     }
2668     if (f & MachO::MH_NOMULTIDEFS) {
2669       outs() << " NOMULTIDEFS";
2670       f &= ~MachO::MH_NOMULTIDEFS;
2671     }
2672     if (f & MachO::MH_NOFIXPREBINDING) {
2673       outs() << " NOFIXPREBINDING";
2674       f &= ~MachO::MH_NOFIXPREBINDING;
2675     }
2676     if (f & MachO::MH_PREBINDABLE) {
2677       outs() << " PREBINDABLE";
2678       f &= ~MachO::MH_PREBINDABLE;
2679     }
2680     if (f & MachO::MH_ALLMODSBOUND) {
2681       outs() << " ALLMODSBOUND";
2682       f &= ~MachO::MH_ALLMODSBOUND;
2683     }
2684     if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
2685       outs() << " SUBSECTIONS_VIA_SYMBOLS";
2686       f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
2687     }
2688     if (f & MachO::MH_CANONICAL) {
2689       outs() << " CANONICAL";
2690       f &= ~MachO::MH_CANONICAL;
2691     }
2692     if (f & MachO::MH_WEAK_DEFINES) {
2693       outs() << " WEAK_DEFINES";
2694       f &= ~MachO::MH_WEAK_DEFINES;
2695     }
2696     if (f & MachO::MH_BINDS_TO_WEAK) {
2697       outs() << " BINDS_TO_WEAK";
2698       f &= ~MachO::MH_BINDS_TO_WEAK;
2699     }
2700     if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
2701       outs() << " ALLOW_STACK_EXECUTION";
2702       f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
2703     }
2704     if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
2705       outs() << " DEAD_STRIPPABLE_DYLIB";
2706       f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
2707     }
2708     if (f & MachO::MH_PIE) {
2709       outs() << " PIE";
2710       f &= ~MachO::MH_PIE;
2711     }
2712     if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
2713       outs() << " NO_REEXPORTED_DYLIBS";
2714       f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
2715     }
2716     if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
2717       outs() << " MH_HAS_TLV_DESCRIPTORS";
2718       f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
2719     }
2720     if (f & MachO::MH_NO_HEAP_EXECUTION) {
2721       outs() << " MH_NO_HEAP_EXECUTION";
2722       f &= ~MachO::MH_NO_HEAP_EXECUTION;
2723     }
2724     if (f & MachO::MH_APP_EXTENSION_SAFE) {
2725       outs() << " APP_EXTENSION_SAFE";
2726       f &= ~MachO::MH_APP_EXTENSION_SAFE;
2727     }
2728     if (f != 0 || flags == 0)
2729       outs() << format(" 0x%08" PRIx32, f);
2730   } else {
2731     outs() << format(" 0x%08" PRIx32, magic);
2732     outs() << format(" %7d", cputype);
2733     outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2734     outs() << format("  0x%02" PRIx32,
2735                      (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
2736     outs() << format("  %10u", filetype);
2737     outs() << format(" %5u", ncmds);
2738     outs() << format(" %10u", sizeofcmds);
2739     outs() << format(" 0x%08" PRIx32, flags);
2740   }
2741   outs() << "\n";
2742 }
2743
2744 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
2745                                 StringRef SegName, uint64_t vmaddr,
2746                                 uint64_t vmsize, uint64_t fileoff,
2747                                 uint64_t filesize, uint32_t maxprot,
2748                                 uint32_t initprot, uint32_t nsects,
2749                                 uint32_t flags, uint32_t object_size,
2750                                 bool verbose) {
2751   uint64_t expected_cmdsize;
2752   if (cmd == MachO::LC_SEGMENT) {
2753     outs() << "      cmd LC_SEGMENT\n";
2754     expected_cmdsize = nsects;
2755     expected_cmdsize *= sizeof(struct MachO::section);
2756     expected_cmdsize += sizeof(struct MachO::segment_command);
2757   } else {
2758     outs() << "      cmd LC_SEGMENT_64\n";
2759     expected_cmdsize = nsects;
2760     expected_cmdsize *= sizeof(struct MachO::section_64);
2761     expected_cmdsize += sizeof(struct MachO::segment_command_64);
2762   }
2763   outs() << "  cmdsize " << cmdsize;
2764   if (cmdsize != expected_cmdsize)
2765     outs() << " Inconsistent size\n";
2766   else
2767     outs() << "\n";
2768   outs() << "  segname " << SegName << "\n";
2769   if (cmd == MachO::LC_SEGMENT_64) {
2770     outs() << "   vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
2771     outs() << "   vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
2772   } else {
2773     outs() << "   vmaddr " << format("0x%08" PRIx32, vmaddr) << "\n";
2774     outs() << "   vmsize " << format("0x%08" PRIx32, vmsize) << "\n";
2775   }
2776   outs() << "  fileoff " << fileoff;
2777   if (fileoff > object_size)
2778     outs() << " (past end of file)\n";
2779   else
2780     outs() << "\n";
2781   outs() << " filesize " << filesize;
2782   if (fileoff + filesize > object_size)
2783     outs() << " (past end of file)\n";
2784   else
2785     outs() << "\n";
2786   if (verbose) {
2787     if ((maxprot &
2788          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2789            MachO::VM_PROT_EXECUTE)) != 0)
2790       outs() << "  maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
2791     else {
2792       if (maxprot & MachO::VM_PROT_READ)
2793         outs() << "  maxprot r";
2794       else
2795         outs() << "  maxprot -";
2796       if (maxprot & MachO::VM_PROT_WRITE)
2797         outs() << "w";
2798       else
2799         outs() << "-";
2800       if (maxprot & MachO::VM_PROT_EXECUTE)
2801         outs() << "x\n";
2802       else
2803         outs() << "-\n";
2804     }
2805     if ((initprot &
2806          ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
2807            MachO::VM_PROT_EXECUTE)) != 0)
2808       outs() << "  initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
2809     else {
2810       if (initprot & MachO::VM_PROT_READ)
2811         outs() << " initprot r";
2812       else
2813         outs() << " initprot -";
2814       if (initprot & MachO::VM_PROT_WRITE)
2815         outs() << "w";
2816       else
2817         outs() << "-";
2818       if (initprot & MachO::VM_PROT_EXECUTE)
2819         outs() << "x\n";
2820       else
2821         outs() << "-\n";
2822     }
2823   } else {
2824     outs() << "  maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
2825     outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
2826   }
2827   outs() << "   nsects " << nsects << "\n";
2828   if (verbose) {
2829     outs() << "    flags";
2830     if (flags == 0)
2831       outs() << " (none)\n";
2832     else {
2833       if (flags & MachO::SG_HIGHVM) {
2834         outs() << " HIGHVM";
2835         flags &= ~MachO::SG_HIGHVM;
2836       }
2837       if (flags & MachO::SG_FVMLIB) {
2838         outs() << " FVMLIB";
2839         flags &= ~MachO::SG_FVMLIB;
2840       }
2841       if (flags & MachO::SG_NORELOC) {
2842         outs() << " NORELOC";
2843         flags &= ~MachO::SG_NORELOC;
2844       }
2845       if (flags & MachO::SG_PROTECTED_VERSION_1) {
2846         outs() << " PROTECTED_VERSION_1";
2847         flags &= ~MachO::SG_PROTECTED_VERSION_1;
2848       }
2849       if (flags)
2850         outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
2851       else
2852         outs() << "\n";
2853     }
2854   } else {
2855     outs() << "    flags " << format("0x%" PRIx32, flags) << "\n";
2856   }
2857 }
2858
2859 static void PrintSection(const char *sectname, const char *segname,
2860                          uint64_t addr, uint64_t size, uint32_t offset,
2861                          uint32_t align, uint32_t reloff, uint32_t nreloc,
2862                          uint32_t flags, uint32_t reserved1, uint32_t reserved2,
2863                          uint32_t cmd, const char *sg_segname,
2864                          uint32_t filetype, uint32_t object_size,
2865                          bool verbose) {
2866   outs() << "Section\n";
2867   outs() << "  sectname " << format("%.16s\n", sectname);
2868   outs() << "   segname " << format("%.16s", segname);
2869   if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
2870     outs() << " (does not match segment)\n";
2871   else
2872     outs() << "\n";
2873   if (cmd == MachO::LC_SEGMENT_64) {
2874     outs() << "      addr " << format("0x%016" PRIx64, addr) << "\n";
2875     outs() << "      size " << format("0x%016" PRIx64, size);
2876   } else {
2877     outs() << "      addr " << format("0x%08" PRIx32, addr) << "\n";
2878     outs() << "      size " << format("0x%08" PRIx32, size);
2879   }
2880   if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
2881     outs() << " (past end of file)\n";
2882   else
2883     outs() << "\n";
2884   outs() << "    offset " << offset;
2885   if (offset > object_size)
2886     outs() << " (past end of file)\n";
2887   else
2888     outs() << "\n";
2889   uint32_t align_shifted = 1 << align;
2890   outs() << "     align 2^" << align << " (" << align_shifted << ")\n";
2891   outs() << "    reloff " << reloff;
2892   if (reloff > object_size)
2893     outs() << " (past end of file)\n";
2894   else
2895     outs() << "\n";
2896   outs() << "    nreloc " << nreloc;
2897   if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
2898     outs() << " (past end of file)\n";
2899   else
2900     outs() << "\n";
2901   uint32_t section_type = flags & MachO::SECTION_TYPE;
2902   if (verbose) {
2903     outs() << "      type";
2904     if (section_type == MachO::S_REGULAR)
2905       outs() << " S_REGULAR\n";
2906     else if (section_type == MachO::S_ZEROFILL)
2907       outs() << " S_ZEROFILL\n";
2908     else if (section_type == MachO::S_CSTRING_LITERALS)
2909       outs() << " S_CSTRING_LITERALS\n";
2910     else if (section_type == MachO::S_4BYTE_LITERALS)
2911       outs() << " S_4BYTE_LITERALS\n";
2912     else if (section_type == MachO::S_8BYTE_LITERALS)
2913       outs() << " S_8BYTE_LITERALS\n";
2914     else if (section_type == MachO::S_16BYTE_LITERALS)
2915       outs() << " S_16BYTE_LITERALS\n";
2916     else if (section_type == MachO::S_LITERAL_POINTERS)
2917       outs() << " S_LITERAL_POINTERS\n";
2918     else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
2919       outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
2920     else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
2921       outs() << " S_LAZY_SYMBOL_POINTERS\n";
2922     else if (section_type == MachO::S_SYMBOL_STUBS)
2923       outs() << " S_SYMBOL_STUBS\n";
2924     else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
2925       outs() << " S_MOD_INIT_FUNC_POINTERS\n";
2926     else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
2927       outs() << " S_MOD_TERM_FUNC_POINTERS\n";
2928     else if (section_type == MachO::S_COALESCED)
2929       outs() << " S_COALESCED\n";
2930     else if (section_type == MachO::S_INTERPOSING)
2931       outs() << " S_INTERPOSING\n";
2932     else if (section_type == MachO::S_DTRACE_DOF)
2933       outs() << " S_DTRACE_DOF\n";
2934     else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
2935       outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
2936     else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
2937       outs() << " S_THREAD_LOCAL_REGULAR\n";
2938     else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
2939       outs() << " S_THREAD_LOCAL_ZEROFILL\n";
2940     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
2941       outs() << " S_THREAD_LOCAL_VARIABLES\n";
2942     else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2943       outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
2944     else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
2945       outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
2946     else
2947       outs() << format("0x%08" PRIx32, section_type) << "\n";
2948     outs() << "attributes";
2949     uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
2950     if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
2951       outs() << " PURE_INSTRUCTIONS";
2952     if (section_attributes & MachO::S_ATTR_NO_TOC)
2953       outs() << " NO_TOC";
2954     if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
2955       outs() << " STRIP_STATIC_SYMS";
2956     if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
2957       outs() << " NO_DEAD_STRIP";
2958     if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
2959       outs() << " LIVE_SUPPORT";
2960     if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
2961       outs() << " SELF_MODIFYING_CODE";
2962     if (section_attributes & MachO::S_ATTR_DEBUG)
2963       outs() << " DEBUG";
2964     if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
2965       outs() << " SOME_INSTRUCTIONS";
2966     if (section_attributes & MachO::S_ATTR_EXT_RELOC)
2967       outs() << " EXT_RELOC";
2968     if (section_attributes & MachO::S_ATTR_LOC_RELOC)
2969       outs() << " LOC_RELOC";
2970     if (section_attributes == 0)
2971       outs() << " (none)";
2972     outs() << "\n";
2973   } else
2974     outs() << "     flags " << format("0x%08" PRIx32, flags) << "\n";
2975   outs() << " reserved1 " << reserved1;
2976   if (section_type == MachO::S_SYMBOL_STUBS ||
2977       section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2978       section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2979       section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2980       section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
2981     outs() << " (index into indirect symbol table)\n";
2982   else
2983     outs() << "\n";
2984   outs() << " reserved2 " << reserved2;
2985   if (section_type == MachO::S_SYMBOL_STUBS)
2986     outs() << " (size of stubs)\n";
2987   else
2988     outs() << "\n";
2989 }
2990
2991 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
2992                                    uint32_t object_size) {
2993   outs() << "     cmd LC_SYMTAB\n";
2994   outs() << " cmdsize " << st.cmdsize;
2995   if (st.cmdsize != sizeof(struct MachO::symtab_command))
2996     outs() << " Incorrect size\n";
2997   else
2998     outs() << "\n";
2999   outs() << "  symoff " << st.symoff;
3000   if (st.symoff > object_size)
3001     outs() << " (past end of file)\n";
3002   else
3003     outs() << "\n";
3004   outs() << "   nsyms " << st.nsyms;
3005   uint64_t big_size;
3006   if (Is64Bit) {
3007     big_size = st.nsyms;
3008     big_size *= sizeof(struct MachO::nlist_64);
3009     big_size += st.symoff;
3010     if (big_size > object_size)
3011       outs() << " (past end of file)\n";
3012     else
3013       outs() << "\n";
3014   } else {
3015     big_size = st.nsyms;
3016     big_size *= sizeof(struct MachO::nlist);
3017     big_size += st.symoff;
3018     if (big_size > object_size)
3019       outs() << " (past end of file)\n";
3020     else
3021       outs() << "\n";
3022   }
3023   outs() << "  stroff " << st.stroff;
3024   if (st.stroff > object_size)
3025     outs() << " (past end of file)\n";
3026   else
3027     outs() << "\n";
3028   outs() << " strsize " << st.strsize;
3029   big_size = st.stroff;
3030   big_size += st.strsize;
3031   if (big_size > object_size)
3032     outs() << " (past end of file)\n";
3033   else
3034     outs() << "\n";
3035 }
3036
3037 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
3038                                      uint32_t nsyms, uint32_t object_size,
3039                                      bool Is64Bit) {
3040   outs() << "            cmd LC_DYSYMTAB\n";
3041   outs() << "        cmdsize " << dyst.cmdsize;
3042   if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
3043     outs() << " Incorrect size\n";
3044   else
3045     outs() << "\n";
3046   outs() << "      ilocalsym " << dyst.ilocalsym;
3047   if (dyst.ilocalsym > nsyms)
3048     outs() << " (greater than the number of symbols)\n";
3049   else
3050     outs() << "\n";
3051   outs() << "      nlocalsym " << dyst.nlocalsym;
3052   uint64_t big_size;
3053   big_size = dyst.ilocalsym;
3054   big_size += dyst.nlocalsym;
3055   if (big_size > nsyms)
3056     outs() << " (past the end of the symbol table)\n";
3057   else
3058     outs() << "\n";
3059   outs() << "     iextdefsym " << dyst.iextdefsym;
3060   if (dyst.iextdefsym > nsyms)
3061     outs() << " (greater than the number of symbols)\n";
3062   else
3063     outs() << "\n";
3064   outs() << "     nextdefsym " << dyst.nextdefsym;
3065   big_size = dyst.iextdefsym;
3066   big_size += dyst.nextdefsym;
3067   if (big_size > nsyms)
3068     outs() << " (past the end of the symbol table)\n";
3069   else
3070     outs() << "\n";
3071   outs() << "      iundefsym " << dyst.iundefsym;
3072   if (dyst.iundefsym > nsyms)
3073     outs() << " (greater than the number of symbols)\n";
3074   else
3075     outs() << "\n";
3076   outs() << "      nundefsym " << dyst.nundefsym;
3077   big_size = dyst.iundefsym;
3078   big_size += dyst.nundefsym;
3079   if (big_size > nsyms)
3080     outs() << " (past the end of the symbol table)\n";
3081   else
3082     outs() << "\n";
3083   outs() << "         tocoff " << dyst.tocoff;
3084   if (dyst.tocoff > object_size)
3085     outs() << " (past end of file)\n";
3086   else
3087     outs() << "\n";
3088   outs() << "           ntoc " << dyst.ntoc;
3089   big_size = dyst.ntoc;
3090   big_size *= sizeof(struct MachO::dylib_table_of_contents);
3091   big_size += dyst.tocoff;
3092   if (big_size > object_size)
3093     outs() << " (past end of file)\n";
3094   else
3095     outs() << "\n";
3096   outs() << "      modtaboff " << dyst.modtaboff;
3097   if (dyst.modtaboff > object_size)
3098     outs() << " (past end of file)\n";
3099   else
3100     outs() << "\n";
3101   outs() << "        nmodtab " << dyst.nmodtab;
3102   uint64_t modtabend;
3103   if (Is64Bit) {
3104     modtabend = dyst.nmodtab;
3105     modtabend *= sizeof(struct MachO::dylib_module_64);
3106     modtabend += dyst.modtaboff;
3107   } else {
3108     modtabend = dyst.nmodtab;
3109     modtabend *= sizeof(struct MachO::dylib_module);
3110     modtabend += dyst.modtaboff;
3111   }
3112   if (modtabend > object_size)
3113     outs() << " (past end of file)\n";
3114   else
3115     outs() << "\n";
3116   outs() << "   extrefsymoff " << dyst.extrefsymoff;
3117   if (dyst.extrefsymoff > object_size)
3118     outs() << " (past end of file)\n";
3119   else
3120     outs() << "\n";
3121   outs() << "    nextrefsyms " << dyst.nextrefsyms;
3122   big_size = dyst.nextrefsyms;
3123   big_size *= sizeof(struct MachO::dylib_reference);
3124   big_size += dyst.extrefsymoff;
3125   if (big_size > object_size)
3126     outs() << " (past end of file)\n";
3127   else
3128     outs() << "\n";
3129   outs() << " indirectsymoff " << dyst.indirectsymoff;
3130   if (dyst.indirectsymoff > object_size)
3131     outs() << " (past end of file)\n";
3132   else
3133     outs() << "\n";
3134   outs() << "  nindirectsyms " << dyst.nindirectsyms;
3135   big_size = dyst.nindirectsyms;
3136   big_size *= sizeof(uint32_t);
3137   big_size += dyst.indirectsymoff;
3138   if (big_size > object_size)
3139     outs() << " (past end of file)\n";
3140   else
3141     outs() << "\n";
3142   outs() << "      extreloff " << dyst.extreloff;
3143   if (dyst.extreloff > object_size)
3144     outs() << " (past end of file)\n";
3145   else
3146     outs() << "\n";
3147   outs() << "        nextrel " << dyst.nextrel;
3148   big_size = dyst.nextrel;
3149   big_size *= sizeof(struct MachO::relocation_info);
3150   big_size += dyst.extreloff;
3151   if (big_size > object_size)
3152     outs() << " (past end of file)\n";
3153   else
3154     outs() << "\n";
3155   outs() << "      locreloff " << dyst.locreloff;
3156   if (dyst.locreloff > object_size)
3157     outs() << " (past end of file)\n";
3158   else
3159     outs() << "\n";
3160   outs() << "        nlocrel " << dyst.nlocrel;
3161   big_size = dyst.nlocrel;
3162   big_size *= sizeof(struct MachO::relocation_info);
3163   big_size += dyst.locreloff;
3164   if (big_size > object_size)
3165     outs() << " (past end of file)\n";
3166   else
3167     outs() << "\n";
3168 }
3169
3170 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
3171                                      uint32_t object_size) {
3172   if (dc.cmd == MachO::LC_DYLD_INFO)
3173     outs() << "            cmd LC_DYLD_INFO\n";
3174   else
3175     outs() << "            cmd LC_DYLD_INFO_ONLY\n";
3176   outs() << "        cmdsize " << dc.cmdsize;
3177   if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
3178     outs() << " Incorrect size\n";
3179   else
3180     outs() << "\n";
3181   outs() << "     rebase_off " << dc.rebase_off;
3182   if (dc.rebase_off > object_size)
3183     outs() << " (past end of file)\n";
3184   else
3185     outs() << "\n";
3186   outs() << "    rebase_size " << dc.rebase_size;
3187   uint64_t big_size;
3188   big_size = dc.rebase_off;
3189   big_size += dc.rebase_size;
3190   if (big_size > object_size)
3191     outs() << " (past end of file)\n";
3192   else
3193     outs() << "\n";
3194   outs() << "       bind_off " << dc.bind_off;
3195   if (dc.bind_off > object_size)
3196     outs() << " (past end of file)\n";
3197   else
3198     outs() << "\n";
3199   outs() << "      bind_size " << dc.bind_size;
3200   big_size = dc.bind_off;
3201   big_size += dc.bind_size;
3202   if (big_size > object_size)
3203     outs() << " (past end of file)\n";
3204   else
3205     outs() << "\n";
3206   outs() << "  weak_bind_off " << dc.weak_bind_off;
3207   if (dc.weak_bind_off > object_size)
3208     outs() << " (past end of file)\n";
3209   else
3210     outs() << "\n";
3211   outs() << " weak_bind_size " << dc.weak_bind_size;
3212   big_size = dc.weak_bind_off;
3213   big_size += dc.weak_bind_size;
3214   if (big_size > object_size)
3215     outs() << " (past end of file)\n";
3216   else
3217     outs() << "\n";
3218   outs() << "  lazy_bind_off " << dc.lazy_bind_off;
3219   if (dc.lazy_bind_off > object_size)
3220     outs() << " (past end of file)\n";
3221   else
3222     outs() << "\n";
3223   outs() << " lazy_bind_size " << dc.lazy_bind_size;
3224   big_size = dc.lazy_bind_off;
3225   big_size += dc.lazy_bind_size;
3226   if (big_size > object_size)
3227     outs() << " (past end of file)\n";
3228   else
3229     outs() << "\n";
3230   outs() << "     export_off " << dc.export_off;
3231   if (dc.export_off > object_size)
3232     outs() << " (past end of file)\n";
3233   else
3234     outs() << "\n";
3235   outs() << "    export_size " << dc.export_size;
3236   big_size = dc.export_off;
3237   big_size += dc.export_size;
3238   if (big_size > object_size)
3239     outs() << " (past end of file)\n";
3240   else
3241     outs() << "\n";
3242 }
3243
3244 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
3245                                  const char *Ptr) {
3246   if (dyld.cmd == MachO::LC_ID_DYLINKER)
3247     outs() << "          cmd LC_ID_DYLINKER\n";
3248   else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
3249     outs() << "          cmd LC_LOAD_DYLINKER\n";
3250   else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
3251     outs() << "          cmd LC_DYLD_ENVIRONMENT\n";
3252   else
3253     outs() << "          cmd ?(" << dyld.cmd << ")\n";
3254   outs() << "      cmdsize " << dyld.cmdsize;
3255   if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
3256     outs() << " Incorrect size\n";
3257   else
3258     outs() << "\n";
3259   if (dyld.name >= dyld.cmdsize)
3260     outs() << "         name ?(bad offset " << dyld.name << ")\n";
3261   else {
3262     const char *P = (const char *)(Ptr) + dyld.name;
3263     outs() << "         name " << P << " (offset " << dyld.name << ")\n";
3264   }
3265 }
3266
3267 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
3268   outs() << "     cmd LC_UUID\n";
3269   outs() << " cmdsize " << uuid.cmdsize;
3270   if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
3271     outs() << " Incorrect size\n";
3272   else
3273     outs() << "\n";
3274   outs() << "    uuid ";
3275   outs() << format("%02" PRIX32, uuid.uuid[0]);
3276   outs() << format("%02" PRIX32, uuid.uuid[1]);
3277   outs() << format("%02" PRIX32, uuid.uuid[2]);
3278   outs() << format("%02" PRIX32, uuid.uuid[3]);
3279   outs() << "-";
3280   outs() << format("%02" PRIX32, uuid.uuid[4]);
3281   outs() << format("%02" PRIX32, uuid.uuid[5]);
3282   outs() << "-";
3283   outs() << format("%02" PRIX32, uuid.uuid[6]);
3284   outs() << format("%02" PRIX32, uuid.uuid[7]);
3285   outs() << "-";
3286   outs() << format("%02" PRIX32, uuid.uuid[8]);
3287   outs() << format("%02" PRIX32, uuid.uuid[9]);
3288   outs() << "-";
3289   outs() << format("%02" PRIX32, uuid.uuid[10]);
3290   outs() << format("%02" PRIX32, uuid.uuid[11]);
3291   outs() << format("%02" PRIX32, uuid.uuid[12]);
3292   outs() << format("%02" PRIX32, uuid.uuid[13]);
3293   outs() << format("%02" PRIX32, uuid.uuid[14]);
3294   outs() << format("%02" PRIX32, uuid.uuid[15]);
3295   outs() << "\n";
3296 }
3297
3298 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
3299   if (vd.cmd == MachO::LC_VERSION_MIN_MACOSX)
3300     outs() << "      cmd LC_VERSION_MIN_MACOSX\n";
3301   else if (vd.cmd == MachO::LC_VERSION_MIN_IPHONEOS)
3302     outs() << "      cmd LC_VERSION_MIN_IPHONEOS\n";
3303   else
3304     outs() << "      cmd " << vd.cmd << " (?)\n";
3305   outs() << "  cmdsize " << vd.cmdsize;
3306   if (vd.cmdsize != sizeof(struct MachO::version_min_command))
3307     outs() << " Incorrect size\n";
3308   else
3309     outs() << "\n";
3310   outs() << "  version " << ((vd.version >> 16) & 0xffff) << "."
3311          << ((vd.version >> 8) & 0xff);
3312   if ((vd.version & 0xff) != 0)
3313     outs() << "." << (vd.version & 0xff);
3314   outs() << "\n";
3315   if (vd.sdk == 0)
3316     outs() << "      sdk n/a\n";
3317   else {
3318     outs() << "      sdk " << ((vd.sdk >> 16) & 0xffff) << "."
3319            << ((vd.sdk >> 8) & 0xff);
3320   }
3321   if ((vd.sdk & 0xff) != 0)
3322     outs() << "." << (vd.sdk & 0xff);
3323   outs() << "\n";
3324 }
3325
3326 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
3327   outs() << "      cmd LC_SOURCE_VERSION\n";
3328   outs() << "  cmdsize " << sd.cmdsize;
3329   if (sd.cmdsize != sizeof(struct MachO::source_version_command))
3330     outs() << " Incorrect size\n";
3331   else
3332     outs() << "\n";
3333   uint64_t a = (sd.version >> 40) & 0xffffff;
3334   uint64_t b = (sd.version >> 30) & 0x3ff;
3335   uint64_t c = (sd.version >> 20) & 0x3ff;
3336   uint64_t d = (sd.version >> 10) & 0x3ff;
3337   uint64_t e = sd.version & 0x3ff;
3338   outs() << "  version " << a << "." << b;
3339   if (e != 0)
3340     outs() << "." << c << "." << d << "." << e;
3341   else if (d != 0)
3342     outs() << "." << c << "." << d;
3343   else if (c != 0)
3344     outs() << "." << c;
3345   outs() << "\n";
3346 }
3347
3348 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
3349   outs() << "       cmd LC_MAIN\n";
3350   outs() << "   cmdsize " << ep.cmdsize;
3351   if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
3352     outs() << " Incorrect size\n";
3353   else
3354     outs() << "\n";
3355   outs() << "  entryoff " << ep.entryoff << "\n";
3356   outs() << " stacksize " << ep.stacksize << "\n";
3357 }
3358
3359 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
3360   if (dl.cmd == MachO::LC_ID_DYLIB)
3361     outs() << "          cmd LC_ID_DYLIB\n";
3362   else if (dl.cmd == MachO::LC_LOAD_DYLIB)
3363     outs() << "          cmd LC_LOAD_DYLIB\n";
3364   else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
3365     outs() << "          cmd LC_LOAD_WEAK_DYLIB\n";
3366   else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
3367     outs() << "          cmd LC_REEXPORT_DYLIB\n";
3368   else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
3369     outs() << "          cmd LC_LAZY_LOAD_DYLIB\n";
3370   else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
3371     outs() << "          cmd LC_LOAD_UPWARD_DYLIB\n";
3372   else
3373     outs() << "          cmd " << dl.cmd << " (unknown)\n";
3374   outs() << "      cmdsize " << dl.cmdsize;
3375   if (dl.cmdsize < sizeof(struct MachO::dylib_command))
3376     outs() << " Incorrect size\n";
3377   else
3378     outs() << "\n";
3379   if (dl.dylib.name < dl.cmdsize) {
3380     const char *P = (const char *)(Ptr) + dl.dylib.name;
3381     outs() << "         name " << P << " (offset " << dl.dylib.name << ")\n";
3382   } else {
3383     outs() << "         name ?(bad offset " << dl.dylib.name << ")\n";
3384   }
3385   outs() << "   time stamp " << dl.dylib.timestamp << " ";
3386   time_t t = dl.dylib.timestamp;
3387   outs() << ctime(&t);
3388   outs() << "      current version ";
3389   if (dl.dylib.current_version == 0xffffffff)
3390     outs() << "n/a\n";
3391   else
3392     outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
3393            << ((dl.dylib.current_version >> 8) & 0xff) << "."
3394            << (dl.dylib.current_version & 0xff) << "\n";
3395   outs() << "compatibility version ";
3396   if (dl.dylib.compatibility_version == 0xffffffff)
3397     outs() << "n/a\n";
3398   else
3399     outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
3400            << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
3401            << (dl.dylib.compatibility_version & 0xff) << "\n";
3402 }
3403
3404 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
3405                                      uint32_t object_size) {
3406   if (ld.cmd == MachO::LC_CODE_SIGNATURE)
3407     outs() << "      cmd LC_FUNCTION_STARTS\n";
3408   else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
3409     outs() << "      cmd LC_SEGMENT_SPLIT_INFO\n";
3410   else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
3411     outs() << "      cmd LC_FUNCTION_STARTS\n";
3412   else if (ld.cmd == MachO::LC_DATA_IN_CODE)
3413     outs() << "      cmd LC_DATA_IN_CODE\n";
3414   else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
3415     outs() << "      cmd LC_DYLIB_CODE_SIGN_DRS\n";
3416   else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
3417     outs() << "      cmd LC_LINKER_OPTIMIZATION_HINT\n";
3418   else
3419     outs() << "      cmd " << ld.cmd << " (?)\n";
3420   outs() << "  cmdsize " << ld.cmdsize;
3421   if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
3422     outs() << " Incorrect size\n";
3423   else
3424     outs() << "\n";
3425   outs() << "  dataoff " << ld.dataoff;
3426   if (ld.dataoff > object_size)
3427     outs() << " (past end of file)\n";
3428   else
3429     outs() << "\n";
3430   outs() << " datasize " << ld.datasize;
3431   uint64_t big_size = ld.dataoff;
3432   big_size += ld.datasize;
3433   if (big_size > object_size)
3434     outs() << " (past end of file)\n";
3435   else
3436     outs() << "\n";
3437 }
3438
3439 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t ncmds,
3440                               uint32_t filetype, uint32_t cputype,
3441                               bool verbose) {
3442   StringRef Buf = Obj->getData();
3443   MachOObjectFile::LoadCommandInfo Command = Obj->getFirstLoadCommandInfo();
3444   for (unsigned i = 0;; ++i) {
3445     outs() << "Load command " << i << "\n";
3446     if (Command.C.cmd == MachO::LC_SEGMENT) {
3447       MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
3448       const char *sg_segname = SLC.segname;
3449       PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
3450                           SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
3451                           SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
3452                           verbose);
3453       for (unsigned j = 0; j < SLC.nsects; j++) {
3454         MachO::section_64 S = Obj->getSection64(Command, j);
3455         PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
3456                      S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
3457                      SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
3458       }
3459     } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
3460       MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
3461       const char *sg_segname = SLC_64.segname;
3462       PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
3463                           SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
3464                           SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
3465                           SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
3466       for (unsigned j = 0; j < SLC_64.nsects; j++) {
3467         MachO::section_64 S_64 = Obj->getSection64(Command, j);
3468         PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
3469                      S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
3470                      S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
3471                      sg_segname, filetype, Buf.size(), verbose);
3472       }
3473     } else if (Command.C.cmd == MachO::LC_SYMTAB) {
3474       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3475       PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
3476     } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
3477       MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
3478       MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
3479       PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
3480                                Obj->is64Bit());
3481     } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
3482                Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
3483       MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
3484       PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
3485     } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
3486                Command.C.cmd == MachO::LC_ID_DYLINKER ||
3487                Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
3488       MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
3489       PrintDyldLoadCommand(Dyld, Command.Ptr);
3490     } else if (Command.C.cmd == MachO::LC_UUID) {
3491       MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
3492       PrintUuidLoadCommand(Uuid);
3493     } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX) {
3494       MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
3495       PrintVersionMinLoadCommand(Vd);
3496     } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
3497       MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
3498       PrintSourceVersionCommand(Sd);
3499     } else if (Command.C.cmd == MachO::LC_MAIN) {
3500       MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
3501       PrintEntryPointCommand(Ep);
3502     } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
3503                Command.C.cmd == MachO::LC_ID_DYLIB ||
3504                Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
3505                Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
3506                Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
3507                Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
3508       MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
3509       PrintDylibCommand(Dl, Command.Ptr);
3510     } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
3511                Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
3512                Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
3513                Command.C.cmd == MachO::LC_DATA_IN_CODE ||
3514                Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
3515                Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
3516       MachO::linkedit_data_command Ld =
3517           Obj->getLinkeditDataLoadCommand(Command);
3518       PrintLinkEditDataCommand(Ld, Buf.size());
3519     } else {
3520       outs() << "      cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
3521              << ")\n";
3522       outs() << "  cmdsize " << Command.C.cmdsize << "\n";
3523       // TODO: get and print the raw bytes of the load command.
3524     }
3525     // TODO: print all the other kinds of load commands.
3526     if (i == ncmds - 1)
3527       break;
3528     else
3529       Command = Obj->getNextLoadCommandInfo(Command);
3530   }
3531 }
3532
3533 static void getAndPrintMachHeader(const MachOObjectFile *Obj, uint32_t &ncmds,
3534                                   uint32_t &filetype, uint32_t &cputype,
3535                                   bool verbose) {
3536   if (Obj->is64Bit()) {
3537     MachO::mach_header_64 H_64;
3538     H_64 = Obj->getHeader64();
3539     PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
3540                     H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
3541     ncmds = H_64.ncmds;
3542     filetype = H_64.filetype;
3543     cputype = H_64.cputype;
3544   } else {
3545     MachO::mach_header H;
3546     H = Obj->getHeader();
3547     PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
3548                     H.sizeofcmds, H.flags, verbose);
3549     ncmds = H.ncmds;
3550     filetype = H.filetype;
3551     cputype = H.cputype;
3552   }
3553 }
3554
3555 void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
3556   const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
3557   uint32_t ncmds = 0;
3558   uint32_t filetype = 0;
3559   uint32_t cputype = 0;
3560   getAndPrintMachHeader(file, ncmds, filetype, cputype, true);
3561   PrintLoadCommands(file, ncmds, filetype, cputype, true);
3562 }
3563
3564 //===----------------------------------------------------------------------===//
3565 // export trie dumping
3566 //===----------------------------------------------------------------------===//
3567
3568 void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
3569   for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
3570     uint64_t Flags = Entry.flags();
3571     bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
3572     bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
3573     bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3574                         MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
3575     bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
3576                 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
3577     bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
3578     if (ReExport)
3579       outs() << "[re-export] ";
3580     else
3581       outs() << format("0x%08llX  ",
3582                        Entry.address()); // FIXME:add in base address
3583     outs() << Entry.name();
3584     if (WeakDef || ThreadLocal || Resolver || Abs) {
3585       bool NeedsComma = false;
3586       outs() << " [";
3587       if (WeakDef) {
3588         outs() << "weak_def";
3589         NeedsComma = true;
3590       }
3591       if (ThreadLocal) {
3592         if (NeedsComma)
3593           outs() << ", ";
3594         outs() << "per-thread";
3595         NeedsComma = true;
3596       }
3597       if (Abs) {
3598         if (NeedsComma)
3599           outs() << ", ";
3600         outs() << "absolute";
3601         NeedsComma = true;
3602       }
3603       if (Resolver) {
3604         if (NeedsComma)
3605           outs() << ", ";
3606         outs() << format("resolver=0x%08llX", Entry.other());
3607         NeedsComma = true;
3608       }
3609       outs() << "]";
3610     }
3611     if (ReExport) {
3612       StringRef DylibName = "unknown";
3613       int Ordinal = Entry.other() - 1;
3614       Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
3615       if (Entry.otherName().empty())
3616         outs() << " (from " << DylibName << ")";
3617       else
3618         outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
3619     }
3620     outs() << "\n";
3621   }
3622 }
3623
3624 //===----------------------------------------------------------------------===//
3625 // rebase table dumping
3626 //===----------------------------------------------------------------------===//
3627
3628 namespace {
3629 class SegInfo {
3630 public:
3631   SegInfo(const object::MachOObjectFile *Obj);
3632
3633   StringRef segmentName(uint32_t SegIndex);
3634   StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
3635   uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
3636
3637 private:
3638   struct SectionInfo {
3639     uint64_t Address;
3640     uint64_t Size;
3641     StringRef SectionName;
3642     StringRef SegmentName;
3643     uint64_t OffsetInSegment;
3644     uint64_t SegmentStartAddress;
3645     uint32_t SegmentIndex;
3646   };
3647   const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
3648   SmallVector<SectionInfo, 32> Sections;
3649 };
3650 }
3651
3652 SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
3653   // Build table of sections so segIndex/offset pairs can be translated.
3654   uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
3655   StringRef CurSegName;
3656   uint64_t CurSegAddress;
3657   for (const SectionRef &Section : Obj->sections()) {
3658     SectionInfo Info;
3659     if (error(Section.getName(Info.SectionName)))
3660       return;
3661     Info.Address = Section.getAddress();
3662     Info.Size = Section.getSize();
3663     Info.SegmentName =
3664         Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
3665     if (!Info.SegmentName.equals(CurSegName)) {
3666       ++CurSegIndex;
3667       CurSegName = Info.SegmentName;
3668       CurSegAddress = Info.Address;
3669     }
3670     Info.SegmentIndex = CurSegIndex - 1;
3671     Info.OffsetInSegment = Info.Address - CurSegAddress;
3672     Info.SegmentStartAddress = CurSegAddress;
3673     Sections.push_back(Info);
3674   }
3675 }
3676
3677 StringRef SegInfo::segmentName(uint32_t SegIndex) {
3678   for (const SectionInfo &SI : Sections) {
3679     if (SI.SegmentIndex == SegIndex)
3680       return SI.SegmentName;
3681   }
3682   llvm_unreachable("invalid segIndex");
3683 }
3684
3685 const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
3686                                                  uint64_t OffsetInSeg) {
3687   for (const SectionInfo &SI : Sections) {
3688     if (SI.SegmentIndex != SegIndex)
3689       continue;
3690     if (SI.OffsetInSegment > OffsetInSeg)
3691       continue;
3692     if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
3693       continue;
3694     return SI;
3695   }
3696   llvm_unreachable("segIndex and offset not in any section");
3697 }
3698
3699 StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
3700   return findSection(SegIndex, OffsetInSeg).SectionName;
3701 }
3702
3703 uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
3704   const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
3705   return SI.SegmentStartAddress + OffsetInSeg;
3706 }
3707
3708 void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
3709   // Build table of sections so names can used in final output.
3710   SegInfo sectionTable(Obj);
3711
3712   outs() << "segment  section            address     type\n";
3713   for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
3714     uint32_t SegIndex = Entry.segmentIndex();
3715     uint64_t OffsetInSeg = Entry.segmentOffset();
3716     StringRef SegmentName = sectionTable.segmentName(SegIndex);
3717     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3718     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3719
3720     // Table lines look like: __DATA  __nl_symbol_ptr  0x0000F00C  pointer
3721     outs() << format("%-8s %-18s 0x%08" PRIX64 "  %s\n",
3722                      SegmentName.str().c_str(), SectionName.str().c_str(),
3723                      Address, Entry.typeName().str().c_str());
3724   }
3725 }
3726
3727 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
3728   StringRef DylibName;
3729   switch (Ordinal) {
3730   case MachO::BIND_SPECIAL_DYLIB_SELF:
3731     return "this-image";
3732   case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
3733     return "main-executable";
3734   case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
3735     return "flat-namespace";
3736   default:
3737     if (Ordinal > 0) {
3738       std::error_code EC =
3739           Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
3740       if (EC)
3741         return "<<bad library ordinal>>";
3742       return DylibName;
3743     }
3744   }
3745   return "<<unknown special ordinal>>";
3746 }
3747
3748 //===----------------------------------------------------------------------===//
3749 // bind table dumping
3750 //===----------------------------------------------------------------------===//
3751
3752 void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
3753   // Build table of sections so names can used in final output.
3754   SegInfo sectionTable(Obj);
3755
3756   outs() << "segment  section            address    type       "
3757             "addend dylib            symbol\n";
3758   for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
3759     uint32_t SegIndex = Entry.segmentIndex();
3760     uint64_t OffsetInSeg = Entry.segmentOffset();
3761     StringRef SegmentName = sectionTable.segmentName(SegIndex);
3762     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3763     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3764
3765     // Table lines look like:
3766     //  __DATA  __got  0x00012010    pointer   0 libSystem ___stack_chk_guard
3767     StringRef Attr;
3768     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
3769       Attr = " (weak_import)";
3770     outs() << left_justify(SegmentName, 8) << " "
3771            << left_justify(SectionName, 18) << " "
3772            << format_hex(Address, 10, true) << " "
3773            << left_justify(Entry.typeName(), 8) << " "
3774            << format_decimal(Entry.addend(), 8) << " "
3775            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3776            << Entry.symbolName() << Attr << "\n";
3777   }
3778 }
3779
3780 //===----------------------------------------------------------------------===//
3781 // lazy bind table dumping
3782 //===----------------------------------------------------------------------===//
3783
3784 void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
3785   // Build table of sections so names can used in final output.
3786   SegInfo sectionTable(Obj);
3787
3788   outs() << "segment  section            address     "
3789             "dylib            symbol\n";
3790   for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
3791     uint32_t SegIndex = Entry.segmentIndex();
3792     uint64_t OffsetInSeg = Entry.segmentOffset();
3793     StringRef SegmentName = sectionTable.segmentName(SegIndex);
3794     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3795     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3796
3797     // Table lines look like:
3798     //  __DATA  __got  0x00012010 libSystem ___stack_chk_guard
3799     outs() << left_justify(SegmentName, 8) << " "
3800            << left_justify(SectionName, 18) << " "
3801            << format_hex(Address, 10, true) << " "
3802            << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
3803            << Entry.symbolName() << "\n";
3804   }
3805 }
3806
3807 //===----------------------------------------------------------------------===//
3808 // weak bind table dumping
3809 //===----------------------------------------------------------------------===//
3810
3811 void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
3812   // Build table of sections so names can used in final output.
3813   SegInfo sectionTable(Obj);
3814
3815   outs() << "segment  section            address     "
3816             "type       addend   symbol\n";
3817   for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
3818     // Strong symbols don't have a location to update.
3819     if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
3820       outs() << "                                        strong              "
3821              << Entry.symbolName() << "\n";
3822       continue;
3823     }
3824     uint32_t SegIndex = Entry.segmentIndex();
3825     uint64_t OffsetInSeg = Entry.segmentOffset();
3826     StringRef SegmentName = sectionTable.segmentName(SegIndex);
3827     StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
3828     uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3829
3830     // Table lines look like:
3831     // __DATA  __data  0x00001000  pointer    0   _foo
3832     outs() << left_justify(SegmentName, 8) << " "
3833            << left_justify(SectionName, 18) << " "
3834            << format_hex(Address, 10, true) << " "
3835            << left_justify(Entry.typeName(), 8) << " "
3836            << format_decimal(Entry.addend(), 8) << "   " << Entry.symbolName()
3837            << "\n";
3838   }
3839 }
3840
3841 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
3842 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
3843 // information for that address. If the address is found its binding symbol
3844 // name is returned.  If not nullptr is returned.
3845 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3846                                                  struct DisassembleInfo *info) {
3847   if (info->bindtable == nullptr) {
3848     info->bindtable = new (BindTable);
3849     SegInfo sectionTable(info->O);
3850     for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
3851       uint32_t SegIndex = Entry.segmentIndex();
3852       uint64_t OffsetInSeg = Entry.segmentOffset();
3853       uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
3854       const char *SymbolName = nullptr;
3855       StringRef name = Entry.symbolName();
3856       if (!name.empty())
3857         SymbolName = name.data();
3858       info->bindtable->push_back(std::make_pair(Address, SymbolName));
3859     }
3860   }
3861   for (bind_table_iterator BI = info->bindtable->begin(),
3862                            BE = info->bindtable->end();
3863        BI != BE; ++BI) {
3864     uint64_t Address = BI->first;
3865     if (ReferenceValue == Address) {
3866       const char *SymbolName = BI->second;
3867       return SymbolName;
3868     }
3869   }
3870   return nullptr;
3871 }