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