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