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