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