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