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