1 //===-- MachODump.cpp - Object file dumping utility for llvm --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the MachO-specific dumper for llvm-objdump. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "MachODump.h" 14 15 #include "ObjdumpOptID.h" 16 #include "llvm-objdump.h" 17 #include "llvm-c/Disassembler.h" 18 #include "llvm/ADT/STLExtras.h" 19 #include "llvm/ADT/StringExtras.h" 20 #include "llvm/ADT/Triple.h" 21 #include "llvm/BinaryFormat/MachO.h" 22 #include "llvm/Config/config.h" 23 #include "llvm/DebugInfo/DIContext.h" 24 #include "llvm/DebugInfo/DWARF/DWARFContext.h" 25 #include "llvm/Demangle/Demangle.h" 26 #include "llvm/MC/MCAsmInfo.h" 27 #include "llvm/MC/MCContext.h" 28 #include "llvm/MC/MCDisassembler/MCDisassembler.h" 29 #include "llvm/MC/MCInst.h" 30 #include "llvm/MC/MCInstPrinter.h" 31 #include "llvm/MC/MCInstrDesc.h" 32 #include "llvm/MC/MCInstrInfo.h" 33 #include "llvm/MC/MCRegisterInfo.h" 34 #include "llvm/MC/MCSubtargetInfo.h" 35 #include "llvm/MC/MCTargetOptions.h" 36 #include "llvm/MC/TargetRegistry.h" 37 #include "llvm/Object/MachO.h" 38 #include "llvm/Object/MachOUniversal.h" 39 #include "llvm/Option/ArgList.h" 40 #include "llvm/Support/Casting.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/Endian.h" 43 #include "llvm/Support/Format.h" 44 #include "llvm/Support/FormattedStream.h" 45 #include "llvm/Support/GraphWriter.h" 46 #include "llvm/Support/LEB128.h" 47 #include "llvm/Support/MemoryBuffer.h" 48 #include "llvm/Support/TargetSelect.h" 49 #include "llvm/Support/ToolOutputFile.h" 50 #include "llvm/Support/WithColor.h" 51 #include "llvm/Support/raw_ostream.h" 52 #include <algorithm> 53 #include <cstring> 54 #include <system_error> 55 56 #ifdef LLVM_HAVE_LIBXAR 57 extern "C" { 58 #include <xar/xar.h> 59 } 60 #endif 61 62 using namespace llvm; 63 using namespace llvm::object; 64 using namespace llvm::objdump; 65 66 bool objdump::FirstPrivateHeader; 67 bool objdump::ExportsTrie; 68 bool objdump::Rebase; 69 bool objdump::Rpaths; 70 bool objdump::Bind; 71 bool objdump::LazyBind; 72 bool objdump::WeakBind; 73 static bool UseDbg; 74 static std::string DSYMFile; 75 bool objdump::FullLeadingAddr; 76 bool objdump::LeadingHeaders; 77 bool objdump::UniversalHeaders; 78 static bool ArchiveMemberOffsets; 79 bool objdump::IndirectSymbols; 80 bool objdump::DataInCode; 81 bool objdump::FunctionStarts; 82 bool objdump::LinkOptHints; 83 bool objdump::InfoPlist; 84 bool objdump::DyldInfo; 85 bool objdump::DylibsUsed; 86 bool objdump::DylibId; 87 bool objdump::Verbose; 88 bool objdump::ObjcMetaData; 89 std::string objdump::DisSymName; 90 bool objdump::SymbolicOperands; 91 static std::vector<std::string> ArchFlags; 92 93 static bool ArchAll = false; 94 static std::string ThumbTripleName; 95 96 void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) { 97 FirstPrivateHeader = InputArgs.hasArg(OBJDUMP_private_header); 98 ExportsTrie = InputArgs.hasArg(OBJDUMP_exports_trie); 99 Rebase = InputArgs.hasArg(OBJDUMP_rebase); 100 Rpaths = InputArgs.hasArg(OBJDUMP_rpaths); 101 Bind = InputArgs.hasArg(OBJDUMP_bind); 102 LazyBind = InputArgs.hasArg(OBJDUMP_lazy_bind); 103 WeakBind = InputArgs.hasArg(OBJDUMP_weak_bind); 104 UseDbg = InputArgs.hasArg(OBJDUMP_g); 105 DSYMFile = InputArgs.getLastArgValue(OBJDUMP_dsym_EQ).str(); 106 FullLeadingAddr = InputArgs.hasArg(OBJDUMP_full_leading_addr); 107 LeadingHeaders = !InputArgs.hasArg(OBJDUMP_no_leading_headers); 108 UniversalHeaders = InputArgs.hasArg(OBJDUMP_universal_headers); 109 ArchiveMemberOffsets = InputArgs.hasArg(OBJDUMP_archive_member_offsets); 110 IndirectSymbols = InputArgs.hasArg(OBJDUMP_indirect_symbols); 111 DataInCode = InputArgs.hasArg(OBJDUMP_data_in_code); 112 FunctionStarts = InputArgs.hasArg(OBJDUMP_function_starts); 113 LinkOptHints = InputArgs.hasArg(OBJDUMP_link_opt_hints); 114 InfoPlist = InputArgs.hasArg(OBJDUMP_info_plist); 115 DyldInfo = InputArgs.hasArg(OBJDUMP_dyld_info); 116 DylibsUsed = InputArgs.hasArg(OBJDUMP_dylibs_used); 117 DylibId = InputArgs.hasArg(OBJDUMP_dylib_id); 118 Verbose = !InputArgs.hasArg(OBJDUMP_non_verbose); 119 ObjcMetaData = InputArgs.hasArg(OBJDUMP_objc_meta_data); 120 DisSymName = InputArgs.getLastArgValue(OBJDUMP_dis_symname).str(); 121 SymbolicOperands = !InputArgs.hasArg(OBJDUMP_no_symbolic_operands); 122 ArchFlags = InputArgs.getAllArgValues(OBJDUMP_arch_EQ); 123 } 124 125 static const Target *GetTarget(const MachOObjectFile *MachOObj, 126 const char **McpuDefault, 127 const Target **ThumbTarget) { 128 // Figure out the target triple. 129 Triple TT(TripleName); 130 if (TripleName.empty()) { 131 TT = MachOObj->getArchTriple(McpuDefault); 132 TripleName = TT.str(); 133 } 134 135 if (TT.getArch() == Triple::arm) { 136 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs 137 // that support ARM are also capable of Thumb mode. 138 Triple ThumbTriple = TT; 139 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str(); 140 ThumbTriple.setArchName(ThumbName); 141 ThumbTripleName = ThumbTriple.str(); 142 } 143 144 // Get the target specific parser. 145 std::string Error; 146 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 147 if (TheTarget && ThumbTripleName.empty()) 148 return TheTarget; 149 150 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error); 151 if (*ThumbTarget) 152 return TheTarget; 153 154 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '"; 155 if (!TheTarget) 156 errs() << TripleName; 157 else 158 errs() << ThumbTripleName; 159 errs() << "', see --version and --triple.\n"; 160 return nullptr; 161 } 162 163 namespace { 164 struct SymbolSorter { 165 bool operator()(const SymbolRef &A, const SymbolRef &B) { 166 Expected<SymbolRef::Type> ATypeOrErr = A.getType(); 167 if (!ATypeOrErr) 168 reportError(ATypeOrErr.takeError(), A.getObject()->getFileName()); 169 SymbolRef::Type AType = *ATypeOrErr; 170 Expected<SymbolRef::Type> BTypeOrErr = B.getType(); 171 if (!BTypeOrErr) 172 reportError(BTypeOrErr.takeError(), B.getObject()->getFileName()); 173 SymbolRef::Type BType = *BTypeOrErr; 174 uint64_t AAddr = 175 (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue()); 176 uint64_t BAddr = 177 (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue()); 178 return AAddr < BAddr; 179 } 180 }; 181 } // namespace 182 183 // Types for the storted data in code table that is built before disassembly 184 // and the predicate function to sort them. 185 typedef std::pair<uint64_t, DiceRef> DiceTableEntry; 186 typedef std::vector<DiceTableEntry> DiceTable; 187 typedef DiceTable::iterator dice_table_iterator; 188 189 #ifdef LLVM_HAVE_LIBXAR 190 namespace { 191 struct ScopedXarFile { 192 xar_t xar; 193 ScopedXarFile(const char *filename, int32_t flags) { 194 #pragma clang diagnostic push 195 #pragma clang diagnostic ignored "-Wdeprecated-declarations" 196 xar = xar_open(filename, flags); 197 #pragma clang diagnostic pop 198 } 199 ~ScopedXarFile() { 200 if (xar) 201 xar_close(xar); 202 } 203 ScopedXarFile(const ScopedXarFile &) = delete; 204 ScopedXarFile &operator=(const ScopedXarFile &) = delete; 205 operator xar_t() { return xar; } 206 }; 207 208 struct ScopedXarIter { 209 xar_iter_t iter; 210 ScopedXarIter() : iter(xar_iter_new()) {} 211 ~ScopedXarIter() { 212 if (iter) 213 xar_iter_free(iter); 214 } 215 ScopedXarIter(const ScopedXarIter &) = delete; 216 ScopedXarIter &operator=(const ScopedXarIter &) = delete; 217 operator xar_iter_t() { return iter; } 218 }; 219 } // namespace 220 #endif // defined(LLVM_HAVE_LIBXAR) 221 222 // This is used to search for a data in code table entry for the PC being 223 // disassembled. The j parameter has the PC in j.first. A single data in code 224 // table entry can cover many bytes for each of its Kind's. So if the offset, 225 // aka the i.first value, of the data in code table entry plus its Length 226 // covers the PC being searched for this will return true. If not it will 227 // return false. 228 static bool compareDiceTableEntries(const DiceTableEntry &i, 229 const DiceTableEntry &j) { 230 uint16_t Length; 231 i.second.getLength(Length); 232 233 return j.first >= i.first && j.first < i.first + Length; 234 } 235 236 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length, 237 unsigned short Kind) { 238 uint32_t Value, Size = 1; 239 240 switch (Kind) { 241 default: 242 case MachO::DICE_KIND_DATA: 243 if (Length >= 4) { 244 if (ShowRawInsn) 245 dumpBytes(makeArrayRef(bytes, 4), outs()); 246 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; 247 outs() << "\t.long " << Value; 248 Size = 4; 249 } else if (Length >= 2) { 250 if (ShowRawInsn) 251 dumpBytes(makeArrayRef(bytes, 2), outs()); 252 Value = bytes[1] << 8 | bytes[0]; 253 outs() << "\t.short " << Value; 254 Size = 2; 255 } else { 256 if (ShowRawInsn) 257 dumpBytes(makeArrayRef(bytes, 2), outs()); 258 Value = bytes[0]; 259 outs() << "\t.byte " << Value; 260 Size = 1; 261 } 262 if (Kind == MachO::DICE_KIND_DATA) 263 outs() << "\t@ KIND_DATA\n"; 264 else 265 outs() << "\t@ data in code kind = " << Kind << "\n"; 266 break; 267 case MachO::DICE_KIND_JUMP_TABLE8: 268 if (ShowRawInsn) 269 dumpBytes(makeArrayRef(bytes, 1), outs()); 270 Value = bytes[0]; 271 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n"; 272 Size = 1; 273 break; 274 case MachO::DICE_KIND_JUMP_TABLE16: 275 if (ShowRawInsn) 276 dumpBytes(makeArrayRef(bytes, 2), outs()); 277 Value = bytes[1] << 8 | bytes[0]; 278 outs() << "\t.short " << format("%5u", Value & 0xffff) 279 << "\t@ KIND_JUMP_TABLE16\n"; 280 Size = 2; 281 break; 282 case MachO::DICE_KIND_JUMP_TABLE32: 283 case MachO::DICE_KIND_ABS_JUMP_TABLE32: 284 if (ShowRawInsn) 285 dumpBytes(makeArrayRef(bytes, 4), outs()); 286 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; 287 outs() << "\t.long " << Value; 288 if (Kind == MachO::DICE_KIND_JUMP_TABLE32) 289 outs() << "\t@ KIND_JUMP_TABLE32\n"; 290 else 291 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n"; 292 Size = 4; 293 break; 294 } 295 return Size; 296 } 297 298 static void getSectionsAndSymbols(MachOObjectFile *MachOObj, 299 std::vector<SectionRef> &Sections, 300 std::vector<SymbolRef> &Symbols, 301 SmallVectorImpl<uint64_t> &FoundFns, 302 uint64_t &BaseSegmentAddress) { 303 const StringRef FileName = MachOObj->getFileName(); 304 for (const SymbolRef &Symbol : MachOObj->symbols()) { 305 StringRef SymName = unwrapOrError(Symbol.getName(), FileName); 306 if (!SymName.startswith("ltmp")) 307 Symbols.push_back(Symbol); 308 } 309 310 append_range(Sections, MachOObj->sections()); 311 312 bool BaseSegmentAddressSet = false; 313 for (const auto &Command : MachOObj->load_commands()) { 314 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) { 315 // We found a function starts segment, parse the addresses for later 316 // consumption. 317 MachO::linkedit_data_command LLC = 318 MachOObj->getLinkeditDataLoadCommand(Command); 319 320 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns); 321 } else if (Command.C.cmd == MachO::LC_SEGMENT) { 322 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command); 323 StringRef SegName = SLC.segname; 324 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { 325 BaseSegmentAddressSet = true; 326 BaseSegmentAddress = SLC.vmaddr; 327 } 328 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 329 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command); 330 StringRef SegName = SLC.segname; 331 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") { 332 BaseSegmentAddressSet = true; 333 BaseSegmentAddress = SLC.vmaddr; 334 } 335 } 336 } 337 } 338 339 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes, 340 DiceTable &Dices, uint64_t &InstSize) { 341 // Check the data in code table here to see if this is data not an 342 // instruction to be disassembled. 343 DiceTable Dice; 344 Dice.push_back(std::make_pair(PC, DiceRef())); 345 dice_table_iterator DTI = 346 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(), 347 compareDiceTableEntries); 348 if (DTI != Dices.end()) { 349 uint16_t Length; 350 DTI->second.getLength(Length); 351 uint16_t Kind; 352 DTI->second.getKind(Kind); 353 InstSize = DumpDataInCode(bytes, Length, Kind); 354 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) && 355 (PC == (DTI->first + Length - 1)) && (Length & 1)) 356 InstSize++; 357 return true; 358 } 359 return false; 360 } 361 362 static void printRelocationTargetName(const MachOObjectFile *O, 363 const MachO::any_relocation_info &RE, 364 raw_string_ostream &Fmt) { 365 // Target of a scattered relocation is an address. In the interest of 366 // generating pretty output, scan through the symbol table looking for a 367 // symbol that aligns with that address. If we find one, print it. 368 // Otherwise, we just print the hex address of the target. 369 const StringRef FileName = O->getFileName(); 370 if (O->isRelocationScattered(RE)) { 371 uint32_t Val = O->getPlainRelocationSymbolNum(RE); 372 373 for (const SymbolRef &Symbol : O->symbols()) { 374 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName); 375 if (Addr != Val) 376 continue; 377 Fmt << unwrapOrError(Symbol.getName(), FileName); 378 return; 379 } 380 381 // If we couldn't find a symbol that this relocation refers to, try 382 // to find a section beginning instead. 383 for (const SectionRef &Section : ToolSectionFilter(*O)) { 384 uint64_t Addr = Section.getAddress(); 385 if (Addr != Val) 386 continue; 387 StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName()); 388 Fmt << NameOrErr; 389 return; 390 } 391 392 Fmt << format("0x%x", Val); 393 return; 394 } 395 396 StringRef S; 397 bool isExtern = O->getPlainRelocationExternal(RE); 398 uint64_t Val = O->getPlainRelocationSymbolNum(RE); 399 400 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND && 401 (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) { 402 Fmt << format("0x%0" PRIx64, Val); 403 return; 404 } 405 406 if (isExtern) { 407 symbol_iterator SI = O->symbol_begin(); 408 std::advance(SI, Val); 409 S = unwrapOrError(SI->getName(), FileName); 410 } else { 411 section_iterator SI = O->section_begin(); 412 // Adjust for the fact that sections are 1-indexed. 413 if (Val == 0) { 414 Fmt << "0 (?,?)"; 415 return; 416 } 417 uint32_t I = Val - 1; 418 while (I != 0 && SI != O->section_end()) { 419 --I; 420 std::advance(SI, 1); 421 } 422 if (SI == O->section_end()) { 423 Fmt << Val << " (?,?)"; 424 } else { 425 if (Expected<StringRef> NameOrErr = SI->getName()) 426 S = *NameOrErr; 427 else 428 consumeError(NameOrErr.takeError()); 429 } 430 } 431 432 Fmt << S; 433 } 434 435 Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj, 436 const RelocationRef &RelRef, 437 SmallVectorImpl<char> &Result) { 438 DataRefImpl Rel = RelRef.getRawDataRefImpl(); 439 MachO::any_relocation_info RE = Obj->getRelocation(Rel); 440 441 unsigned Arch = Obj->getArch(); 442 443 std::string FmtBuf; 444 raw_string_ostream Fmt(FmtBuf); 445 unsigned Type = Obj->getAnyRelocationType(RE); 446 bool IsPCRel = Obj->getAnyRelocationPCRel(RE); 447 448 // Determine any addends that should be displayed with the relocation. 449 // These require decoding the relocation type, which is triple-specific. 450 451 // X86_64 has entirely custom relocation types. 452 if (Arch == Triple::x86_64) { 453 switch (Type) { 454 case MachO::X86_64_RELOC_GOT_LOAD: 455 case MachO::X86_64_RELOC_GOT: { 456 printRelocationTargetName(Obj, RE, Fmt); 457 Fmt << "@GOT"; 458 if (IsPCRel) 459 Fmt << "PCREL"; 460 break; 461 } 462 case MachO::X86_64_RELOC_SUBTRACTOR: { 463 DataRefImpl RelNext = Rel; 464 Obj->moveRelocationNext(RelNext); 465 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 466 467 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type 468 // X86_64_RELOC_UNSIGNED. 469 // NOTE: Scattered relocations don't exist on x86_64. 470 unsigned RType = Obj->getAnyRelocationType(RENext); 471 if (RType != MachO::X86_64_RELOC_UNSIGNED) 472 reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after " 473 "X86_64_RELOC_SUBTRACTOR."); 474 475 // The X86_64_RELOC_UNSIGNED contains the minuend symbol; 476 // X86_64_RELOC_SUBTRACTOR contains the subtrahend. 477 printRelocationTargetName(Obj, RENext, Fmt); 478 Fmt << "-"; 479 printRelocationTargetName(Obj, RE, Fmt); 480 break; 481 } 482 case MachO::X86_64_RELOC_TLV: 483 printRelocationTargetName(Obj, RE, Fmt); 484 Fmt << "@TLV"; 485 if (IsPCRel) 486 Fmt << "P"; 487 break; 488 case MachO::X86_64_RELOC_SIGNED_1: 489 printRelocationTargetName(Obj, RE, Fmt); 490 Fmt << "-1"; 491 break; 492 case MachO::X86_64_RELOC_SIGNED_2: 493 printRelocationTargetName(Obj, RE, Fmt); 494 Fmt << "-2"; 495 break; 496 case MachO::X86_64_RELOC_SIGNED_4: 497 printRelocationTargetName(Obj, RE, Fmt); 498 Fmt << "-4"; 499 break; 500 default: 501 printRelocationTargetName(Obj, RE, Fmt); 502 break; 503 } 504 // X86 and ARM share some relocation types in common. 505 } else if (Arch == Triple::x86 || Arch == Triple::arm || 506 Arch == Triple::ppc) { 507 // Generic relocation types... 508 switch (Type) { 509 case MachO::GENERIC_RELOC_PAIR: // prints no info 510 return Error::success(); 511 case MachO::GENERIC_RELOC_SECTDIFF: { 512 DataRefImpl RelNext = Rel; 513 Obj->moveRelocationNext(RelNext); 514 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 515 516 // X86 sect diff's must be followed by a relocation of type 517 // GENERIC_RELOC_PAIR. 518 unsigned RType = Obj->getAnyRelocationType(RENext); 519 520 if (RType != MachO::GENERIC_RELOC_PAIR) 521 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 522 "GENERIC_RELOC_SECTDIFF."); 523 524 printRelocationTargetName(Obj, RE, Fmt); 525 Fmt << "-"; 526 printRelocationTargetName(Obj, RENext, Fmt); 527 break; 528 } 529 } 530 531 if (Arch == Triple::x86 || Arch == Triple::ppc) { 532 switch (Type) { 533 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: { 534 DataRefImpl RelNext = Rel; 535 Obj->moveRelocationNext(RelNext); 536 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 537 538 // X86 sect diff's must be followed by a relocation of type 539 // GENERIC_RELOC_PAIR. 540 unsigned RType = Obj->getAnyRelocationType(RENext); 541 if (RType != MachO::GENERIC_RELOC_PAIR) 542 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after " 543 "GENERIC_RELOC_LOCAL_SECTDIFF."); 544 545 printRelocationTargetName(Obj, RE, Fmt); 546 Fmt << "-"; 547 printRelocationTargetName(Obj, RENext, Fmt); 548 break; 549 } 550 case MachO::GENERIC_RELOC_TLV: { 551 printRelocationTargetName(Obj, RE, Fmt); 552 Fmt << "@TLV"; 553 if (IsPCRel) 554 Fmt << "P"; 555 break; 556 } 557 default: 558 printRelocationTargetName(Obj, RE, Fmt); 559 } 560 } else { // ARM-specific relocations 561 switch (Type) { 562 case MachO::ARM_RELOC_HALF: 563 case MachO::ARM_RELOC_HALF_SECTDIFF: { 564 // Half relocations steal a bit from the length field to encode 565 // whether this is an upper16 or a lower16 relocation. 566 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1; 567 568 if (isUpper) 569 Fmt << ":upper16:("; 570 else 571 Fmt << ":lower16:("; 572 printRelocationTargetName(Obj, RE, Fmt); 573 574 DataRefImpl RelNext = Rel; 575 Obj->moveRelocationNext(RelNext); 576 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext); 577 578 // ARM half relocs must be followed by a relocation of type 579 // ARM_RELOC_PAIR. 580 unsigned RType = Obj->getAnyRelocationType(RENext); 581 if (RType != MachO::ARM_RELOC_PAIR) 582 reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after " 583 "ARM_RELOC_HALF"); 584 585 // NOTE: The half of the target virtual address is stashed in the 586 // address field of the secondary relocation, but we can't reverse 587 // engineer the constant offset from it without decoding the movw/movt 588 // instruction to find the other half in its immediate field. 589 590 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the 591 // symbol/section pointer of the follow-on relocation. 592 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) { 593 Fmt << "-"; 594 printRelocationTargetName(Obj, RENext, Fmt); 595 } 596 597 Fmt << ")"; 598 break; 599 } 600 default: { 601 printRelocationTargetName(Obj, RE, Fmt); 602 } 603 } 604 } 605 } else 606 printRelocationTargetName(Obj, RE, Fmt); 607 608 Fmt.flush(); 609 Result.append(FmtBuf.begin(), FmtBuf.end()); 610 return Error::success(); 611 } 612 613 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose, 614 uint32_t n, uint32_t count, 615 uint32_t stride, uint64_t addr) { 616 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 617 uint32_t nindirectsyms = Dysymtab.nindirectsyms; 618 if (n > nindirectsyms) 619 outs() << " (entries start past the end of the indirect symbol " 620 "table) (reserved1 field greater than the table size)"; 621 else if (n + count > nindirectsyms) 622 outs() << " (entries extends past the end of the indirect symbol " 623 "table)"; 624 outs() << "\n"; 625 uint32_t cputype = O->getHeader().cputype; 626 if (cputype & MachO::CPU_ARCH_ABI64) 627 outs() << "address index"; 628 else 629 outs() << "address index"; 630 if (verbose) 631 outs() << " name\n"; 632 else 633 outs() << "\n"; 634 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) { 635 if (cputype & MachO::CPU_ARCH_ABI64) 636 outs() << format("0x%016" PRIx64, addr + j * stride) << " "; 637 else 638 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " "; 639 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 640 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j); 641 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) { 642 outs() << "LOCAL\n"; 643 continue; 644 } 645 if (indirect_symbol == 646 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) { 647 outs() << "LOCAL ABSOLUTE\n"; 648 continue; 649 } 650 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) { 651 outs() << "ABSOLUTE\n"; 652 continue; 653 } 654 outs() << format("%5u ", indirect_symbol); 655 if (verbose) { 656 MachO::symtab_command Symtab = O->getSymtabLoadCommand(); 657 if (indirect_symbol < Symtab.nsyms) { 658 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol); 659 SymbolRef Symbol = *Sym; 660 outs() << unwrapOrError(Symbol.getName(), O->getFileName()); 661 } else { 662 outs() << "?"; 663 } 664 } 665 outs() << "\n"; 666 } 667 } 668 669 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) { 670 for (const auto &Load : O->load_commands()) { 671 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 672 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); 673 for (unsigned J = 0; J < Seg.nsects; ++J) { 674 MachO::section_64 Sec = O->getSection64(Load, J); 675 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 676 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 677 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 678 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 679 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 680 section_type == MachO::S_SYMBOL_STUBS) { 681 uint32_t stride; 682 if (section_type == MachO::S_SYMBOL_STUBS) 683 stride = Sec.reserved2; 684 else 685 stride = 8; 686 if (stride == 0) { 687 outs() << "Can't print indirect symbols for (" << Sec.segname << "," 688 << Sec.sectname << ") " 689 << "(size of stubs in reserved2 field is zero)\n"; 690 continue; 691 } 692 uint32_t count = Sec.size / stride; 693 outs() << "Indirect symbols for (" << Sec.segname << "," 694 << Sec.sectname << ") " << count << " entries"; 695 uint32_t n = Sec.reserved1; 696 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); 697 } 698 } 699 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 700 MachO::segment_command Seg = O->getSegmentLoadCommand(Load); 701 for (unsigned J = 0; J < Seg.nsects; ++J) { 702 MachO::section Sec = O->getSection(Load, J); 703 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 704 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 705 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 706 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 707 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 708 section_type == MachO::S_SYMBOL_STUBS) { 709 uint32_t stride; 710 if (section_type == MachO::S_SYMBOL_STUBS) 711 stride = Sec.reserved2; 712 else 713 stride = 4; 714 if (stride == 0) { 715 outs() << "Can't print indirect symbols for (" << Sec.segname << "," 716 << Sec.sectname << ") " 717 << "(size of stubs in reserved2 field is zero)\n"; 718 continue; 719 } 720 uint32_t count = Sec.size / stride; 721 outs() << "Indirect symbols for (" << Sec.segname << "," 722 << Sec.sectname << ") " << count << " entries"; 723 uint32_t n = Sec.reserved1; 724 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr); 725 } 726 } 727 } 728 } 729 } 730 731 static void PrintRType(const uint64_t cputype, const unsigned r_type) { 732 static char const *generic_r_types[] = { 733 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ", 734 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ", 735 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 736 }; 737 static char const *x86_64_r_types[] = { 738 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ", 739 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ", 740 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 741 }; 742 static char const *arm_r_types[] = { 743 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ", 744 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ", 745 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 746 }; 747 static char const *arm64_r_types[] = { 748 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ", 749 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF", 750 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) " 751 }; 752 753 if (r_type > 0xf){ 754 outs() << format("%-7u", r_type) << " "; 755 return; 756 } 757 switch (cputype) { 758 case MachO::CPU_TYPE_I386: 759 outs() << generic_r_types[r_type]; 760 break; 761 case MachO::CPU_TYPE_X86_64: 762 outs() << x86_64_r_types[r_type]; 763 break; 764 case MachO::CPU_TYPE_ARM: 765 outs() << arm_r_types[r_type]; 766 break; 767 case MachO::CPU_TYPE_ARM64: 768 case MachO::CPU_TYPE_ARM64_32: 769 outs() << arm64_r_types[r_type]; 770 break; 771 default: 772 outs() << format("%-7u ", r_type); 773 } 774 } 775 776 static void PrintRLength(const uint64_t cputype, const unsigned r_type, 777 const unsigned r_length, const bool previous_arm_half){ 778 if (cputype == MachO::CPU_TYPE_ARM && 779 (r_type == MachO::ARM_RELOC_HALF || 780 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) { 781 if ((r_length & 0x1) == 0) 782 outs() << "lo/"; 783 else 784 outs() << "hi/"; 785 if ((r_length & 0x1) == 0) 786 outs() << "arm "; 787 else 788 outs() << "thm "; 789 } else { 790 switch (r_length) { 791 case 0: 792 outs() << "byte "; 793 break; 794 case 1: 795 outs() << "word "; 796 break; 797 case 2: 798 outs() << "long "; 799 break; 800 case 3: 801 if (cputype == MachO::CPU_TYPE_X86_64) 802 outs() << "quad "; 803 else 804 outs() << format("?(%2d) ", r_length); 805 break; 806 default: 807 outs() << format("?(%2d) ", r_length); 808 } 809 } 810 } 811 812 static void PrintRelocationEntries(const MachOObjectFile *O, 813 const relocation_iterator Begin, 814 const relocation_iterator End, 815 const uint64_t cputype, 816 const bool verbose) { 817 const MachO::symtab_command Symtab = O->getSymtabLoadCommand(); 818 bool previous_arm_half = false; 819 bool previous_sectdiff = false; 820 uint32_t sectdiff_r_type = 0; 821 822 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) { 823 const DataRefImpl Rel = Reloc->getRawDataRefImpl(); 824 const MachO::any_relocation_info RE = O->getRelocation(Rel); 825 const unsigned r_type = O->getAnyRelocationType(RE); 826 const bool r_scattered = O->isRelocationScattered(RE); 827 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE); 828 const unsigned r_length = O->getAnyRelocationLength(RE); 829 const unsigned r_address = O->getAnyRelocationAddress(RE); 830 const bool r_extern = (r_scattered ? false : 831 O->getPlainRelocationExternal(RE)); 832 const uint32_t r_value = (r_scattered ? 833 O->getScatteredRelocationValue(RE) : 0); 834 const unsigned r_symbolnum = (r_scattered ? 0 : 835 O->getPlainRelocationSymbolNum(RE)); 836 837 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) { 838 if (verbose) { 839 // scattered: address 840 if ((cputype == MachO::CPU_TYPE_I386 && 841 r_type == MachO::GENERIC_RELOC_PAIR) || 842 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)) 843 outs() << " "; 844 else 845 outs() << format("%08x ", (unsigned int)r_address); 846 847 // scattered: pcrel 848 if (r_pcrel) 849 outs() << "True "; 850 else 851 outs() << "False "; 852 853 // scattered: length 854 PrintRLength(cputype, r_type, r_length, previous_arm_half); 855 856 // scattered: extern & type 857 outs() << "n/a "; 858 PrintRType(cputype, r_type); 859 860 // scattered: scattered & value 861 outs() << format("True 0x%08x", (unsigned int)r_value); 862 if (previous_sectdiff == false) { 863 if ((cputype == MachO::CPU_TYPE_ARM && 864 r_type == MachO::ARM_RELOC_PAIR)) 865 outs() << format(" half = 0x%04x ", (unsigned int)r_address); 866 } else if (cputype == MachO::CPU_TYPE_ARM && 867 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF) 868 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address); 869 if ((cputype == MachO::CPU_TYPE_I386 && 870 (r_type == MachO::GENERIC_RELOC_SECTDIFF || 871 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) || 872 (cputype == MachO::CPU_TYPE_ARM && 873 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF || 874 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || 875 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) { 876 previous_sectdiff = true; 877 sectdiff_r_type = r_type; 878 } else { 879 previous_sectdiff = false; 880 sectdiff_r_type = 0; 881 } 882 if (cputype == MachO::CPU_TYPE_ARM && 883 (r_type == MachO::ARM_RELOC_HALF || 884 r_type == MachO::ARM_RELOC_HALF_SECTDIFF)) 885 previous_arm_half = true; 886 else 887 previous_arm_half = false; 888 outs() << "\n"; 889 } 890 else { 891 // scattered: address pcrel length extern type scattered value 892 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n", 893 (unsigned int)r_address, r_pcrel, r_length, r_type, 894 (unsigned int)r_value); 895 } 896 } 897 else { 898 if (verbose) { 899 // plain: address 900 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR) 901 outs() << " "; 902 else 903 outs() << format("%08x ", (unsigned int)r_address); 904 905 // plain: pcrel 906 if (r_pcrel) 907 outs() << "True "; 908 else 909 outs() << "False "; 910 911 // plain: length 912 PrintRLength(cputype, r_type, r_length, previous_arm_half); 913 914 if (r_extern) { 915 // plain: extern & type & scattered 916 outs() << "True "; 917 PrintRType(cputype, r_type); 918 outs() << "False "; 919 920 // plain: symbolnum/value 921 if (r_symbolnum > Symtab.nsyms) 922 outs() << format("?(%d)\n", r_symbolnum); 923 else { 924 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum); 925 Expected<StringRef> SymNameNext = Symbol.getName(); 926 const char *name = nullptr; 927 if (SymNameNext) 928 name = SymNameNext->data(); 929 if (name == nullptr) 930 outs() << format("?(%d)\n", r_symbolnum); 931 else 932 outs() << name << "\n"; 933 } 934 } 935 else { 936 // plain: extern & type & scattered 937 outs() << "False "; 938 PrintRType(cputype, r_type); 939 outs() << "False "; 940 941 // plain: symbolnum/value 942 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR) 943 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address); 944 else if ((cputype == MachO::CPU_TYPE_ARM64 || 945 cputype == MachO::CPU_TYPE_ARM64_32) && 946 r_type == MachO::ARM64_RELOC_ADDEND) 947 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum); 948 else { 949 outs() << format("%d ", r_symbolnum); 950 if (r_symbolnum == MachO::R_ABS) 951 outs() << "R_ABS\n"; 952 else { 953 // in this case, r_symbolnum is actually a 1-based section number 954 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a; 955 if (r_symbolnum > 0 && r_symbolnum <= nsects) { 956 object::DataRefImpl DRI; 957 DRI.d.a = r_symbolnum-1; 958 StringRef SegName = O->getSectionFinalSegmentName(DRI); 959 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 960 outs() << "(" << SegName << "," << *NameOrErr << ")\n"; 961 else 962 outs() << "(?,?)\n"; 963 } 964 else { 965 outs() << "(?,?)\n"; 966 } 967 } 968 } 969 } 970 if (cputype == MachO::CPU_TYPE_ARM && 971 (r_type == MachO::ARM_RELOC_HALF || 972 r_type == MachO::ARM_RELOC_HALF_SECTDIFF)) 973 previous_arm_half = true; 974 else 975 previous_arm_half = false; 976 } 977 else { 978 // plain: address pcrel length extern type scattered symbolnum/section 979 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n", 980 (unsigned int)r_address, r_pcrel, r_length, r_extern, 981 r_type, r_symbolnum); 982 } 983 } 984 } 985 } 986 987 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) { 988 const uint64_t cputype = O->getHeader().cputype; 989 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand(); 990 if (Dysymtab.nextrel != 0) { 991 outs() << "External relocation information " << Dysymtab.nextrel 992 << " entries"; 993 outs() << "\naddress pcrel length extern type scattered " 994 "symbolnum/value\n"; 995 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype, 996 verbose); 997 } 998 if (Dysymtab.nlocrel != 0) { 999 outs() << format("Local relocation information %u entries", 1000 Dysymtab.nlocrel); 1001 outs() << "\naddress pcrel length extern type scattered " 1002 "symbolnum/value\n"; 1003 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype, 1004 verbose); 1005 } 1006 for (const auto &Load : O->load_commands()) { 1007 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 1008 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load); 1009 for (unsigned J = 0; J < Seg.nsects; ++J) { 1010 const MachO::section_64 Sec = O->getSection64(Load, J); 1011 if (Sec.nreloc != 0) { 1012 DataRefImpl DRI; 1013 DRI.d.a = J; 1014 const StringRef SegName = O->getSectionFinalSegmentName(DRI); 1015 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1016 outs() << "Relocation information (" << SegName << "," << *NameOrErr 1017 << format(") %u entries", Sec.nreloc); 1018 else 1019 outs() << "Relocation information (" << SegName << ",?) " 1020 << format("%u entries", Sec.nreloc); 1021 outs() << "\naddress pcrel length extern type scattered " 1022 "symbolnum/value\n"; 1023 PrintRelocationEntries(O, O->section_rel_begin(DRI), 1024 O->section_rel_end(DRI), cputype, verbose); 1025 } 1026 } 1027 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 1028 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load); 1029 for (unsigned J = 0; J < Seg.nsects; ++J) { 1030 const MachO::section Sec = O->getSection(Load, J); 1031 if (Sec.nreloc != 0) { 1032 DataRefImpl DRI; 1033 DRI.d.a = J; 1034 const StringRef SegName = O->getSectionFinalSegmentName(DRI); 1035 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI)) 1036 outs() << "Relocation information (" << SegName << "," << *NameOrErr 1037 << format(") %u entries", Sec.nreloc); 1038 else 1039 outs() << "Relocation information (" << SegName << ",?) " 1040 << format("%u entries", Sec.nreloc); 1041 outs() << "\naddress pcrel length extern type scattered " 1042 "symbolnum/value\n"; 1043 PrintRelocationEntries(O, O->section_rel_begin(DRI), 1044 O->section_rel_end(DRI), cputype, verbose); 1045 } 1046 } 1047 } 1048 } 1049 } 1050 1051 static void PrintFunctionStarts(MachOObjectFile *O) { 1052 uint64_t BaseSegmentAddress = 0; 1053 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) { 1054 if (Command.C.cmd == MachO::LC_SEGMENT) { 1055 MachO::segment_command SLC = O->getSegmentLoadCommand(Command); 1056 if (StringRef(SLC.segname) == "__TEXT") { 1057 BaseSegmentAddress = SLC.vmaddr; 1058 break; 1059 } 1060 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 1061 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(Command); 1062 if (StringRef(SLC.segname) == "__TEXT") { 1063 BaseSegmentAddress = SLC.vmaddr; 1064 break; 1065 } 1066 } 1067 } 1068 1069 SmallVector<uint64_t, 8> FunctionStarts; 1070 for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) { 1071 if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) { 1072 MachO::linkedit_data_command FunctionStartsLC = 1073 O->getLinkeditDataLoadCommand(LC); 1074 O->ReadULEB128s(FunctionStartsLC.dataoff, FunctionStarts); 1075 break; 1076 } 1077 } 1078 1079 for (uint64_t S : FunctionStarts) { 1080 uint64_t Addr = BaseSegmentAddress + S; 1081 if (O->is64Bit()) 1082 outs() << format("%016" PRIx64, Addr) << "\n"; 1083 else 1084 outs() << format("%08" PRIx32, static_cast<uint32_t>(Addr)) << "\n"; 1085 } 1086 } 1087 1088 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) { 1089 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand(); 1090 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry); 1091 outs() << "Data in code table (" << nentries << " entries)\n"; 1092 outs() << "offset length kind\n"; 1093 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE; 1094 ++DI) { 1095 uint32_t Offset; 1096 DI->getOffset(Offset); 1097 outs() << format("0x%08" PRIx32, Offset) << " "; 1098 uint16_t Length; 1099 DI->getLength(Length); 1100 outs() << format("%6u", Length) << " "; 1101 uint16_t Kind; 1102 DI->getKind(Kind); 1103 if (verbose) { 1104 switch (Kind) { 1105 case MachO::DICE_KIND_DATA: 1106 outs() << "DATA"; 1107 break; 1108 case MachO::DICE_KIND_JUMP_TABLE8: 1109 outs() << "JUMP_TABLE8"; 1110 break; 1111 case MachO::DICE_KIND_JUMP_TABLE16: 1112 outs() << "JUMP_TABLE16"; 1113 break; 1114 case MachO::DICE_KIND_JUMP_TABLE32: 1115 outs() << "JUMP_TABLE32"; 1116 break; 1117 case MachO::DICE_KIND_ABS_JUMP_TABLE32: 1118 outs() << "ABS_JUMP_TABLE32"; 1119 break; 1120 default: 1121 outs() << format("0x%04" PRIx32, Kind); 1122 break; 1123 } 1124 } else 1125 outs() << format("0x%04" PRIx32, Kind); 1126 outs() << "\n"; 1127 } 1128 } 1129 1130 static void PrintLinkOptHints(MachOObjectFile *O) { 1131 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand(); 1132 const char *loh = O->getData().substr(LohLC.dataoff, 1).data(); 1133 uint32_t nloh = LohLC.datasize; 1134 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n"; 1135 for (uint32_t i = 0; i < nloh;) { 1136 unsigned n; 1137 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n); 1138 i += n; 1139 outs() << " identifier " << identifier << " "; 1140 if (i >= nloh) 1141 return; 1142 switch (identifier) { 1143 case 1: 1144 outs() << "AdrpAdrp\n"; 1145 break; 1146 case 2: 1147 outs() << "AdrpLdr\n"; 1148 break; 1149 case 3: 1150 outs() << "AdrpAddLdr\n"; 1151 break; 1152 case 4: 1153 outs() << "AdrpLdrGotLdr\n"; 1154 break; 1155 case 5: 1156 outs() << "AdrpAddStr\n"; 1157 break; 1158 case 6: 1159 outs() << "AdrpLdrGotStr\n"; 1160 break; 1161 case 7: 1162 outs() << "AdrpAdd\n"; 1163 break; 1164 case 8: 1165 outs() << "AdrpLdrGot\n"; 1166 break; 1167 default: 1168 outs() << "Unknown identifier value\n"; 1169 break; 1170 } 1171 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n); 1172 i += n; 1173 outs() << " narguments " << narguments << "\n"; 1174 if (i >= nloh) 1175 return; 1176 1177 for (uint32_t j = 0; j < narguments; j++) { 1178 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n); 1179 i += n; 1180 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n"; 1181 if (i >= nloh) 1182 return; 1183 } 1184 } 1185 } 1186 1187 static void printMachOChainedFixups(object::MachOObjectFile *Obj) { 1188 Error Err = Error::success(); 1189 for (const object::MachOChainedFixupEntry &Entry : Obj->fixupTable(Err)) { 1190 (void)Entry; 1191 } 1192 if (Err) 1193 reportError(std::move(Err), Obj->getFileName()); 1194 } 1195 1196 static void PrintDyldInfo(MachOObjectFile *O) { 1197 outs() << "dyld information:" << '\n'; 1198 printMachOChainedFixups(O); 1199 } 1200 1201 static void PrintDylibs(MachOObjectFile *O, bool JustId) { 1202 unsigned Index = 0; 1203 for (const auto &Load : O->load_commands()) { 1204 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) || 1205 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB || 1206 Load.C.cmd == MachO::LC_LOAD_DYLIB || 1207 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || 1208 Load.C.cmd == MachO::LC_REEXPORT_DYLIB || 1209 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || 1210 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) { 1211 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load); 1212 if (dl.dylib.name < dl.cmdsize) { 1213 const char *p = (const char *)(Load.Ptr) + dl.dylib.name; 1214 if (JustId) 1215 outs() << p << "\n"; 1216 else { 1217 outs() << "\t" << p; 1218 outs() << " (compatibility version " 1219 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." 1220 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." 1221 << (dl.dylib.compatibility_version & 0xff) << ","; 1222 outs() << " current version " 1223 << ((dl.dylib.current_version >> 16) & 0xffff) << "." 1224 << ((dl.dylib.current_version >> 8) & 0xff) << "." 1225 << (dl.dylib.current_version & 0xff); 1226 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) 1227 outs() << ", weak"; 1228 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) 1229 outs() << ", reexport"; 1230 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 1231 outs() << ", upward"; 1232 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) 1233 outs() << ", lazy"; 1234 outs() << ")\n"; 1235 } 1236 } else { 1237 outs() << "\tBad offset (" << dl.dylib.name << ") for name of "; 1238 if (Load.C.cmd == MachO::LC_ID_DYLIB) 1239 outs() << "LC_ID_DYLIB "; 1240 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB) 1241 outs() << "LC_LOAD_DYLIB "; 1242 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB) 1243 outs() << "LC_LOAD_WEAK_DYLIB "; 1244 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB) 1245 outs() << "LC_LAZY_LOAD_DYLIB "; 1246 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB) 1247 outs() << "LC_REEXPORT_DYLIB "; 1248 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 1249 outs() << "LC_LOAD_UPWARD_DYLIB "; 1250 else 1251 outs() << "LC_??? "; 1252 outs() << "command " << Index++ << "\n"; 1253 } 1254 } 1255 } 1256 } 1257 1258 static void printRpaths(MachOObjectFile *O) { 1259 for (const auto &Command : O->load_commands()) { 1260 if (Command.C.cmd == MachO::LC_RPATH) { 1261 auto Rpath = O->getRpathCommand(Command); 1262 const char *P = (const char *)(Command.Ptr) + Rpath.path; 1263 outs() << P << "\n"; 1264 } 1265 } 1266 } 1267 1268 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap; 1269 1270 static void CreateSymbolAddressMap(MachOObjectFile *O, 1271 SymbolAddressMap *AddrMap) { 1272 // Create a map of symbol addresses to symbol names. 1273 const StringRef FileName = O->getFileName(); 1274 for (const SymbolRef &Symbol : O->symbols()) { 1275 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName); 1276 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || 1277 ST == SymbolRef::ST_Other) { 1278 uint64_t Address = cantFail(Symbol.getValue()); 1279 StringRef SymName = unwrapOrError(Symbol.getName(), FileName); 1280 if (!SymName.startswith(".objc")) 1281 (*AddrMap)[Address] = SymName; 1282 } 1283 } 1284 } 1285 1286 // GuessSymbolName is passed the address of what might be a symbol and a 1287 // pointer to the SymbolAddressMap. It returns the name of a symbol 1288 // with that address or nullptr if no symbol is found with that address. 1289 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) { 1290 const char *SymbolName = nullptr; 1291 // A DenseMap can't lookup up some values. 1292 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) { 1293 StringRef name = AddrMap->lookup(value); 1294 if (!name.empty()) 1295 SymbolName = name.data(); 1296 } 1297 return SymbolName; 1298 } 1299 1300 static void DumpCstringChar(const char c) { 1301 char p[2]; 1302 p[0] = c; 1303 p[1] = '\0'; 1304 outs().write_escaped(p); 1305 } 1306 1307 static void DumpCstringSection(MachOObjectFile *O, const char *sect, 1308 uint32_t sect_size, uint64_t sect_addr, 1309 bool print_addresses) { 1310 for (uint32_t i = 0; i < sect_size; i++) { 1311 if (print_addresses) { 1312 if (O->is64Bit()) 1313 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1314 else 1315 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1316 } 1317 for (; i < sect_size && sect[i] != '\0'; i++) 1318 DumpCstringChar(sect[i]); 1319 if (i < sect_size && sect[i] == '\0') 1320 outs() << "\n"; 1321 } 1322 } 1323 1324 static void DumpLiteral4(uint32_t l, float f) { 1325 outs() << format("0x%08" PRIx32, l); 1326 if ((l & 0x7f800000) != 0x7f800000) 1327 outs() << format(" (%.16e)\n", f); 1328 else { 1329 if (l == 0x7f800000) 1330 outs() << " (+Infinity)\n"; 1331 else if (l == 0xff800000) 1332 outs() << " (-Infinity)\n"; 1333 else if ((l & 0x00400000) == 0x00400000) 1334 outs() << " (non-signaling Not-a-Number)\n"; 1335 else 1336 outs() << " (signaling Not-a-Number)\n"; 1337 } 1338 } 1339 1340 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect, 1341 uint32_t sect_size, uint64_t sect_addr, 1342 bool print_addresses) { 1343 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) { 1344 if (print_addresses) { 1345 if (O->is64Bit()) 1346 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1347 else 1348 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1349 } 1350 float f; 1351 memcpy(&f, sect + i, sizeof(float)); 1352 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1353 sys::swapByteOrder(f); 1354 uint32_t l; 1355 memcpy(&l, sect + i, sizeof(uint32_t)); 1356 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1357 sys::swapByteOrder(l); 1358 DumpLiteral4(l, f); 1359 } 1360 } 1361 1362 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1, 1363 double d) { 1364 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1); 1365 uint32_t Hi, Lo; 1366 Hi = (O->isLittleEndian()) ? l1 : l0; 1367 Lo = (O->isLittleEndian()) ? l0 : l1; 1368 1369 // Hi is the high word, so this is equivalent to if(isfinite(d)) 1370 if ((Hi & 0x7ff00000) != 0x7ff00000) 1371 outs() << format(" (%.16e)\n", d); 1372 else { 1373 if (Hi == 0x7ff00000 && Lo == 0) 1374 outs() << " (+Infinity)\n"; 1375 else if (Hi == 0xfff00000 && Lo == 0) 1376 outs() << " (-Infinity)\n"; 1377 else if ((Hi & 0x00080000) == 0x00080000) 1378 outs() << " (non-signaling Not-a-Number)\n"; 1379 else 1380 outs() << " (signaling Not-a-Number)\n"; 1381 } 1382 } 1383 1384 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect, 1385 uint32_t sect_size, uint64_t sect_addr, 1386 bool print_addresses) { 1387 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) { 1388 if (print_addresses) { 1389 if (O->is64Bit()) 1390 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1391 else 1392 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1393 } 1394 double d; 1395 memcpy(&d, sect + i, sizeof(double)); 1396 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1397 sys::swapByteOrder(d); 1398 uint32_t l0, l1; 1399 memcpy(&l0, sect + i, sizeof(uint32_t)); 1400 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); 1401 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1402 sys::swapByteOrder(l0); 1403 sys::swapByteOrder(l1); 1404 } 1405 DumpLiteral8(O, l0, l1, d); 1406 } 1407 } 1408 1409 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) { 1410 outs() << format("0x%08" PRIx32, l0) << " "; 1411 outs() << format("0x%08" PRIx32, l1) << " "; 1412 outs() << format("0x%08" PRIx32, l2) << " "; 1413 outs() << format("0x%08" PRIx32, l3) << "\n"; 1414 } 1415 1416 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect, 1417 uint32_t sect_size, uint64_t sect_addr, 1418 bool print_addresses) { 1419 for (uint32_t i = 0; i < sect_size; i += 16) { 1420 if (print_addresses) { 1421 if (O->is64Bit()) 1422 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1423 else 1424 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1425 } 1426 uint32_t l0, l1, l2, l3; 1427 memcpy(&l0, sect + i, sizeof(uint32_t)); 1428 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t)); 1429 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t)); 1430 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t)); 1431 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1432 sys::swapByteOrder(l0); 1433 sys::swapByteOrder(l1); 1434 sys::swapByteOrder(l2); 1435 sys::swapByteOrder(l3); 1436 } 1437 DumpLiteral16(l0, l1, l2, l3); 1438 } 1439 } 1440 1441 static void DumpLiteralPointerSection(MachOObjectFile *O, 1442 const SectionRef &Section, 1443 const char *sect, uint32_t sect_size, 1444 uint64_t sect_addr, 1445 bool print_addresses) { 1446 // Collect the literal sections in this Mach-O file. 1447 std::vector<SectionRef> LiteralSections; 1448 for (const SectionRef &Section : O->sections()) { 1449 DataRefImpl Ref = Section.getRawDataRefImpl(); 1450 uint32_t section_type; 1451 if (O->is64Bit()) { 1452 const MachO::section_64 Sec = O->getSection64(Ref); 1453 section_type = Sec.flags & MachO::SECTION_TYPE; 1454 } else { 1455 const MachO::section Sec = O->getSection(Ref); 1456 section_type = Sec.flags & MachO::SECTION_TYPE; 1457 } 1458 if (section_type == MachO::S_CSTRING_LITERALS || 1459 section_type == MachO::S_4BYTE_LITERALS || 1460 section_type == MachO::S_8BYTE_LITERALS || 1461 section_type == MachO::S_16BYTE_LITERALS) 1462 LiteralSections.push_back(Section); 1463 } 1464 1465 // Set the size of the literal pointer. 1466 uint32_t lp_size = O->is64Bit() ? 8 : 4; 1467 1468 // Collect the external relocation symbols for the literal pointers. 1469 std::vector<std::pair<uint64_t, SymbolRef>> Relocs; 1470 for (const RelocationRef &Reloc : Section.relocations()) { 1471 DataRefImpl Rel; 1472 MachO::any_relocation_info RE; 1473 bool isExtern = false; 1474 Rel = Reloc.getRawDataRefImpl(); 1475 RE = O->getRelocation(Rel); 1476 isExtern = O->getPlainRelocationExternal(RE); 1477 if (isExtern) { 1478 uint64_t RelocOffset = Reloc.getOffset(); 1479 symbol_iterator RelocSym = Reloc.getSymbol(); 1480 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); 1481 } 1482 } 1483 array_pod_sort(Relocs.begin(), Relocs.end()); 1484 1485 // Dump each literal pointer. 1486 for (uint32_t i = 0; i < sect_size; i += lp_size) { 1487 if (print_addresses) { 1488 if (O->is64Bit()) 1489 outs() << format("%016" PRIx64, sect_addr + i) << " "; 1490 else 1491 outs() << format("%08" PRIx64, sect_addr + i) << " "; 1492 } 1493 uint64_t lp; 1494 if (O->is64Bit()) { 1495 memcpy(&lp, sect + i, sizeof(uint64_t)); 1496 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1497 sys::swapByteOrder(lp); 1498 } else { 1499 uint32_t li; 1500 memcpy(&li, sect + i, sizeof(uint32_t)); 1501 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1502 sys::swapByteOrder(li); 1503 lp = li; 1504 } 1505 1506 // First look for an external relocation entry for this literal pointer. 1507 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) { 1508 return P.first == i; 1509 }); 1510 if (Reloc != Relocs.end()) { 1511 symbol_iterator RelocSym = Reloc->second; 1512 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName()); 1513 outs() << "external relocation entry for symbol:" << SymName << "\n"; 1514 continue; 1515 } 1516 1517 // For local references see what the section the literal pointer points to. 1518 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) { 1519 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize(); 1520 }); 1521 if (Sect == LiteralSections.end()) { 1522 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n"; 1523 continue; 1524 } 1525 1526 uint64_t SectAddress = Sect->getAddress(); 1527 uint64_t SectSize = Sect->getSize(); 1528 1529 StringRef SectName; 1530 Expected<StringRef> SectNameOrErr = Sect->getName(); 1531 if (SectNameOrErr) 1532 SectName = *SectNameOrErr; 1533 else 1534 consumeError(SectNameOrErr.takeError()); 1535 1536 DataRefImpl Ref = Sect->getRawDataRefImpl(); 1537 StringRef SegmentName = O->getSectionFinalSegmentName(Ref); 1538 outs() << SegmentName << ":" << SectName << ":"; 1539 1540 uint32_t section_type; 1541 if (O->is64Bit()) { 1542 const MachO::section_64 Sec = O->getSection64(Ref); 1543 section_type = Sec.flags & MachO::SECTION_TYPE; 1544 } else { 1545 const MachO::section Sec = O->getSection(Ref); 1546 section_type = Sec.flags & MachO::SECTION_TYPE; 1547 } 1548 1549 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName()); 1550 1551 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 1552 1553 switch (section_type) { 1554 case MachO::S_CSTRING_LITERALS: 1555 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0'; 1556 i++) { 1557 DumpCstringChar(Contents[i]); 1558 } 1559 outs() << "\n"; 1560 break; 1561 case MachO::S_4BYTE_LITERALS: 1562 float f; 1563 memcpy(&f, Contents + (lp - SectAddress), sizeof(float)); 1564 uint32_t l; 1565 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t)); 1566 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1567 sys::swapByteOrder(f); 1568 sys::swapByteOrder(l); 1569 } 1570 DumpLiteral4(l, f); 1571 break; 1572 case MachO::S_8BYTE_LITERALS: { 1573 double d; 1574 memcpy(&d, Contents + (lp - SectAddress), sizeof(double)); 1575 uint32_t l0, l1; 1576 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); 1577 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), 1578 sizeof(uint32_t)); 1579 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1580 sys::swapByteOrder(f); 1581 sys::swapByteOrder(l0); 1582 sys::swapByteOrder(l1); 1583 } 1584 DumpLiteral8(O, l0, l1, d); 1585 break; 1586 } 1587 case MachO::S_16BYTE_LITERALS: { 1588 uint32_t l0, l1, l2, l3; 1589 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t)); 1590 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t), 1591 sizeof(uint32_t)); 1592 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t), 1593 sizeof(uint32_t)); 1594 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t), 1595 sizeof(uint32_t)); 1596 if (O->isLittleEndian() != sys::IsLittleEndianHost) { 1597 sys::swapByteOrder(l0); 1598 sys::swapByteOrder(l1); 1599 sys::swapByteOrder(l2); 1600 sys::swapByteOrder(l3); 1601 } 1602 DumpLiteral16(l0, l1, l2, l3); 1603 break; 1604 } 1605 } 1606 } 1607 } 1608 1609 static void DumpInitTermPointerSection(MachOObjectFile *O, 1610 const SectionRef &Section, 1611 const char *sect, 1612 uint32_t sect_size, uint64_t sect_addr, 1613 SymbolAddressMap *AddrMap, 1614 bool verbose) { 1615 uint32_t stride; 1616 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t); 1617 1618 // Collect the external relocation symbols for the pointers. 1619 std::vector<std::pair<uint64_t, SymbolRef>> Relocs; 1620 for (const RelocationRef &Reloc : Section.relocations()) { 1621 DataRefImpl Rel; 1622 MachO::any_relocation_info RE; 1623 bool isExtern = false; 1624 Rel = Reloc.getRawDataRefImpl(); 1625 RE = O->getRelocation(Rel); 1626 isExtern = O->getPlainRelocationExternal(RE); 1627 if (isExtern) { 1628 uint64_t RelocOffset = Reloc.getOffset(); 1629 symbol_iterator RelocSym = Reloc.getSymbol(); 1630 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym)); 1631 } 1632 } 1633 array_pod_sort(Relocs.begin(), Relocs.end()); 1634 1635 for (uint32_t i = 0; i < sect_size; i += stride) { 1636 const char *SymbolName = nullptr; 1637 uint64_t p; 1638 if (O->is64Bit()) { 1639 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " "; 1640 uint64_t pointer_value; 1641 memcpy(&pointer_value, sect + i, stride); 1642 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1643 sys::swapByteOrder(pointer_value); 1644 outs() << format("0x%016" PRIx64, pointer_value); 1645 p = pointer_value; 1646 } else { 1647 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " "; 1648 uint32_t pointer_value; 1649 memcpy(&pointer_value, sect + i, stride); 1650 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1651 sys::swapByteOrder(pointer_value); 1652 outs() << format("0x%08" PRIx32, pointer_value); 1653 p = pointer_value; 1654 } 1655 if (verbose) { 1656 // First look for an external relocation entry for this pointer. 1657 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) { 1658 return P.first == i; 1659 }); 1660 if (Reloc != Relocs.end()) { 1661 symbol_iterator RelocSym = Reloc->second; 1662 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName()); 1663 } else { 1664 SymbolName = GuessSymbolName(p, AddrMap); 1665 if (SymbolName) 1666 outs() << " " << SymbolName; 1667 } 1668 } 1669 outs() << "\n"; 1670 } 1671 } 1672 1673 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect, 1674 uint32_t size, uint64_t addr) { 1675 uint32_t cputype = O->getHeader().cputype; 1676 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) { 1677 uint32_t j; 1678 for (uint32_t i = 0; i < size; i += j, addr += j) { 1679 if (O->is64Bit()) 1680 outs() << format("%016" PRIx64, addr) << "\t"; 1681 else 1682 outs() << format("%08" PRIx64, addr) << "\t"; 1683 for (j = 0; j < 16 && i + j < size; j++) { 1684 uint8_t byte_word = *(sect + i + j); 1685 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; 1686 } 1687 outs() << "\n"; 1688 } 1689 } else { 1690 uint32_t j; 1691 for (uint32_t i = 0; i < size; i += j, addr += j) { 1692 if (O->is64Bit()) 1693 outs() << format("%016" PRIx64, addr) << "\t"; 1694 else 1695 outs() << format("%08" PRIx64, addr) << "\t"; 1696 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size; 1697 j += sizeof(int32_t)) { 1698 if (i + j + sizeof(int32_t) <= size) { 1699 uint32_t long_word; 1700 memcpy(&long_word, sect + i + j, sizeof(int32_t)); 1701 if (O->isLittleEndian() != sys::IsLittleEndianHost) 1702 sys::swapByteOrder(long_word); 1703 outs() << format("%08" PRIx32, long_word) << " "; 1704 } else { 1705 for (uint32_t k = 0; i + j + k < size; k++) { 1706 uint8_t byte_word = *(sect + i + j + k); 1707 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " "; 1708 } 1709 } 1710 } 1711 outs() << "\n"; 1712 } 1713 } 1714 } 1715 1716 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, 1717 StringRef DisSegName, StringRef DisSectName); 1718 static void DumpProtocolSection(MachOObjectFile *O, const char *sect, 1719 uint32_t size, uint32_t addr); 1720 #ifdef LLVM_HAVE_LIBXAR 1721 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect, 1722 uint32_t size, bool verbose, 1723 bool PrintXarHeader, bool PrintXarFileHeaders, 1724 std::string XarMemberName); 1725 #endif // defined(LLVM_HAVE_LIBXAR) 1726 1727 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O, 1728 bool verbose) { 1729 SymbolAddressMap AddrMap; 1730 if (verbose) 1731 CreateSymbolAddressMap(O, &AddrMap); 1732 1733 for (unsigned i = 0; i < FilterSections.size(); ++i) { 1734 StringRef DumpSection = FilterSections[i]; 1735 std::pair<StringRef, StringRef> DumpSegSectName; 1736 DumpSegSectName = DumpSection.split(','); 1737 StringRef DumpSegName, DumpSectName; 1738 if (!DumpSegSectName.second.empty()) { 1739 DumpSegName = DumpSegSectName.first; 1740 DumpSectName = DumpSegSectName.second; 1741 } else { 1742 DumpSegName = ""; 1743 DumpSectName = DumpSegSectName.first; 1744 } 1745 for (const SectionRef &Section : O->sections()) { 1746 StringRef SectName; 1747 Expected<StringRef> SecNameOrErr = Section.getName(); 1748 if (SecNameOrErr) 1749 SectName = *SecNameOrErr; 1750 else 1751 consumeError(SecNameOrErr.takeError()); 1752 1753 if (!DumpSection.empty()) 1754 FoundSectionSet.insert(DumpSection); 1755 1756 DataRefImpl Ref = Section.getRawDataRefImpl(); 1757 StringRef SegName = O->getSectionFinalSegmentName(Ref); 1758 if ((DumpSegName.empty() || SegName == DumpSegName) && 1759 (SectName == DumpSectName)) { 1760 1761 uint32_t section_flags; 1762 if (O->is64Bit()) { 1763 const MachO::section_64 Sec = O->getSection64(Ref); 1764 section_flags = Sec.flags; 1765 1766 } else { 1767 const MachO::section Sec = O->getSection(Ref); 1768 section_flags = Sec.flags; 1769 } 1770 uint32_t section_type = section_flags & MachO::SECTION_TYPE; 1771 1772 StringRef BytesStr = 1773 unwrapOrError(Section.getContents(), O->getFileName()); 1774 const char *sect = reinterpret_cast<const char *>(BytesStr.data()); 1775 uint32_t sect_size = BytesStr.size(); 1776 uint64_t sect_addr = Section.getAddress(); 1777 1778 if (LeadingHeaders) 1779 outs() << "Contents of (" << SegName << "," << SectName 1780 << ") section\n"; 1781 1782 if (verbose) { 1783 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) || 1784 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) { 1785 DisassembleMachO(Filename, O, SegName, SectName); 1786 continue; 1787 } 1788 if (SegName == "__TEXT" && SectName == "__info_plist") { 1789 outs() << sect; 1790 continue; 1791 } 1792 if (SegName == "__OBJC" && SectName == "__protocol") { 1793 DumpProtocolSection(O, sect, sect_size, sect_addr); 1794 continue; 1795 } 1796 #ifdef LLVM_HAVE_LIBXAR 1797 if (SegName == "__LLVM" && SectName == "__bundle") { 1798 DumpBitcodeSection(O, sect, sect_size, verbose, SymbolicOperands, 1799 ArchiveHeaders, ""); 1800 continue; 1801 } 1802 #endif // defined(LLVM_HAVE_LIBXAR) 1803 switch (section_type) { 1804 case MachO::S_REGULAR: 1805 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1806 break; 1807 case MachO::S_ZEROFILL: 1808 outs() << "zerofill section and has no contents in the file\n"; 1809 break; 1810 case MachO::S_CSTRING_LITERALS: 1811 DumpCstringSection(O, sect, sect_size, sect_addr, LeadingAddr); 1812 break; 1813 case MachO::S_4BYTE_LITERALS: 1814 DumpLiteral4Section(O, sect, sect_size, sect_addr, LeadingAddr); 1815 break; 1816 case MachO::S_8BYTE_LITERALS: 1817 DumpLiteral8Section(O, sect, sect_size, sect_addr, LeadingAddr); 1818 break; 1819 case MachO::S_16BYTE_LITERALS: 1820 DumpLiteral16Section(O, sect, sect_size, sect_addr, LeadingAddr); 1821 break; 1822 case MachO::S_LITERAL_POINTERS: 1823 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr, 1824 LeadingAddr); 1825 break; 1826 case MachO::S_MOD_INIT_FUNC_POINTERS: 1827 case MachO::S_MOD_TERM_FUNC_POINTERS: 1828 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr, 1829 &AddrMap, verbose); 1830 break; 1831 default: 1832 outs() << "Unknown section type (" 1833 << format("0x%08" PRIx32, section_type) << ")\n"; 1834 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1835 break; 1836 } 1837 } else { 1838 if (section_type == MachO::S_ZEROFILL) 1839 outs() << "zerofill section and has no contents in the file\n"; 1840 else 1841 DumpRawSectionContents(O, sect, sect_size, sect_addr); 1842 } 1843 } 1844 } 1845 } 1846 } 1847 1848 static void DumpInfoPlistSectionContents(StringRef Filename, 1849 MachOObjectFile *O) { 1850 for (const SectionRef &Section : O->sections()) { 1851 StringRef SectName; 1852 Expected<StringRef> SecNameOrErr = Section.getName(); 1853 if (SecNameOrErr) 1854 SectName = *SecNameOrErr; 1855 else 1856 consumeError(SecNameOrErr.takeError()); 1857 1858 DataRefImpl Ref = Section.getRawDataRefImpl(); 1859 StringRef SegName = O->getSectionFinalSegmentName(Ref); 1860 if (SegName == "__TEXT" && SectName == "__info_plist") { 1861 if (LeadingHeaders) 1862 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 1863 StringRef BytesStr = 1864 unwrapOrError(Section.getContents(), O->getFileName()); 1865 const char *sect = reinterpret_cast<const char *>(BytesStr.data()); 1866 outs() << format("%.*s", BytesStr.size(), sect) << "\n"; 1867 return; 1868 } 1869 } 1870 } 1871 1872 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file 1873 // and if it is and there is a list of architecture flags is specified then 1874 // check to make sure this Mach-O file is one of those architectures or all 1875 // architectures were specified. If not then an error is generated and this 1876 // routine returns false. Else it returns true. 1877 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) { 1878 auto *MachO = dyn_cast<MachOObjectFile>(O); 1879 1880 if (!MachO || ArchAll || ArchFlags.empty()) 1881 return true; 1882 1883 MachO::mach_header H; 1884 MachO::mach_header_64 H_64; 1885 Triple T; 1886 const char *McpuDefault, *ArchFlag; 1887 if (MachO->is64Bit()) { 1888 H_64 = MachO->MachOObjectFile::getHeader64(); 1889 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype, 1890 &McpuDefault, &ArchFlag); 1891 } else { 1892 H = MachO->MachOObjectFile::getHeader(); 1893 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype, 1894 &McpuDefault, &ArchFlag); 1895 } 1896 const std::string ArchFlagName(ArchFlag); 1897 if (!llvm::is_contained(ArchFlags, ArchFlagName)) { 1898 WithColor::error(errs(), "llvm-objdump") 1899 << Filename << ": no architecture specified.\n"; 1900 return false; 1901 } 1902 return true; 1903 } 1904 1905 static void printObjcMetaData(MachOObjectFile *O, bool verbose); 1906 1907 // ProcessMachO() is passed a single opened Mach-O file, which may be an 1908 // archive member and or in a slice of a universal file. It prints the 1909 // the file name and header info and then processes it according to the 1910 // command line options. 1911 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF, 1912 StringRef ArchiveMemberName = StringRef(), 1913 StringRef ArchitectureName = StringRef()) { 1914 // If we are doing some processing here on the Mach-O file print the header 1915 // info. And don't print it otherwise like in the case of printing the 1916 // UniversalHeaders or ArchiveHeaders. 1917 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase || 1918 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols || 1919 DataInCode || FunctionStarts || LinkOptHints || DyldInfo || DylibsUsed || 1920 DylibId || Rpaths || ObjcMetaData || (!FilterSections.empty())) { 1921 if (LeadingHeaders) { 1922 outs() << Name; 1923 if (!ArchiveMemberName.empty()) 1924 outs() << '(' << ArchiveMemberName << ')'; 1925 if (!ArchitectureName.empty()) 1926 outs() << " (architecture " << ArchitectureName << ")"; 1927 outs() << ":\n"; 1928 } 1929 } 1930 // To use the report_error() form with an ArchiveName and FileName set 1931 // these up based on what is passed for Name and ArchiveMemberName. 1932 StringRef ArchiveName; 1933 StringRef FileName; 1934 if (!ArchiveMemberName.empty()) { 1935 ArchiveName = Name; 1936 FileName = ArchiveMemberName; 1937 } else { 1938 ArchiveName = StringRef(); 1939 FileName = Name; 1940 } 1941 1942 // If we need the symbol table to do the operation then check it here to 1943 // produce a good error message as to where the Mach-O file comes from in 1944 // the error message. 1945 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo) 1946 if (Error Err = MachOOF->checkSymbolTable()) 1947 reportError(std::move(Err), FileName, ArchiveName, ArchitectureName); 1948 1949 if (DisassembleAll) { 1950 for (const SectionRef &Section : MachOOF->sections()) { 1951 StringRef SectName; 1952 if (Expected<StringRef> NameOrErr = Section.getName()) 1953 SectName = *NameOrErr; 1954 else 1955 consumeError(NameOrErr.takeError()); 1956 1957 if (SectName.equals("__text")) { 1958 DataRefImpl Ref = Section.getRawDataRefImpl(); 1959 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref); 1960 DisassembleMachO(FileName, MachOOF, SegName, SectName); 1961 } 1962 } 1963 } 1964 else if (Disassemble) { 1965 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE && 1966 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64) 1967 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text"); 1968 else 1969 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text"); 1970 } 1971 if (IndirectSymbols) 1972 PrintIndirectSymbols(MachOOF, Verbose); 1973 if (DataInCode) 1974 PrintDataInCodeTable(MachOOF, Verbose); 1975 if (FunctionStarts) 1976 PrintFunctionStarts(MachOOF); 1977 if (LinkOptHints) 1978 PrintLinkOptHints(MachOOF); 1979 if (Relocations) 1980 PrintRelocations(MachOOF, Verbose); 1981 if (SectionHeaders) 1982 printSectionHeaders(MachOOF); 1983 if (SectionContents) 1984 printSectionContents(MachOOF); 1985 if (!FilterSections.empty()) 1986 DumpSectionContents(FileName, MachOOF, Verbose); 1987 if (InfoPlist) 1988 DumpInfoPlistSectionContents(FileName, MachOOF); 1989 if (DyldInfo) 1990 PrintDyldInfo(MachOOF); 1991 if (DylibsUsed) 1992 PrintDylibs(MachOOF, false); 1993 if (DylibId) 1994 PrintDylibs(MachOOF, true); 1995 if (SymbolTable) 1996 printSymbolTable(MachOOF, ArchiveName, ArchitectureName); 1997 if (UnwindInfo) 1998 printMachOUnwindInfo(MachOOF); 1999 if (PrivateHeaders) { 2000 printMachOFileHeader(MachOOF); 2001 printMachOLoadCommands(MachOOF); 2002 } 2003 if (FirstPrivateHeader) 2004 printMachOFileHeader(MachOOF); 2005 if (ObjcMetaData) 2006 printObjcMetaData(MachOOF, Verbose); 2007 if (ExportsTrie) 2008 printExportsTrie(MachOOF); 2009 if (Rebase) 2010 printRebaseTable(MachOOF); 2011 if (Rpaths) 2012 printRpaths(MachOOF); 2013 if (Bind) 2014 printBindTable(MachOOF); 2015 if (LazyBind) 2016 printLazyBindTable(MachOOF); 2017 if (WeakBind) 2018 printWeakBindTable(MachOOF); 2019 2020 if (DwarfDumpType != DIDT_Null) { 2021 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF); 2022 // Dump the complete DWARF structure. 2023 DIDumpOptions DumpOpts; 2024 DumpOpts.DumpType = DwarfDumpType; 2025 DICtx->dump(outs(), DumpOpts); 2026 } 2027 } 2028 2029 // printUnknownCPUType() helps print_fat_headers for unknown CPU's. 2030 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) { 2031 outs() << " cputype (" << cputype << ")\n"; 2032 outs() << " cpusubtype (" << cpusubtype << ")\n"; 2033 } 2034 2035 // printCPUType() helps print_fat_headers by printing the cputype and 2036 // pusubtype (symbolically for the one's it knows about). 2037 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) { 2038 switch (cputype) { 2039 case MachO::CPU_TYPE_I386: 2040 switch (cpusubtype) { 2041 case MachO::CPU_SUBTYPE_I386_ALL: 2042 outs() << " cputype CPU_TYPE_I386\n"; 2043 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n"; 2044 break; 2045 default: 2046 printUnknownCPUType(cputype, cpusubtype); 2047 break; 2048 } 2049 break; 2050 case MachO::CPU_TYPE_X86_64: 2051 switch (cpusubtype) { 2052 case MachO::CPU_SUBTYPE_X86_64_ALL: 2053 outs() << " cputype CPU_TYPE_X86_64\n"; 2054 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n"; 2055 break; 2056 case MachO::CPU_SUBTYPE_X86_64_H: 2057 outs() << " cputype CPU_TYPE_X86_64\n"; 2058 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n"; 2059 break; 2060 default: 2061 printUnknownCPUType(cputype, cpusubtype); 2062 break; 2063 } 2064 break; 2065 case MachO::CPU_TYPE_ARM: 2066 switch (cpusubtype) { 2067 case MachO::CPU_SUBTYPE_ARM_ALL: 2068 outs() << " cputype CPU_TYPE_ARM\n"; 2069 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n"; 2070 break; 2071 case MachO::CPU_SUBTYPE_ARM_V4T: 2072 outs() << " cputype CPU_TYPE_ARM\n"; 2073 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n"; 2074 break; 2075 case MachO::CPU_SUBTYPE_ARM_V5TEJ: 2076 outs() << " cputype CPU_TYPE_ARM\n"; 2077 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n"; 2078 break; 2079 case MachO::CPU_SUBTYPE_ARM_XSCALE: 2080 outs() << " cputype CPU_TYPE_ARM\n"; 2081 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n"; 2082 break; 2083 case MachO::CPU_SUBTYPE_ARM_V6: 2084 outs() << " cputype CPU_TYPE_ARM\n"; 2085 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n"; 2086 break; 2087 case MachO::CPU_SUBTYPE_ARM_V6M: 2088 outs() << " cputype CPU_TYPE_ARM\n"; 2089 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n"; 2090 break; 2091 case MachO::CPU_SUBTYPE_ARM_V7: 2092 outs() << " cputype CPU_TYPE_ARM\n"; 2093 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n"; 2094 break; 2095 case MachO::CPU_SUBTYPE_ARM_V7EM: 2096 outs() << " cputype CPU_TYPE_ARM\n"; 2097 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n"; 2098 break; 2099 case MachO::CPU_SUBTYPE_ARM_V7K: 2100 outs() << " cputype CPU_TYPE_ARM\n"; 2101 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n"; 2102 break; 2103 case MachO::CPU_SUBTYPE_ARM_V7M: 2104 outs() << " cputype CPU_TYPE_ARM\n"; 2105 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n"; 2106 break; 2107 case MachO::CPU_SUBTYPE_ARM_V7S: 2108 outs() << " cputype CPU_TYPE_ARM\n"; 2109 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n"; 2110 break; 2111 default: 2112 printUnknownCPUType(cputype, cpusubtype); 2113 break; 2114 } 2115 break; 2116 case MachO::CPU_TYPE_ARM64: 2117 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 2118 case MachO::CPU_SUBTYPE_ARM64_ALL: 2119 outs() << " cputype CPU_TYPE_ARM64\n"; 2120 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n"; 2121 break; 2122 case MachO::CPU_SUBTYPE_ARM64_V8: 2123 outs() << " cputype CPU_TYPE_ARM64\n"; 2124 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n"; 2125 break; 2126 case MachO::CPU_SUBTYPE_ARM64E: 2127 outs() << " cputype CPU_TYPE_ARM64\n"; 2128 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n"; 2129 break; 2130 default: 2131 printUnknownCPUType(cputype, cpusubtype); 2132 break; 2133 } 2134 break; 2135 case MachO::CPU_TYPE_ARM64_32: 2136 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 2137 case MachO::CPU_SUBTYPE_ARM64_32_V8: 2138 outs() << " cputype CPU_TYPE_ARM64_32\n"; 2139 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n"; 2140 break; 2141 default: 2142 printUnknownCPUType(cputype, cpusubtype); 2143 break; 2144 } 2145 break; 2146 default: 2147 printUnknownCPUType(cputype, cpusubtype); 2148 break; 2149 } 2150 } 2151 2152 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB, 2153 bool verbose) { 2154 outs() << "Fat headers\n"; 2155 if (verbose) { 2156 if (UB->getMagic() == MachO::FAT_MAGIC) 2157 outs() << "fat_magic FAT_MAGIC\n"; 2158 else // UB->getMagic() == MachO::FAT_MAGIC_64 2159 outs() << "fat_magic FAT_MAGIC_64\n"; 2160 } else 2161 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n"; 2162 2163 uint32_t nfat_arch = UB->getNumberOfObjects(); 2164 StringRef Buf = UB->getData(); 2165 uint64_t size = Buf.size(); 2166 uint64_t big_size = sizeof(struct MachO::fat_header) + 2167 nfat_arch * sizeof(struct MachO::fat_arch); 2168 outs() << "nfat_arch " << UB->getNumberOfObjects(); 2169 if (nfat_arch == 0) 2170 outs() << " (malformed, contains zero architecture types)\n"; 2171 else if (big_size > size) 2172 outs() << " (malformed, architectures past end of file)\n"; 2173 else 2174 outs() << "\n"; 2175 2176 for (uint32_t i = 0; i < nfat_arch; ++i) { 2177 MachOUniversalBinary::ObjectForArch OFA(UB, i); 2178 uint32_t cputype = OFA.getCPUType(); 2179 uint32_t cpusubtype = OFA.getCPUSubType(); 2180 outs() << "architecture "; 2181 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) { 2182 MachOUniversalBinary::ObjectForArch other_OFA(UB, j); 2183 uint32_t other_cputype = other_OFA.getCPUType(); 2184 uint32_t other_cpusubtype = other_OFA.getCPUSubType(); 2185 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype && 2186 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) == 2187 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) { 2188 outs() << "(illegal duplicate architecture) "; 2189 break; 2190 } 2191 } 2192 if (verbose) { 2193 outs() << OFA.getArchFlagName() << "\n"; 2194 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 2195 } else { 2196 outs() << i << "\n"; 2197 outs() << " cputype " << cputype << "\n"; 2198 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) 2199 << "\n"; 2200 } 2201 if (verbose && 2202 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) 2203 outs() << " capabilities CPU_SUBTYPE_LIB64\n"; 2204 else 2205 outs() << " capabilities " 2206 << format("0x%" PRIx32, 2207 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n"; 2208 outs() << " offset " << OFA.getOffset(); 2209 if (OFA.getOffset() > size) 2210 outs() << " (past end of file)"; 2211 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0) 2212 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")"; 2213 outs() << "\n"; 2214 outs() << " size " << OFA.getSize(); 2215 big_size = OFA.getOffset() + OFA.getSize(); 2216 if (big_size > size) 2217 outs() << " (past end of file)"; 2218 outs() << "\n"; 2219 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign()) 2220 << ")\n"; 2221 } 2222 } 2223 2224 static void printArchiveChild(StringRef Filename, const Archive::Child &C, 2225 size_t ChildIndex, bool verbose, 2226 bool print_offset, 2227 StringRef ArchitectureName = StringRef()) { 2228 if (print_offset) 2229 outs() << C.getChildOffset() << "\t"; 2230 sys::fs::perms Mode = 2231 unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex), 2232 Filename, ArchitectureName); 2233 if (verbose) { 2234 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG. 2235 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG. 2236 outs() << "-"; 2237 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-"); 2238 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-"); 2239 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-"); 2240 outs() << ((Mode & sys::fs::group_read) ? "r" : "-"); 2241 outs() << ((Mode & sys::fs::group_write) ? "w" : "-"); 2242 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-"); 2243 outs() << ((Mode & sys::fs::others_read) ? "r" : "-"); 2244 outs() << ((Mode & sys::fs::others_write) ? "w" : "-"); 2245 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-"); 2246 } else { 2247 outs() << format("0%o ", Mode); 2248 } 2249 2250 outs() << format("%3d/%-3d %5" PRId64 " ", 2251 unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex), 2252 Filename, ArchitectureName), 2253 unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex), 2254 Filename, ArchitectureName), 2255 unwrapOrError(C.getRawSize(), 2256 getFileNameForError(C, ChildIndex), Filename, 2257 ArchitectureName)); 2258 2259 StringRef RawLastModified = C.getRawLastModified(); 2260 if (verbose) { 2261 unsigned Seconds; 2262 if (RawLastModified.getAsInteger(10, Seconds)) 2263 outs() << "(date: \"" << RawLastModified 2264 << "\" contains non-decimal chars) "; 2265 else { 2266 // Since cime(3) returns a 26 character string of the form: 2267 // "Sun Sep 16 01:03:52 1973\n\0" 2268 // just print 24 characters. 2269 time_t t = Seconds; 2270 outs() << format("%.24s ", ctime(&t)); 2271 } 2272 } else { 2273 outs() << RawLastModified << " "; 2274 } 2275 2276 if (verbose) { 2277 Expected<StringRef> NameOrErr = C.getName(); 2278 if (!NameOrErr) { 2279 consumeError(NameOrErr.takeError()); 2280 outs() << unwrapOrError(C.getRawName(), 2281 getFileNameForError(C, ChildIndex), Filename, 2282 ArchitectureName) 2283 << "\n"; 2284 } else { 2285 StringRef Name = NameOrErr.get(); 2286 outs() << Name << "\n"; 2287 } 2288 } else { 2289 outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex), 2290 Filename, ArchitectureName) 2291 << "\n"; 2292 } 2293 } 2294 2295 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose, 2296 bool print_offset, 2297 StringRef ArchitectureName = StringRef()) { 2298 Error Err = Error::success(); 2299 size_t I = 0; 2300 for (const auto &C : A->children(Err, false)) 2301 printArchiveChild(Filename, C, I++, verbose, print_offset, 2302 ArchitectureName); 2303 2304 if (Err) 2305 reportError(std::move(Err), Filename, "", ArchitectureName); 2306 } 2307 2308 static bool ValidateArchFlags() { 2309 // Check for -arch all and verifiy the -arch flags are valid. 2310 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2311 if (ArchFlags[i] == "all") { 2312 ArchAll = true; 2313 } else { 2314 if (!MachOObjectFile::isValidArch(ArchFlags[i])) { 2315 WithColor::error(errs(), "llvm-objdump") 2316 << "unknown architecture named '" + ArchFlags[i] + 2317 "'for the -arch option\n"; 2318 return false; 2319 } 2320 } 2321 } 2322 return true; 2323 } 2324 2325 // ParseInputMachO() parses the named Mach-O file in Filename and handles the 2326 // -arch flags selecting just those slices as specified by them and also parses 2327 // archive files. Then for each individual Mach-O file ProcessMachO() is 2328 // called to process the file based on the command line options. 2329 void objdump::parseInputMachO(StringRef Filename) { 2330 if (!ValidateArchFlags()) 2331 return; 2332 2333 // Attempt to open the binary. 2334 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename); 2335 if (!BinaryOrErr) { 2336 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError())) 2337 reportError(std::move(E), Filename); 2338 else 2339 outs() << Filename << ": is not an object file\n"; 2340 return; 2341 } 2342 Binary &Bin = *BinaryOrErr.get().getBinary(); 2343 2344 if (Archive *A = dyn_cast<Archive>(&Bin)) { 2345 outs() << "Archive : " << Filename << "\n"; 2346 if (ArchiveHeaders) 2347 printArchiveHeaders(Filename, A, Verbose, ArchiveMemberOffsets); 2348 2349 Error Err = Error::success(); 2350 unsigned I = -1; 2351 for (auto &C : A->children(Err)) { 2352 ++I; 2353 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2354 if (!ChildOrErr) { 2355 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2356 reportError(std::move(E), getFileNameForError(C, I), Filename); 2357 continue; 2358 } 2359 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { 2360 if (!checkMachOAndArchFlags(O, Filename)) 2361 return; 2362 ProcessMachO(Filename, O, O->getFileName()); 2363 } 2364 } 2365 if (Err) 2366 reportError(std::move(Err), Filename); 2367 return; 2368 } 2369 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) { 2370 parseInputMachO(UB); 2371 return; 2372 } 2373 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) { 2374 if (!checkMachOAndArchFlags(O, Filename)) 2375 return; 2376 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) 2377 ProcessMachO(Filename, MachOOF); 2378 else 2379 WithColor::error(errs(), "llvm-objdump") 2380 << Filename << "': " 2381 << "object is not a Mach-O file type.\n"; 2382 return; 2383 } 2384 llvm_unreachable("Input object can't be invalid at this point"); 2385 } 2386 2387 void objdump::parseInputMachO(MachOUniversalBinary *UB) { 2388 if (!ValidateArchFlags()) 2389 return; 2390 2391 auto Filename = UB->getFileName(); 2392 2393 if (UniversalHeaders) 2394 printMachOUniversalHeaders(UB, Verbose); 2395 2396 // If we have a list of architecture flags specified dump only those. 2397 if (!ArchAll && !ArchFlags.empty()) { 2398 // Look for a slice in the universal binary that matches each ArchFlag. 2399 bool ArchFound; 2400 for (unsigned i = 0; i < ArchFlags.size(); ++i) { 2401 ArchFound = false; 2402 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2403 E = UB->end_objects(); 2404 I != E; ++I) { 2405 if (ArchFlags[i] == I->getArchFlagName()) { 2406 ArchFound = true; 2407 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = 2408 I->getAsObjectFile(); 2409 std::string ArchitectureName; 2410 if (ArchFlags.size() > 1) 2411 ArchitectureName = I->getArchFlagName(); 2412 if (ObjOrErr) { 2413 ObjectFile &O = *ObjOrErr.get(); 2414 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) 2415 ProcessMachO(Filename, MachOOF, "", ArchitectureName); 2416 } else if (Error E = isNotObjectErrorInvalidFileType( 2417 ObjOrErr.takeError())) { 2418 reportError(std::move(E), "", Filename, ArchitectureName); 2419 continue; 2420 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2421 I->getAsArchive()) { 2422 std::unique_ptr<Archive> &A = *AOrErr; 2423 outs() << "Archive : " << Filename; 2424 if (!ArchitectureName.empty()) 2425 outs() << " (architecture " << ArchitectureName << ")"; 2426 outs() << "\n"; 2427 if (ArchiveHeaders) 2428 printArchiveHeaders(Filename, A.get(), Verbose, 2429 ArchiveMemberOffsets, ArchitectureName); 2430 Error Err = Error::success(); 2431 unsigned I = -1; 2432 for (auto &C : A->children(Err)) { 2433 ++I; 2434 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2435 if (!ChildOrErr) { 2436 if (Error E = 2437 isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2438 reportError(std::move(E), getFileNameForError(C, I), Filename, 2439 ArchitectureName); 2440 continue; 2441 } 2442 if (MachOObjectFile *O = 2443 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) 2444 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName); 2445 } 2446 if (Err) 2447 reportError(std::move(Err), Filename); 2448 } else { 2449 consumeError(AOrErr.takeError()); 2450 reportError(Filename, 2451 "Mach-O universal file for architecture " + 2452 StringRef(I->getArchFlagName()) + 2453 " is not a Mach-O file or an archive file"); 2454 } 2455 } 2456 } 2457 if (!ArchFound) { 2458 WithColor::error(errs(), "llvm-objdump") 2459 << "file: " + Filename + " does not contain " 2460 << "architecture: " + ArchFlags[i] + "\n"; 2461 return; 2462 } 2463 } 2464 return; 2465 } 2466 // No architecture flags were specified so if this contains a slice that 2467 // matches the host architecture dump only that. 2468 if (!ArchAll) { 2469 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2470 E = UB->end_objects(); 2471 I != E; ++I) { 2472 if (MachOObjectFile::getHostArch().getArchName() == 2473 I->getArchFlagName()) { 2474 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2475 std::string ArchiveName; 2476 ArchiveName.clear(); 2477 if (ObjOrErr) { 2478 ObjectFile &O = *ObjOrErr.get(); 2479 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O)) 2480 ProcessMachO(Filename, MachOOF); 2481 } else if (Error E = 2482 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2483 reportError(std::move(E), Filename); 2484 } else if (Expected<std::unique_ptr<Archive>> AOrErr = 2485 I->getAsArchive()) { 2486 std::unique_ptr<Archive> &A = *AOrErr; 2487 outs() << "Archive : " << Filename << "\n"; 2488 if (ArchiveHeaders) 2489 printArchiveHeaders(Filename, A.get(), Verbose, 2490 ArchiveMemberOffsets); 2491 Error Err = Error::success(); 2492 unsigned I = -1; 2493 for (auto &C : A->children(Err)) { 2494 ++I; 2495 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2496 if (!ChildOrErr) { 2497 if (Error E = 2498 isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2499 reportError(std::move(E), getFileNameForError(C, I), Filename); 2500 continue; 2501 } 2502 if (MachOObjectFile *O = 2503 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) 2504 ProcessMachO(Filename, O, O->getFileName()); 2505 } 2506 if (Err) 2507 reportError(std::move(Err), Filename); 2508 } else { 2509 consumeError(AOrErr.takeError()); 2510 reportError(Filename, "Mach-O universal file for architecture " + 2511 StringRef(I->getArchFlagName()) + 2512 " is not a Mach-O file or an archive file"); 2513 } 2514 return; 2515 } 2516 } 2517 } 2518 // Either all architectures have been specified or none have been specified 2519 // and this does not contain the host architecture so dump all the slices. 2520 bool moreThanOneArch = UB->getNumberOfObjects() > 1; 2521 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(), 2522 E = UB->end_objects(); 2523 I != E; ++I) { 2524 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile(); 2525 std::string ArchitectureName; 2526 if (moreThanOneArch) 2527 ArchitectureName = I->getArchFlagName(); 2528 if (ObjOrErr) { 2529 ObjectFile &Obj = *ObjOrErr.get(); 2530 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj)) 2531 ProcessMachO(Filename, MachOOF, "", ArchitectureName); 2532 } else if (Error E = 2533 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) { 2534 reportError(std::move(E), Filename, "", ArchitectureName); 2535 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) { 2536 std::unique_ptr<Archive> &A = *AOrErr; 2537 outs() << "Archive : " << Filename; 2538 if (!ArchitectureName.empty()) 2539 outs() << " (architecture " << ArchitectureName << ")"; 2540 outs() << "\n"; 2541 if (ArchiveHeaders) 2542 printArchiveHeaders(Filename, A.get(), Verbose, ArchiveMemberOffsets, 2543 ArchitectureName); 2544 Error Err = Error::success(); 2545 unsigned I = -1; 2546 for (auto &C : A->children(Err)) { 2547 ++I; 2548 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); 2549 if (!ChildOrErr) { 2550 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) 2551 reportError(std::move(E), getFileNameForError(C, I), Filename, 2552 ArchitectureName); 2553 continue; 2554 } 2555 if (MachOObjectFile *O = 2556 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) { 2557 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O)) 2558 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(), 2559 ArchitectureName); 2560 } 2561 } 2562 if (Err) 2563 reportError(std::move(Err), Filename); 2564 } else { 2565 consumeError(AOrErr.takeError()); 2566 reportError(Filename, "Mach-O universal file for architecture " + 2567 StringRef(I->getArchFlagName()) + 2568 " is not a Mach-O file or an archive file"); 2569 } 2570 } 2571 } 2572 2573 namespace { 2574 // The block of info used by the Symbolizer call backs. 2575 struct DisassembleInfo { 2576 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap, 2577 std::vector<SectionRef> *Sections, bool verbose) 2578 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {} 2579 bool verbose; 2580 MachOObjectFile *O; 2581 SectionRef S; 2582 SymbolAddressMap *AddrMap; 2583 std::vector<SectionRef> *Sections; 2584 const char *class_name = nullptr; 2585 const char *selector_name = nullptr; 2586 std::unique_ptr<char[]> method = nullptr; 2587 char *demangled_name = nullptr; 2588 uint64_t adrp_addr = 0; 2589 uint32_t adrp_inst = 0; 2590 std::unique_ptr<SymbolAddressMap> bindtable; 2591 uint32_t depth = 0; 2592 }; 2593 } // namespace 2594 2595 // SymbolizerGetOpInfo() is the operand information call back function. 2596 // This is called to get the symbolic information for operand(s) of an 2597 // instruction when it is being done. This routine does this from 2598 // the relocation information, symbol table, etc. That block of information 2599 // is a pointer to the struct DisassembleInfo that was passed when the 2600 // disassembler context was created and passed to back to here when 2601 // called back by the disassembler for instruction operands that could have 2602 // relocation information. The address of the instruction containing operand is 2603 // at the Pc parameter. The immediate value the operand has is passed in 2604 // op_info->Value and is at Offset past the start of the instruction and has a 2605 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the 2606 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol 2607 // names and addends of the symbolic expression to add for the operand. The 2608 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic 2609 // information is returned then this function returns 1 else it returns 0. 2610 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset, 2611 uint64_t Size, int TagType, void *TagBuf) { 2612 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; 2613 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf; 2614 uint64_t value = op_info->Value; 2615 2616 // Make sure all fields returned are zero if we don't set them. 2617 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1)); 2618 op_info->Value = value; 2619 2620 // If the TagType is not the value 1 which it code knows about or if no 2621 // verbose symbolic information is wanted then just return 0, indicating no 2622 // information is being returned. 2623 if (TagType != 1 || !info->verbose) 2624 return 0; 2625 2626 unsigned int Arch = info->O->getArch(); 2627 if (Arch == Triple::x86) { 2628 if (Size != 1 && Size != 2 && Size != 4 && Size != 0) 2629 return 0; 2630 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2631 // TODO: 2632 // Search the external relocation entries of a fully linked image 2633 // (if any) for an entry that matches this segment offset. 2634 // uint32_t seg_offset = (Pc + Offset); 2635 return 0; 2636 } 2637 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2638 // for an entry for this section offset. 2639 uint32_t sect_addr = info->S.getAddress(); 2640 uint32_t sect_offset = (Pc + Offset) - sect_addr; 2641 bool reloc_found = false; 2642 DataRefImpl Rel; 2643 MachO::any_relocation_info RE; 2644 bool isExtern = false; 2645 SymbolRef Symbol; 2646 bool r_scattered = false; 2647 uint32_t r_value, pair_r_value, r_type; 2648 for (const RelocationRef &Reloc : info->S.relocations()) { 2649 uint64_t RelocOffset = Reloc.getOffset(); 2650 if (RelocOffset == sect_offset) { 2651 Rel = Reloc.getRawDataRefImpl(); 2652 RE = info->O->getRelocation(Rel); 2653 r_type = info->O->getAnyRelocationType(RE); 2654 r_scattered = info->O->isRelocationScattered(RE); 2655 if (r_scattered) { 2656 r_value = info->O->getScatteredRelocationValue(RE); 2657 if (r_type == MachO::GENERIC_RELOC_SECTDIFF || 2658 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) { 2659 DataRefImpl RelNext = Rel; 2660 info->O->moveRelocationNext(RelNext); 2661 MachO::any_relocation_info RENext; 2662 RENext = info->O->getRelocation(RelNext); 2663 if (info->O->isRelocationScattered(RENext)) 2664 pair_r_value = info->O->getScatteredRelocationValue(RENext); 2665 else 2666 return 0; 2667 } 2668 } else { 2669 isExtern = info->O->getPlainRelocationExternal(RE); 2670 if (isExtern) { 2671 symbol_iterator RelocSym = Reloc.getSymbol(); 2672 Symbol = *RelocSym; 2673 } 2674 } 2675 reloc_found = true; 2676 break; 2677 } 2678 } 2679 if (reloc_found && isExtern) { 2680 op_info->AddSymbol.Present = 1; 2681 op_info->AddSymbol.Name = 2682 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2683 // For i386 extern relocation entries the value in the instruction is 2684 // the offset from the symbol, and value is already set in op_info->Value. 2685 return 1; 2686 } 2687 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF || 2688 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) { 2689 const char *add = GuessSymbolName(r_value, info->AddrMap); 2690 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); 2691 uint32_t offset = value - (r_value - pair_r_value); 2692 op_info->AddSymbol.Present = 1; 2693 if (add != nullptr) 2694 op_info->AddSymbol.Name = add; 2695 else 2696 op_info->AddSymbol.Value = r_value; 2697 op_info->SubtractSymbol.Present = 1; 2698 if (sub != nullptr) 2699 op_info->SubtractSymbol.Name = sub; 2700 else 2701 op_info->SubtractSymbol.Value = pair_r_value; 2702 op_info->Value = offset; 2703 return 1; 2704 } 2705 return 0; 2706 } 2707 if (Arch == Triple::x86_64) { 2708 if (Size != 1 && Size != 2 && Size != 4 && Size != 0) 2709 return 0; 2710 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external 2711 // relocation entries of a linked image (if any) for an entry that matches 2712 // this segment offset. 2713 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2714 uint64_t seg_offset = Pc + Offset; 2715 bool reloc_found = false; 2716 DataRefImpl Rel; 2717 MachO::any_relocation_info RE; 2718 bool isExtern = false; 2719 SymbolRef Symbol; 2720 for (const RelocationRef &Reloc : info->O->external_relocations()) { 2721 uint64_t RelocOffset = Reloc.getOffset(); 2722 if (RelocOffset == seg_offset) { 2723 Rel = Reloc.getRawDataRefImpl(); 2724 RE = info->O->getRelocation(Rel); 2725 // external relocation entries should always be external. 2726 isExtern = info->O->getPlainRelocationExternal(RE); 2727 if (isExtern) { 2728 symbol_iterator RelocSym = Reloc.getSymbol(); 2729 Symbol = *RelocSym; 2730 } 2731 reloc_found = true; 2732 break; 2733 } 2734 } 2735 if (reloc_found && isExtern) { 2736 // The Value passed in will be adjusted by the Pc if the instruction 2737 // adds the Pc. But for x86_64 external relocation entries the Value 2738 // is the offset from the external symbol. 2739 if (info->O->getAnyRelocationPCRel(RE)) 2740 op_info->Value -= Pc + Offset + Size; 2741 const char *name = 2742 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2743 op_info->AddSymbol.Present = 1; 2744 op_info->AddSymbol.Name = name; 2745 return 1; 2746 } 2747 return 0; 2748 } 2749 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2750 // for an entry for this section offset. 2751 uint64_t sect_addr = info->S.getAddress(); 2752 uint64_t sect_offset = (Pc + Offset) - sect_addr; 2753 bool reloc_found = false; 2754 DataRefImpl Rel; 2755 MachO::any_relocation_info RE; 2756 bool isExtern = false; 2757 SymbolRef Symbol; 2758 for (const RelocationRef &Reloc : info->S.relocations()) { 2759 uint64_t RelocOffset = Reloc.getOffset(); 2760 if (RelocOffset == sect_offset) { 2761 Rel = Reloc.getRawDataRefImpl(); 2762 RE = info->O->getRelocation(Rel); 2763 // NOTE: Scattered relocations don't exist on x86_64. 2764 isExtern = info->O->getPlainRelocationExternal(RE); 2765 if (isExtern) { 2766 symbol_iterator RelocSym = Reloc.getSymbol(); 2767 Symbol = *RelocSym; 2768 } 2769 reloc_found = true; 2770 break; 2771 } 2772 } 2773 if (reloc_found && isExtern) { 2774 // The Value passed in will be adjusted by the Pc if the instruction 2775 // adds the Pc. But for x86_64 external relocation entries the Value 2776 // is the offset from the external symbol. 2777 if (info->O->getAnyRelocationPCRel(RE)) 2778 op_info->Value -= Pc + Offset + Size; 2779 const char *name = 2780 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2781 unsigned Type = info->O->getAnyRelocationType(RE); 2782 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) { 2783 DataRefImpl RelNext = Rel; 2784 info->O->moveRelocationNext(RelNext); 2785 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); 2786 unsigned TypeNext = info->O->getAnyRelocationType(RENext); 2787 bool isExternNext = info->O->getPlainRelocationExternal(RENext); 2788 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext); 2789 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) { 2790 op_info->SubtractSymbol.Present = 1; 2791 op_info->SubtractSymbol.Name = name; 2792 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum); 2793 Symbol = *RelocSymNext; 2794 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2795 } 2796 } 2797 // TODO: add the VariantKinds to op_info->VariantKind for relocation types 2798 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT. 2799 op_info->AddSymbol.Present = 1; 2800 op_info->AddSymbol.Name = name; 2801 return 1; 2802 } 2803 return 0; 2804 } 2805 if (Arch == Triple::arm) { 2806 if (Offset != 0 || (Size != 4 && Size != 2)) 2807 return 0; 2808 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2809 // TODO: 2810 // Search the external relocation entries of a fully linked image 2811 // (if any) for an entry that matches this segment offset. 2812 // uint32_t seg_offset = (Pc + Offset); 2813 return 0; 2814 } 2815 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2816 // for an entry for this section offset. 2817 uint32_t sect_addr = info->S.getAddress(); 2818 uint32_t sect_offset = (Pc + Offset) - sect_addr; 2819 DataRefImpl Rel; 2820 MachO::any_relocation_info RE; 2821 bool isExtern = false; 2822 SymbolRef Symbol; 2823 bool r_scattered = false; 2824 uint32_t r_value, pair_r_value, r_type, r_length, other_half; 2825 auto Reloc = 2826 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) { 2827 uint64_t RelocOffset = Reloc.getOffset(); 2828 return RelocOffset == sect_offset; 2829 }); 2830 2831 if (Reloc == info->S.relocations().end()) 2832 return 0; 2833 2834 Rel = Reloc->getRawDataRefImpl(); 2835 RE = info->O->getRelocation(Rel); 2836 r_length = info->O->getAnyRelocationLength(RE); 2837 r_scattered = info->O->isRelocationScattered(RE); 2838 if (r_scattered) { 2839 r_value = info->O->getScatteredRelocationValue(RE); 2840 r_type = info->O->getScatteredRelocationType(RE); 2841 } else { 2842 r_type = info->O->getAnyRelocationType(RE); 2843 isExtern = info->O->getPlainRelocationExternal(RE); 2844 if (isExtern) { 2845 symbol_iterator RelocSym = Reloc->getSymbol(); 2846 Symbol = *RelocSym; 2847 } 2848 } 2849 if (r_type == MachO::ARM_RELOC_HALF || 2850 r_type == MachO::ARM_RELOC_SECTDIFF || 2851 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF || 2852 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2853 DataRefImpl RelNext = Rel; 2854 info->O->moveRelocationNext(RelNext); 2855 MachO::any_relocation_info RENext; 2856 RENext = info->O->getRelocation(RelNext); 2857 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff; 2858 if (info->O->isRelocationScattered(RENext)) 2859 pair_r_value = info->O->getScatteredRelocationValue(RENext); 2860 } 2861 2862 if (isExtern) { 2863 const char *name = 2864 unwrapOrError(Symbol.getName(), info->O->getFileName()).data(); 2865 op_info->AddSymbol.Present = 1; 2866 op_info->AddSymbol.Name = name; 2867 switch (r_type) { 2868 case MachO::ARM_RELOC_HALF: 2869 if ((r_length & 0x1) == 1) { 2870 op_info->Value = value << 16 | other_half; 2871 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2872 } else { 2873 op_info->Value = other_half << 16 | value; 2874 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2875 } 2876 break; 2877 default: 2878 break; 2879 } 2880 return 1; 2881 } 2882 // If we have a branch that is not an external relocation entry then 2883 // return 0 so the code in tryAddingSymbolicOperand() can use the 2884 // SymbolLookUp call back with the branch target address to look up the 2885 // symbol and possibility add an annotation for a symbol stub. 2886 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 || 2887 r_type == MachO::ARM_THUMB_RELOC_BR22)) 2888 return 0; 2889 2890 uint32_t offset = 0; 2891 if (r_type == MachO::ARM_RELOC_HALF || 2892 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2893 if ((r_length & 0x1) == 1) 2894 value = value << 16 | other_half; 2895 else 2896 value = other_half << 16 | value; 2897 } 2898 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF && 2899 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) { 2900 offset = value - r_value; 2901 value = r_value; 2902 } 2903 2904 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) { 2905 if ((r_length & 0x1) == 1) 2906 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2907 else 2908 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2909 const char *add = GuessSymbolName(r_value, info->AddrMap); 2910 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap); 2911 int32_t offset = value - (r_value - pair_r_value); 2912 op_info->AddSymbol.Present = 1; 2913 if (add != nullptr) 2914 op_info->AddSymbol.Name = add; 2915 else 2916 op_info->AddSymbol.Value = r_value; 2917 op_info->SubtractSymbol.Present = 1; 2918 if (sub != nullptr) 2919 op_info->SubtractSymbol.Name = sub; 2920 else 2921 op_info->SubtractSymbol.Value = pair_r_value; 2922 op_info->Value = offset; 2923 return 1; 2924 } 2925 2926 op_info->AddSymbol.Present = 1; 2927 op_info->Value = offset; 2928 if (r_type == MachO::ARM_RELOC_HALF) { 2929 if ((r_length & 0x1) == 1) 2930 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16; 2931 else 2932 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16; 2933 } 2934 const char *add = GuessSymbolName(value, info->AddrMap); 2935 if (add != nullptr) { 2936 op_info->AddSymbol.Name = add; 2937 return 1; 2938 } 2939 op_info->AddSymbol.Value = value; 2940 return 1; 2941 } 2942 if (Arch == Triple::aarch64) { 2943 if (Offset != 0 || Size != 4) 2944 return 0; 2945 if (info->O->getHeader().filetype != MachO::MH_OBJECT) { 2946 // TODO: 2947 // Search the external relocation entries of a fully linked image 2948 // (if any) for an entry that matches this segment offset. 2949 // uint64_t seg_offset = (Pc + Offset); 2950 return 0; 2951 } 2952 // In MH_OBJECT filetypes search the section's relocation entries (if any) 2953 // for an entry for this section offset. 2954 uint64_t sect_addr = info->S.getAddress(); 2955 uint64_t sect_offset = (Pc + Offset) - sect_addr; 2956 auto Reloc = 2957 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) { 2958 uint64_t RelocOffset = Reloc.getOffset(); 2959 return RelocOffset == sect_offset; 2960 }); 2961 2962 if (Reloc == info->S.relocations().end()) 2963 return 0; 2964 2965 DataRefImpl Rel = Reloc->getRawDataRefImpl(); 2966 MachO::any_relocation_info RE = info->O->getRelocation(Rel); 2967 uint32_t r_type = info->O->getAnyRelocationType(RE); 2968 if (r_type == MachO::ARM64_RELOC_ADDEND) { 2969 DataRefImpl RelNext = Rel; 2970 info->O->moveRelocationNext(RelNext); 2971 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext); 2972 if (value == 0) { 2973 value = info->O->getPlainRelocationSymbolNum(RENext); 2974 op_info->Value = value; 2975 } 2976 } 2977 // NOTE: Scattered relocations don't exist on arm64. 2978 if (!info->O->getPlainRelocationExternal(RE)) 2979 return 0; 2980 const char *name = 2981 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName()) 2982 .data(); 2983 op_info->AddSymbol.Present = 1; 2984 op_info->AddSymbol.Name = name; 2985 2986 switch (r_type) { 2987 case MachO::ARM64_RELOC_PAGE21: 2988 /* @page */ 2989 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE; 2990 break; 2991 case MachO::ARM64_RELOC_PAGEOFF12: 2992 /* @pageoff */ 2993 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF; 2994 break; 2995 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21: 2996 /* @gotpage */ 2997 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE; 2998 break; 2999 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12: 3000 /* @gotpageoff */ 3001 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF; 3002 break; 3003 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21: 3004 /* @tvlppage is not implemented in llvm-mc */ 3005 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP; 3006 break; 3007 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12: 3008 /* @tvlppageoff is not implemented in llvm-mc */ 3009 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF; 3010 break; 3011 default: 3012 case MachO::ARM64_RELOC_BRANCH26: 3013 op_info->VariantKind = LLVMDisassembler_VariantKind_None; 3014 break; 3015 } 3016 return 1; 3017 } 3018 return 0; 3019 } 3020 3021 // GuessCstringPointer is passed the address of what might be a pointer to a 3022 // literal string in a cstring section. If that address is in a cstring section 3023 // it returns a pointer to that string. Else it returns nullptr. 3024 static const char *GuessCstringPointer(uint64_t ReferenceValue, 3025 struct DisassembleInfo *info) { 3026 for (const auto &Load : info->O->load_commands()) { 3027 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3028 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3029 for (unsigned J = 0; J < Seg.nsects; ++J) { 3030 MachO::section_64 Sec = info->O->getSection64(Load, J); 3031 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3032 if (section_type == MachO::S_CSTRING_LITERALS && 3033 ReferenceValue >= Sec.addr && 3034 ReferenceValue < Sec.addr + Sec.size) { 3035 uint64_t sect_offset = ReferenceValue - Sec.addr; 3036 uint64_t object_offset = Sec.offset + sect_offset; 3037 StringRef MachOContents = info->O->getData(); 3038 uint64_t object_size = MachOContents.size(); 3039 const char *object_addr = (const char *)MachOContents.data(); 3040 if (object_offset < object_size) { 3041 const char *name = object_addr + object_offset; 3042 return name; 3043 } else { 3044 return nullptr; 3045 } 3046 } 3047 } 3048 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 3049 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); 3050 for (unsigned J = 0; J < Seg.nsects; ++J) { 3051 MachO::section Sec = info->O->getSection(Load, J); 3052 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3053 if (section_type == MachO::S_CSTRING_LITERALS && 3054 ReferenceValue >= Sec.addr && 3055 ReferenceValue < Sec.addr + Sec.size) { 3056 uint64_t sect_offset = ReferenceValue - Sec.addr; 3057 uint64_t object_offset = Sec.offset + sect_offset; 3058 StringRef MachOContents = info->O->getData(); 3059 uint64_t object_size = MachOContents.size(); 3060 const char *object_addr = (const char *)MachOContents.data(); 3061 if (object_offset < object_size) { 3062 const char *name = object_addr + object_offset; 3063 return name; 3064 } else { 3065 return nullptr; 3066 } 3067 } 3068 } 3069 } 3070 } 3071 return nullptr; 3072 } 3073 3074 // GuessIndirectSymbol returns the name of the indirect symbol for the 3075 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe 3076 // an address of a symbol stub or a lazy or non-lazy pointer to associate the 3077 // symbol name being referenced by the stub or pointer. 3078 static const char *GuessIndirectSymbol(uint64_t ReferenceValue, 3079 struct DisassembleInfo *info) { 3080 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand(); 3081 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand(); 3082 for (const auto &Load : info->O->load_commands()) { 3083 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3084 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3085 for (unsigned J = 0; J < Seg.nsects; ++J) { 3086 MachO::section_64 Sec = info->O->getSection64(Load, J); 3087 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3088 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 3089 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 3090 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 3091 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 3092 section_type == MachO::S_SYMBOL_STUBS) && 3093 ReferenceValue >= Sec.addr && 3094 ReferenceValue < Sec.addr + Sec.size) { 3095 uint32_t stride; 3096 if (section_type == MachO::S_SYMBOL_STUBS) 3097 stride = Sec.reserved2; 3098 else 3099 stride = 8; 3100 if (stride == 0) 3101 return nullptr; 3102 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; 3103 if (index < Dysymtab.nindirectsyms) { 3104 uint32_t indirect_symbol = 3105 info->O->getIndirectSymbolTableEntry(Dysymtab, index); 3106 if (indirect_symbol < Symtab.nsyms) { 3107 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); 3108 return unwrapOrError(Sym->getName(), info->O->getFileName()) 3109 .data(); 3110 } 3111 } 3112 } 3113 } 3114 } else if (Load.C.cmd == MachO::LC_SEGMENT) { 3115 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load); 3116 for (unsigned J = 0; J < Seg.nsects; ++J) { 3117 MachO::section Sec = info->O->getSection(Load, J); 3118 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE; 3119 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 3120 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 3121 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 3122 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS || 3123 section_type == MachO::S_SYMBOL_STUBS) && 3124 ReferenceValue >= Sec.addr && 3125 ReferenceValue < Sec.addr + Sec.size) { 3126 uint32_t stride; 3127 if (section_type == MachO::S_SYMBOL_STUBS) 3128 stride = Sec.reserved2; 3129 else 3130 stride = 4; 3131 if (stride == 0) 3132 return nullptr; 3133 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride; 3134 if (index < Dysymtab.nindirectsyms) { 3135 uint32_t indirect_symbol = 3136 info->O->getIndirectSymbolTableEntry(Dysymtab, index); 3137 if (indirect_symbol < Symtab.nsyms) { 3138 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol); 3139 return unwrapOrError(Sym->getName(), info->O->getFileName()) 3140 .data(); 3141 } 3142 } 3143 } 3144 } 3145 } 3146 } 3147 return nullptr; 3148 } 3149 3150 // method_reference() is called passing it the ReferenceName that might be 3151 // a reference it to an Objective-C method call. If so then it allocates and 3152 // assembles a method call string with the values last seen and saved in 3153 // the DisassembleInfo's class_name and selector_name fields. This is saved 3154 // into the method field of the info and any previous string is free'ed. 3155 // Then the class_name field in the info is set to nullptr. The method call 3156 // string is set into ReferenceName and ReferenceType is set to 3157 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call 3158 // then both ReferenceType and ReferenceName are left unchanged. 3159 static void method_reference(struct DisassembleInfo *info, 3160 uint64_t *ReferenceType, 3161 const char **ReferenceName) { 3162 unsigned int Arch = info->O->getArch(); 3163 if (*ReferenceName != nullptr) { 3164 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) { 3165 if (info->selector_name != nullptr) { 3166 if (info->class_name != nullptr) { 3167 info->method = std::make_unique<char[]>( 3168 5 + strlen(info->class_name) + strlen(info->selector_name)); 3169 char *method = info->method.get(); 3170 if (method != nullptr) { 3171 strcpy(method, "+["); 3172 strcat(method, info->class_name); 3173 strcat(method, " "); 3174 strcat(method, info->selector_name); 3175 strcat(method, "]"); 3176 *ReferenceName = method; 3177 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3178 } 3179 } else { 3180 info->method = 3181 std::make_unique<char[]>(9 + strlen(info->selector_name)); 3182 char *method = info->method.get(); 3183 if (method != nullptr) { 3184 if (Arch == Triple::x86_64) 3185 strcpy(method, "-[%rdi "); 3186 else if (Arch == Triple::aarch64) 3187 strcpy(method, "-[x0 "); 3188 else 3189 strcpy(method, "-[r? "); 3190 strcat(method, info->selector_name); 3191 strcat(method, "]"); 3192 *ReferenceName = method; 3193 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3194 } 3195 } 3196 info->class_name = nullptr; 3197 } 3198 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) { 3199 if (info->selector_name != nullptr) { 3200 info->method = 3201 std::make_unique<char[]>(17 + strlen(info->selector_name)); 3202 char *method = info->method.get(); 3203 if (method != nullptr) { 3204 if (Arch == Triple::x86_64) 3205 strcpy(method, "-[[%rdi super] "); 3206 else if (Arch == Triple::aarch64) 3207 strcpy(method, "-[[x0 super] "); 3208 else 3209 strcpy(method, "-[[r? super] "); 3210 strcat(method, info->selector_name); 3211 strcat(method, "]"); 3212 *ReferenceName = method; 3213 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message; 3214 } 3215 info->class_name = nullptr; 3216 } 3217 } 3218 } 3219 } 3220 3221 // GuessPointerPointer() is passed the address of what might be a pointer to 3222 // a reference to an Objective-C class, selector, message ref or cfstring. 3223 // If so the value of the pointer is returned and one of the booleans are set 3224 // to true. If not zero is returned and all the booleans are set to false. 3225 static uint64_t GuessPointerPointer(uint64_t ReferenceValue, 3226 struct DisassembleInfo *info, 3227 bool &classref, bool &selref, bool &msgref, 3228 bool &cfstring) { 3229 classref = false; 3230 selref = false; 3231 msgref = false; 3232 cfstring = false; 3233 for (const auto &Load : info->O->load_commands()) { 3234 if (Load.C.cmd == MachO::LC_SEGMENT_64) { 3235 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load); 3236 for (unsigned J = 0; J < Seg.nsects; ++J) { 3237 MachO::section_64 Sec = info->O->getSection64(Load, J); 3238 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 || 3239 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || 3240 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 || 3241 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 || 3242 strncmp(Sec.sectname, "__cfstring", 16) == 0) && 3243 ReferenceValue >= Sec.addr && 3244 ReferenceValue < Sec.addr + Sec.size) { 3245 uint64_t sect_offset = ReferenceValue - Sec.addr; 3246 uint64_t object_offset = Sec.offset + sect_offset; 3247 StringRef MachOContents = info->O->getData(); 3248 uint64_t object_size = MachOContents.size(); 3249 const char *object_addr = (const char *)MachOContents.data(); 3250 if (object_offset < object_size) { 3251 uint64_t pointer_value; 3252 memcpy(&pointer_value, object_addr + object_offset, 3253 sizeof(uint64_t)); 3254 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3255 sys::swapByteOrder(pointer_value); 3256 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0) 3257 selref = true; 3258 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 || 3259 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0) 3260 classref = true; 3261 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 && 3262 ReferenceValue + 8 < Sec.addr + Sec.size) { 3263 msgref = true; 3264 memcpy(&pointer_value, object_addr + object_offset + 8, 3265 sizeof(uint64_t)); 3266 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 3267 sys::swapByteOrder(pointer_value); 3268 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0) 3269 cfstring = true; 3270 return pointer_value; 3271 } else { 3272 return 0; 3273 } 3274 } 3275 } 3276 } 3277 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files. 3278 } 3279 return 0; 3280 } 3281 3282 // get_pointer_64 returns a pointer to the bytes in the object file at the 3283 // Address from a section in the Mach-O file. And indirectly returns the 3284 // offset into the section, number of bytes left in the section past the offset 3285 // and which section is was being referenced. If the Address is not in a 3286 // section nullptr is returned. 3287 static const char *get_pointer_64(uint64_t Address, uint32_t &offset, 3288 uint32_t &left, SectionRef &S, 3289 DisassembleInfo *info, 3290 bool objc_only = false) { 3291 offset = 0; 3292 left = 0; 3293 S = SectionRef(); 3294 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) { 3295 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress(); 3296 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize(); 3297 if (SectSize == 0) 3298 continue; 3299 if (objc_only) { 3300 StringRef SectName; 3301 Expected<StringRef> SecNameOrErr = 3302 ((*(info->Sections))[SectIdx]).getName(); 3303 if (SecNameOrErr) 3304 SectName = *SecNameOrErr; 3305 else 3306 consumeError(SecNameOrErr.takeError()); 3307 3308 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl(); 3309 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 3310 if (SegName != "__OBJC" && SectName != "__cstring") 3311 continue; 3312 } 3313 if (Address >= SectAddress && Address < SectAddress + SectSize) { 3314 S = (*(info->Sections))[SectIdx]; 3315 offset = Address - SectAddress; 3316 left = SectSize - offset; 3317 StringRef SectContents = unwrapOrError( 3318 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName()); 3319 return SectContents.data() + offset; 3320 } 3321 } 3322 return nullptr; 3323 } 3324 3325 static const char *get_pointer_32(uint32_t Address, uint32_t &offset, 3326 uint32_t &left, SectionRef &S, 3327 DisassembleInfo *info, 3328 bool objc_only = false) { 3329 return get_pointer_64(Address, offset, left, S, info, objc_only); 3330 } 3331 3332 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of 3333 // the symbol indirectly through n_value. Based on the relocation information 3334 // for the specified section offset in the specified section reference. 3335 // If no relocation information is found and a non-zero ReferenceValue for the 3336 // symbol is passed, look up that address in the info's AddrMap. 3337 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S, 3338 DisassembleInfo *info, uint64_t &n_value, 3339 uint64_t ReferenceValue = 0) { 3340 n_value = 0; 3341 if (!info->verbose) 3342 return nullptr; 3343 3344 // See if there is an external relocation entry at the sect_offset. 3345 bool reloc_found = false; 3346 DataRefImpl Rel; 3347 MachO::any_relocation_info RE; 3348 bool isExtern = false; 3349 SymbolRef Symbol; 3350 for (const RelocationRef &Reloc : S.relocations()) { 3351 uint64_t RelocOffset = Reloc.getOffset(); 3352 if (RelocOffset == sect_offset) { 3353 Rel = Reloc.getRawDataRefImpl(); 3354 RE = info->O->getRelocation(Rel); 3355 if (info->O->isRelocationScattered(RE)) 3356 continue; 3357 isExtern = info->O->getPlainRelocationExternal(RE); 3358 if (isExtern) { 3359 symbol_iterator RelocSym = Reloc.getSymbol(); 3360 Symbol = *RelocSym; 3361 } 3362 reloc_found = true; 3363 break; 3364 } 3365 } 3366 // If there is an external relocation entry for a symbol in this section 3367 // at this section_offset then use that symbol's value for the n_value 3368 // and return its name. 3369 const char *SymbolName = nullptr; 3370 if (reloc_found && isExtern) { 3371 n_value = cantFail(Symbol.getValue()); 3372 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName()); 3373 if (!Name.empty()) { 3374 SymbolName = Name.data(); 3375 return SymbolName; 3376 } 3377 } 3378 3379 // TODO: For fully linked images, look through the external relocation 3380 // entries off the dynamic symtab command. For these the r_offset is from the 3381 // start of the first writeable segment in the Mach-O file. So the offset 3382 // to this section from that segment is passed to this routine by the caller, 3383 // as the database_offset. Which is the difference of the section's starting 3384 // address and the first writable segment. 3385 // 3386 // NOTE: need add passing the database_offset to this routine. 3387 3388 // We did not find an external relocation entry so look up the ReferenceValue 3389 // as an address of a symbol and if found return that symbol's name. 3390 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); 3391 3392 return SymbolName; 3393 } 3394 3395 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S, 3396 DisassembleInfo *info, 3397 uint32_t ReferenceValue) { 3398 uint64_t n_value64; 3399 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue); 3400 } 3401 3402 namespace { 3403 3404 // These are structs in the Objective-C meta data and read to produce the 3405 // comments for disassembly. While these are part of the ABI they are no 3406 // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h 3407 // . 3408 3409 // The cfstring object in a 64-bit Mach-O file. 3410 struct cfstring64_t { 3411 uint64_t isa; // class64_t * (64-bit pointer) 3412 uint64_t flags; // flag bits 3413 uint64_t characters; // char * (64-bit pointer) 3414 uint64_t length; // number of non-NULL characters in above 3415 }; 3416 3417 // The class object in a 64-bit Mach-O file. 3418 struct class64_t { 3419 uint64_t isa; // class64_t * (64-bit pointer) 3420 uint64_t superclass; // class64_t * (64-bit pointer) 3421 uint64_t cache; // Cache (64-bit pointer) 3422 uint64_t vtable; // IMP * (64-bit pointer) 3423 uint64_t data; // class_ro64_t * (64-bit pointer) 3424 }; 3425 3426 struct class32_t { 3427 uint32_t isa; /* class32_t * (32-bit pointer) */ 3428 uint32_t superclass; /* class32_t * (32-bit pointer) */ 3429 uint32_t cache; /* Cache (32-bit pointer) */ 3430 uint32_t vtable; /* IMP * (32-bit pointer) */ 3431 uint32_t data; /* class_ro32_t * (32-bit pointer) */ 3432 }; 3433 3434 struct class_ro64_t { 3435 uint32_t flags; 3436 uint32_t instanceStart; 3437 uint32_t instanceSize; 3438 uint32_t reserved; 3439 uint64_t ivarLayout; // const uint8_t * (64-bit pointer) 3440 uint64_t name; // const char * (64-bit pointer) 3441 uint64_t baseMethods; // const method_list_t * (64-bit pointer) 3442 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer) 3443 uint64_t ivars; // const ivar_list_t * (64-bit pointer) 3444 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer) 3445 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer) 3446 }; 3447 3448 struct class_ro32_t { 3449 uint32_t flags; 3450 uint32_t instanceStart; 3451 uint32_t instanceSize; 3452 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */ 3453 uint32_t name; /* const char * (32-bit pointer) */ 3454 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */ 3455 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */ 3456 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */ 3457 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */ 3458 uint32_t baseProperties; /* const struct objc_property_list * 3459 (32-bit pointer) */ 3460 }; 3461 3462 /* Values for class_ro{64,32}_t->flags */ 3463 #define RO_META (1 << 0) 3464 #define RO_ROOT (1 << 1) 3465 #define RO_HAS_CXX_STRUCTORS (1 << 2) 3466 3467 struct method_list64_t { 3468 uint32_t entsize; 3469 uint32_t count; 3470 /* struct method64_t first; These structures follow inline */ 3471 }; 3472 3473 struct method_list32_t { 3474 uint32_t entsize; 3475 uint32_t count; 3476 /* struct method32_t first; These structures follow inline */ 3477 }; 3478 3479 struct method64_t { 3480 uint64_t name; /* SEL (64-bit pointer) */ 3481 uint64_t types; /* const char * (64-bit pointer) */ 3482 uint64_t imp; /* IMP (64-bit pointer) */ 3483 }; 3484 3485 struct method32_t { 3486 uint32_t name; /* SEL (32-bit pointer) */ 3487 uint32_t types; /* const char * (32-bit pointer) */ 3488 uint32_t imp; /* IMP (32-bit pointer) */ 3489 }; 3490 3491 struct protocol_list64_t { 3492 uint64_t count; /* uintptr_t (a 64-bit value) */ 3493 /* struct protocol64_t * list[0]; These pointers follow inline */ 3494 }; 3495 3496 struct protocol_list32_t { 3497 uint32_t count; /* uintptr_t (a 32-bit value) */ 3498 /* struct protocol32_t * list[0]; These pointers follow inline */ 3499 }; 3500 3501 struct protocol64_t { 3502 uint64_t isa; /* id * (64-bit pointer) */ 3503 uint64_t name; /* const char * (64-bit pointer) */ 3504 uint64_t protocols; /* struct protocol_list64_t * 3505 (64-bit pointer) */ 3506 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */ 3507 uint64_t classMethods; /* method_list_t * (64-bit pointer) */ 3508 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */ 3509 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */ 3510 uint64_t instanceProperties; /* struct objc_property_list * 3511 (64-bit pointer) */ 3512 }; 3513 3514 struct protocol32_t { 3515 uint32_t isa; /* id * (32-bit pointer) */ 3516 uint32_t name; /* const char * (32-bit pointer) */ 3517 uint32_t protocols; /* struct protocol_list_t * 3518 (32-bit pointer) */ 3519 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */ 3520 uint32_t classMethods; /* method_list_t * (32-bit pointer) */ 3521 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */ 3522 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */ 3523 uint32_t instanceProperties; /* struct objc_property_list * 3524 (32-bit pointer) */ 3525 }; 3526 3527 struct ivar_list64_t { 3528 uint32_t entsize; 3529 uint32_t count; 3530 /* struct ivar64_t first; These structures follow inline */ 3531 }; 3532 3533 struct ivar_list32_t { 3534 uint32_t entsize; 3535 uint32_t count; 3536 /* struct ivar32_t first; These structures follow inline */ 3537 }; 3538 3539 struct ivar64_t { 3540 uint64_t offset; /* uintptr_t * (64-bit pointer) */ 3541 uint64_t name; /* const char * (64-bit pointer) */ 3542 uint64_t type; /* const char * (64-bit pointer) */ 3543 uint32_t alignment; 3544 uint32_t size; 3545 }; 3546 3547 struct ivar32_t { 3548 uint32_t offset; /* uintptr_t * (32-bit pointer) */ 3549 uint32_t name; /* const char * (32-bit pointer) */ 3550 uint32_t type; /* const char * (32-bit pointer) */ 3551 uint32_t alignment; 3552 uint32_t size; 3553 }; 3554 3555 struct objc_property_list64 { 3556 uint32_t entsize; 3557 uint32_t count; 3558 /* struct objc_property64 first; These structures follow inline */ 3559 }; 3560 3561 struct objc_property_list32 { 3562 uint32_t entsize; 3563 uint32_t count; 3564 /* struct objc_property32 first; These structures follow inline */ 3565 }; 3566 3567 struct objc_property64 { 3568 uint64_t name; /* const char * (64-bit pointer) */ 3569 uint64_t attributes; /* const char * (64-bit pointer) */ 3570 }; 3571 3572 struct objc_property32 { 3573 uint32_t name; /* const char * (32-bit pointer) */ 3574 uint32_t attributes; /* const char * (32-bit pointer) */ 3575 }; 3576 3577 struct category64_t { 3578 uint64_t name; /* const char * (64-bit pointer) */ 3579 uint64_t cls; /* struct class_t * (64-bit pointer) */ 3580 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */ 3581 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */ 3582 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */ 3583 uint64_t instanceProperties; /* struct objc_property_list * 3584 (64-bit pointer) */ 3585 }; 3586 3587 struct category32_t { 3588 uint32_t name; /* const char * (32-bit pointer) */ 3589 uint32_t cls; /* struct class_t * (32-bit pointer) */ 3590 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */ 3591 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */ 3592 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */ 3593 uint32_t instanceProperties; /* struct objc_property_list * 3594 (32-bit pointer) */ 3595 }; 3596 3597 struct objc_image_info64 { 3598 uint32_t version; 3599 uint32_t flags; 3600 }; 3601 struct objc_image_info32 { 3602 uint32_t version; 3603 uint32_t flags; 3604 }; 3605 struct imageInfo_t { 3606 uint32_t version; 3607 uint32_t flags; 3608 }; 3609 /* masks for objc_image_info.flags */ 3610 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0) 3611 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1) 3612 #define OBJC_IMAGE_IS_SIMULATED (1 << 5) 3613 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6) 3614 3615 struct message_ref64 { 3616 uint64_t imp; /* IMP (64-bit pointer) */ 3617 uint64_t sel; /* SEL (64-bit pointer) */ 3618 }; 3619 3620 struct message_ref32 { 3621 uint32_t imp; /* IMP (32-bit pointer) */ 3622 uint32_t sel; /* SEL (32-bit pointer) */ 3623 }; 3624 3625 // Objective-C 1 (32-bit only) meta data structs. 3626 3627 struct objc_module_t { 3628 uint32_t version; 3629 uint32_t size; 3630 uint32_t name; /* char * (32-bit pointer) */ 3631 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */ 3632 }; 3633 3634 struct objc_symtab_t { 3635 uint32_t sel_ref_cnt; 3636 uint32_t refs; /* SEL * (32-bit pointer) */ 3637 uint16_t cls_def_cnt; 3638 uint16_t cat_def_cnt; 3639 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */ 3640 }; 3641 3642 struct objc_class_t { 3643 uint32_t isa; /* struct objc_class * (32-bit pointer) */ 3644 uint32_t super_class; /* struct objc_class * (32-bit pointer) */ 3645 uint32_t name; /* const char * (32-bit pointer) */ 3646 int32_t version; 3647 int32_t info; 3648 int32_t instance_size; 3649 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */ 3650 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */ 3651 uint32_t cache; /* struct objc_cache * (32-bit pointer) */ 3652 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */ 3653 }; 3654 3655 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask)) 3656 // class is not a metaclass 3657 #define CLS_CLASS 0x1 3658 // class is a metaclass 3659 #define CLS_META 0x2 3660 3661 struct objc_category_t { 3662 uint32_t category_name; /* char * (32-bit pointer) */ 3663 uint32_t class_name; /* char * (32-bit pointer) */ 3664 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */ 3665 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */ 3666 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */ 3667 }; 3668 3669 struct objc_ivar_t { 3670 uint32_t ivar_name; /* char * (32-bit pointer) */ 3671 uint32_t ivar_type; /* char * (32-bit pointer) */ 3672 int32_t ivar_offset; 3673 }; 3674 3675 struct objc_ivar_list_t { 3676 int32_t ivar_count; 3677 // struct objc_ivar_t ivar_list[1]; /* variable length structure */ 3678 }; 3679 3680 struct objc_method_list_t { 3681 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */ 3682 int32_t method_count; 3683 // struct objc_method_t method_list[1]; /* variable length structure */ 3684 }; 3685 3686 struct objc_method_t { 3687 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */ 3688 uint32_t method_types; /* char * (32-bit pointer) */ 3689 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...) 3690 (32-bit pointer) */ 3691 }; 3692 3693 struct objc_protocol_list_t { 3694 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */ 3695 int32_t count; 3696 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t * 3697 // (32-bit pointer) */ 3698 }; 3699 3700 struct objc_protocol_t { 3701 uint32_t isa; /* struct objc_class * (32-bit pointer) */ 3702 uint32_t protocol_name; /* char * (32-bit pointer) */ 3703 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */ 3704 uint32_t instance_methods; /* struct objc_method_description_list * 3705 (32-bit pointer) */ 3706 uint32_t class_methods; /* struct objc_method_description_list * 3707 (32-bit pointer) */ 3708 }; 3709 3710 struct objc_method_description_list_t { 3711 int32_t count; 3712 // struct objc_method_description_t list[1]; 3713 }; 3714 3715 struct objc_method_description_t { 3716 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */ 3717 uint32_t types; /* char * (32-bit pointer) */ 3718 }; 3719 3720 inline void swapStruct(struct cfstring64_t &cfs) { 3721 sys::swapByteOrder(cfs.isa); 3722 sys::swapByteOrder(cfs.flags); 3723 sys::swapByteOrder(cfs.characters); 3724 sys::swapByteOrder(cfs.length); 3725 } 3726 3727 inline void swapStruct(struct class64_t &c) { 3728 sys::swapByteOrder(c.isa); 3729 sys::swapByteOrder(c.superclass); 3730 sys::swapByteOrder(c.cache); 3731 sys::swapByteOrder(c.vtable); 3732 sys::swapByteOrder(c.data); 3733 } 3734 3735 inline void swapStruct(struct class32_t &c) { 3736 sys::swapByteOrder(c.isa); 3737 sys::swapByteOrder(c.superclass); 3738 sys::swapByteOrder(c.cache); 3739 sys::swapByteOrder(c.vtable); 3740 sys::swapByteOrder(c.data); 3741 } 3742 3743 inline void swapStruct(struct class_ro64_t &cro) { 3744 sys::swapByteOrder(cro.flags); 3745 sys::swapByteOrder(cro.instanceStart); 3746 sys::swapByteOrder(cro.instanceSize); 3747 sys::swapByteOrder(cro.reserved); 3748 sys::swapByteOrder(cro.ivarLayout); 3749 sys::swapByteOrder(cro.name); 3750 sys::swapByteOrder(cro.baseMethods); 3751 sys::swapByteOrder(cro.baseProtocols); 3752 sys::swapByteOrder(cro.ivars); 3753 sys::swapByteOrder(cro.weakIvarLayout); 3754 sys::swapByteOrder(cro.baseProperties); 3755 } 3756 3757 inline void swapStruct(struct class_ro32_t &cro) { 3758 sys::swapByteOrder(cro.flags); 3759 sys::swapByteOrder(cro.instanceStart); 3760 sys::swapByteOrder(cro.instanceSize); 3761 sys::swapByteOrder(cro.ivarLayout); 3762 sys::swapByteOrder(cro.name); 3763 sys::swapByteOrder(cro.baseMethods); 3764 sys::swapByteOrder(cro.baseProtocols); 3765 sys::swapByteOrder(cro.ivars); 3766 sys::swapByteOrder(cro.weakIvarLayout); 3767 sys::swapByteOrder(cro.baseProperties); 3768 } 3769 3770 inline void swapStruct(struct method_list64_t &ml) { 3771 sys::swapByteOrder(ml.entsize); 3772 sys::swapByteOrder(ml.count); 3773 } 3774 3775 inline void swapStruct(struct method_list32_t &ml) { 3776 sys::swapByteOrder(ml.entsize); 3777 sys::swapByteOrder(ml.count); 3778 } 3779 3780 inline void swapStruct(struct method64_t &m) { 3781 sys::swapByteOrder(m.name); 3782 sys::swapByteOrder(m.types); 3783 sys::swapByteOrder(m.imp); 3784 } 3785 3786 inline void swapStruct(struct method32_t &m) { 3787 sys::swapByteOrder(m.name); 3788 sys::swapByteOrder(m.types); 3789 sys::swapByteOrder(m.imp); 3790 } 3791 3792 inline void swapStruct(struct protocol_list64_t &pl) { 3793 sys::swapByteOrder(pl.count); 3794 } 3795 3796 inline void swapStruct(struct protocol_list32_t &pl) { 3797 sys::swapByteOrder(pl.count); 3798 } 3799 3800 inline void swapStruct(struct protocol64_t &p) { 3801 sys::swapByteOrder(p.isa); 3802 sys::swapByteOrder(p.name); 3803 sys::swapByteOrder(p.protocols); 3804 sys::swapByteOrder(p.instanceMethods); 3805 sys::swapByteOrder(p.classMethods); 3806 sys::swapByteOrder(p.optionalInstanceMethods); 3807 sys::swapByteOrder(p.optionalClassMethods); 3808 sys::swapByteOrder(p.instanceProperties); 3809 } 3810 3811 inline void swapStruct(struct protocol32_t &p) { 3812 sys::swapByteOrder(p.isa); 3813 sys::swapByteOrder(p.name); 3814 sys::swapByteOrder(p.protocols); 3815 sys::swapByteOrder(p.instanceMethods); 3816 sys::swapByteOrder(p.classMethods); 3817 sys::swapByteOrder(p.optionalInstanceMethods); 3818 sys::swapByteOrder(p.optionalClassMethods); 3819 sys::swapByteOrder(p.instanceProperties); 3820 } 3821 3822 inline void swapStruct(struct ivar_list64_t &il) { 3823 sys::swapByteOrder(il.entsize); 3824 sys::swapByteOrder(il.count); 3825 } 3826 3827 inline void swapStruct(struct ivar_list32_t &il) { 3828 sys::swapByteOrder(il.entsize); 3829 sys::swapByteOrder(il.count); 3830 } 3831 3832 inline void swapStruct(struct ivar64_t &i) { 3833 sys::swapByteOrder(i.offset); 3834 sys::swapByteOrder(i.name); 3835 sys::swapByteOrder(i.type); 3836 sys::swapByteOrder(i.alignment); 3837 sys::swapByteOrder(i.size); 3838 } 3839 3840 inline void swapStruct(struct ivar32_t &i) { 3841 sys::swapByteOrder(i.offset); 3842 sys::swapByteOrder(i.name); 3843 sys::swapByteOrder(i.type); 3844 sys::swapByteOrder(i.alignment); 3845 sys::swapByteOrder(i.size); 3846 } 3847 3848 inline void swapStruct(struct objc_property_list64 &pl) { 3849 sys::swapByteOrder(pl.entsize); 3850 sys::swapByteOrder(pl.count); 3851 } 3852 3853 inline void swapStruct(struct objc_property_list32 &pl) { 3854 sys::swapByteOrder(pl.entsize); 3855 sys::swapByteOrder(pl.count); 3856 } 3857 3858 inline void swapStruct(struct objc_property64 &op) { 3859 sys::swapByteOrder(op.name); 3860 sys::swapByteOrder(op.attributes); 3861 } 3862 3863 inline void swapStruct(struct objc_property32 &op) { 3864 sys::swapByteOrder(op.name); 3865 sys::swapByteOrder(op.attributes); 3866 } 3867 3868 inline void swapStruct(struct category64_t &c) { 3869 sys::swapByteOrder(c.name); 3870 sys::swapByteOrder(c.cls); 3871 sys::swapByteOrder(c.instanceMethods); 3872 sys::swapByteOrder(c.classMethods); 3873 sys::swapByteOrder(c.protocols); 3874 sys::swapByteOrder(c.instanceProperties); 3875 } 3876 3877 inline void swapStruct(struct category32_t &c) { 3878 sys::swapByteOrder(c.name); 3879 sys::swapByteOrder(c.cls); 3880 sys::swapByteOrder(c.instanceMethods); 3881 sys::swapByteOrder(c.classMethods); 3882 sys::swapByteOrder(c.protocols); 3883 sys::swapByteOrder(c.instanceProperties); 3884 } 3885 3886 inline void swapStruct(struct objc_image_info64 &o) { 3887 sys::swapByteOrder(o.version); 3888 sys::swapByteOrder(o.flags); 3889 } 3890 3891 inline void swapStruct(struct objc_image_info32 &o) { 3892 sys::swapByteOrder(o.version); 3893 sys::swapByteOrder(o.flags); 3894 } 3895 3896 inline void swapStruct(struct imageInfo_t &o) { 3897 sys::swapByteOrder(o.version); 3898 sys::swapByteOrder(o.flags); 3899 } 3900 3901 inline void swapStruct(struct message_ref64 &mr) { 3902 sys::swapByteOrder(mr.imp); 3903 sys::swapByteOrder(mr.sel); 3904 } 3905 3906 inline void swapStruct(struct message_ref32 &mr) { 3907 sys::swapByteOrder(mr.imp); 3908 sys::swapByteOrder(mr.sel); 3909 } 3910 3911 inline void swapStruct(struct objc_module_t &module) { 3912 sys::swapByteOrder(module.version); 3913 sys::swapByteOrder(module.size); 3914 sys::swapByteOrder(module.name); 3915 sys::swapByteOrder(module.symtab); 3916 } 3917 3918 inline void swapStruct(struct objc_symtab_t &symtab) { 3919 sys::swapByteOrder(symtab.sel_ref_cnt); 3920 sys::swapByteOrder(symtab.refs); 3921 sys::swapByteOrder(symtab.cls_def_cnt); 3922 sys::swapByteOrder(symtab.cat_def_cnt); 3923 } 3924 3925 inline void swapStruct(struct objc_class_t &objc_class) { 3926 sys::swapByteOrder(objc_class.isa); 3927 sys::swapByteOrder(objc_class.super_class); 3928 sys::swapByteOrder(objc_class.name); 3929 sys::swapByteOrder(objc_class.version); 3930 sys::swapByteOrder(objc_class.info); 3931 sys::swapByteOrder(objc_class.instance_size); 3932 sys::swapByteOrder(objc_class.ivars); 3933 sys::swapByteOrder(objc_class.methodLists); 3934 sys::swapByteOrder(objc_class.cache); 3935 sys::swapByteOrder(objc_class.protocols); 3936 } 3937 3938 inline void swapStruct(struct objc_category_t &objc_category) { 3939 sys::swapByteOrder(objc_category.category_name); 3940 sys::swapByteOrder(objc_category.class_name); 3941 sys::swapByteOrder(objc_category.instance_methods); 3942 sys::swapByteOrder(objc_category.class_methods); 3943 sys::swapByteOrder(objc_category.protocols); 3944 } 3945 3946 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) { 3947 sys::swapByteOrder(objc_ivar_list.ivar_count); 3948 } 3949 3950 inline void swapStruct(struct objc_ivar_t &objc_ivar) { 3951 sys::swapByteOrder(objc_ivar.ivar_name); 3952 sys::swapByteOrder(objc_ivar.ivar_type); 3953 sys::swapByteOrder(objc_ivar.ivar_offset); 3954 } 3955 3956 inline void swapStruct(struct objc_method_list_t &method_list) { 3957 sys::swapByteOrder(method_list.obsolete); 3958 sys::swapByteOrder(method_list.method_count); 3959 } 3960 3961 inline void swapStruct(struct objc_method_t &method) { 3962 sys::swapByteOrder(method.method_name); 3963 sys::swapByteOrder(method.method_types); 3964 sys::swapByteOrder(method.method_imp); 3965 } 3966 3967 inline void swapStruct(struct objc_protocol_list_t &protocol_list) { 3968 sys::swapByteOrder(protocol_list.next); 3969 sys::swapByteOrder(protocol_list.count); 3970 } 3971 3972 inline void swapStruct(struct objc_protocol_t &protocol) { 3973 sys::swapByteOrder(protocol.isa); 3974 sys::swapByteOrder(protocol.protocol_name); 3975 sys::swapByteOrder(protocol.protocol_list); 3976 sys::swapByteOrder(protocol.instance_methods); 3977 sys::swapByteOrder(protocol.class_methods); 3978 } 3979 3980 inline void swapStruct(struct objc_method_description_list_t &mdl) { 3981 sys::swapByteOrder(mdl.count); 3982 } 3983 3984 inline void swapStruct(struct objc_method_description_t &md) { 3985 sys::swapByteOrder(md.name); 3986 sys::swapByteOrder(md.types); 3987 } 3988 3989 } // namespace 3990 3991 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, 3992 struct DisassembleInfo *info); 3993 3994 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer 3995 // to an Objective-C class and returns the class name. It is also passed the 3996 // address of the pointer, so when the pointer is zero as it can be in an .o 3997 // file, that is used to look for an external relocation entry with a symbol 3998 // name. 3999 static const char *get_objc2_64bit_class_name(uint64_t pointer_value, 4000 uint64_t ReferenceValue, 4001 struct DisassembleInfo *info) { 4002 const char *r; 4003 uint32_t offset, left; 4004 SectionRef S; 4005 4006 // The pointer_value can be 0 in an object file and have a relocation 4007 // entry for the class symbol at the ReferenceValue (the address of the 4008 // pointer). 4009 if (pointer_value == 0) { 4010 r = get_pointer_64(ReferenceValue, offset, left, S, info); 4011 if (r == nullptr || left < sizeof(uint64_t)) 4012 return nullptr; 4013 uint64_t n_value; 4014 const char *symbol_name = get_symbol_64(offset, S, info, n_value); 4015 if (symbol_name == nullptr) 4016 return nullptr; 4017 const char *class_name = strrchr(symbol_name, '$'); 4018 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0') 4019 return class_name + 2; 4020 else 4021 return nullptr; 4022 } 4023 4024 // The case were the pointer_value is non-zero and points to a class defined 4025 // in this Mach-O file. 4026 r = get_pointer_64(pointer_value, offset, left, S, info); 4027 if (r == nullptr || left < sizeof(struct class64_t)) 4028 return nullptr; 4029 struct class64_t c; 4030 memcpy(&c, r, sizeof(struct class64_t)); 4031 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4032 swapStruct(c); 4033 if (c.data == 0) 4034 return nullptr; 4035 r = get_pointer_64(c.data, offset, left, S, info); 4036 if (r == nullptr || left < sizeof(struct class_ro64_t)) 4037 return nullptr; 4038 struct class_ro64_t cro; 4039 memcpy(&cro, r, sizeof(struct class_ro64_t)); 4040 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4041 swapStruct(cro); 4042 if (cro.name == 0) 4043 return nullptr; 4044 const char *name = get_pointer_64(cro.name, offset, left, S, info); 4045 return name; 4046 } 4047 4048 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a 4049 // pointer to a cfstring and returns its name or nullptr. 4050 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue, 4051 struct DisassembleInfo *info) { 4052 const char *r, *name; 4053 uint32_t offset, left; 4054 SectionRef S; 4055 struct cfstring64_t cfs; 4056 uint64_t cfs_characters; 4057 4058 r = get_pointer_64(ReferenceValue, offset, left, S, info); 4059 if (r == nullptr || left < sizeof(struct cfstring64_t)) 4060 return nullptr; 4061 memcpy(&cfs, r, sizeof(struct cfstring64_t)); 4062 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4063 swapStruct(cfs); 4064 if (cfs.characters == 0) { 4065 uint64_t n_value; 4066 const char *symbol_name = get_symbol_64( 4067 offset + offsetof(struct cfstring64_t, characters), S, info, n_value); 4068 if (symbol_name == nullptr) 4069 return nullptr; 4070 cfs_characters = n_value; 4071 } else 4072 cfs_characters = cfs.characters; 4073 name = get_pointer_64(cfs_characters, offset, left, S, info); 4074 4075 return name; 4076 } 4077 4078 // get_objc2_64bit_selref() is used for disassembly and is passed a the address 4079 // of a pointer to an Objective-C selector reference when the pointer value is 4080 // zero as in a .o file and is likely to have a external relocation entry with 4081 // who's symbol's n_value is the real pointer to the selector name. If that is 4082 // the case the real pointer to the selector name is returned else 0 is 4083 // returned 4084 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue, 4085 struct DisassembleInfo *info) { 4086 uint32_t offset, left; 4087 SectionRef S; 4088 4089 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info); 4090 if (r == nullptr || left < sizeof(uint64_t)) 4091 return 0; 4092 uint64_t n_value; 4093 const char *symbol_name = get_symbol_64(offset, S, info, n_value); 4094 if (symbol_name == nullptr) 4095 return 0; 4096 return n_value; 4097 } 4098 4099 static const SectionRef get_section(MachOObjectFile *O, const char *segname, 4100 const char *sectname) { 4101 for (const SectionRef &Section : O->sections()) { 4102 StringRef SectName; 4103 Expected<StringRef> SecNameOrErr = Section.getName(); 4104 if (SecNameOrErr) 4105 SectName = *SecNameOrErr; 4106 else 4107 consumeError(SecNameOrErr.takeError()); 4108 4109 DataRefImpl Ref = Section.getRawDataRefImpl(); 4110 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4111 if (SegName == segname && SectName == sectname) 4112 return Section; 4113 } 4114 return SectionRef(); 4115 } 4116 4117 static void 4118 walk_pointer_list_64(const char *listname, const SectionRef S, 4119 MachOObjectFile *O, struct DisassembleInfo *info, 4120 void (*func)(uint64_t, struct DisassembleInfo *info)) { 4121 if (S == SectionRef()) 4122 return; 4123 4124 StringRef SectName; 4125 Expected<StringRef> SecNameOrErr = S.getName(); 4126 if (SecNameOrErr) 4127 SectName = *SecNameOrErr; 4128 else 4129 consumeError(SecNameOrErr.takeError()); 4130 4131 DataRefImpl Ref = S.getRawDataRefImpl(); 4132 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4133 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 4134 4135 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName()); 4136 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 4137 4138 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) { 4139 uint32_t left = S.getSize() - i; 4140 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t); 4141 uint64_t p = 0; 4142 memcpy(&p, Contents + i, size); 4143 if (i + sizeof(uint64_t) > S.getSize()) 4144 outs() << listname << " list pointer extends past end of (" << SegName 4145 << "," << SectName << ") section\n"; 4146 outs() << format("%016" PRIx64, S.getAddress() + i) << " "; 4147 4148 if (O->isLittleEndian() != sys::IsLittleEndianHost) 4149 sys::swapByteOrder(p); 4150 4151 uint64_t n_value = 0; 4152 const char *name = get_symbol_64(i, S, info, n_value, p); 4153 if (name == nullptr) 4154 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info); 4155 4156 if (n_value != 0) { 4157 outs() << format("0x%" PRIx64, n_value); 4158 if (p != 0) 4159 outs() << " + " << format("0x%" PRIx64, p); 4160 } else 4161 outs() << format("0x%" PRIx64, p); 4162 if (name != nullptr) 4163 outs() << " " << name; 4164 outs() << "\n"; 4165 4166 p += n_value; 4167 if (func) 4168 func(p, info); 4169 } 4170 } 4171 4172 static void 4173 walk_pointer_list_32(const char *listname, const SectionRef S, 4174 MachOObjectFile *O, struct DisassembleInfo *info, 4175 void (*func)(uint32_t, struct DisassembleInfo *info)) { 4176 if (S == SectionRef()) 4177 return; 4178 4179 StringRef SectName = unwrapOrError(S.getName(), O->getFileName()); 4180 DataRefImpl Ref = S.getRawDataRefImpl(); 4181 StringRef SegName = O->getSectionFinalSegmentName(Ref); 4182 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 4183 4184 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName()); 4185 const char *Contents = reinterpret_cast<const char *>(BytesStr.data()); 4186 4187 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) { 4188 uint32_t left = S.getSize() - i; 4189 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t); 4190 uint32_t p = 0; 4191 memcpy(&p, Contents + i, size); 4192 if (i + sizeof(uint32_t) > S.getSize()) 4193 outs() << listname << " list pointer extends past end of (" << SegName 4194 << "," << SectName << ") section\n"; 4195 uint32_t Address = S.getAddress() + i; 4196 outs() << format("%08" PRIx32, Address) << " "; 4197 4198 if (O->isLittleEndian() != sys::IsLittleEndianHost) 4199 sys::swapByteOrder(p); 4200 outs() << format("0x%" PRIx32, p); 4201 4202 const char *name = get_symbol_32(i, S, info, p); 4203 if (name != nullptr) 4204 outs() << " " << name; 4205 outs() << "\n"; 4206 4207 if (func) 4208 func(p, info); 4209 } 4210 } 4211 4212 static void print_layout_map(const char *layout_map, uint32_t left) { 4213 if (layout_map == nullptr) 4214 return; 4215 outs() << " layout map: "; 4216 do { 4217 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " "; 4218 left--; 4219 layout_map++; 4220 } while (*layout_map != '\0' && left != 0); 4221 outs() << "\n"; 4222 } 4223 4224 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) { 4225 uint32_t offset, left; 4226 SectionRef S; 4227 const char *layout_map; 4228 4229 if (p == 0) 4230 return; 4231 layout_map = get_pointer_64(p, offset, left, S, info); 4232 print_layout_map(layout_map, left); 4233 } 4234 4235 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) { 4236 uint32_t offset, left; 4237 SectionRef S; 4238 const char *layout_map; 4239 4240 if (p == 0) 4241 return; 4242 layout_map = get_pointer_32(p, offset, left, S, info); 4243 print_layout_map(layout_map, left); 4244 } 4245 4246 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info, 4247 const char *indent) { 4248 struct method_list64_t ml; 4249 struct method64_t m; 4250 const char *r; 4251 uint32_t offset, xoffset, left, i; 4252 SectionRef S, xS; 4253 const char *name, *sym_name; 4254 uint64_t n_value; 4255 4256 r = get_pointer_64(p, offset, left, S, info); 4257 if (r == nullptr) 4258 return; 4259 memset(&ml, '\0', sizeof(struct method_list64_t)); 4260 if (left < sizeof(struct method_list64_t)) { 4261 memcpy(&ml, r, left); 4262 outs() << " (method_list_t entends past the end of the section)\n"; 4263 } else 4264 memcpy(&ml, r, sizeof(struct method_list64_t)); 4265 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4266 swapStruct(ml); 4267 outs() << indent << "\t\t entsize " << ml.entsize << "\n"; 4268 outs() << indent << "\t\t count " << ml.count << "\n"; 4269 4270 p += sizeof(struct method_list64_t); 4271 offset += sizeof(struct method_list64_t); 4272 for (i = 0; i < ml.count; i++) { 4273 r = get_pointer_64(p, offset, left, S, info); 4274 if (r == nullptr) 4275 return; 4276 memset(&m, '\0', sizeof(struct method64_t)); 4277 if (left < sizeof(struct method64_t)) { 4278 memcpy(&m, r, left); 4279 outs() << indent << " (method_t extends past the end of the section)\n"; 4280 } else 4281 memcpy(&m, r, sizeof(struct method64_t)); 4282 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4283 swapStruct(m); 4284 4285 outs() << indent << "\t\t name "; 4286 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S, 4287 info, n_value, m.name); 4288 if (n_value != 0) { 4289 if (info->verbose && sym_name != nullptr) 4290 outs() << sym_name; 4291 else 4292 outs() << format("0x%" PRIx64, n_value); 4293 if (m.name != 0) 4294 outs() << " + " << format("0x%" PRIx64, m.name); 4295 } else 4296 outs() << format("0x%" PRIx64, m.name); 4297 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info); 4298 if (name != nullptr) 4299 outs() << format(" %.*s", left, name); 4300 outs() << "\n"; 4301 4302 outs() << indent << "\t\t types "; 4303 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S, 4304 info, n_value, m.types); 4305 if (n_value != 0) { 4306 if (info->verbose && sym_name != nullptr) 4307 outs() << sym_name; 4308 else 4309 outs() << format("0x%" PRIx64, n_value); 4310 if (m.types != 0) 4311 outs() << " + " << format("0x%" PRIx64, m.types); 4312 } else 4313 outs() << format("0x%" PRIx64, m.types); 4314 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info); 4315 if (name != nullptr) 4316 outs() << format(" %.*s", left, name); 4317 outs() << "\n"; 4318 4319 outs() << indent << "\t\t imp "; 4320 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info, 4321 n_value, m.imp); 4322 if (info->verbose && name == nullptr) { 4323 if (n_value != 0) { 4324 outs() << format("0x%" PRIx64, n_value) << " "; 4325 if (m.imp != 0) 4326 outs() << "+ " << format("0x%" PRIx64, m.imp) << " "; 4327 } else 4328 outs() << format("0x%" PRIx64, m.imp) << " "; 4329 } 4330 if (name != nullptr) 4331 outs() << name; 4332 outs() << "\n"; 4333 4334 p += sizeof(struct method64_t); 4335 offset += sizeof(struct method64_t); 4336 } 4337 } 4338 4339 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info, 4340 const char *indent) { 4341 struct method_list32_t ml; 4342 struct method32_t m; 4343 const char *r, *name; 4344 uint32_t offset, xoffset, left, i; 4345 SectionRef S, xS; 4346 4347 r = get_pointer_32(p, offset, left, S, info); 4348 if (r == nullptr) 4349 return; 4350 memset(&ml, '\0', sizeof(struct method_list32_t)); 4351 if (left < sizeof(struct method_list32_t)) { 4352 memcpy(&ml, r, left); 4353 outs() << " (method_list_t entends past the end of the section)\n"; 4354 } else 4355 memcpy(&ml, r, sizeof(struct method_list32_t)); 4356 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4357 swapStruct(ml); 4358 outs() << indent << "\t\t entsize " << ml.entsize << "\n"; 4359 outs() << indent << "\t\t count " << ml.count << "\n"; 4360 4361 p += sizeof(struct method_list32_t); 4362 offset += sizeof(struct method_list32_t); 4363 for (i = 0; i < ml.count; i++) { 4364 r = get_pointer_32(p, offset, left, S, info); 4365 if (r == nullptr) 4366 return; 4367 memset(&m, '\0', sizeof(struct method32_t)); 4368 if (left < sizeof(struct method32_t)) { 4369 memcpy(&ml, r, left); 4370 outs() << indent << " (method_t entends past the end of the section)\n"; 4371 } else 4372 memcpy(&m, r, sizeof(struct method32_t)); 4373 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4374 swapStruct(m); 4375 4376 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name); 4377 name = get_pointer_32(m.name, xoffset, left, xS, info); 4378 if (name != nullptr) 4379 outs() << format(" %.*s", left, name); 4380 outs() << "\n"; 4381 4382 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types); 4383 name = get_pointer_32(m.types, xoffset, left, xS, info); 4384 if (name != nullptr) 4385 outs() << format(" %.*s", left, name); 4386 outs() << "\n"; 4387 4388 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp); 4389 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info, 4390 m.imp); 4391 if (name != nullptr) 4392 outs() << " " << name; 4393 outs() << "\n"; 4394 4395 p += sizeof(struct method32_t); 4396 offset += sizeof(struct method32_t); 4397 } 4398 } 4399 4400 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) { 4401 uint32_t offset, left, xleft; 4402 SectionRef S; 4403 struct objc_method_list_t method_list; 4404 struct objc_method_t method; 4405 const char *r, *methods, *name, *SymbolName; 4406 int32_t i; 4407 4408 r = get_pointer_32(p, offset, left, S, info, true); 4409 if (r == nullptr) 4410 return true; 4411 4412 outs() << "\n"; 4413 if (left > sizeof(struct objc_method_list_t)) { 4414 memcpy(&method_list, r, sizeof(struct objc_method_list_t)); 4415 } else { 4416 outs() << "\t\t objc_method_list extends past end of the section\n"; 4417 memset(&method_list, '\0', sizeof(struct objc_method_list_t)); 4418 memcpy(&method_list, r, left); 4419 } 4420 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4421 swapStruct(method_list); 4422 4423 outs() << "\t\t obsolete " 4424 << format("0x%08" PRIx32, method_list.obsolete) << "\n"; 4425 outs() << "\t\t method_count " << method_list.method_count << "\n"; 4426 4427 methods = r + sizeof(struct objc_method_list_t); 4428 for (i = 0; i < method_list.method_count; i++) { 4429 if ((i + 1) * sizeof(struct objc_method_t) > left) { 4430 outs() << "\t\t remaining method's extend past the of the section\n"; 4431 break; 4432 } 4433 memcpy(&method, methods + i * sizeof(struct objc_method_t), 4434 sizeof(struct objc_method_t)); 4435 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4436 swapStruct(method); 4437 4438 outs() << "\t\t method_name " 4439 << format("0x%08" PRIx32, method.method_name); 4440 if (info->verbose) { 4441 name = get_pointer_32(method.method_name, offset, xleft, S, info, true); 4442 if (name != nullptr) 4443 outs() << format(" %.*s", xleft, name); 4444 else 4445 outs() << " (not in an __OBJC section)"; 4446 } 4447 outs() << "\n"; 4448 4449 outs() << "\t\t method_types " 4450 << format("0x%08" PRIx32, method.method_types); 4451 if (info->verbose) { 4452 name = get_pointer_32(method.method_types, offset, xleft, S, info, true); 4453 if (name != nullptr) 4454 outs() << format(" %.*s", xleft, name); 4455 else 4456 outs() << " (not in an __OBJC section)"; 4457 } 4458 outs() << "\n"; 4459 4460 outs() << "\t\t method_imp " 4461 << format("0x%08" PRIx32, method.method_imp) << " "; 4462 if (info->verbose) { 4463 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap); 4464 if (SymbolName != nullptr) 4465 outs() << SymbolName; 4466 } 4467 outs() << "\n"; 4468 } 4469 return false; 4470 } 4471 4472 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) { 4473 struct protocol_list64_t pl; 4474 uint64_t q, n_value; 4475 struct protocol64_t pc; 4476 const char *r; 4477 uint32_t offset, xoffset, left, i; 4478 SectionRef S, xS; 4479 const char *name, *sym_name; 4480 4481 r = get_pointer_64(p, offset, left, S, info); 4482 if (r == nullptr) 4483 return; 4484 memset(&pl, '\0', sizeof(struct protocol_list64_t)); 4485 if (left < sizeof(struct protocol_list64_t)) { 4486 memcpy(&pl, r, left); 4487 outs() << " (protocol_list_t entends past the end of the section)\n"; 4488 } else 4489 memcpy(&pl, r, sizeof(struct protocol_list64_t)); 4490 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4491 swapStruct(pl); 4492 outs() << " count " << pl.count << "\n"; 4493 4494 p += sizeof(struct protocol_list64_t); 4495 offset += sizeof(struct protocol_list64_t); 4496 for (i = 0; i < pl.count; i++) { 4497 r = get_pointer_64(p, offset, left, S, info); 4498 if (r == nullptr) 4499 return; 4500 q = 0; 4501 if (left < sizeof(uint64_t)) { 4502 memcpy(&q, r, left); 4503 outs() << " (protocol_t * entends past the end of the section)\n"; 4504 } else 4505 memcpy(&q, r, sizeof(uint64_t)); 4506 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4507 sys::swapByteOrder(q); 4508 4509 outs() << "\t\t list[" << i << "] "; 4510 sym_name = get_symbol_64(offset, S, info, n_value, q); 4511 if (n_value != 0) { 4512 if (info->verbose && sym_name != nullptr) 4513 outs() << sym_name; 4514 else 4515 outs() << format("0x%" PRIx64, n_value); 4516 if (q != 0) 4517 outs() << " + " << format("0x%" PRIx64, q); 4518 } else 4519 outs() << format("0x%" PRIx64, q); 4520 outs() << " (struct protocol_t *)\n"; 4521 4522 r = get_pointer_64(q + n_value, offset, left, S, info); 4523 if (r == nullptr) 4524 return; 4525 memset(&pc, '\0', sizeof(struct protocol64_t)); 4526 if (left < sizeof(struct protocol64_t)) { 4527 memcpy(&pc, r, left); 4528 outs() << " (protocol_t entends past the end of the section)\n"; 4529 } else 4530 memcpy(&pc, r, sizeof(struct protocol64_t)); 4531 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4532 swapStruct(pc); 4533 4534 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n"; 4535 4536 outs() << "\t\t\t name "; 4537 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S, 4538 info, n_value, pc.name); 4539 if (n_value != 0) { 4540 if (info->verbose && sym_name != nullptr) 4541 outs() << sym_name; 4542 else 4543 outs() << format("0x%" PRIx64, n_value); 4544 if (pc.name != 0) 4545 outs() << " + " << format("0x%" PRIx64, pc.name); 4546 } else 4547 outs() << format("0x%" PRIx64, pc.name); 4548 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info); 4549 if (name != nullptr) 4550 outs() << format(" %.*s", left, name); 4551 outs() << "\n"; 4552 4553 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n"; 4554 4555 outs() << "\t\t instanceMethods "; 4556 sym_name = 4557 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods), 4558 S, info, n_value, pc.instanceMethods); 4559 if (n_value != 0) { 4560 if (info->verbose && sym_name != nullptr) 4561 outs() << sym_name; 4562 else 4563 outs() << format("0x%" PRIx64, n_value); 4564 if (pc.instanceMethods != 0) 4565 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods); 4566 } else 4567 outs() << format("0x%" PRIx64, pc.instanceMethods); 4568 outs() << " (struct method_list_t *)\n"; 4569 if (pc.instanceMethods + n_value != 0) 4570 print_method_list64_t(pc.instanceMethods + n_value, info, "\t"); 4571 4572 outs() << "\t\t classMethods "; 4573 sym_name = 4574 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S, 4575 info, n_value, pc.classMethods); 4576 if (n_value != 0) { 4577 if (info->verbose && sym_name != nullptr) 4578 outs() << sym_name; 4579 else 4580 outs() << format("0x%" PRIx64, n_value); 4581 if (pc.classMethods != 0) 4582 outs() << " + " << format("0x%" PRIx64, pc.classMethods); 4583 } else 4584 outs() << format("0x%" PRIx64, pc.classMethods); 4585 outs() << " (struct method_list_t *)\n"; 4586 if (pc.classMethods + n_value != 0) 4587 print_method_list64_t(pc.classMethods + n_value, info, "\t"); 4588 4589 outs() << "\t optionalInstanceMethods " 4590 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n"; 4591 outs() << "\t optionalClassMethods " 4592 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n"; 4593 outs() << "\t instanceProperties " 4594 << format("0x%" PRIx64, pc.instanceProperties) << "\n"; 4595 4596 p += sizeof(uint64_t); 4597 offset += sizeof(uint64_t); 4598 } 4599 } 4600 4601 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) { 4602 struct protocol_list32_t pl; 4603 uint32_t q; 4604 struct protocol32_t pc; 4605 const char *r; 4606 uint32_t offset, xoffset, left, i; 4607 SectionRef S, xS; 4608 const char *name; 4609 4610 r = get_pointer_32(p, offset, left, S, info); 4611 if (r == nullptr) 4612 return; 4613 memset(&pl, '\0', sizeof(struct protocol_list32_t)); 4614 if (left < sizeof(struct protocol_list32_t)) { 4615 memcpy(&pl, r, left); 4616 outs() << " (protocol_list_t entends past the end of the section)\n"; 4617 } else 4618 memcpy(&pl, r, sizeof(struct protocol_list32_t)); 4619 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4620 swapStruct(pl); 4621 outs() << " count " << pl.count << "\n"; 4622 4623 p += sizeof(struct protocol_list32_t); 4624 offset += sizeof(struct protocol_list32_t); 4625 for (i = 0; i < pl.count; i++) { 4626 r = get_pointer_32(p, offset, left, S, info); 4627 if (r == nullptr) 4628 return; 4629 q = 0; 4630 if (left < sizeof(uint32_t)) { 4631 memcpy(&q, r, left); 4632 outs() << " (protocol_t * entends past the end of the section)\n"; 4633 } else 4634 memcpy(&q, r, sizeof(uint32_t)); 4635 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4636 sys::swapByteOrder(q); 4637 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q) 4638 << " (struct protocol_t *)\n"; 4639 r = get_pointer_32(q, offset, left, S, info); 4640 if (r == nullptr) 4641 return; 4642 memset(&pc, '\0', sizeof(struct protocol32_t)); 4643 if (left < sizeof(struct protocol32_t)) { 4644 memcpy(&pc, r, left); 4645 outs() << " (protocol_t entends past the end of the section)\n"; 4646 } else 4647 memcpy(&pc, r, sizeof(struct protocol32_t)); 4648 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4649 swapStruct(pc); 4650 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n"; 4651 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name); 4652 name = get_pointer_32(pc.name, xoffset, left, xS, info); 4653 if (name != nullptr) 4654 outs() << format(" %.*s", left, name); 4655 outs() << "\n"; 4656 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n"; 4657 outs() << "\t\t instanceMethods " 4658 << format("0x%" PRIx32, pc.instanceMethods) 4659 << " (struct method_list_t *)\n"; 4660 if (pc.instanceMethods != 0) 4661 print_method_list32_t(pc.instanceMethods, info, "\t"); 4662 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods) 4663 << " (struct method_list_t *)\n"; 4664 if (pc.classMethods != 0) 4665 print_method_list32_t(pc.classMethods, info, "\t"); 4666 outs() << "\t optionalInstanceMethods " 4667 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n"; 4668 outs() << "\t optionalClassMethods " 4669 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n"; 4670 outs() << "\t instanceProperties " 4671 << format("0x%" PRIx32, pc.instanceProperties) << "\n"; 4672 p += sizeof(uint32_t); 4673 offset += sizeof(uint32_t); 4674 } 4675 } 4676 4677 static void print_indent(uint32_t indent) { 4678 for (uint32_t i = 0; i < indent;) { 4679 if (indent - i >= 8) { 4680 outs() << "\t"; 4681 i += 8; 4682 } else { 4683 for (uint32_t j = i; j < indent; j++) 4684 outs() << " "; 4685 return; 4686 } 4687 } 4688 } 4689 4690 static bool print_method_description_list(uint32_t p, uint32_t indent, 4691 struct DisassembleInfo *info) { 4692 uint32_t offset, left, xleft; 4693 SectionRef S; 4694 struct objc_method_description_list_t mdl; 4695 struct objc_method_description_t md; 4696 const char *r, *list, *name; 4697 int32_t i; 4698 4699 r = get_pointer_32(p, offset, left, S, info, true); 4700 if (r == nullptr) 4701 return true; 4702 4703 outs() << "\n"; 4704 if (left > sizeof(struct objc_method_description_list_t)) { 4705 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t)); 4706 } else { 4707 print_indent(indent); 4708 outs() << " objc_method_description_list extends past end of the section\n"; 4709 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t)); 4710 memcpy(&mdl, r, left); 4711 } 4712 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4713 swapStruct(mdl); 4714 4715 print_indent(indent); 4716 outs() << " count " << mdl.count << "\n"; 4717 4718 list = r + sizeof(struct objc_method_description_list_t); 4719 for (i = 0; i < mdl.count; i++) { 4720 if ((i + 1) * sizeof(struct objc_method_description_t) > left) { 4721 print_indent(indent); 4722 outs() << " remaining list entries extend past the of the section\n"; 4723 break; 4724 } 4725 print_indent(indent); 4726 outs() << " list[" << i << "]\n"; 4727 memcpy(&md, list + i * sizeof(struct objc_method_description_t), 4728 sizeof(struct objc_method_description_t)); 4729 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4730 swapStruct(md); 4731 4732 print_indent(indent); 4733 outs() << " name " << format("0x%08" PRIx32, md.name); 4734 if (info->verbose) { 4735 name = get_pointer_32(md.name, offset, xleft, S, info, true); 4736 if (name != nullptr) 4737 outs() << format(" %.*s", xleft, name); 4738 else 4739 outs() << " (not in an __OBJC section)"; 4740 } 4741 outs() << "\n"; 4742 4743 print_indent(indent); 4744 outs() << " types " << format("0x%08" PRIx32, md.types); 4745 if (info->verbose) { 4746 name = get_pointer_32(md.types, offset, xleft, S, info, true); 4747 if (name != nullptr) 4748 outs() << format(" %.*s", xleft, name); 4749 else 4750 outs() << " (not in an __OBJC section)"; 4751 } 4752 outs() << "\n"; 4753 } 4754 return false; 4755 } 4756 4757 static bool print_protocol_list(uint32_t p, uint32_t indent, 4758 struct DisassembleInfo *info); 4759 4760 static bool print_protocol(uint32_t p, uint32_t indent, 4761 struct DisassembleInfo *info) { 4762 uint32_t offset, left; 4763 SectionRef S; 4764 struct objc_protocol_t protocol; 4765 const char *r, *name; 4766 4767 r = get_pointer_32(p, offset, left, S, info, true); 4768 if (r == nullptr) 4769 return true; 4770 4771 outs() << "\n"; 4772 if (left >= sizeof(struct objc_protocol_t)) { 4773 memcpy(&protocol, r, sizeof(struct objc_protocol_t)); 4774 } else { 4775 print_indent(indent); 4776 outs() << " Protocol extends past end of the section\n"; 4777 memset(&protocol, '\0', sizeof(struct objc_protocol_t)); 4778 memcpy(&protocol, r, left); 4779 } 4780 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4781 swapStruct(protocol); 4782 4783 print_indent(indent); 4784 outs() << " isa " << format("0x%08" PRIx32, protocol.isa) 4785 << "\n"; 4786 4787 print_indent(indent); 4788 outs() << " protocol_name " 4789 << format("0x%08" PRIx32, protocol.protocol_name); 4790 if (info->verbose) { 4791 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true); 4792 if (name != nullptr) 4793 outs() << format(" %.*s", left, name); 4794 else 4795 outs() << " (not in an __OBJC section)"; 4796 } 4797 outs() << "\n"; 4798 4799 print_indent(indent); 4800 outs() << " protocol_list " 4801 << format("0x%08" PRIx32, protocol.protocol_list); 4802 if (print_protocol_list(protocol.protocol_list, indent + 4, info)) 4803 outs() << " (not in an __OBJC section)\n"; 4804 4805 print_indent(indent); 4806 outs() << " instance_methods " 4807 << format("0x%08" PRIx32, protocol.instance_methods); 4808 if (print_method_description_list(protocol.instance_methods, indent, info)) 4809 outs() << " (not in an __OBJC section)\n"; 4810 4811 print_indent(indent); 4812 outs() << " class_methods " 4813 << format("0x%08" PRIx32, protocol.class_methods); 4814 if (print_method_description_list(protocol.class_methods, indent, info)) 4815 outs() << " (not in an __OBJC section)\n"; 4816 4817 return false; 4818 } 4819 4820 static bool print_protocol_list(uint32_t p, uint32_t indent, 4821 struct DisassembleInfo *info) { 4822 uint32_t offset, left, l; 4823 SectionRef S; 4824 struct objc_protocol_list_t protocol_list; 4825 const char *r, *list; 4826 int32_t i; 4827 4828 r = get_pointer_32(p, offset, left, S, info, true); 4829 if (r == nullptr) 4830 return true; 4831 4832 outs() << "\n"; 4833 if (left > sizeof(struct objc_protocol_list_t)) { 4834 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t)); 4835 } else { 4836 outs() << "\t\t objc_protocol_list_t extends past end of the section\n"; 4837 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t)); 4838 memcpy(&protocol_list, r, left); 4839 } 4840 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4841 swapStruct(protocol_list); 4842 4843 print_indent(indent); 4844 outs() << " next " << format("0x%08" PRIx32, protocol_list.next) 4845 << "\n"; 4846 print_indent(indent); 4847 outs() << " count " << protocol_list.count << "\n"; 4848 4849 list = r + sizeof(struct objc_protocol_list_t); 4850 for (i = 0; i < protocol_list.count; i++) { 4851 if ((i + 1) * sizeof(uint32_t) > left) { 4852 outs() << "\t\t remaining list entries extend past the of the section\n"; 4853 break; 4854 } 4855 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t)); 4856 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4857 sys::swapByteOrder(l); 4858 4859 print_indent(indent); 4860 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l); 4861 if (print_protocol(l, indent, info)) 4862 outs() << "(not in an __OBJC section)\n"; 4863 } 4864 return false; 4865 } 4866 4867 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) { 4868 struct ivar_list64_t il; 4869 struct ivar64_t i; 4870 const char *r; 4871 uint32_t offset, xoffset, left, j; 4872 SectionRef S, xS; 4873 const char *name, *sym_name, *ivar_offset_p; 4874 uint64_t ivar_offset, n_value; 4875 4876 r = get_pointer_64(p, offset, left, S, info); 4877 if (r == nullptr) 4878 return; 4879 memset(&il, '\0', sizeof(struct ivar_list64_t)); 4880 if (left < sizeof(struct ivar_list64_t)) { 4881 memcpy(&il, r, left); 4882 outs() << " (ivar_list_t entends past the end of the section)\n"; 4883 } else 4884 memcpy(&il, r, sizeof(struct ivar_list64_t)); 4885 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4886 swapStruct(il); 4887 outs() << " entsize " << il.entsize << "\n"; 4888 outs() << " count " << il.count << "\n"; 4889 4890 p += sizeof(struct ivar_list64_t); 4891 offset += sizeof(struct ivar_list64_t); 4892 for (j = 0; j < il.count; j++) { 4893 r = get_pointer_64(p, offset, left, S, info); 4894 if (r == nullptr) 4895 return; 4896 memset(&i, '\0', sizeof(struct ivar64_t)); 4897 if (left < sizeof(struct ivar64_t)) { 4898 memcpy(&i, r, left); 4899 outs() << " (ivar_t entends past the end of the section)\n"; 4900 } else 4901 memcpy(&i, r, sizeof(struct ivar64_t)); 4902 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4903 swapStruct(i); 4904 4905 outs() << "\t\t\t offset "; 4906 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S, 4907 info, n_value, i.offset); 4908 if (n_value != 0) { 4909 if (info->verbose && sym_name != nullptr) 4910 outs() << sym_name; 4911 else 4912 outs() << format("0x%" PRIx64, n_value); 4913 if (i.offset != 0) 4914 outs() << " + " << format("0x%" PRIx64, i.offset); 4915 } else 4916 outs() << format("0x%" PRIx64, i.offset); 4917 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info); 4918 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { 4919 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); 4920 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4921 sys::swapByteOrder(ivar_offset); 4922 outs() << " " << ivar_offset << "\n"; 4923 } else 4924 outs() << "\n"; 4925 4926 outs() << "\t\t\t name "; 4927 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info, 4928 n_value, i.name); 4929 if (n_value != 0) { 4930 if (info->verbose && sym_name != nullptr) 4931 outs() << sym_name; 4932 else 4933 outs() << format("0x%" PRIx64, n_value); 4934 if (i.name != 0) 4935 outs() << " + " << format("0x%" PRIx64, i.name); 4936 } else 4937 outs() << format("0x%" PRIx64, i.name); 4938 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info); 4939 if (name != nullptr) 4940 outs() << format(" %.*s", left, name); 4941 outs() << "\n"; 4942 4943 outs() << "\t\t\t type "; 4944 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info, 4945 n_value, i.name); 4946 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info); 4947 if (n_value != 0) { 4948 if (info->verbose && sym_name != nullptr) 4949 outs() << sym_name; 4950 else 4951 outs() << format("0x%" PRIx64, n_value); 4952 if (i.type != 0) 4953 outs() << " + " << format("0x%" PRIx64, i.type); 4954 } else 4955 outs() << format("0x%" PRIx64, i.type); 4956 if (name != nullptr) 4957 outs() << format(" %.*s", left, name); 4958 outs() << "\n"; 4959 4960 outs() << "\t\t\talignment " << i.alignment << "\n"; 4961 outs() << "\t\t\t size " << i.size << "\n"; 4962 4963 p += sizeof(struct ivar64_t); 4964 offset += sizeof(struct ivar64_t); 4965 } 4966 } 4967 4968 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) { 4969 struct ivar_list32_t il; 4970 struct ivar32_t i; 4971 const char *r; 4972 uint32_t offset, xoffset, left, j; 4973 SectionRef S, xS; 4974 const char *name, *ivar_offset_p; 4975 uint32_t ivar_offset; 4976 4977 r = get_pointer_32(p, offset, left, S, info); 4978 if (r == nullptr) 4979 return; 4980 memset(&il, '\0', sizeof(struct ivar_list32_t)); 4981 if (left < sizeof(struct ivar_list32_t)) { 4982 memcpy(&il, r, left); 4983 outs() << " (ivar_list_t entends past the end of the section)\n"; 4984 } else 4985 memcpy(&il, r, sizeof(struct ivar_list32_t)); 4986 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 4987 swapStruct(il); 4988 outs() << " entsize " << il.entsize << "\n"; 4989 outs() << " count " << il.count << "\n"; 4990 4991 p += sizeof(struct ivar_list32_t); 4992 offset += sizeof(struct ivar_list32_t); 4993 for (j = 0; j < il.count; j++) { 4994 r = get_pointer_32(p, offset, left, S, info); 4995 if (r == nullptr) 4996 return; 4997 memset(&i, '\0', sizeof(struct ivar32_t)); 4998 if (left < sizeof(struct ivar32_t)) { 4999 memcpy(&i, r, left); 5000 outs() << " (ivar_t entends past the end of the section)\n"; 5001 } else 5002 memcpy(&i, r, sizeof(struct ivar32_t)); 5003 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5004 swapStruct(i); 5005 5006 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset); 5007 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info); 5008 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) { 5009 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset)); 5010 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5011 sys::swapByteOrder(ivar_offset); 5012 outs() << " " << ivar_offset << "\n"; 5013 } else 5014 outs() << "\n"; 5015 5016 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name); 5017 name = get_pointer_32(i.name, xoffset, left, xS, info); 5018 if (name != nullptr) 5019 outs() << format(" %.*s", left, name); 5020 outs() << "\n"; 5021 5022 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type); 5023 name = get_pointer_32(i.type, xoffset, left, xS, info); 5024 if (name != nullptr) 5025 outs() << format(" %.*s", left, name); 5026 outs() << "\n"; 5027 5028 outs() << "\t\t\talignment " << i.alignment << "\n"; 5029 outs() << "\t\t\t size " << i.size << "\n"; 5030 5031 p += sizeof(struct ivar32_t); 5032 offset += sizeof(struct ivar32_t); 5033 } 5034 } 5035 5036 static void print_objc_property_list64(uint64_t p, 5037 struct DisassembleInfo *info) { 5038 struct objc_property_list64 opl; 5039 struct objc_property64 op; 5040 const char *r; 5041 uint32_t offset, xoffset, left, j; 5042 SectionRef S, xS; 5043 const char *name, *sym_name; 5044 uint64_t n_value; 5045 5046 r = get_pointer_64(p, offset, left, S, info); 5047 if (r == nullptr) 5048 return; 5049 memset(&opl, '\0', sizeof(struct objc_property_list64)); 5050 if (left < sizeof(struct objc_property_list64)) { 5051 memcpy(&opl, r, left); 5052 outs() << " (objc_property_list entends past the end of the section)\n"; 5053 } else 5054 memcpy(&opl, r, sizeof(struct objc_property_list64)); 5055 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5056 swapStruct(opl); 5057 outs() << " entsize " << opl.entsize << "\n"; 5058 outs() << " count " << opl.count << "\n"; 5059 5060 p += sizeof(struct objc_property_list64); 5061 offset += sizeof(struct objc_property_list64); 5062 for (j = 0; j < opl.count; j++) { 5063 r = get_pointer_64(p, offset, left, S, info); 5064 if (r == nullptr) 5065 return; 5066 memset(&op, '\0', sizeof(struct objc_property64)); 5067 if (left < sizeof(struct objc_property64)) { 5068 memcpy(&op, r, left); 5069 outs() << " (objc_property entends past the end of the section)\n"; 5070 } else 5071 memcpy(&op, r, sizeof(struct objc_property64)); 5072 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5073 swapStruct(op); 5074 5075 outs() << "\t\t\t name "; 5076 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S, 5077 info, n_value, op.name); 5078 if (n_value != 0) { 5079 if (info->verbose && sym_name != nullptr) 5080 outs() << sym_name; 5081 else 5082 outs() << format("0x%" PRIx64, n_value); 5083 if (op.name != 0) 5084 outs() << " + " << format("0x%" PRIx64, op.name); 5085 } else 5086 outs() << format("0x%" PRIx64, op.name); 5087 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info); 5088 if (name != nullptr) 5089 outs() << format(" %.*s", left, name); 5090 outs() << "\n"; 5091 5092 outs() << "\t\t\tattributes "; 5093 sym_name = 5094 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S, 5095 info, n_value, op.attributes); 5096 if (n_value != 0) { 5097 if (info->verbose && sym_name != nullptr) 5098 outs() << sym_name; 5099 else 5100 outs() << format("0x%" PRIx64, n_value); 5101 if (op.attributes != 0) 5102 outs() << " + " << format("0x%" PRIx64, op.attributes); 5103 } else 5104 outs() << format("0x%" PRIx64, op.attributes); 5105 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info); 5106 if (name != nullptr) 5107 outs() << format(" %.*s", left, name); 5108 outs() << "\n"; 5109 5110 p += sizeof(struct objc_property64); 5111 offset += sizeof(struct objc_property64); 5112 } 5113 } 5114 5115 static void print_objc_property_list32(uint32_t p, 5116 struct DisassembleInfo *info) { 5117 struct objc_property_list32 opl; 5118 struct objc_property32 op; 5119 const char *r; 5120 uint32_t offset, xoffset, left, j; 5121 SectionRef S, xS; 5122 const char *name; 5123 5124 r = get_pointer_32(p, offset, left, S, info); 5125 if (r == nullptr) 5126 return; 5127 memset(&opl, '\0', sizeof(struct objc_property_list32)); 5128 if (left < sizeof(struct objc_property_list32)) { 5129 memcpy(&opl, r, left); 5130 outs() << " (objc_property_list entends past the end of the section)\n"; 5131 } else 5132 memcpy(&opl, r, sizeof(struct objc_property_list32)); 5133 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5134 swapStruct(opl); 5135 outs() << " entsize " << opl.entsize << "\n"; 5136 outs() << " count " << opl.count << "\n"; 5137 5138 p += sizeof(struct objc_property_list32); 5139 offset += sizeof(struct objc_property_list32); 5140 for (j = 0; j < opl.count; j++) { 5141 r = get_pointer_32(p, offset, left, S, info); 5142 if (r == nullptr) 5143 return; 5144 memset(&op, '\0', sizeof(struct objc_property32)); 5145 if (left < sizeof(struct objc_property32)) { 5146 memcpy(&op, r, left); 5147 outs() << " (objc_property entends past the end of the section)\n"; 5148 } else 5149 memcpy(&op, r, sizeof(struct objc_property32)); 5150 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5151 swapStruct(op); 5152 5153 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name); 5154 name = get_pointer_32(op.name, xoffset, left, xS, info); 5155 if (name != nullptr) 5156 outs() << format(" %.*s", left, name); 5157 outs() << "\n"; 5158 5159 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes); 5160 name = get_pointer_32(op.attributes, xoffset, left, xS, info); 5161 if (name != nullptr) 5162 outs() << format(" %.*s", left, name); 5163 outs() << "\n"; 5164 5165 p += sizeof(struct objc_property32); 5166 offset += sizeof(struct objc_property32); 5167 } 5168 } 5169 5170 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info, 5171 bool &is_meta_class) { 5172 struct class_ro64_t cro; 5173 const char *r; 5174 uint32_t offset, xoffset, left; 5175 SectionRef S, xS; 5176 const char *name, *sym_name; 5177 uint64_t n_value; 5178 5179 r = get_pointer_64(p, offset, left, S, info); 5180 if (r == nullptr || left < sizeof(struct class_ro64_t)) 5181 return false; 5182 memcpy(&cro, r, sizeof(struct class_ro64_t)); 5183 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5184 swapStruct(cro); 5185 outs() << " flags " << format("0x%" PRIx32, cro.flags); 5186 if (cro.flags & RO_META) 5187 outs() << " RO_META"; 5188 if (cro.flags & RO_ROOT) 5189 outs() << " RO_ROOT"; 5190 if (cro.flags & RO_HAS_CXX_STRUCTORS) 5191 outs() << " RO_HAS_CXX_STRUCTORS"; 5192 outs() << "\n"; 5193 outs() << " instanceStart " << cro.instanceStart << "\n"; 5194 outs() << " instanceSize " << cro.instanceSize << "\n"; 5195 outs() << " reserved " << format("0x%" PRIx32, cro.reserved) 5196 << "\n"; 5197 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout) 5198 << "\n"; 5199 print_layout_map64(cro.ivarLayout, info); 5200 5201 outs() << " name "; 5202 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S, 5203 info, n_value, cro.name); 5204 if (n_value != 0) { 5205 if (info->verbose && sym_name != nullptr) 5206 outs() << sym_name; 5207 else 5208 outs() << format("0x%" PRIx64, n_value); 5209 if (cro.name != 0) 5210 outs() << " + " << format("0x%" PRIx64, cro.name); 5211 } else 5212 outs() << format("0x%" PRIx64, cro.name); 5213 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info); 5214 if (name != nullptr) 5215 outs() << format(" %.*s", left, name); 5216 outs() << "\n"; 5217 5218 outs() << " baseMethods "; 5219 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods), 5220 S, info, n_value, cro.baseMethods); 5221 if (n_value != 0) { 5222 if (info->verbose && sym_name != nullptr) 5223 outs() << sym_name; 5224 else 5225 outs() << format("0x%" PRIx64, n_value); 5226 if (cro.baseMethods != 0) 5227 outs() << " + " << format("0x%" PRIx64, cro.baseMethods); 5228 } else 5229 outs() << format("0x%" PRIx64, cro.baseMethods); 5230 outs() << " (struct method_list_t *)\n"; 5231 if (cro.baseMethods + n_value != 0) 5232 print_method_list64_t(cro.baseMethods + n_value, info, ""); 5233 5234 outs() << " baseProtocols "; 5235 sym_name = 5236 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S, 5237 info, n_value, cro.baseProtocols); 5238 if (n_value != 0) { 5239 if (info->verbose && sym_name != nullptr) 5240 outs() << sym_name; 5241 else 5242 outs() << format("0x%" PRIx64, n_value); 5243 if (cro.baseProtocols != 0) 5244 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols); 5245 } else 5246 outs() << format("0x%" PRIx64, cro.baseProtocols); 5247 outs() << "\n"; 5248 if (cro.baseProtocols + n_value != 0) 5249 print_protocol_list64_t(cro.baseProtocols + n_value, info); 5250 5251 outs() << " ivars "; 5252 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S, 5253 info, n_value, cro.ivars); 5254 if (n_value != 0) { 5255 if (info->verbose && sym_name != nullptr) 5256 outs() << sym_name; 5257 else 5258 outs() << format("0x%" PRIx64, n_value); 5259 if (cro.ivars != 0) 5260 outs() << " + " << format("0x%" PRIx64, cro.ivars); 5261 } else 5262 outs() << format("0x%" PRIx64, cro.ivars); 5263 outs() << "\n"; 5264 if (cro.ivars + n_value != 0) 5265 print_ivar_list64_t(cro.ivars + n_value, info); 5266 5267 outs() << " weakIvarLayout "; 5268 sym_name = 5269 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S, 5270 info, n_value, cro.weakIvarLayout); 5271 if (n_value != 0) { 5272 if (info->verbose && sym_name != nullptr) 5273 outs() << sym_name; 5274 else 5275 outs() << format("0x%" PRIx64, n_value); 5276 if (cro.weakIvarLayout != 0) 5277 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout); 5278 } else 5279 outs() << format("0x%" PRIx64, cro.weakIvarLayout); 5280 outs() << "\n"; 5281 print_layout_map64(cro.weakIvarLayout + n_value, info); 5282 5283 outs() << " baseProperties "; 5284 sym_name = 5285 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S, 5286 info, n_value, cro.baseProperties); 5287 if (n_value != 0) { 5288 if (info->verbose && sym_name != nullptr) 5289 outs() << sym_name; 5290 else 5291 outs() << format("0x%" PRIx64, n_value); 5292 if (cro.baseProperties != 0) 5293 outs() << " + " << format("0x%" PRIx64, cro.baseProperties); 5294 } else 5295 outs() << format("0x%" PRIx64, cro.baseProperties); 5296 outs() << "\n"; 5297 if (cro.baseProperties + n_value != 0) 5298 print_objc_property_list64(cro.baseProperties + n_value, info); 5299 5300 is_meta_class = (cro.flags & RO_META) != 0; 5301 return true; 5302 } 5303 5304 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info, 5305 bool &is_meta_class) { 5306 struct class_ro32_t cro; 5307 const char *r; 5308 uint32_t offset, xoffset, left; 5309 SectionRef S, xS; 5310 const char *name; 5311 5312 r = get_pointer_32(p, offset, left, S, info); 5313 if (r == nullptr) 5314 return false; 5315 memset(&cro, '\0', sizeof(struct class_ro32_t)); 5316 if (left < sizeof(struct class_ro32_t)) { 5317 memcpy(&cro, r, left); 5318 outs() << " (class_ro_t entends past the end of the section)\n"; 5319 } else 5320 memcpy(&cro, r, sizeof(struct class_ro32_t)); 5321 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5322 swapStruct(cro); 5323 outs() << " flags " << format("0x%" PRIx32, cro.flags); 5324 if (cro.flags & RO_META) 5325 outs() << " RO_META"; 5326 if (cro.flags & RO_ROOT) 5327 outs() << " RO_ROOT"; 5328 if (cro.flags & RO_HAS_CXX_STRUCTORS) 5329 outs() << " RO_HAS_CXX_STRUCTORS"; 5330 outs() << "\n"; 5331 outs() << " instanceStart " << cro.instanceStart << "\n"; 5332 outs() << " instanceSize " << cro.instanceSize << "\n"; 5333 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout) 5334 << "\n"; 5335 print_layout_map32(cro.ivarLayout, info); 5336 5337 outs() << " name " << format("0x%" PRIx32, cro.name); 5338 name = get_pointer_32(cro.name, xoffset, left, xS, info); 5339 if (name != nullptr) 5340 outs() << format(" %.*s", left, name); 5341 outs() << "\n"; 5342 5343 outs() << " baseMethods " 5344 << format("0x%" PRIx32, cro.baseMethods) 5345 << " (struct method_list_t *)\n"; 5346 if (cro.baseMethods != 0) 5347 print_method_list32_t(cro.baseMethods, info, ""); 5348 5349 outs() << " baseProtocols " 5350 << format("0x%" PRIx32, cro.baseProtocols) << "\n"; 5351 if (cro.baseProtocols != 0) 5352 print_protocol_list32_t(cro.baseProtocols, info); 5353 outs() << " ivars " << format("0x%" PRIx32, cro.ivars) 5354 << "\n"; 5355 if (cro.ivars != 0) 5356 print_ivar_list32_t(cro.ivars, info); 5357 outs() << " weakIvarLayout " 5358 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n"; 5359 print_layout_map32(cro.weakIvarLayout, info); 5360 outs() << " baseProperties " 5361 << format("0x%" PRIx32, cro.baseProperties) << "\n"; 5362 if (cro.baseProperties != 0) 5363 print_objc_property_list32(cro.baseProperties, info); 5364 is_meta_class = (cro.flags & RO_META) != 0; 5365 return true; 5366 } 5367 5368 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) { 5369 struct class64_t c; 5370 const char *r; 5371 uint32_t offset, left; 5372 SectionRef S; 5373 const char *name; 5374 uint64_t isa_n_value, n_value; 5375 5376 r = get_pointer_64(p, offset, left, S, info); 5377 if (r == nullptr || left < sizeof(struct class64_t)) 5378 return; 5379 memcpy(&c, r, sizeof(struct class64_t)); 5380 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5381 swapStruct(c); 5382 5383 outs() << " isa " << format("0x%" PRIx64, c.isa); 5384 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info, 5385 isa_n_value, c.isa); 5386 if (name != nullptr) 5387 outs() << " " << name; 5388 outs() << "\n"; 5389 5390 outs() << " superclass " << format("0x%" PRIx64, c.superclass); 5391 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info, 5392 n_value, c.superclass); 5393 if (name != nullptr) 5394 outs() << " " << name; 5395 else { 5396 name = get_dyld_bind_info_symbolname(S.getAddress() + 5397 offset + offsetof(struct class64_t, superclass), info); 5398 if (name != nullptr) 5399 outs() << " " << name; 5400 } 5401 outs() << "\n"; 5402 5403 outs() << " cache " << format("0x%" PRIx64, c.cache); 5404 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info, 5405 n_value, c.cache); 5406 if (name != nullptr) 5407 outs() << " " << name; 5408 outs() << "\n"; 5409 5410 outs() << " vtable " << format("0x%" PRIx64, c.vtable); 5411 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info, 5412 n_value, c.vtable); 5413 if (name != nullptr) 5414 outs() << " " << name; 5415 outs() << "\n"; 5416 5417 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info, 5418 n_value, c.data); 5419 outs() << " data "; 5420 if (n_value != 0) { 5421 if (info->verbose && name != nullptr) 5422 outs() << name; 5423 else 5424 outs() << format("0x%" PRIx64, n_value); 5425 if (c.data != 0) 5426 outs() << " + " << format("0x%" PRIx64, c.data); 5427 } else 5428 outs() << format("0x%" PRIx64, c.data); 5429 outs() << " (struct class_ro_t *)"; 5430 5431 // This is a Swift class if some of the low bits of the pointer are set. 5432 if ((c.data + n_value) & 0x7) 5433 outs() << " Swift class"; 5434 outs() << "\n"; 5435 bool is_meta_class; 5436 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class)) 5437 return; 5438 5439 if (!is_meta_class && 5440 c.isa + isa_n_value != p && 5441 c.isa + isa_n_value != 0 && 5442 info->depth < 100) { 5443 info->depth++; 5444 outs() << "Meta Class\n"; 5445 print_class64_t(c.isa + isa_n_value, info); 5446 } 5447 } 5448 5449 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) { 5450 struct class32_t c; 5451 const char *r; 5452 uint32_t offset, left; 5453 SectionRef S; 5454 const char *name; 5455 5456 r = get_pointer_32(p, offset, left, S, info); 5457 if (r == nullptr) 5458 return; 5459 memset(&c, '\0', sizeof(struct class32_t)); 5460 if (left < sizeof(struct class32_t)) { 5461 memcpy(&c, r, left); 5462 outs() << " (class_t entends past the end of the section)\n"; 5463 } else 5464 memcpy(&c, r, sizeof(struct class32_t)); 5465 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5466 swapStruct(c); 5467 5468 outs() << " isa " << format("0x%" PRIx32, c.isa); 5469 name = 5470 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa); 5471 if (name != nullptr) 5472 outs() << " " << name; 5473 outs() << "\n"; 5474 5475 outs() << " superclass " << format("0x%" PRIx32, c.superclass); 5476 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info, 5477 c.superclass); 5478 if (name != nullptr) 5479 outs() << " " << name; 5480 outs() << "\n"; 5481 5482 outs() << " cache " << format("0x%" PRIx32, c.cache); 5483 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info, 5484 c.cache); 5485 if (name != nullptr) 5486 outs() << " " << name; 5487 outs() << "\n"; 5488 5489 outs() << " vtable " << format("0x%" PRIx32, c.vtable); 5490 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info, 5491 c.vtable); 5492 if (name != nullptr) 5493 outs() << " " << name; 5494 outs() << "\n"; 5495 5496 name = 5497 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data); 5498 outs() << " data " << format("0x%" PRIx32, c.data) 5499 << " (struct class_ro_t *)"; 5500 5501 // This is a Swift class if some of the low bits of the pointer are set. 5502 if (c.data & 0x3) 5503 outs() << " Swift class"; 5504 outs() << "\n"; 5505 bool is_meta_class; 5506 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class)) 5507 return; 5508 5509 if (!is_meta_class) { 5510 outs() << "Meta Class\n"; 5511 print_class32_t(c.isa, info); 5512 } 5513 } 5514 5515 static void print_objc_class_t(struct objc_class_t *objc_class, 5516 struct DisassembleInfo *info) { 5517 uint32_t offset, left, xleft; 5518 const char *name, *p, *ivar_list; 5519 SectionRef S; 5520 int32_t i; 5521 struct objc_ivar_list_t objc_ivar_list; 5522 struct objc_ivar_t ivar; 5523 5524 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa); 5525 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) { 5526 name = get_pointer_32(objc_class->isa, offset, left, S, info, true); 5527 if (name != nullptr) 5528 outs() << format(" %.*s", left, name); 5529 else 5530 outs() << " (not in an __OBJC section)"; 5531 } 5532 outs() << "\n"; 5533 5534 outs() << "\t super_class " 5535 << format("0x%08" PRIx32, objc_class->super_class); 5536 if (info->verbose) { 5537 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true); 5538 if (name != nullptr) 5539 outs() << format(" %.*s", left, name); 5540 else 5541 outs() << " (not in an __OBJC section)"; 5542 } 5543 outs() << "\n"; 5544 5545 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name); 5546 if (info->verbose) { 5547 name = get_pointer_32(objc_class->name, offset, left, S, info, true); 5548 if (name != nullptr) 5549 outs() << format(" %.*s", left, name); 5550 else 5551 outs() << " (not in an __OBJC section)"; 5552 } 5553 outs() << "\n"; 5554 5555 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version) 5556 << "\n"; 5557 5558 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info); 5559 if (info->verbose) { 5560 if (CLS_GETINFO(objc_class, CLS_CLASS)) 5561 outs() << " CLS_CLASS"; 5562 else if (CLS_GETINFO(objc_class, CLS_META)) 5563 outs() << " CLS_META"; 5564 } 5565 outs() << "\n"; 5566 5567 outs() << "\t instance_size " 5568 << format("0x%08" PRIx32, objc_class->instance_size) << "\n"; 5569 5570 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true); 5571 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars); 5572 if (p != nullptr) { 5573 if (left > sizeof(struct objc_ivar_list_t)) { 5574 outs() << "\n"; 5575 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t)); 5576 } else { 5577 outs() << " (entends past the end of the section)\n"; 5578 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t)); 5579 memcpy(&objc_ivar_list, p, left); 5580 } 5581 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5582 swapStruct(objc_ivar_list); 5583 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n"; 5584 ivar_list = p + sizeof(struct objc_ivar_list_t); 5585 for (i = 0; i < objc_ivar_list.ivar_count; i++) { 5586 if ((i + 1) * sizeof(struct objc_ivar_t) > left) { 5587 outs() << "\t\t remaining ivar's extend past the of the section\n"; 5588 break; 5589 } 5590 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t), 5591 sizeof(struct objc_ivar_t)); 5592 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5593 swapStruct(ivar); 5594 5595 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name); 5596 if (info->verbose) { 5597 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true); 5598 if (name != nullptr) 5599 outs() << format(" %.*s", xleft, name); 5600 else 5601 outs() << " (not in an __OBJC section)"; 5602 } 5603 outs() << "\n"; 5604 5605 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type); 5606 if (info->verbose) { 5607 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true); 5608 if (name != nullptr) 5609 outs() << format(" %.*s", xleft, name); 5610 else 5611 outs() << " (not in an __OBJC section)"; 5612 } 5613 outs() << "\n"; 5614 5615 outs() << "\t\t ivar_offset " 5616 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n"; 5617 } 5618 } else { 5619 outs() << " (not in an __OBJC section)\n"; 5620 } 5621 5622 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists); 5623 if (print_method_list(objc_class->methodLists, info)) 5624 outs() << " (not in an __OBJC section)\n"; 5625 5626 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache) 5627 << "\n"; 5628 5629 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols); 5630 if (print_protocol_list(objc_class->protocols, 16, info)) 5631 outs() << " (not in an __OBJC section)\n"; 5632 } 5633 5634 static void print_objc_objc_category_t(struct objc_category_t *objc_category, 5635 struct DisassembleInfo *info) { 5636 uint32_t offset, left; 5637 const char *name; 5638 SectionRef S; 5639 5640 outs() << "\t category name " 5641 << format("0x%08" PRIx32, objc_category->category_name); 5642 if (info->verbose) { 5643 name = get_pointer_32(objc_category->category_name, offset, left, S, info, 5644 true); 5645 if (name != nullptr) 5646 outs() << format(" %.*s", left, name); 5647 else 5648 outs() << " (not in an __OBJC section)"; 5649 } 5650 outs() << "\n"; 5651 5652 outs() << "\t\t class name " 5653 << format("0x%08" PRIx32, objc_category->class_name); 5654 if (info->verbose) { 5655 name = 5656 get_pointer_32(objc_category->class_name, offset, left, S, info, true); 5657 if (name != nullptr) 5658 outs() << format(" %.*s", left, name); 5659 else 5660 outs() << " (not in an __OBJC section)"; 5661 } 5662 outs() << "\n"; 5663 5664 outs() << "\t instance methods " 5665 << format("0x%08" PRIx32, objc_category->instance_methods); 5666 if (print_method_list(objc_category->instance_methods, info)) 5667 outs() << " (not in an __OBJC section)\n"; 5668 5669 outs() << "\t class methods " 5670 << format("0x%08" PRIx32, objc_category->class_methods); 5671 if (print_method_list(objc_category->class_methods, info)) 5672 outs() << " (not in an __OBJC section)\n"; 5673 } 5674 5675 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) { 5676 struct category64_t c; 5677 const char *r; 5678 uint32_t offset, xoffset, left; 5679 SectionRef S, xS; 5680 const char *name, *sym_name; 5681 uint64_t n_value; 5682 5683 r = get_pointer_64(p, offset, left, S, info); 5684 if (r == nullptr) 5685 return; 5686 memset(&c, '\0', sizeof(struct category64_t)); 5687 if (left < sizeof(struct category64_t)) { 5688 memcpy(&c, r, left); 5689 outs() << " (category_t entends past the end of the section)\n"; 5690 } else 5691 memcpy(&c, r, sizeof(struct category64_t)); 5692 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5693 swapStruct(c); 5694 5695 outs() << " name "; 5696 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S, 5697 info, n_value, c.name); 5698 if (n_value != 0) { 5699 if (info->verbose && sym_name != nullptr) 5700 outs() << sym_name; 5701 else 5702 outs() << format("0x%" PRIx64, n_value); 5703 if (c.name != 0) 5704 outs() << " + " << format("0x%" PRIx64, c.name); 5705 } else 5706 outs() << format("0x%" PRIx64, c.name); 5707 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info); 5708 if (name != nullptr) 5709 outs() << format(" %.*s", left, name); 5710 outs() << "\n"; 5711 5712 outs() << " cls "; 5713 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info, 5714 n_value, c.cls); 5715 if (n_value != 0) { 5716 if (info->verbose && sym_name != nullptr) 5717 outs() << sym_name; 5718 else 5719 outs() << format("0x%" PRIx64, n_value); 5720 if (c.cls != 0) 5721 outs() << " + " << format("0x%" PRIx64, c.cls); 5722 } else 5723 outs() << format("0x%" PRIx64, c.cls); 5724 outs() << "\n"; 5725 if (c.cls + n_value != 0) 5726 print_class64_t(c.cls + n_value, info); 5727 5728 outs() << " instanceMethods "; 5729 sym_name = 5730 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S, 5731 info, n_value, c.instanceMethods); 5732 if (n_value != 0) { 5733 if (info->verbose && sym_name != nullptr) 5734 outs() << sym_name; 5735 else 5736 outs() << format("0x%" PRIx64, n_value); 5737 if (c.instanceMethods != 0) 5738 outs() << " + " << format("0x%" PRIx64, c.instanceMethods); 5739 } else 5740 outs() << format("0x%" PRIx64, c.instanceMethods); 5741 outs() << "\n"; 5742 if (c.instanceMethods + n_value != 0) 5743 print_method_list64_t(c.instanceMethods + n_value, info, ""); 5744 5745 outs() << " classMethods "; 5746 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods), 5747 S, info, n_value, c.classMethods); 5748 if (n_value != 0) { 5749 if (info->verbose && sym_name != nullptr) 5750 outs() << sym_name; 5751 else 5752 outs() << format("0x%" PRIx64, n_value); 5753 if (c.classMethods != 0) 5754 outs() << " + " << format("0x%" PRIx64, c.classMethods); 5755 } else 5756 outs() << format("0x%" PRIx64, c.classMethods); 5757 outs() << "\n"; 5758 if (c.classMethods + n_value != 0) 5759 print_method_list64_t(c.classMethods + n_value, info, ""); 5760 5761 outs() << " protocols "; 5762 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S, 5763 info, n_value, c.protocols); 5764 if (n_value != 0) { 5765 if (info->verbose && sym_name != nullptr) 5766 outs() << sym_name; 5767 else 5768 outs() << format("0x%" PRIx64, n_value); 5769 if (c.protocols != 0) 5770 outs() << " + " << format("0x%" PRIx64, c.protocols); 5771 } else 5772 outs() << format("0x%" PRIx64, c.protocols); 5773 outs() << "\n"; 5774 if (c.protocols + n_value != 0) 5775 print_protocol_list64_t(c.protocols + n_value, info); 5776 5777 outs() << "instanceProperties "; 5778 sym_name = 5779 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties), 5780 S, info, n_value, c.instanceProperties); 5781 if (n_value != 0) { 5782 if (info->verbose && sym_name != nullptr) 5783 outs() << sym_name; 5784 else 5785 outs() << format("0x%" PRIx64, n_value); 5786 if (c.instanceProperties != 0) 5787 outs() << " + " << format("0x%" PRIx64, c.instanceProperties); 5788 } else 5789 outs() << format("0x%" PRIx64, c.instanceProperties); 5790 outs() << "\n"; 5791 if (c.instanceProperties + n_value != 0) 5792 print_objc_property_list64(c.instanceProperties + n_value, info); 5793 } 5794 5795 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) { 5796 struct category32_t c; 5797 const char *r; 5798 uint32_t offset, left; 5799 SectionRef S, xS; 5800 const char *name; 5801 5802 r = get_pointer_32(p, offset, left, S, info); 5803 if (r == nullptr) 5804 return; 5805 memset(&c, '\0', sizeof(struct category32_t)); 5806 if (left < sizeof(struct category32_t)) { 5807 memcpy(&c, r, left); 5808 outs() << " (category_t entends past the end of the section)\n"; 5809 } else 5810 memcpy(&c, r, sizeof(struct category32_t)); 5811 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5812 swapStruct(c); 5813 5814 outs() << " name " << format("0x%" PRIx32, c.name); 5815 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info, 5816 c.name); 5817 if (name) 5818 outs() << " " << name; 5819 outs() << "\n"; 5820 5821 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n"; 5822 if (c.cls != 0) 5823 print_class32_t(c.cls, info); 5824 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods) 5825 << "\n"; 5826 if (c.instanceMethods != 0) 5827 print_method_list32_t(c.instanceMethods, info, ""); 5828 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods) 5829 << "\n"; 5830 if (c.classMethods != 0) 5831 print_method_list32_t(c.classMethods, info, ""); 5832 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n"; 5833 if (c.protocols != 0) 5834 print_protocol_list32_t(c.protocols, info); 5835 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties) 5836 << "\n"; 5837 if (c.instanceProperties != 0) 5838 print_objc_property_list32(c.instanceProperties, info); 5839 } 5840 5841 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) { 5842 uint32_t i, left, offset, xoffset; 5843 uint64_t p, n_value; 5844 struct message_ref64 mr; 5845 const char *name, *sym_name; 5846 const char *r; 5847 SectionRef xS; 5848 5849 if (S == SectionRef()) 5850 return; 5851 5852 StringRef SectName; 5853 Expected<StringRef> SecNameOrErr = S.getName(); 5854 if (SecNameOrErr) 5855 SectName = *SecNameOrErr; 5856 else 5857 consumeError(SecNameOrErr.takeError()); 5858 5859 DataRefImpl Ref = S.getRawDataRefImpl(); 5860 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5861 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5862 offset = 0; 5863 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { 5864 p = S.getAddress() + i; 5865 r = get_pointer_64(p, offset, left, S, info); 5866 if (r == nullptr) 5867 return; 5868 memset(&mr, '\0', sizeof(struct message_ref64)); 5869 if (left < sizeof(struct message_ref64)) { 5870 memcpy(&mr, r, left); 5871 outs() << " (message_ref entends past the end of the section)\n"; 5872 } else 5873 memcpy(&mr, r, sizeof(struct message_ref64)); 5874 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5875 swapStruct(mr); 5876 5877 outs() << " imp "; 5878 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info, 5879 n_value, mr.imp); 5880 if (n_value != 0) { 5881 outs() << format("0x%" PRIx64, n_value) << " "; 5882 if (mr.imp != 0) 5883 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " "; 5884 } else 5885 outs() << format("0x%" PRIx64, mr.imp) << " "; 5886 if (name != nullptr) 5887 outs() << " " << name; 5888 outs() << "\n"; 5889 5890 outs() << " sel "; 5891 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S, 5892 info, n_value, mr.sel); 5893 if (n_value != 0) { 5894 if (info->verbose && sym_name != nullptr) 5895 outs() << sym_name; 5896 else 5897 outs() << format("0x%" PRIx64, n_value); 5898 if (mr.sel != 0) 5899 outs() << " + " << format("0x%" PRIx64, mr.sel); 5900 } else 5901 outs() << format("0x%" PRIx64, mr.sel); 5902 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info); 5903 if (name != nullptr) 5904 outs() << format(" %.*s", left, name); 5905 outs() << "\n"; 5906 5907 offset += sizeof(struct message_ref64); 5908 } 5909 } 5910 5911 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) { 5912 uint32_t i, left, offset, xoffset, p; 5913 struct message_ref32 mr; 5914 const char *name, *r; 5915 SectionRef xS; 5916 5917 if (S == SectionRef()) 5918 return; 5919 5920 StringRef SectName; 5921 Expected<StringRef> SecNameOrErr = S.getName(); 5922 if (SecNameOrErr) 5923 SectName = *SecNameOrErr; 5924 else 5925 consumeError(SecNameOrErr.takeError()); 5926 5927 DataRefImpl Ref = S.getRawDataRefImpl(); 5928 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5929 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5930 offset = 0; 5931 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) { 5932 p = S.getAddress() + i; 5933 r = get_pointer_32(p, offset, left, S, info); 5934 if (r == nullptr) 5935 return; 5936 memset(&mr, '\0', sizeof(struct message_ref32)); 5937 if (left < sizeof(struct message_ref32)) { 5938 memcpy(&mr, r, left); 5939 outs() << " (message_ref entends past the end of the section)\n"; 5940 } else 5941 memcpy(&mr, r, sizeof(struct message_ref32)); 5942 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5943 swapStruct(mr); 5944 5945 outs() << " imp " << format("0x%" PRIx32, mr.imp); 5946 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info, 5947 mr.imp); 5948 if (name != nullptr) 5949 outs() << " " << name; 5950 outs() << "\n"; 5951 5952 outs() << " sel " << format("0x%" PRIx32, mr.sel); 5953 name = get_pointer_32(mr.sel, xoffset, left, xS, info); 5954 if (name != nullptr) 5955 outs() << " " << name; 5956 outs() << "\n"; 5957 5958 offset += sizeof(struct message_ref32); 5959 } 5960 } 5961 5962 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) { 5963 uint32_t left, offset, swift_version; 5964 uint64_t p; 5965 struct objc_image_info64 o; 5966 const char *r; 5967 5968 if (S == SectionRef()) 5969 return; 5970 5971 StringRef SectName; 5972 Expected<StringRef> SecNameOrErr = S.getName(); 5973 if (SecNameOrErr) 5974 SectName = *SecNameOrErr; 5975 else 5976 consumeError(SecNameOrErr.takeError()); 5977 5978 DataRefImpl Ref = S.getRawDataRefImpl(); 5979 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 5980 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 5981 p = S.getAddress(); 5982 r = get_pointer_64(p, offset, left, S, info); 5983 if (r == nullptr) 5984 return; 5985 memset(&o, '\0', sizeof(struct objc_image_info64)); 5986 if (left < sizeof(struct objc_image_info64)) { 5987 memcpy(&o, r, left); 5988 outs() << " (objc_image_info entends past the end of the section)\n"; 5989 } else 5990 memcpy(&o, r, sizeof(struct objc_image_info64)); 5991 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 5992 swapStruct(o); 5993 outs() << " version " << o.version << "\n"; 5994 outs() << " flags " << format("0x%" PRIx32, o.flags); 5995 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) 5996 outs() << " OBJC_IMAGE_IS_REPLACEMENT"; 5997 if (o.flags & OBJC_IMAGE_SUPPORTS_GC) 5998 outs() << " OBJC_IMAGE_SUPPORTS_GC"; 5999 if (o.flags & OBJC_IMAGE_IS_SIMULATED) 6000 outs() << " OBJC_IMAGE_IS_SIMULATED"; 6001 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES) 6002 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES"; 6003 swift_version = (o.flags >> 8) & 0xff; 6004 if (swift_version != 0) { 6005 if (swift_version == 1) 6006 outs() << " Swift 1.0"; 6007 else if (swift_version == 2) 6008 outs() << " Swift 1.1"; 6009 else if(swift_version == 3) 6010 outs() << " Swift 2.0"; 6011 else if(swift_version == 4) 6012 outs() << " Swift 3.0"; 6013 else if(swift_version == 5) 6014 outs() << " Swift 4.0"; 6015 else if(swift_version == 6) 6016 outs() << " Swift 4.1/Swift 4.2"; 6017 else if(swift_version == 7) 6018 outs() << " Swift 5 or later"; 6019 else 6020 outs() << " unknown future Swift version (" << swift_version << ")"; 6021 } 6022 outs() << "\n"; 6023 } 6024 6025 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) { 6026 uint32_t left, offset, swift_version, p; 6027 struct objc_image_info32 o; 6028 const char *r; 6029 6030 if (S == SectionRef()) 6031 return; 6032 6033 StringRef SectName; 6034 Expected<StringRef> SecNameOrErr = S.getName(); 6035 if (SecNameOrErr) 6036 SectName = *SecNameOrErr; 6037 else 6038 consumeError(SecNameOrErr.takeError()); 6039 6040 DataRefImpl Ref = S.getRawDataRefImpl(); 6041 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 6042 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 6043 p = S.getAddress(); 6044 r = get_pointer_32(p, offset, left, S, info); 6045 if (r == nullptr) 6046 return; 6047 memset(&o, '\0', sizeof(struct objc_image_info32)); 6048 if (left < sizeof(struct objc_image_info32)) { 6049 memcpy(&o, r, left); 6050 outs() << " (objc_image_info entends past the end of the section)\n"; 6051 } else 6052 memcpy(&o, r, sizeof(struct objc_image_info32)); 6053 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 6054 swapStruct(o); 6055 outs() << " version " << o.version << "\n"; 6056 outs() << " flags " << format("0x%" PRIx32, o.flags); 6057 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT) 6058 outs() << " OBJC_IMAGE_IS_REPLACEMENT"; 6059 if (o.flags & OBJC_IMAGE_SUPPORTS_GC) 6060 outs() << " OBJC_IMAGE_SUPPORTS_GC"; 6061 swift_version = (o.flags >> 8) & 0xff; 6062 if (swift_version != 0) { 6063 if (swift_version == 1) 6064 outs() << " Swift 1.0"; 6065 else if (swift_version == 2) 6066 outs() << " Swift 1.1"; 6067 else if(swift_version == 3) 6068 outs() << " Swift 2.0"; 6069 else if(swift_version == 4) 6070 outs() << " Swift 3.0"; 6071 else if(swift_version == 5) 6072 outs() << " Swift 4.0"; 6073 else if(swift_version == 6) 6074 outs() << " Swift 4.1/Swift 4.2"; 6075 else if(swift_version == 7) 6076 outs() << " Swift 5 or later"; 6077 else 6078 outs() << " unknown future Swift version (" << swift_version << ")"; 6079 } 6080 outs() << "\n"; 6081 } 6082 6083 static void print_image_info(SectionRef S, struct DisassembleInfo *info) { 6084 uint32_t left, offset, p; 6085 struct imageInfo_t o; 6086 const char *r; 6087 6088 StringRef SectName; 6089 Expected<StringRef> SecNameOrErr = S.getName(); 6090 if (SecNameOrErr) 6091 SectName = *SecNameOrErr; 6092 else 6093 consumeError(SecNameOrErr.takeError()); 6094 6095 DataRefImpl Ref = S.getRawDataRefImpl(); 6096 StringRef SegName = info->O->getSectionFinalSegmentName(Ref); 6097 outs() << "Contents of (" << SegName << "," << SectName << ") section\n"; 6098 p = S.getAddress(); 6099 r = get_pointer_32(p, offset, left, S, info); 6100 if (r == nullptr) 6101 return; 6102 memset(&o, '\0', sizeof(struct imageInfo_t)); 6103 if (left < sizeof(struct imageInfo_t)) { 6104 memcpy(&o, r, left); 6105 outs() << " (imageInfo entends past the end of the section)\n"; 6106 } else 6107 memcpy(&o, r, sizeof(struct imageInfo_t)); 6108 if (info->O->isLittleEndian() != sys::IsLittleEndianHost) 6109 swapStruct(o); 6110 outs() << " version " << o.version << "\n"; 6111 outs() << " flags " << format("0x%" PRIx32, o.flags); 6112 if (o.flags & 0x1) 6113 outs() << " F&C"; 6114 if (o.flags & 0x2) 6115 outs() << " GC"; 6116 if (o.flags & 0x4) 6117 outs() << " GC-only"; 6118 else 6119 outs() << " RR"; 6120 outs() << "\n"; 6121 } 6122 6123 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) { 6124 SymbolAddressMap AddrMap; 6125 if (verbose) 6126 CreateSymbolAddressMap(O, &AddrMap); 6127 6128 std::vector<SectionRef> Sections; 6129 append_range(Sections, O->sections()); 6130 6131 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6132 6133 SectionRef CL = get_section(O, "__OBJC2", "__class_list"); 6134 if (CL == SectionRef()) 6135 CL = get_section(O, "__DATA", "__objc_classlist"); 6136 if (CL == SectionRef()) 6137 CL = get_section(O, "__DATA_CONST", "__objc_classlist"); 6138 if (CL == SectionRef()) 6139 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist"); 6140 info.S = CL; 6141 walk_pointer_list_64("class", CL, O, &info, print_class64_t); 6142 6143 SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); 6144 if (CR == SectionRef()) 6145 CR = get_section(O, "__DATA", "__objc_classrefs"); 6146 if (CR == SectionRef()) 6147 CR = get_section(O, "__DATA_CONST", "__objc_classrefs"); 6148 if (CR == SectionRef()) 6149 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs"); 6150 info.S = CR; 6151 walk_pointer_list_64("class refs", CR, O, &info, nullptr); 6152 6153 SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); 6154 if (SR == SectionRef()) 6155 SR = get_section(O, "__DATA", "__objc_superrefs"); 6156 if (SR == SectionRef()) 6157 SR = get_section(O, "__DATA_CONST", "__objc_superrefs"); 6158 if (SR == SectionRef()) 6159 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs"); 6160 info.S = SR; 6161 walk_pointer_list_64("super refs", SR, O, &info, nullptr); 6162 6163 SectionRef CA = get_section(O, "__OBJC2", "__category_list"); 6164 if (CA == SectionRef()) 6165 CA = get_section(O, "__DATA", "__objc_catlist"); 6166 if (CA == SectionRef()) 6167 CA = get_section(O, "__DATA_CONST", "__objc_catlist"); 6168 if (CA == SectionRef()) 6169 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist"); 6170 info.S = CA; 6171 walk_pointer_list_64("category", CA, O, &info, print_category64_t); 6172 6173 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); 6174 if (PL == SectionRef()) 6175 PL = get_section(O, "__DATA", "__objc_protolist"); 6176 if (PL == SectionRef()) 6177 PL = get_section(O, "__DATA_CONST", "__objc_protolist"); 6178 if (PL == SectionRef()) 6179 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist"); 6180 info.S = PL; 6181 walk_pointer_list_64("protocol", PL, O, &info, nullptr); 6182 6183 SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); 6184 if (MR == SectionRef()) 6185 MR = get_section(O, "__DATA", "__objc_msgrefs"); 6186 if (MR == SectionRef()) 6187 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs"); 6188 if (MR == SectionRef()) 6189 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs"); 6190 info.S = MR; 6191 print_message_refs64(MR, &info); 6192 6193 SectionRef II = get_section(O, "__OBJC2", "__image_info"); 6194 if (II == SectionRef()) 6195 II = get_section(O, "__DATA", "__objc_imageinfo"); 6196 if (II == SectionRef()) 6197 II = get_section(O, "__DATA_CONST", "__objc_imageinfo"); 6198 if (II == SectionRef()) 6199 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo"); 6200 info.S = II; 6201 print_image_info64(II, &info); 6202 } 6203 6204 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) { 6205 SymbolAddressMap AddrMap; 6206 if (verbose) 6207 CreateSymbolAddressMap(O, &AddrMap); 6208 6209 std::vector<SectionRef> Sections; 6210 append_range(Sections, O->sections()); 6211 6212 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6213 6214 SectionRef CL = get_section(O, "__OBJC2", "__class_list"); 6215 if (CL == SectionRef()) 6216 CL = get_section(O, "__DATA", "__objc_classlist"); 6217 if (CL == SectionRef()) 6218 CL = get_section(O, "__DATA_CONST", "__objc_classlist"); 6219 if (CL == SectionRef()) 6220 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist"); 6221 info.S = CL; 6222 walk_pointer_list_32("class", CL, O, &info, print_class32_t); 6223 6224 SectionRef CR = get_section(O, "__OBJC2", "__class_refs"); 6225 if (CR == SectionRef()) 6226 CR = get_section(O, "__DATA", "__objc_classrefs"); 6227 if (CR == SectionRef()) 6228 CR = get_section(O, "__DATA_CONST", "__objc_classrefs"); 6229 if (CR == SectionRef()) 6230 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs"); 6231 info.S = CR; 6232 walk_pointer_list_32("class refs", CR, O, &info, nullptr); 6233 6234 SectionRef SR = get_section(O, "__OBJC2", "__super_refs"); 6235 if (SR == SectionRef()) 6236 SR = get_section(O, "__DATA", "__objc_superrefs"); 6237 if (SR == SectionRef()) 6238 SR = get_section(O, "__DATA_CONST", "__objc_superrefs"); 6239 if (SR == SectionRef()) 6240 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs"); 6241 info.S = SR; 6242 walk_pointer_list_32("super refs", SR, O, &info, nullptr); 6243 6244 SectionRef CA = get_section(O, "__OBJC2", "__category_list"); 6245 if (CA == SectionRef()) 6246 CA = get_section(O, "__DATA", "__objc_catlist"); 6247 if (CA == SectionRef()) 6248 CA = get_section(O, "__DATA_CONST", "__objc_catlist"); 6249 if (CA == SectionRef()) 6250 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist"); 6251 info.S = CA; 6252 walk_pointer_list_32("category", CA, O, &info, print_category32_t); 6253 6254 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list"); 6255 if (PL == SectionRef()) 6256 PL = get_section(O, "__DATA", "__objc_protolist"); 6257 if (PL == SectionRef()) 6258 PL = get_section(O, "__DATA_CONST", "__objc_protolist"); 6259 if (PL == SectionRef()) 6260 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist"); 6261 info.S = PL; 6262 walk_pointer_list_32("protocol", PL, O, &info, nullptr); 6263 6264 SectionRef MR = get_section(O, "__OBJC2", "__message_refs"); 6265 if (MR == SectionRef()) 6266 MR = get_section(O, "__DATA", "__objc_msgrefs"); 6267 if (MR == SectionRef()) 6268 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs"); 6269 if (MR == SectionRef()) 6270 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs"); 6271 info.S = MR; 6272 print_message_refs32(MR, &info); 6273 6274 SectionRef II = get_section(O, "__OBJC2", "__image_info"); 6275 if (II == SectionRef()) 6276 II = get_section(O, "__DATA", "__objc_imageinfo"); 6277 if (II == SectionRef()) 6278 II = get_section(O, "__DATA_CONST", "__objc_imageinfo"); 6279 if (II == SectionRef()) 6280 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo"); 6281 info.S = II; 6282 print_image_info32(II, &info); 6283 } 6284 6285 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) { 6286 uint32_t i, j, p, offset, xoffset, left, defs_left, def; 6287 const char *r, *name, *defs; 6288 struct objc_module_t module; 6289 SectionRef S, xS; 6290 struct objc_symtab_t symtab; 6291 struct objc_class_t objc_class; 6292 struct objc_category_t objc_category; 6293 6294 outs() << "Objective-C segment\n"; 6295 S = get_section(O, "__OBJC", "__module_info"); 6296 if (S == SectionRef()) 6297 return false; 6298 6299 SymbolAddressMap AddrMap; 6300 if (verbose) 6301 CreateSymbolAddressMap(O, &AddrMap); 6302 6303 std::vector<SectionRef> Sections; 6304 append_range(Sections, O->sections()); 6305 6306 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose); 6307 6308 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) { 6309 p = S.getAddress() + i; 6310 r = get_pointer_32(p, offset, left, S, &info, true); 6311 if (r == nullptr) 6312 return true; 6313 memset(&module, '\0', sizeof(struct objc_module_t)); 6314 if (left < sizeof(struct objc_module_t)) { 6315 memcpy(&module, r, left); 6316 outs() << " (module extends past end of __module_info section)\n"; 6317 } else 6318 memcpy(&module, r, sizeof(struct objc_module_t)); 6319 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6320 swapStruct(module); 6321 6322 outs() << "Module " << format("0x%" PRIx32, p) << "\n"; 6323 outs() << " version " << module.version << "\n"; 6324 outs() << " size " << module.size << "\n"; 6325 outs() << " name "; 6326 name = get_pointer_32(module.name, xoffset, left, xS, &info, true); 6327 if (name != nullptr) 6328 outs() << format("%.*s", left, name); 6329 else 6330 outs() << format("0x%08" PRIx32, module.name) 6331 << "(not in an __OBJC section)"; 6332 outs() << "\n"; 6333 6334 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true); 6335 if (module.symtab == 0 || r == nullptr) { 6336 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) 6337 << " (not in an __OBJC section)\n"; 6338 continue; 6339 } 6340 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n"; 6341 memset(&symtab, '\0', sizeof(struct objc_symtab_t)); 6342 defs_left = 0; 6343 defs = nullptr; 6344 if (left < sizeof(struct objc_symtab_t)) { 6345 memcpy(&symtab, r, left); 6346 outs() << "\tsymtab extends past end of an __OBJC section)\n"; 6347 } else { 6348 memcpy(&symtab, r, sizeof(struct objc_symtab_t)); 6349 if (left > sizeof(struct objc_symtab_t)) { 6350 defs_left = left - sizeof(struct objc_symtab_t); 6351 defs = r + sizeof(struct objc_symtab_t); 6352 } 6353 } 6354 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6355 swapStruct(symtab); 6356 6357 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n"; 6358 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true); 6359 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs); 6360 if (r == nullptr) 6361 outs() << " (not in an __OBJC section)"; 6362 outs() << "\n"; 6363 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n"; 6364 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n"; 6365 if (symtab.cls_def_cnt > 0) 6366 outs() << "\tClass Definitions\n"; 6367 for (j = 0; j < symtab.cls_def_cnt; j++) { 6368 if ((j + 1) * sizeof(uint32_t) > defs_left) { 6369 outs() << "\t(remaining class defs entries entends past the end of the " 6370 << "section)\n"; 6371 break; 6372 } 6373 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t)); 6374 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6375 sys::swapByteOrder(def); 6376 6377 r = get_pointer_32(def, xoffset, left, xS, &info, true); 6378 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def); 6379 if (r != nullptr) { 6380 if (left > sizeof(struct objc_class_t)) { 6381 outs() << "\n"; 6382 memcpy(&objc_class, r, sizeof(struct objc_class_t)); 6383 } else { 6384 outs() << " (entends past the end of the section)\n"; 6385 memset(&objc_class, '\0', sizeof(struct objc_class_t)); 6386 memcpy(&objc_class, r, left); 6387 } 6388 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6389 swapStruct(objc_class); 6390 print_objc_class_t(&objc_class, &info); 6391 } else { 6392 outs() << "(not in an __OBJC section)\n"; 6393 } 6394 6395 if (CLS_GETINFO(&objc_class, CLS_CLASS)) { 6396 outs() << "\tMeta Class"; 6397 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true); 6398 if (r != nullptr) { 6399 if (left > sizeof(struct objc_class_t)) { 6400 outs() << "\n"; 6401 memcpy(&objc_class, r, sizeof(struct objc_class_t)); 6402 } else { 6403 outs() << " (entends past the end of the section)\n"; 6404 memset(&objc_class, '\0', sizeof(struct objc_class_t)); 6405 memcpy(&objc_class, r, left); 6406 } 6407 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6408 swapStruct(objc_class); 6409 print_objc_class_t(&objc_class, &info); 6410 } else { 6411 outs() << "(not in an __OBJC section)\n"; 6412 } 6413 } 6414 } 6415 if (symtab.cat_def_cnt > 0) 6416 outs() << "\tCategory Definitions\n"; 6417 for (j = 0; j < symtab.cat_def_cnt; j++) { 6418 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) { 6419 outs() << "\t(remaining category defs entries entends past the end of " 6420 << "the section)\n"; 6421 break; 6422 } 6423 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t), 6424 sizeof(uint32_t)); 6425 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6426 sys::swapByteOrder(def); 6427 6428 r = get_pointer_32(def, xoffset, left, xS, &info, true); 6429 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] " 6430 << format("0x%08" PRIx32, def); 6431 if (r != nullptr) { 6432 if (left > sizeof(struct objc_category_t)) { 6433 outs() << "\n"; 6434 memcpy(&objc_category, r, sizeof(struct objc_category_t)); 6435 } else { 6436 outs() << " (entends past the end of the section)\n"; 6437 memset(&objc_category, '\0', sizeof(struct objc_category_t)); 6438 memcpy(&objc_category, r, left); 6439 } 6440 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6441 swapStruct(objc_category); 6442 print_objc_objc_category_t(&objc_category, &info); 6443 } else { 6444 outs() << "(not in an __OBJC section)\n"; 6445 } 6446 } 6447 } 6448 const SectionRef II = get_section(O, "__OBJC", "__image_info"); 6449 if (II != SectionRef()) 6450 print_image_info(II, &info); 6451 6452 return true; 6453 } 6454 6455 static void DumpProtocolSection(MachOObjectFile *O, const char *sect, 6456 uint32_t size, uint32_t addr) { 6457 SymbolAddressMap AddrMap; 6458 CreateSymbolAddressMap(O, &AddrMap); 6459 6460 std::vector<SectionRef> Sections; 6461 append_range(Sections, O->sections()); 6462 6463 struct DisassembleInfo info(O, &AddrMap, &Sections, true); 6464 6465 const char *p; 6466 struct objc_protocol_t protocol; 6467 uint32_t left, paddr; 6468 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) { 6469 memset(&protocol, '\0', sizeof(struct objc_protocol_t)); 6470 left = size - (p - sect); 6471 if (left < sizeof(struct objc_protocol_t)) { 6472 outs() << "Protocol extends past end of __protocol section\n"; 6473 memcpy(&protocol, p, left); 6474 } else 6475 memcpy(&protocol, p, sizeof(struct objc_protocol_t)); 6476 if (O->isLittleEndian() != sys::IsLittleEndianHost) 6477 swapStruct(protocol); 6478 paddr = addr + (p - sect); 6479 outs() << "Protocol " << format("0x%" PRIx32, paddr); 6480 if (print_protocol(paddr, 0, &info)) 6481 outs() << "(not in an __OBJC section)\n"; 6482 } 6483 } 6484 6485 #ifdef LLVM_HAVE_LIBXAR 6486 static inline void swapStruct(struct xar_header &xar) { 6487 sys::swapByteOrder(xar.magic); 6488 sys::swapByteOrder(xar.size); 6489 sys::swapByteOrder(xar.version); 6490 sys::swapByteOrder(xar.toc_length_compressed); 6491 sys::swapByteOrder(xar.toc_length_uncompressed); 6492 sys::swapByteOrder(xar.cksum_alg); 6493 } 6494 6495 static void PrintModeVerbose(uint32_t mode) { 6496 switch(mode & S_IFMT){ 6497 case S_IFDIR: 6498 outs() << "d"; 6499 break; 6500 case S_IFCHR: 6501 outs() << "c"; 6502 break; 6503 case S_IFBLK: 6504 outs() << "b"; 6505 break; 6506 case S_IFREG: 6507 outs() << "-"; 6508 break; 6509 case S_IFLNK: 6510 outs() << "l"; 6511 break; 6512 case S_IFSOCK: 6513 outs() << "s"; 6514 break; 6515 default: 6516 outs() << "?"; 6517 break; 6518 } 6519 6520 /* owner permissions */ 6521 if(mode & S_IREAD) 6522 outs() << "r"; 6523 else 6524 outs() << "-"; 6525 if(mode & S_IWRITE) 6526 outs() << "w"; 6527 else 6528 outs() << "-"; 6529 if(mode & S_ISUID) 6530 outs() << "s"; 6531 else if(mode & S_IEXEC) 6532 outs() << "x"; 6533 else 6534 outs() << "-"; 6535 6536 /* group permissions */ 6537 if(mode & (S_IREAD >> 3)) 6538 outs() << "r"; 6539 else 6540 outs() << "-"; 6541 if(mode & (S_IWRITE >> 3)) 6542 outs() << "w"; 6543 else 6544 outs() << "-"; 6545 if(mode & S_ISGID) 6546 outs() << "s"; 6547 else if(mode & (S_IEXEC >> 3)) 6548 outs() << "x"; 6549 else 6550 outs() << "-"; 6551 6552 /* other permissions */ 6553 if(mode & (S_IREAD >> 6)) 6554 outs() << "r"; 6555 else 6556 outs() << "-"; 6557 if(mode & (S_IWRITE >> 6)) 6558 outs() << "w"; 6559 else 6560 outs() << "-"; 6561 if(mode & S_ISVTX) 6562 outs() << "t"; 6563 else if(mode & (S_IEXEC >> 6)) 6564 outs() << "x"; 6565 else 6566 outs() << "-"; 6567 } 6568 6569 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) { 6570 xar_file_t xf; 6571 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m; 6572 char *endp; 6573 uint32_t mode_value; 6574 6575 ScopedXarIter xi; 6576 if (!xi) { 6577 WithColor::error(errs(), "llvm-objdump") 6578 << "can't obtain an xar iterator for xar archive " << XarFilename 6579 << "\n"; 6580 return; 6581 } 6582 6583 // Go through the xar's files. 6584 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) { 6585 ScopedXarIter xp; 6586 if(!xp){ 6587 WithColor::error(errs(), "llvm-objdump") 6588 << "can't obtain an xar iterator for xar archive " << XarFilename 6589 << "\n"; 6590 return; 6591 } 6592 type = nullptr; 6593 mode = nullptr; 6594 user = nullptr; 6595 group = nullptr; 6596 size = nullptr; 6597 mtime = nullptr; 6598 name = nullptr; 6599 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){ 6600 const char *val = nullptr; 6601 xar_prop_get(xf, key, &val); 6602 #if 0 // Useful for debugging. 6603 outs() << "key: " << key << " value: " << val << "\n"; 6604 #endif 6605 if(strcmp(key, "type") == 0) 6606 type = val; 6607 if(strcmp(key, "mode") == 0) 6608 mode = val; 6609 if(strcmp(key, "user") == 0) 6610 user = val; 6611 if(strcmp(key, "group") == 0) 6612 group = val; 6613 if(strcmp(key, "data/size") == 0) 6614 size = val; 6615 if(strcmp(key, "mtime") == 0) 6616 mtime = val; 6617 if(strcmp(key, "name") == 0) 6618 name = val; 6619 } 6620 if(mode != nullptr){ 6621 mode_value = strtoul(mode, &endp, 8); 6622 if(*endp != '\0') 6623 outs() << "(mode: \"" << mode << "\" contains non-octal chars) "; 6624 if(strcmp(type, "file") == 0) 6625 mode_value |= S_IFREG; 6626 PrintModeVerbose(mode_value); 6627 outs() << " "; 6628 } 6629 if(user != nullptr) 6630 outs() << format("%10s/", user); 6631 if(group != nullptr) 6632 outs() << format("%-10s ", group); 6633 if(size != nullptr) 6634 outs() << format("%7s ", size); 6635 if(mtime != nullptr){ 6636 for(m = mtime; *m != 'T' && *m != '\0'; m++) 6637 outs() << *m; 6638 if(*m == 'T') 6639 m++; 6640 outs() << " "; 6641 for( ; *m != 'Z' && *m != '\0'; m++) 6642 outs() << *m; 6643 outs() << " "; 6644 } 6645 if(name != nullptr) 6646 outs() << name; 6647 outs() << "\n"; 6648 } 6649 } 6650 6651 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect, 6652 uint32_t size, bool verbose, 6653 bool PrintXarHeader, bool PrintXarFileHeaders, 6654 std::string XarMemberName) { 6655 if(size < sizeof(struct xar_header)) { 6656 outs() << "size of (__LLVM,__bundle) section too small (smaller than size " 6657 "of struct xar_header)\n"; 6658 return; 6659 } 6660 struct xar_header XarHeader; 6661 memcpy(&XarHeader, sect, sizeof(struct xar_header)); 6662 if (sys::IsLittleEndianHost) 6663 swapStruct(XarHeader); 6664 if (PrintXarHeader) { 6665 if (!XarMemberName.empty()) 6666 outs() << "In xar member " << XarMemberName << ": "; 6667 else 6668 outs() << "For (__LLVM,__bundle) section: "; 6669 outs() << "xar header\n"; 6670 if (XarHeader.magic == XAR_HEADER_MAGIC) 6671 outs() << " magic XAR_HEADER_MAGIC\n"; 6672 else 6673 outs() << " magic " 6674 << format_hex(XarHeader.magic, 10, true) 6675 << " (not XAR_HEADER_MAGIC)\n"; 6676 outs() << " size " << XarHeader.size << "\n"; 6677 outs() << " version " << XarHeader.version << "\n"; 6678 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed 6679 << "\n"; 6680 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed 6681 << "\n"; 6682 outs() << " cksum_alg "; 6683 switch (XarHeader.cksum_alg) { 6684 case XAR_CKSUM_NONE: 6685 outs() << "XAR_CKSUM_NONE\n"; 6686 break; 6687 case XAR_CKSUM_SHA1: 6688 outs() << "XAR_CKSUM_SHA1\n"; 6689 break; 6690 case XAR_CKSUM_MD5: 6691 outs() << "XAR_CKSUM_MD5\n"; 6692 break; 6693 #ifdef XAR_CKSUM_SHA256 6694 case XAR_CKSUM_SHA256: 6695 outs() << "XAR_CKSUM_SHA256\n"; 6696 break; 6697 #endif 6698 #ifdef XAR_CKSUM_SHA512 6699 case XAR_CKSUM_SHA512: 6700 outs() << "XAR_CKSUM_SHA512\n"; 6701 break; 6702 #endif 6703 default: 6704 outs() << XarHeader.cksum_alg << "\n"; 6705 } 6706 } 6707 6708 SmallString<128> XarFilename; 6709 int FD; 6710 std::error_code XarEC = 6711 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename); 6712 if (XarEC) { 6713 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n"; 6714 return; 6715 } 6716 ToolOutputFile XarFile(XarFilename, FD); 6717 raw_fd_ostream &XarOut = XarFile.os(); 6718 StringRef XarContents(sect, size); 6719 XarOut << XarContents; 6720 XarOut.close(); 6721 if (XarOut.has_error()) 6722 return; 6723 6724 ScopedXarFile xar(XarFilename.c_str(), READ); 6725 if (!xar) { 6726 WithColor::error(errs(), "llvm-objdump") 6727 << "can't create temporary xar archive " << XarFilename << "\n"; 6728 return; 6729 } 6730 6731 SmallString<128> TocFilename; 6732 std::error_code TocEC = 6733 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename); 6734 if (TocEC) { 6735 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n"; 6736 return; 6737 } 6738 xar_serialize(xar, TocFilename.c_str()); 6739 6740 if (PrintXarFileHeaders) { 6741 if (!XarMemberName.empty()) 6742 outs() << "In xar member " << XarMemberName << ": "; 6743 else 6744 outs() << "For (__LLVM,__bundle) section: "; 6745 outs() << "xar archive files:\n"; 6746 PrintXarFilesSummary(XarFilename.c_str(), xar); 6747 } 6748 6749 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr = 6750 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str()); 6751 if (std::error_code EC = FileOrErr.getError()) { 6752 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n"; 6753 return; 6754 } 6755 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get(); 6756 6757 if (!XarMemberName.empty()) 6758 outs() << "In xar member " << XarMemberName << ": "; 6759 else 6760 outs() << "For (__LLVM,__bundle) section: "; 6761 outs() << "xar table of contents:\n"; 6762 outs() << Buffer->getBuffer() << "\n"; 6763 6764 // TODO: Go through the xar's files. 6765 ScopedXarIter xi; 6766 if(!xi){ 6767 WithColor::error(errs(), "llvm-objdump") 6768 << "can't obtain an xar iterator for xar archive " 6769 << XarFilename.c_str() << "\n"; 6770 return; 6771 } 6772 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){ 6773 const char *key; 6774 const char *member_name, *member_type, *member_size_string; 6775 size_t member_size; 6776 6777 ScopedXarIter xp; 6778 if(!xp){ 6779 WithColor::error(errs(), "llvm-objdump") 6780 << "can't obtain an xar iterator for xar archive " 6781 << XarFilename.c_str() << "\n"; 6782 return; 6783 } 6784 member_name = NULL; 6785 member_type = NULL; 6786 member_size_string = NULL; 6787 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){ 6788 const char *val = nullptr; 6789 xar_prop_get(xf, key, &val); 6790 #if 0 // Useful for debugging. 6791 outs() << "key: " << key << " value: " << val << "\n"; 6792 #endif 6793 if (strcmp(key, "name") == 0) 6794 member_name = val; 6795 if (strcmp(key, "type") == 0) 6796 member_type = val; 6797 if (strcmp(key, "data/size") == 0) 6798 member_size_string = val; 6799 } 6800 /* 6801 * If we find a file with a name, date/size and type properties 6802 * and with the type being "file" see if that is a xar file. 6803 */ 6804 if (member_name != NULL && member_type != NULL && 6805 strcmp(member_type, "file") == 0 && 6806 member_size_string != NULL){ 6807 // Extract the file into a buffer. 6808 char *endptr; 6809 member_size = strtoul(member_size_string, &endptr, 10); 6810 if (*endptr == '\0' && member_size != 0) { 6811 char *buffer; 6812 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) { 6813 #if 0 // Useful for debugging. 6814 outs() << "xar member: " << member_name << " extracted\n"; 6815 #endif 6816 // Set the XarMemberName we want to see printed in the header. 6817 std::string OldXarMemberName; 6818 // If XarMemberName is already set this is nested. So 6819 // save the old name and create the nested name. 6820 if (!XarMemberName.empty()) { 6821 OldXarMemberName = XarMemberName; 6822 XarMemberName = 6823 (Twine("[") + XarMemberName + "]" + member_name).str(); 6824 } else { 6825 OldXarMemberName = ""; 6826 XarMemberName = member_name; 6827 } 6828 // See if this is could be a xar file (nested). 6829 if (member_size >= sizeof(struct xar_header)) { 6830 #if 0 // Useful for debugging. 6831 outs() << "could be a xar file: " << member_name << "\n"; 6832 #endif 6833 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header)); 6834 if (sys::IsLittleEndianHost) 6835 swapStruct(XarHeader); 6836 if (XarHeader.magic == XAR_HEADER_MAGIC) 6837 DumpBitcodeSection(O, buffer, member_size, verbose, 6838 PrintXarHeader, PrintXarFileHeaders, 6839 XarMemberName); 6840 } 6841 XarMemberName = OldXarMemberName; 6842 delete buffer; 6843 } 6844 } 6845 } 6846 } 6847 } 6848 #endif // defined(LLVM_HAVE_LIBXAR) 6849 6850 static void printObjcMetaData(MachOObjectFile *O, bool verbose) { 6851 if (O->is64Bit()) 6852 printObjc2_64bit_MetaData(O, verbose); 6853 else { 6854 MachO::mach_header H; 6855 H = O->getHeader(); 6856 if (H.cputype == MachO::CPU_TYPE_ARM) 6857 printObjc2_32bit_MetaData(O, verbose); 6858 else { 6859 // This is the 32-bit non-arm cputype case. Which is normally 6860 // the first Objective-C ABI. But it may be the case of a 6861 // binary for the iOS simulator which is the second Objective-C 6862 // ABI. In that case printObjc1_32bit_MetaData() will determine that 6863 // and return false. 6864 if (!printObjc1_32bit_MetaData(O, verbose)) 6865 printObjc2_32bit_MetaData(O, verbose); 6866 } 6867 } 6868 } 6869 6870 // GuessLiteralPointer returns a string which for the item in the Mach-O file 6871 // for the address passed in as ReferenceValue for printing as a comment with 6872 // the instruction and also returns the corresponding type of that item 6873 // indirectly through ReferenceType. 6874 // 6875 // If ReferenceValue is an address of literal cstring then a pointer to the 6876 // cstring is returned and ReferenceType is set to 6877 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr . 6878 // 6879 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or 6880 // Class ref that name is returned and the ReferenceType is set accordingly. 6881 // 6882 // Lastly, literals which are Symbol address in a literal pool are looked for 6883 // and if found the symbol name is returned and ReferenceType is set to 6884 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr . 6885 // 6886 // If there is no item in the Mach-O file for the address passed in as 6887 // ReferenceValue nullptr is returned and ReferenceType is unchanged. 6888 static const char *GuessLiteralPointer(uint64_t ReferenceValue, 6889 uint64_t ReferencePC, 6890 uint64_t *ReferenceType, 6891 struct DisassembleInfo *info) { 6892 // First see if there is an external relocation entry at the ReferencePC. 6893 if (info->O->getHeader().filetype == MachO::MH_OBJECT) { 6894 uint64_t sect_addr = info->S.getAddress(); 6895 uint64_t sect_offset = ReferencePC - sect_addr; 6896 bool reloc_found = false; 6897 DataRefImpl Rel; 6898 MachO::any_relocation_info RE; 6899 bool isExtern = false; 6900 SymbolRef Symbol; 6901 for (const RelocationRef &Reloc : info->S.relocations()) { 6902 uint64_t RelocOffset = Reloc.getOffset(); 6903 if (RelocOffset == sect_offset) { 6904 Rel = Reloc.getRawDataRefImpl(); 6905 RE = info->O->getRelocation(Rel); 6906 if (info->O->isRelocationScattered(RE)) 6907 continue; 6908 isExtern = info->O->getPlainRelocationExternal(RE); 6909 if (isExtern) { 6910 symbol_iterator RelocSym = Reloc.getSymbol(); 6911 Symbol = *RelocSym; 6912 } 6913 reloc_found = true; 6914 break; 6915 } 6916 } 6917 // If there is an external relocation entry for a symbol in a section 6918 // then used that symbol's value for the value of the reference. 6919 if (reloc_found && isExtern) { 6920 if (info->O->getAnyRelocationPCRel(RE)) { 6921 unsigned Type = info->O->getAnyRelocationType(RE); 6922 if (Type == MachO::X86_64_RELOC_SIGNED) { 6923 ReferenceValue = cantFail(Symbol.getValue()); 6924 } 6925 } 6926 } 6927 } 6928 6929 // Look for literals such as Objective-C CFStrings refs, Selector refs, 6930 // Message refs and Class refs. 6931 bool classref, selref, msgref, cfstring; 6932 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref, 6933 selref, msgref, cfstring); 6934 if (classref && pointer_value == 0) { 6935 // Note the ReferenceValue is a pointer into the __objc_classrefs section. 6936 // And the pointer_value in that section is typically zero as it will be 6937 // set by dyld as part of the "bind information". 6938 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info); 6939 if (name != nullptr) { 6940 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; 6941 const char *class_name = strrchr(name, '$'); 6942 if (class_name != nullptr && class_name[1] == '_' && 6943 class_name[2] != '\0') { 6944 info->class_name = class_name + 2; 6945 return name; 6946 } 6947 } 6948 } 6949 6950 if (classref) { 6951 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref; 6952 const char *name = 6953 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info); 6954 if (name != nullptr) 6955 info->class_name = name; 6956 else 6957 name = "bad class ref"; 6958 return name; 6959 } 6960 6961 if (cfstring) { 6962 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref; 6963 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info); 6964 return name; 6965 } 6966 6967 if (selref && pointer_value == 0) 6968 pointer_value = get_objc2_64bit_selref(ReferenceValue, info); 6969 6970 if (pointer_value != 0) 6971 ReferenceValue = pointer_value; 6972 6973 const char *name = GuessCstringPointer(ReferenceValue, info); 6974 if (name) { 6975 if (pointer_value != 0 && selref) { 6976 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref; 6977 info->selector_name = name; 6978 } else if (pointer_value != 0 && msgref) { 6979 info->class_name = nullptr; 6980 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref; 6981 info->selector_name = name; 6982 } else 6983 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr; 6984 return name; 6985 } 6986 6987 // Lastly look for an indirect symbol with this ReferenceValue which is in 6988 // a literal pool. If found return that symbol name. 6989 name = GuessIndirectSymbol(ReferenceValue, info); 6990 if (name) { 6991 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr; 6992 return name; 6993 } 6994 6995 return nullptr; 6996 } 6997 6998 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating 6999 // the Symbolizer. It looks up the ReferenceValue using the info passed via the 7000 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer 7001 // is created and returns the symbol name that matches the ReferenceValue or 7002 // nullptr if none. The ReferenceType is passed in for the IN type of 7003 // reference the instruction is making from the values in defined in the header 7004 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific 7005 // Out type and the ReferenceName will also be set which is added as a comment 7006 // to the disassembled instruction. 7007 // 7008 // If the symbol name is a C++ mangled name then the demangled name is 7009 // returned through ReferenceName and ReferenceType is set to 7010 // LLVMDisassembler_ReferenceType_DeMangled_Name . 7011 // 7012 // When this is called to get a symbol name for a branch target then the 7013 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then 7014 // SymbolValue will be looked for in the indirect symbol table to determine if 7015 // it is an address for a symbol stub. If so then the symbol name for that 7016 // stub is returned indirectly through ReferenceName and then ReferenceType is 7017 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub. 7018 // 7019 // When this is called with an value loaded via a PC relative load then 7020 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the 7021 // SymbolValue is checked to be an address of literal pointer, symbol pointer, 7022 // or an Objective-C meta data reference. If so the output ReferenceType is 7023 // set to correspond to that as well as setting the ReferenceName. 7024 static const char *SymbolizerSymbolLookUp(void *DisInfo, 7025 uint64_t ReferenceValue, 7026 uint64_t *ReferenceType, 7027 uint64_t ReferencePC, 7028 const char **ReferenceName) { 7029 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo; 7030 // If no verbose symbolic information is wanted then just return nullptr. 7031 if (!info->verbose) { 7032 *ReferenceName = nullptr; 7033 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7034 return nullptr; 7035 } 7036 7037 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap); 7038 7039 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) { 7040 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info); 7041 if (*ReferenceName != nullptr) { 7042 method_reference(info, ReferenceType, ReferenceName); 7043 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message) 7044 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub; 7045 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { 7046 if (info->demangled_name != nullptr) 7047 free(info->demangled_name); 7048 int status; 7049 info->demangled_name = 7050 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status); 7051 if (info->demangled_name != nullptr) { 7052 *ReferenceName = info->demangled_name; 7053 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; 7054 } else 7055 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7056 } else 7057 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7058 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) { 7059 *ReferenceName = 7060 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7061 if (*ReferenceName) 7062 method_reference(info, ReferenceType, ReferenceName); 7063 else 7064 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7065 // If this is arm64 and the reference is an adrp instruction save the 7066 // instruction, passed in ReferenceValue and the address of the instruction 7067 // for use later if we see and add immediate instruction. 7068 } else if (info->O->getArch() == Triple::aarch64 && 7069 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) { 7070 info->adrp_inst = ReferenceValue; 7071 info->adrp_addr = ReferencePC; 7072 SymbolName = nullptr; 7073 *ReferenceName = nullptr; 7074 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7075 // If this is arm64 and reference is an add immediate instruction and we 7076 // have 7077 // seen an adrp instruction just before it and the adrp's Xd register 7078 // matches 7079 // this add's Xn register reconstruct the value being referenced and look to 7080 // see if it is a literal pointer. Note the add immediate instruction is 7081 // passed in ReferenceValue. 7082 } else if (info->O->getArch() == Triple::aarch64 && 7083 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri && 7084 ReferencePC - 4 == info->adrp_addr && 7085 (info->adrp_inst & 0x9f000000) == 0x90000000 && 7086 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { 7087 uint32_t addxri_inst; 7088 uint64_t adrp_imm, addxri_imm; 7089 7090 adrp_imm = 7091 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); 7092 if (info->adrp_inst & 0x0200000) 7093 adrp_imm |= 0xfffffffffc000000LL; 7094 7095 addxri_inst = ReferenceValue; 7096 addxri_imm = (addxri_inst >> 10) & 0xfff; 7097 if (((addxri_inst >> 22) & 0x3) == 1) 7098 addxri_imm <<= 12; 7099 7100 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + 7101 (adrp_imm << 12) + addxri_imm; 7102 7103 *ReferenceName = 7104 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7105 if (*ReferenceName == nullptr) 7106 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7107 // If this is arm64 and the reference is a load register instruction and we 7108 // have seen an adrp instruction just before it and the adrp's Xd register 7109 // matches this add's Xn register reconstruct the value being referenced and 7110 // look to see if it is a literal pointer. Note the load register 7111 // instruction is passed in ReferenceValue. 7112 } else if (info->O->getArch() == Triple::aarch64 && 7113 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui && 7114 ReferencePC - 4 == info->adrp_addr && 7115 (info->adrp_inst & 0x9f000000) == 0x90000000 && 7116 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) { 7117 uint32_t ldrxui_inst; 7118 uint64_t adrp_imm, ldrxui_imm; 7119 7120 adrp_imm = 7121 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3); 7122 if (info->adrp_inst & 0x0200000) 7123 adrp_imm |= 0xfffffffffc000000LL; 7124 7125 ldrxui_inst = ReferenceValue; 7126 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff; 7127 7128 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) + 7129 (adrp_imm << 12) + (ldrxui_imm << 3); 7130 7131 *ReferenceName = 7132 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7133 if (*ReferenceName == nullptr) 7134 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7135 } 7136 // If this arm64 and is an load register (PC-relative) instruction the 7137 // ReferenceValue is the PC plus the immediate value. 7138 else if (info->O->getArch() == Triple::aarch64 && 7139 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl || 7140 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) { 7141 *ReferenceName = 7142 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info); 7143 if (*ReferenceName == nullptr) 7144 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7145 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) { 7146 if (info->demangled_name != nullptr) 7147 free(info->demangled_name); 7148 int status; 7149 info->demangled_name = 7150 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status); 7151 if (info->demangled_name != nullptr) { 7152 *ReferenceName = info->demangled_name; 7153 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name; 7154 } 7155 } 7156 else { 7157 *ReferenceName = nullptr; 7158 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None; 7159 } 7160 7161 return SymbolName; 7162 } 7163 7164 /// Emits the comments that are stored in the CommentStream. 7165 /// Each comment in the CommentStream must end with a newline. 7166 static void emitComments(raw_svector_ostream &CommentStream, 7167 SmallString<128> &CommentsToEmit, 7168 formatted_raw_ostream &FormattedOS, 7169 const MCAsmInfo &MAI) { 7170 // Flush the stream before taking its content. 7171 StringRef Comments = CommentsToEmit.str(); 7172 // Get the default information for printing a comment. 7173 StringRef CommentBegin = MAI.getCommentString(); 7174 unsigned CommentColumn = MAI.getCommentColumn(); 7175 ListSeparator LS("\n"); 7176 while (!Comments.empty()) { 7177 FormattedOS << LS; 7178 // Emit a line of comments. 7179 FormattedOS.PadToColumn(CommentColumn); 7180 size_t Position = Comments.find('\n'); 7181 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position); 7182 // Move after the newline character. 7183 Comments = Comments.substr(Position + 1); 7184 } 7185 FormattedOS.flush(); 7186 7187 // Tell the comment stream that the vector changed underneath it. 7188 CommentsToEmit.clear(); 7189 } 7190 7191 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF, 7192 StringRef DisSegName, StringRef DisSectName) { 7193 const char *McpuDefault = nullptr; 7194 const Target *ThumbTarget = nullptr; 7195 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget); 7196 if (!TheTarget) { 7197 // GetTarget prints out stuff. 7198 return; 7199 } 7200 std::string MachOMCPU; 7201 if (MCPU.empty() && McpuDefault) 7202 MachOMCPU = McpuDefault; 7203 else 7204 MachOMCPU = MCPU; 7205 7206 #define CHECK_TARGET_INFO_CREATION(NAME) \ 7207 do { \ 7208 if (!NAME) { \ 7209 WithColor::error(errs(), "llvm-objdump") \ 7210 << "couldn't initialize disassembler for target " << TripleName \ 7211 << '\n'; \ 7212 return; \ 7213 } \ 7214 } while (false) 7215 #define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \ 7216 do { \ 7217 if (!NAME) { \ 7218 WithColor::error(errs(), "llvm-objdump") \ 7219 << "couldn't initialize disassembler for target " << ThumbTripleName \ 7220 << '\n'; \ 7221 return; \ 7222 } \ 7223 } while (false) 7224 7225 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo()); 7226 CHECK_TARGET_INFO_CREATION(InstrInfo); 7227 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo; 7228 if (ThumbTarget) { 7229 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo()); 7230 CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo); 7231 } 7232 7233 // Package up features to be passed to target/subtarget 7234 std::string FeaturesStr; 7235 if (!MAttrs.empty()) { 7236 SubtargetFeatures Features; 7237 for (unsigned i = 0; i != MAttrs.size(); ++i) 7238 Features.AddFeature(MAttrs[i]); 7239 FeaturesStr = Features.getString(); 7240 } 7241 7242 MCTargetOptions MCOptions; 7243 // Set up disassembler. 7244 std::unique_ptr<const MCRegisterInfo> MRI( 7245 TheTarget->createMCRegInfo(TripleName)); 7246 CHECK_TARGET_INFO_CREATION(MRI); 7247 std::unique_ptr<const MCAsmInfo> AsmInfo( 7248 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 7249 CHECK_TARGET_INFO_CREATION(AsmInfo); 7250 std::unique_ptr<const MCSubtargetInfo> STI( 7251 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr)); 7252 CHECK_TARGET_INFO_CREATION(STI); 7253 MCContext Ctx(Triple(TripleName), AsmInfo.get(), MRI.get(), STI.get()); 7254 std::unique_ptr<MCDisassembler> DisAsm( 7255 TheTarget->createMCDisassembler(*STI, Ctx)); 7256 CHECK_TARGET_INFO_CREATION(DisAsm); 7257 std::unique_ptr<MCSymbolizer> Symbolizer; 7258 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false); 7259 std::unique_ptr<MCRelocationInfo> RelInfo( 7260 TheTarget->createMCRelocationInfo(TripleName, Ctx)); 7261 if (RelInfo) { 7262 Symbolizer.reset(TheTarget->createMCSymbolizer( 7263 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, 7264 &SymbolizerInfo, &Ctx, std::move(RelInfo))); 7265 DisAsm->setSymbolizer(std::move(Symbolizer)); 7266 } 7267 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 7268 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 7269 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI)); 7270 CHECK_TARGET_INFO_CREATION(IP); 7271 // Set the display preference for hex vs. decimal immediates. 7272 IP->setPrintImmHex(PrintImmHex); 7273 // Comment stream and backing vector. 7274 SmallString<128> CommentsToEmit; 7275 raw_svector_ostream CommentStream(CommentsToEmit); 7276 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that 7277 // if it is done then arm64 comments for string literals don't get printed 7278 // and some constant get printed instead and not setting it causes intel 7279 // (32-bit and 64-bit) comments printed with different spacing before the 7280 // comment causing different diffs with the 'C' disassembler library API. 7281 // IP->setCommentStream(CommentStream); 7282 7283 // Set up separate thumb disassembler if needed. 7284 std::unique_ptr<const MCRegisterInfo> ThumbMRI; 7285 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo; 7286 std::unique_ptr<const MCSubtargetInfo> ThumbSTI; 7287 std::unique_ptr<MCDisassembler> ThumbDisAsm; 7288 std::unique_ptr<MCInstPrinter> ThumbIP; 7289 std::unique_ptr<MCContext> ThumbCtx; 7290 std::unique_ptr<MCSymbolizer> ThumbSymbolizer; 7291 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false); 7292 std::unique_ptr<MCRelocationInfo> ThumbRelInfo; 7293 if (ThumbTarget) { 7294 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName)); 7295 CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI); 7296 ThumbAsmInfo.reset( 7297 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions)); 7298 CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo); 7299 ThumbSTI.reset( 7300 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU, 7301 FeaturesStr)); 7302 CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI); 7303 ThumbCtx.reset(new MCContext(Triple(ThumbTripleName), ThumbAsmInfo.get(), 7304 ThumbMRI.get(), ThumbSTI.get())); 7305 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx)); 7306 CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm); 7307 MCContext *PtrThumbCtx = ThumbCtx.get(); 7308 ThumbRelInfo.reset( 7309 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx)); 7310 if (ThumbRelInfo) { 7311 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer( 7312 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp, 7313 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo))); 7314 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer)); 7315 } 7316 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect(); 7317 ThumbIP.reset(ThumbTarget->createMCInstPrinter( 7318 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo, 7319 *ThumbInstrInfo, *ThumbMRI)); 7320 CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP); 7321 // Set the display preference for hex vs. decimal immediates. 7322 ThumbIP->setPrintImmHex(PrintImmHex); 7323 } 7324 7325 #undef CHECK_TARGET_INFO_CREATION 7326 #undef CHECK_THUMB_TARGET_INFO_CREATION 7327 7328 MachO::mach_header Header = MachOOF->getHeader(); 7329 7330 // FIXME: Using the -cfg command line option, this code used to be able to 7331 // annotate relocations with the referenced symbol's name, and if this was 7332 // inside a __[cf]string section, the data it points to. This is now replaced 7333 // by the upcoming MCSymbolizer, which needs the appropriate setup done above. 7334 std::vector<SectionRef> Sections; 7335 std::vector<SymbolRef> Symbols; 7336 SmallVector<uint64_t, 8> FoundFns; 7337 uint64_t BaseSegmentAddress = 0; 7338 7339 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns, 7340 BaseSegmentAddress); 7341 7342 // Sort the symbols by address, just in case they didn't come in that way. 7343 llvm::stable_sort(Symbols, SymbolSorter()); 7344 7345 // Build a data in code table that is sorted on by the address of each entry. 7346 uint64_t BaseAddress = 0; 7347 if (Header.filetype == MachO::MH_OBJECT) 7348 BaseAddress = Sections[0].getAddress(); 7349 else 7350 BaseAddress = BaseSegmentAddress; 7351 DiceTable Dices; 7352 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices(); 7353 DI != DE; ++DI) { 7354 uint32_t Offset; 7355 DI->getOffset(Offset); 7356 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI)); 7357 } 7358 array_pod_sort(Dices.begin(), Dices.end()); 7359 7360 // Try to find debug info and set up the DIContext for it. 7361 std::unique_ptr<DIContext> diContext; 7362 std::unique_ptr<Binary> DSYMBinary; 7363 std::unique_ptr<MemoryBuffer> DSYMBuf; 7364 if (UseDbg) { 7365 ObjectFile *DbgObj = MachOOF; 7366 7367 // A separate DSym file path was specified, parse it as a macho file, 7368 // get the sections and supply it to the section name parsing machinery. 7369 if (!DSYMFile.empty()) { 7370 std::string DSYMPath(DSYMFile); 7371 7372 // If DSYMPath is a .dSYM directory, append the Mach-O file. 7373 if (llvm::sys::fs::is_directory(DSYMPath) && 7374 llvm::sys::path::extension(DSYMPath) == ".dSYM") { 7375 SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath)); 7376 llvm::sys::path::replace_extension(ShortName, ""); 7377 SmallString<1024> FullPath(DSYMPath); 7378 llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF", 7379 ShortName); 7380 DSYMPath = std::string(FullPath.str()); 7381 } 7382 7383 // Load the file. 7384 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = 7385 MemoryBuffer::getFileOrSTDIN(DSYMPath); 7386 if (std::error_code EC = BufOrErr.getError()) { 7387 reportError(errorCodeToError(EC), DSYMPath); 7388 return; 7389 } 7390 7391 // We need to keep the file alive, because we're replacing DbgObj with it. 7392 DSYMBuf = std::move(BufOrErr.get()); 7393 7394 Expected<std::unique_ptr<Binary>> BinaryOrErr = 7395 createBinary(DSYMBuf.get()->getMemBufferRef()); 7396 if (!BinaryOrErr) { 7397 reportError(BinaryOrErr.takeError(), DSYMPath); 7398 return; 7399 } 7400 7401 // We need to keep the Binary alive with the buffer 7402 DSYMBinary = std::move(BinaryOrErr.get()); 7403 if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) { 7404 // this is a Mach-O object file, use it 7405 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) { 7406 DbgObj = MachDSYM; 7407 } 7408 else { 7409 WithColor::error(errs(), "llvm-objdump") 7410 << DSYMPath << " is not a Mach-O file type.\n"; 7411 return; 7412 } 7413 } 7414 else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){ 7415 // this is a Universal Binary, find a Mach-O for this architecture 7416 uint32_t CPUType, CPUSubType; 7417 const char *ArchFlag; 7418 if (MachOOF->is64Bit()) { 7419 const MachO::mach_header_64 H_64 = MachOOF->getHeader64(); 7420 CPUType = H_64.cputype; 7421 CPUSubType = H_64.cpusubtype; 7422 } else { 7423 const MachO::mach_header H = MachOOF->getHeader(); 7424 CPUType = H.cputype; 7425 CPUSubType = H.cpusubtype; 7426 } 7427 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr, 7428 &ArchFlag); 7429 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM = 7430 UB->getMachOObjectForArch(ArchFlag); 7431 if (!MachDSYM) { 7432 reportError(MachDSYM.takeError(), DSYMPath); 7433 return; 7434 } 7435 7436 // We need to keep the Binary alive with the buffer 7437 DbgObj = &*MachDSYM.get(); 7438 DSYMBinary = std::move(*MachDSYM); 7439 } 7440 else { 7441 WithColor::error(errs(), "llvm-objdump") 7442 << DSYMPath << " is not a Mach-O or Universal file type.\n"; 7443 return; 7444 } 7445 } 7446 7447 // Setup the DIContext 7448 diContext = DWARFContext::create(*DbgObj); 7449 } 7450 7451 if (FilterSections.empty()) 7452 outs() << "(" << DisSegName << "," << DisSectName << ") section\n"; 7453 7454 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) { 7455 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName(); 7456 if (!SecNameOrErr) { 7457 consumeError(SecNameOrErr.takeError()); 7458 continue; 7459 } 7460 if (*SecNameOrErr != DisSectName) 7461 continue; 7462 7463 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl(); 7464 7465 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR); 7466 if (SegmentName != DisSegName) 7467 continue; 7468 7469 StringRef BytesStr = 7470 unwrapOrError(Sections[SectIdx].getContents(), Filename); 7471 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr); 7472 uint64_t SectAddress = Sections[SectIdx].getAddress(); 7473 7474 bool symbolTableWorked = false; 7475 7476 // Create a map of symbol addresses to symbol names for use by 7477 // the SymbolizerSymbolLookUp() routine. 7478 SymbolAddressMap AddrMap; 7479 bool DisSymNameFound = false; 7480 for (const SymbolRef &Symbol : MachOOF->symbols()) { 7481 SymbolRef::Type ST = 7482 unwrapOrError(Symbol.getType(), MachOOF->getFileName()); 7483 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data || 7484 ST == SymbolRef::ST_Other) { 7485 uint64_t Address = cantFail(Symbol.getValue()); 7486 StringRef SymName = 7487 unwrapOrError(Symbol.getName(), MachOOF->getFileName()); 7488 AddrMap[Address] = SymName; 7489 if (!DisSymName.empty() && DisSymName == SymName) 7490 DisSymNameFound = true; 7491 } 7492 } 7493 if (!DisSymName.empty() && !DisSymNameFound) { 7494 outs() << "Can't find -dis-symname: " << DisSymName << "\n"; 7495 return; 7496 } 7497 // Set up the block of info used by the Symbolizer call backs. 7498 SymbolizerInfo.verbose = SymbolicOperands; 7499 SymbolizerInfo.O = MachOOF; 7500 SymbolizerInfo.S = Sections[SectIdx]; 7501 SymbolizerInfo.AddrMap = &AddrMap; 7502 SymbolizerInfo.Sections = &Sections; 7503 // Same for the ThumbSymbolizer 7504 ThumbSymbolizerInfo.verbose = SymbolicOperands; 7505 ThumbSymbolizerInfo.O = MachOOF; 7506 ThumbSymbolizerInfo.S = Sections[SectIdx]; 7507 ThumbSymbolizerInfo.AddrMap = &AddrMap; 7508 ThumbSymbolizerInfo.Sections = &Sections; 7509 7510 unsigned int Arch = MachOOF->getArch(); 7511 7512 // Skip all symbols if this is a stubs file. 7513 if (Bytes.empty()) 7514 return; 7515 7516 // If the section has symbols but no symbol at the start of the section 7517 // these are used to make sure the bytes before the first symbol are 7518 // disassembled. 7519 bool FirstSymbol = true; 7520 bool FirstSymbolAtSectionStart = true; 7521 7522 // Disassemble symbol by symbol. 7523 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) { 7524 StringRef SymName = 7525 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName()); 7526 SymbolRef::Type ST = 7527 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName()); 7528 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data) 7529 continue; 7530 7531 // Make sure the symbol is defined in this section. 7532 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]); 7533 if (!containsSym) { 7534 if (!DisSymName.empty() && DisSymName == SymName) { 7535 outs() << "-dis-symname: " << DisSymName << " not in the section\n"; 7536 return; 7537 } 7538 continue; 7539 } 7540 // The __mh_execute_header is special and we need to deal with that fact 7541 // this symbol is before the start of the (__TEXT,__text) section and at the 7542 // address of the start of the __TEXT segment. This is because this symbol 7543 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the 7544 // start of the section in a standard MH_EXECUTE filetype. 7545 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") { 7546 outs() << "-dis-symname: __mh_execute_header not in any section\n"; 7547 return; 7548 } 7549 // When this code is trying to disassemble a symbol at a time and in the 7550 // case there is only the __mh_execute_header symbol left as in a stripped 7551 // executable, we need to deal with this by ignoring this symbol so the 7552 // whole section is disassembled and this symbol is then not displayed. 7553 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" || 7554 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" || 7555 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header") 7556 continue; 7557 7558 // If we are only disassembling one symbol see if this is that symbol. 7559 if (!DisSymName.empty() && DisSymName != SymName) 7560 continue; 7561 7562 // Start at the address of the symbol relative to the section's address. 7563 uint64_t SectSize = Sections[SectIdx].getSize(); 7564 uint64_t Start = cantFail(Symbols[SymIdx].getValue()); 7565 uint64_t SectionAddress = Sections[SectIdx].getAddress(); 7566 Start -= SectionAddress; 7567 7568 if (Start > SectSize) { 7569 outs() << "section data ends, " << SymName 7570 << " lies outside valid range\n"; 7571 return; 7572 } 7573 7574 // Stop disassembling either at the beginning of the next symbol or at 7575 // the end of the section. 7576 bool containsNextSym = false; 7577 uint64_t NextSym = 0; 7578 uint64_t NextSymIdx = SymIdx + 1; 7579 while (Symbols.size() > NextSymIdx) { 7580 SymbolRef::Type NextSymType = unwrapOrError( 7581 Symbols[NextSymIdx].getType(), MachOOF->getFileName()); 7582 if (NextSymType == SymbolRef::ST_Function) { 7583 containsNextSym = 7584 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]); 7585 NextSym = cantFail(Symbols[NextSymIdx].getValue()); 7586 NextSym -= SectionAddress; 7587 break; 7588 } 7589 ++NextSymIdx; 7590 } 7591 7592 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize; 7593 uint64_t Size; 7594 7595 symbolTableWorked = true; 7596 7597 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl(); 7598 uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb)); 7599 bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb; 7600 7601 // We only need the dedicated Thumb target if there's a real choice 7602 // (i.e. we're not targeting M-class) and the function is Thumb. 7603 bool UseThumbTarget = IsThumb && ThumbTarget; 7604 7605 // If we are not specifying a symbol to start disassembly with and this 7606 // is the first symbol in the section but not at the start of the section 7607 // then move the disassembly index to the start of the section and 7608 // don't print the symbol name just yet. This is so the bytes before the 7609 // first symbol are disassembled. 7610 uint64_t SymbolStart = Start; 7611 if (DisSymName.empty() && FirstSymbol && Start != 0) { 7612 FirstSymbolAtSectionStart = false; 7613 Start = 0; 7614 } 7615 else 7616 outs() << SymName << ":\n"; 7617 7618 DILineInfo lastLine; 7619 for (uint64_t Index = Start; Index < End; Index += Size) { 7620 MCInst Inst; 7621 7622 // If this is the first symbol in the section and it was not at the 7623 // start of the section, see if we are at its Index now and if so print 7624 // the symbol name. 7625 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart) 7626 outs() << SymName << ":\n"; 7627 7628 uint64_t PC = SectAddress + Index; 7629 if (LeadingAddr) { 7630 if (FullLeadingAddr) { 7631 if (MachOOF->is64Bit()) 7632 outs() << format("%016" PRIx64, PC); 7633 else 7634 outs() << format("%08" PRIx64, PC); 7635 } else { 7636 outs() << format("%8" PRIx64 ":", PC); 7637 } 7638 } 7639 if (ShowRawInsn || Arch == Triple::arm) 7640 outs() << "\t"; 7641 7642 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size)) 7643 continue; 7644 7645 SmallVector<char, 64> AnnotationsBytes; 7646 raw_svector_ostream Annotations(AnnotationsBytes); 7647 7648 bool gotInst; 7649 if (UseThumbTarget) 7650 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index), 7651 PC, Annotations); 7652 else 7653 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC, 7654 Annotations); 7655 if (gotInst) { 7656 if (ShowRawInsn || Arch == Triple::arm) { 7657 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs()); 7658 } 7659 formatted_raw_ostream FormattedOS(outs()); 7660 StringRef AnnotationsStr = Annotations.str(); 7661 if (UseThumbTarget) 7662 ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI, 7663 FormattedOS); 7664 else 7665 IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS); 7666 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo); 7667 7668 // Print debug info. 7669 if (diContext) { 7670 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx}); 7671 // Print valid line info if it changed. 7672 if (dli != lastLine && dli.Line != 0) 7673 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':' 7674 << dli.Column; 7675 lastLine = dli; 7676 } 7677 outs() << "\n"; 7678 } else { 7679 if (MachOOF->getArchTriple().isX86()) { 7680 outs() << format("\t.byte 0x%02x #bad opcode\n", 7681 *(Bytes.data() + Index) & 0xff); 7682 Size = 1; // skip exactly one illegible byte and move on. 7683 } else if (Arch == Triple::aarch64 || 7684 (Arch == Triple::arm && !IsThumb)) { 7685 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | 7686 (*(Bytes.data() + Index + 1) & 0xff) << 8 | 7687 (*(Bytes.data() + Index + 2) & 0xff) << 16 | 7688 (*(Bytes.data() + Index + 3) & 0xff) << 24; 7689 outs() << format("\t.long\t0x%08x\n", opcode); 7690 Size = 4; 7691 } else if (Arch == Triple::arm) { 7692 assert(IsThumb && "ARM mode should have been dealt with above"); 7693 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) | 7694 (*(Bytes.data() + Index + 1) & 0xff) << 8; 7695 outs() << format("\t.short\t0x%04x\n", opcode); 7696 Size = 2; 7697 } else{ 7698 WithColor::warning(errs(), "llvm-objdump") 7699 << "invalid instruction encoding\n"; 7700 if (Size == 0) 7701 Size = 1; // skip illegible bytes 7702 } 7703 } 7704 } 7705 // Now that we are done disassembled the first symbol set the bool that 7706 // were doing this to false. 7707 FirstSymbol = false; 7708 } 7709 if (!symbolTableWorked) { 7710 // Reading the symbol table didn't work, disassemble the whole section. 7711 uint64_t SectAddress = Sections[SectIdx].getAddress(); 7712 uint64_t SectSize = Sections[SectIdx].getSize(); 7713 uint64_t InstSize; 7714 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) { 7715 MCInst Inst; 7716 7717 uint64_t PC = SectAddress + Index; 7718 7719 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize)) 7720 continue; 7721 7722 SmallVector<char, 64> AnnotationsBytes; 7723 raw_svector_ostream Annotations(AnnotationsBytes); 7724 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC, 7725 Annotations)) { 7726 if (LeadingAddr) { 7727 if (FullLeadingAddr) { 7728 if (MachOOF->is64Bit()) 7729 outs() << format("%016" PRIx64, PC); 7730 else 7731 outs() << format("%08" PRIx64, PC); 7732 } else { 7733 outs() << format("%8" PRIx64 ":", PC); 7734 } 7735 } 7736 if (ShowRawInsn || Arch == Triple::arm) { 7737 outs() << "\t"; 7738 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs()); 7739 } 7740 StringRef AnnotationsStr = Annotations.str(); 7741 IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs()); 7742 outs() << "\n"; 7743 } else { 7744 if (MachOOF->getArchTriple().isX86()) { 7745 outs() << format("\t.byte 0x%02x #bad opcode\n", 7746 *(Bytes.data() + Index) & 0xff); 7747 InstSize = 1; // skip exactly one illegible byte and move on. 7748 } else { 7749 WithColor::warning(errs(), "llvm-objdump") 7750 << "invalid instruction encoding\n"; 7751 if (InstSize == 0) 7752 InstSize = 1; // skip illegible bytes 7753 } 7754 } 7755 } 7756 } 7757 // The TripleName's need to be reset if we are called again for a different 7758 // architecture. 7759 TripleName = ""; 7760 ThumbTripleName = ""; 7761 7762 if (SymbolizerInfo.demangled_name != nullptr) 7763 free(SymbolizerInfo.demangled_name); 7764 if (ThumbSymbolizerInfo.demangled_name != nullptr) 7765 free(ThumbSymbolizerInfo.demangled_name); 7766 } 7767 } 7768 7769 //===----------------------------------------------------------------------===// 7770 // __compact_unwind section dumping 7771 //===----------------------------------------------------------------------===// 7772 7773 namespace { 7774 7775 template <typename T> 7776 static uint64_t read(StringRef Contents, ptrdiff_t Offset) { 7777 using llvm::support::little; 7778 using llvm::support::unaligned; 7779 7780 if (Offset + sizeof(T) > Contents.size()) { 7781 outs() << "warning: attempt to read past end of buffer\n"; 7782 return T(); 7783 } 7784 7785 uint64_t Val = 7786 support::endian::read<T, little, unaligned>(Contents.data() + Offset); 7787 return Val; 7788 } 7789 7790 template <typename T> 7791 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) { 7792 T Val = read<T>(Contents, Offset); 7793 Offset += sizeof(T); 7794 return Val; 7795 } 7796 7797 struct CompactUnwindEntry { 7798 uint32_t OffsetInSection; 7799 7800 uint64_t FunctionAddr; 7801 uint32_t Length; 7802 uint32_t CompactEncoding; 7803 uint64_t PersonalityAddr; 7804 uint64_t LSDAAddr; 7805 7806 RelocationRef FunctionReloc; 7807 RelocationRef PersonalityReloc; 7808 RelocationRef LSDAReloc; 7809 7810 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64) 7811 : OffsetInSection(Offset) { 7812 if (Is64) 7813 read<uint64_t>(Contents, Offset); 7814 else 7815 read<uint32_t>(Contents, Offset); 7816 } 7817 7818 private: 7819 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) { 7820 FunctionAddr = readNext<UIntPtr>(Contents, Offset); 7821 Length = readNext<uint32_t>(Contents, Offset); 7822 CompactEncoding = readNext<uint32_t>(Contents, Offset); 7823 PersonalityAddr = readNext<UIntPtr>(Contents, Offset); 7824 LSDAAddr = readNext<UIntPtr>(Contents, Offset); 7825 } 7826 }; 7827 } 7828 7829 /// Given a relocation from __compact_unwind, consisting of the RelocationRef 7830 /// and data being relocated, determine the best base Name and Addend to use for 7831 /// display purposes. 7832 /// 7833 /// 1. An Extern relocation will directly reference a symbol (and the data is 7834 /// then already an addend), so use that. 7835 /// 2. Otherwise the data is an offset in the object file's layout; try to find 7836 // a symbol before it in the same section, and use the offset from there. 7837 /// 3. Finally, if all that fails, fall back to an offset from the start of the 7838 /// referenced section. 7839 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj, 7840 std::map<uint64_t, SymbolRef> &Symbols, 7841 const RelocationRef &Reloc, uint64_t Addr, 7842 StringRef &Name, uint64_t &Addend) { 7843 if (Reloc.getSymbol() != Obj->symbol_end()) { 7844 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName()); 7845 Addend = Addr; 7846 return; 7847 } 7848 7849 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl()); 7850 SectionRef RelocSection = Obj->getAnyRelocationSection(RE); 7851 7852 uint64_t SectionAddr = RelocSection.getAddress(); 7853 7854 auto Sym = Symbols.upper_bound(Addr); 7855 if (Sym == Symbols.begin()) { 7856 // The first symbol in the object is after this reference, the best we can 7857 // do is section-relative notation. 7858 if (Expected<StringRef> NameOrErr = RelocSection.getName()) 7859 Name = *NameOrErr; 7860 else 7861 consumeError(NameOrErr.takeError()); 7862 7863 Addend = Addr - SectionAddr; 7864 return; 7865 } 7866 7867 // Go back one so that SymbolAddress <= Addr. 7868 --Sym; 7869 7870 section_iterator SymSection = 7871 unwrapOrError(Sym->second.getSection(), Obj->getFileName()); 7872 if (RelocSection == *SymSection) { 7873 // There's a valid symbol in the same section before this reference. 7874 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName()); 7875 Addend = Addr - Sym->first; 7876 return; 7877 } 7878 7879 // There is a symbol before this reference, but it's in a different 7880 // section. Probably not helpful to mention it, so use the section name. 7881 if (Expected<StringRef> NameOrErr = RelocSection.getName()) 7882 Name = *NameOrErr; 7883 else 7884 consumeError(NameOrErr.takeError()); 7885 7886 Addend = Addr - SectionAddr; 7887 } 7888 7889 static void printUnwindRelocDest(const MachOObjectFile *Obj, 7890 std::map<uint64_t, SymbolRef> &Symbols, 7891 const RelocationRef &Reloc, uint64_t Addr) { 7892 StringRef Name; 7893 uint64_t Addend; 7894 7895 if (!Reloc.getObject()) 7896 return; 7897 7898 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend); 7899 7900 outs() << Name; 7901 if (Addend) 7902 outs() << " + " << format("0x%" PRIx64, Addend); 7903 } 7904 7905 static void 7906 printMachOCompactUnwindSection(const MachOObjectFile *Obj, 7907 std::map<uint64_t, SymbolRef> &Symbols, 7908 const SectionRef &CompactUnwind) { 7909 7910 if (!Obj->isLittleEndian()) { 7911 outs() << "Skipping big-endian __compact_unwind section\n"; 7912 return; 7913 } 7914 7915 bool Is64 = Obj->is64Bit(); 7916 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t); 7917 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t); 7918 7919 StringRef Contents = 7920 unwrapOrError(CompactUnwind.getContents(), Obj->getFileName()); 7921 SmallVector<CompactUnwindEntry, 4> CompactUnwinds; 7922 7923 // First populate the initial raw offsets, encodings and so on from the entry. 7924 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) { 7925 CompactUnwindEntry Entry(Contents, Offset, Is64); 7926 CompactUnwinds.push_back(Entry); 7927 } 7928 7929 // Next we need to look at the relocations to find out what objects are 7930 // actually being referred to. 7931 for (const RelocationRef &Reloc : CompactUnwind.relocations()) { 7932 uint64_t RelocAddress = Reloc.getOffset(); 7933 7934 uint32_t EntryIdx = RelocAddress / EntrySize; 7935 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize; 7936 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx]; 7937 7938 if (OffsetInEntry == 0) 7939 Entry.FunctionReloc = Reloc; 7940 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t)) 7941 Entry.PersonalityReloc = Reloc; 7942 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t)) 7943 Entry.LSDAReloc = Reloc; 7944 else { 7945 outs() << "Invalid relocation in __compact_unwind section\n"; 7946 return; 7947 } 7948 } 7949 7950 // Finally, we're ready to print the data we've gathered. 7951 outs() << "Contents of __compact_unwind section:\n"; 7952 for (auto &Entry : CompactUnwinds) { 7953 outs() << " Entry at offset " 7954 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n"; 7955 7956 // 1. Start of the region this entry applies to. 7957 outs() << " start: " << format("0x%" PRIx64, 7958 Entry.FunctionAddr) << ' '; 7959 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr); 7960 outs() << '\n'; 7961 7962 // 2. Length of the region this entry applies to. 7963 outs() << " length: " << format("0x%" PRIx32, Entry.Length) 7964 << '\n'; 7965 // 3. The 32-bit compact encoding. 7966 outs() << " compact encoding: " 7967 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n'; 7968 7969 // 4. The personality function, if present. 7970 if (Entry.PersonalityReloc.getObject()) { 7971 outs() << " personality function: " 7972 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' '; 7973 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc, 7974 Entry.PersonalityAddr); 7975 outs() << '\n'; 7976 } 7977 7978 // 5. This entry's language-specific data area. 7979 if (Entry.LSDAReloc.getObject()) { 7980 outs() << " LSDA: " << format("0x%" PRIx64, 7981 Entry.LSDAAddr) << ' '; 7982 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr); 7983 outs() << '\n'; 7984 } 7985 } 7986 } 7987 7988 //===----------------------------------------------------------------------===// 7989 // __unwind_info section dumping 7990 //===----------------------------------------------------------------------===// 7991 7992 static void printRegularSecondLevelUnwindPage(StringRef PageData) { 7993 ptrdiff_t Pos = 0; 7994 uint32_t Kind = readNext<uint32_t>(PageData, Pos); 7995 (void)Kind; 7996 assert(Kind == 2 && "kind for a regular 2nd level index should be 2"); 7997 7998 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos); 7999 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos); 8000 8001 Pos = EntriesStart; 8002 for (unsigned i = 0; i < NumEntries; ++i) { 8003 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos); 8004 uint32_t Encoding = readNext<uint32_t>(PageData, Pos); 8005 8006 outs() << " [" << i << "]: " 8007 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8008 << ", " 8009 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n'; 8010 } 8011 } 8012 8013 static void printCompressedSecondLevelUnwindPage( 8014 StringRef PageData, uint32_t FunctionBase, 8015 const SmallVectorImpl<uint32_t> &CommonEncodings) { 8016 ptrdiff_t Pos = 0; 8017 uint32_t Kind = readNext<uint32_t>(PageData, Pos); 8018 (void)Kind; 8019 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3"); 8020 8021 uint32_t NumCommonEncodings = CommonEncodings.size(); 8022 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos); 8023 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos); 8024 8025 uint16_t PageEncodingsStart = readNext<uint16_t>(PageData, Pos); 8026 uint16_t NumPageEncodings = readNext<uint16_t>(PageData, Pos); 8027 SmallVector<uint32_t, 64> PageEncodings; 8028 if (NumPageEncodings) { 8029 outs() << " Page encodings: (count = " << NumPageEncodings << ")\n"; 8030 Pos = PageEncodingsStart; 8031 for (unsigned i = 0; i < NumPageEncodings; ++i) { 8032 uint32_t Encoding = readNext<uint32_t>(PageData, Pos); 8033 PageEncodings.push_back(Encoding); 8034 outs() << " encoding[" << (i + NumCommonEncodings) 8035 << "]: " << format("0x%08" PRIx32, Encoding) << '\n'; 8036 } 8037 } 8038 8039 Pos = EntriesStart; 8040 for (unsigned i = 0; i < NumEntries; ++i) { 8041 uint32_t Entry = readNext<uint32_t>(PageData, Pos); 8042 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff); 8043 uint32_t EncodingIdx = Entry >> 24; 8044 8045 uint32_t Encoding; 8046 if (EncodingIdx < NumCommonEncodings) 8047 Encoding = CommonEncodings[EncodingIdx]; 8048 else 8049 Encoding = PageEncodings[EncodingIdx - NumCommonEncodings]; 8050 8051 outs() << " [" << i << "]: " 8052 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8053 << ", " 8054 << "encoding[" << EncodingIdx 8055 << "]=" << format("0x%08" PRIx32, Encoding) << '\n'; 8056 } 8057 } 8058 8059 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj, 8060 std::map<uint64_t, SymbolRef> &Symbols, 8061 const SectionRef &UnwindInfo) { 8062 8063 if (!Obj->isLittleEndian()) { 8064 outs() << "Skipping big-endian __unwind_info section\n"; 8065 return; 8066 } 8067 8068 outs() << "Contents of __unwind_info section:\n"; 8069 8070 StringRef Contents = 8071 unwrapOrError(UnwindInfo.getContents(), Obj->getFileName()); 8072 ptrdiff_t Pos = 0; 8073 8074 //===---------------------------------- 8075 // Section header 8076 //===---------------------------------- 8077 8078 uint32_t Version = readNext<uint32_t>(Contents, Pos); 8079 outs() << " Version: " 8080 << format("0x%" PRIx32, Version) << '\n'; 8081 if (Version != 1) { 8082 outs() << " Skipping section with unknown version\n"; 8083 return; 8084 } 8085 8086 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos); 8087 outs() << " Common encodings array section offset: " 8088 << format("0x%" PRIx32, CommonEncodingsStart) << '\n'; 8089 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos); 8090 outs() << " Number of common encodings in array: " 8091 << format("0x%" PRIx32, NumCommonEncodings) << '\n'; 8092 8093 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos); 8094 outs() << " Personality function array section offset: " 8095 << format("0x%" PRIx32, PersonalitiesStart) << '\n'; 8096 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos); 8097 outs() << " Number of personality functions in array: " 8098 << format("0x%" PRIx32, NumPersonalities) << '\n'; 8099 8100 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos); 8101 outs() << " Index array section offset: " 8102 << format("0x%" PRIx32, IndicesStart) << '\n'; 8103 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos); 8104 outs() << " Number of indices in array: " 8105 << format("0x%" PRIx32, NumIndices) << '\n'; 8106 8107 //===---------------------------------- 8108 // A shared list of common encodings 8109 //===---------------------------------- 8110 8111 // These occupy indices in the range [0, N] whenever an encoding is referenced 8112 // from a compressed 2nd level index table. In practice the linker only 8113 // creates ~128 of these, so that indices are available to embed encodings in 8114 // the 2nd level index. 8115 8116 SmallVector<uint32_t, 64> CommonEncodings; 8117 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n"; 8118 Pos = CommonEncodingsStart; 8119 for (unsigned i = 0; i < NumCommonEncodings; ++i) { 8120 uint32_t Encoding = readNext<uint32_t>(Contents, Pos); 8121 CommonEncodings.push_back(Encoding); 8122 8123 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding) 8124 << '\n'; 8125 } 8126 8127 //===---------------------------------- 8128 // Personality functions used in this executable 8129 //===---------------------------------- 8130 8131 // There should be only a handful of these (one per source language, 8132 // roughly). Particularly since they only get 2 bits in the compact encoding. 8133 8134 outs() << " Personality functions: (count = " << NumPersonalities << ")\n"; 8135 Pos = PersonalitiesStart; 8136 for (unsigned i = 0; i < NumPersonalities; ++i) { 8137 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos); 8138 outs() << " personality[" << i + 1 8139 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n'; 8140 } 8141 8142 //===---------------------------------- 8143 // The level 1 index entries 8144 //===---------------------------------- 8145 8146 // These specify an approximate place to start searching for the more detailed 8147 // information, sorted by PC. 8148 8149 struct IndexEntry { 8150 uint32_t FunctionOffset; 8151 uint32_t SecondLevelPageStart; 8152 uint32_t LSDAStart; 8153 }; 8154 8155 SmallVector<IndexEntry, 4> IndexEntries; 8156 8157 outs() << " Top level indices: (count = " << NumIndices << ")\n"; 8158 Pos = IndicesStart; 8159 for (unsigned i = 0; i < NumIndices; ++i) { 8160 IndexEntry Entry; 8161 8162 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos); 8163 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos); 8164 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos); 8165 IndexEntries.push_back(Entry); 8166 8167 outs() << " [" << i << "]: " 8168 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset) 8169 << ", " 8170 << "2nd level page offset=" 8171 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", " 8172 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n'; 8173 } 8174 8175 //===---------------------------------- 8176 // Next come the LSDA tables 8177 //===---------------------------------- 8178 8179 // The LSDA layout is rather implicit: it's a contiguous array of entries from 8180 // the first top-level index's LSDAOffset to the last (sentinel). 8181 8182 outs() << " LSDA descriptors:\n"; 8183 Pos = IndexEntries[0].LSDAStart; 8184 const uint32_t LSDASize = 2 * sizeof(uint32_t); 8185 int NumLSDAs = 8186 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize; 8187 8188 for (int i = 0; i < NumLSDAs; ++i) { 8189 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos); 8190 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos); 8191 outs() << " [" << i << "]: " 8192 << "function offset=" << format("0x%08" PRIx32, FunctionOffset) 8193 << ", " 8194 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n'; 8195 } 8196 8197 //===---------------------------------- 8198 // Finally, the 2nd level indices 8199 //===---------------------------------- 8200 8201 // Generally these are 4K in size, and have 2 possible forms: 8202 // + Regular stores up to 511 entries with disparate encodings 8203 // + Compressed stores up to 1021 entries if few enough compact encoding 8204 // values are used. 8205 outs() << " Second level indices:\n"; 8206 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) { 8207 // The final sentinel top-level index has no associated 2nd level page 8208 if (IndexEntries[i].SecondLevelPageStart == 0) 8209 break; 8210 8211 outs() << " Second level index[" << i << "]: " 8212 << "offset in section=" 8213 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart) 8214 << ", " 8215 << "base function offset=" 8216 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n'; 8217 8218 Pos = IndexEntries[i].SecondLevelPageStart; 8219 if (Pos + sizeof(uint32_t) > Contents.size()) { 8220 outs() << "warning: invalid offset for second level page: " << Pos << '\n'; 8221 continue; 8222 } 8223 8224 uint32_t Kind = 8225 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos); 8226 if (Kind == 2) 8227 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096)); 8228 else if (Kind == 3) 8229 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096), 8230 IndexEntries[i].FunctionOffset, 8231 CommonEncodings); 8232 else 8233 outs() << " Skipping 2nd level page with unknown kind " << Kind 8234 << '\n'; 8235 } 8236 } 8237 8238 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) { 8239 std::map<uint64_t, SymbolRef> Symbols; 8240 for (const SymbolRef &SymRef : Obj->symbols()) { 8241 // Discard any undefined or absolute symbols. They're not going to take part 8242 // in the convenience lookup for unwind info and just take up resources. 8243 auto SectOrErr = SymRef.getSection(); 8244 if (!SectOrErr) { 8245 // TODO: Actually report errors helpfully. 8246 consumeError(SectOrErr.takeError()); 8247 continue; 8248 } 8249 section_iterator Section = *SectOrErr; 8250 if (Section == Obj->section_end()) 8251 continue; 8252 8253 uint64_t Addr = cantFail(SymRef.getValue()); 8254 Symbols.insert(std::make_pair(Addr, SymRef)); 8255 } 8256 8257 for (const SectionRef &Section : Obj->sections()) { 8258 StringRef SectName; 8259 if (Expected<StringRef> NameOrErr = Section.getName()) 8260 SectName = *NameOrErr; 8261 else 8262 consumeError(NameOrErr.takeError()); 8263 8264 if (SectName == "__compact_unwind") 8265 printMachOCompactUnwindSection(Obj, Symbols, Section); 8266 else if (SectName == "__unwind_info") 8267 printMachOUnwindInfoSection(Obj, Symbols, Section); 8268 } 8269 } 8270 8271 static void PrintMachHeader(uint32_t magic, uint32_t cputype, 8272 uint32_t cpusubtype, uint32_t filetype, 8273 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags, 8274 bool verbose) { 8275 outs() << "Mach header\n"; 8276 outs() << " magic cputype cpusubtype caps filetype ncmds " 8277 "sizeofcmds flags\n"; 8278 if (verbose) { 8279 if (magic == MachO::MH_MAGIC) 8280 outs() << " MH_MAGIC"; 8281 else if (magic == MachO::MH_MAGIC_64) 8282 outs() << "MH_MAGIC_64"; 8283 else 8284 outs() << format(" 0x%08" PRIx32, magic); 8285 switch (cputype) { 8286 case MachO::CPU_TYPE_I386: 8287 outs() << " I386"; 8288 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8289 case MachO::CPU_SUBTYPE_I386_ALL: 8290 outs() << " ALL"; 8291 break; 8292 default: 8293 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8294 break; 8295 } 8296 break; 8297 case MachO::CPU_TYPE_X86_64: 8298 outs() << " X86_64"; 8299 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8300 case MachO::CPU_SUBTYPE_X86_64_ALL: 8301 outs() << " ALL"; 8302 break; 8303 case MachO::CPU_SUBTYPE_X86_64_H: 8304 outs() << " Haswell"; 8305 break; 8306 default: 8307 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8308 break; 8309 } 8310 break; 8311 case MachO::CPU_TYPE_ARM: 8312 outs() << " ARM"; 8313 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8314 case MachO::CPU_SUBTYPE_ARM_ALL: 8315 outs() << " ALL"; 8316 break; 8317 case MachO::CPU_SUBTYPE_ARM_V4T: 8318 outs() << " V4T"; 8319 break; 8320 case MachO::CPU_SUBTYPE_ARM_V5TEJ: 8321 outs() << " V5TEJ"; 8322 break; 8323 case MachO::CPU_SUBTYPE_ARM_XSCALE: 8324 outs() << " XSCALE"; 8325 break; 8326 case MachO::CPU_SUBTYPE_ARM_V6: 8327 outs() << " V6"; 8328 break; 8329 case MachO::CPU_SUBTYPE_ARM_V6M: 8330 outs() << " V6M"; 8331 break; 8332 case MachO::CPU_SUBTYPE_ARM_V7: 8333 outs() << " V7"; 8334 break; 8335 case MachO::CPU_SUBTYPE_ARM_V7EM: 8336 outs() << " V7EM"; 8337 break; 8338 case MachO::CPU_SUBTYPE_ARM_V7K: 8339 outs() << " V7K"; 8340 break; 8341 case MachO::CPU_SUBTYPE_ARM_V7M: 8342 outs() << " V7M"; 8343 break; 8344 case MachO::CPU_SUBTYPE_ARM_V7S: 8345 outs() << " V7S"; 8346 break; 8347 default: 8348 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8349 break; 8350 } 8351 break; 8352 case MachO::CPU_TYPE_ARM64: 8353 outs() << " ARM64"; 8354 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8355 case MachO::CPU_SUBTYPE_ARM64_ALL: 8356 outs() << " ALL"; 8357 break; 8358 case MachO::CPU_SUBTYPE_ARM64_V8: 8359 outs() << " V8"; 8360 break; 8361 case MachO::CPU_SUBTYPE_ARM64E: 8362 outs() << " E"; 8363 break; 8364 default: 8365 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8366 break; 8367 } 8368 break; 8369 case MachO::CPU_TYPE_ARM64_32: 8370 outs() << " ARM64_32"; 8371 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8372 case MachO::CPU_SUBTYPE_ARM64_32_V8: 8373 outs() << " V8"; 8374 break; 8375 default: 8376 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8377 break; 8378 } 8379 break; 8380 case MachO::CPU_TYPE_POWERPC: 8381 outs() << " PPC"; 8382 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8383 case MachO::CPU_SUBTYPE_POWERPC_ALL: 8384 outs() << " ALL"; 8385 break; 8386 default: 8387 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8388 break; 8389 } 8390 break; 8391 case MachO::CPU_TYPE_POWERPC64: 8392 outs() << " PPC64"; 8393 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) { 8394 case MachO::CPU_SUBTYPE_POWERPC_ALL: 8395 outs() << " ALL"; 8396 break; 8397 default: 8398 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8399 break; 8400 } 8401 break; 8402 default: 8403 outs() << format(" %7d", cputype); 8404 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8405 break; 8406 } 8407 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) { 8408 outs() << " LIB64"; 8409 } else { 8410 outs() << format(" 0x%02" PRIx32, 8411 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); 8412 } 8413 switch (filetype) { 8414 case MachO::MH_OBJECT: 8415 outs() << " OBJECT"; 8416 break; 8417 case MachO::MH_EXECUTE: 8418 outs() << " EXECUTE"; 8419 break; 8420 case MachO::MH_FVMLIB: 8421 outs() << " FVMLIB"; 8422 break; 8423 case MachO::MH_CORE: 8424 outs() << " CORE"; 8425 break; 8426 case MachO::MH_PRELOAD: 8427 outs() << " PRELOAD"; 8428 break; 8429 case MachO::MH_DYLIB: 8430 outs() << " DYLIB"; 8431 break; 8432 case MachO::MH_DYLIB_STUB: 8433 outs() << " DYLIB_STUB"; 8434 break; 8435 case MachO::MH_DYLINKER: 8436 outs() << " DYLINKER"; 8437 break; 8438 case MachO::MH_BUNDLE: 8439 outs() << " BUNDLE"; 8440 break; 8441 case MachO::MH_DSYM: 8442 outs() << " DSYM"; 8443 break; 8444 case MachO::MH_KEXT_BUNDLE: 8445 outs() << " KEXTBUNDLE"; 8446 break; 8447 default: 8448 outs() << format(" %10u", filetype); 8449 break; 8450 } 8451 outs() << format(" %5u", ncmds); 8452 outs() << format(" %10u", sizeofcmds); 8453 uint32_t f = flags; 8454 if (f & MachO::MH_NOUNDEFS) { 8455 outs() << " NOUNDEFS"; 8456 f &= ~MachO::MH_NOUNDEFS; 8457 } 8458 if (f & MachO::MH_INCRLINK) { 8459 outs() << " INCRLINK"; 8460 f &= ~MachO::MH_INCRLINK; 8461 } 8462 if (f & MachO::MH_DYLDLINK) { 8463 outs() << " DYLDLINK"; 8464 f &= ~MachO::MH_DYLDLINK; 8465 } 8466 if (f & MachO::MH_BINDATLOAD) { 8467 outs() << " BINDATLOAD"; 8468 f &= ~MachO::MH_BINDATLOAD; 8469 } 8470 if (f & MachO::MH_PREBOUND) { 8471 outs() << " PREBOUND"; 8472 f &= ~MachO::MH_PREBOUND; 8473 } 8474 if (f & MachO::MH_SPLIT_SEGS) { 8475 outs() << " SPLIT_SEGS"; 8476 f &= ~MachO::MH_SPLIT_SEGS; 8477 } 8478 if (f & MachO::MH_LAZY_INIT) { 8479 outs() << " LAZY_INIT"; 8480 f &= ~MachO::MH_LAZY_INIT; 8481 } 8482 if (f & MachO::MH_TWOLEVEL) { 8483 outs() << " TWOLEVEL"; 8484 f &= ~MachO::MH_TWOLEVEL; 8485 } 8486 if (f & MachO::MH_FORCE_FLAT) { 8487 outs() << " FORCE_FLAT"; 8488 f &= ~MachO::MH_FORCE_FLAT; 8489 } 8490 if (f & MachO::MH_NOMULTIDEFS) { 8491 outs() << " NOMULTIDEFS"; 8492 f &= ~MachO::MH_NOMULTIDEFS; 8493 } 8494 if (f & MachO::MH_NOFIXPREBINDING) { 8495 outs() << " NOFIXPREBINDING"; 8496 f &= ~MachO::MH_NOFIXPREBINDING; 8497 } 8498 if (f & MachO::MH_PREBINDABLE) { 8499 outs() << " PREBINDABLE"; 8500 f &= ~MachO::MH_PREBINDABLE; 8501 } 8502 if (f & MachO::MH_ALLMODSBOUND) { 8503 outs() << " ALLMODSBOUND"; 8504 f &= ~MachO::MH_ALLMODSBOUND; 8505 } 8506 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) { 8507 outs() << " SUBSECTIONS_VIA_SYMBOLS"; 8508 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS; 8509 } 8510 if (f & MachO::MH_CANONICAL) { 8511 outs() << " CANONICAL"; 8512 f &= ~MachO::MH_CANONICAL; 8513 } 8514 if (f & MachO::MH_WEAK_DEFINES) { 8515 outs() << " WEAK_DEFINES"; 8516 f &= ~MachO::MH_WEAK_DEFINES; 8517 } 8518 if (f & MachO::MH_BINDS_TO_WEAK) { 8519 outs() << " BINDS_TO_WEAK"; 8520 f &= ~MachO::MH_BINDS_TO_WEAK; 8521 } 8522 if (f & MachO::MH_ALLOW_STACK_EXECUTION) { 8523 outs() << " ALLOW_STACK_EXECUTION"; 8524 f &= ~MachO::MH_ALLOW_STACK_EXECUTION; 8525 } 8526 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) { 8527 outs() << " DEAD_STRIPPABLE_DYLIB"; 8528 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB; 8529 } 8530 if (f & MachO::MH_PIE) { 8531 outs() << " PIE"; 8532 f &= ~MachO::MH_PIE; 8533 } 8534 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) { 8535 outs() << " NO_REEXPORTED_DYLIBS"; 8536 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS; 8537 } 8538 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) { 8539 outs() << " MH_HAS_TLV_DESCRIPTORS"; 8540 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS; 8541 } 8542 if (f & MachO::MH_NO_HEAP_EXECUTION) { 8543 outs() << " MH_NO_HEAP_EXECUTION"; 8544 f &= ~MachO::MH_NO_HEAP_EXECUTION; 8545 } 8546 if (f & MachO::MH_APP_EXTENSION_SAFE) { 8547 outs() << " APP_EXTENSION_SAFE"; 8548 f &= ~MachO::MH_APP_EXTENSION_SAFE; 8549 } 8550 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) { 8551 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO"; 8552 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO; 8553 } 8554 if (f != 0 || flags == 0) 8555 outs() << format(" 0x%08" PRIx32, f); 8556 } else { 8557 outs() << format(" 0x%08" PRIx32, magic); 8558 outs() << format(" %7d", cputype); 8559 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK); 8560 outs() << format(" 0x%02" PRIx32, 8561 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24); 8562 outs() << format(" %10u", filetype); 8563 outs() << format(" %5u", ncmds); 8564 outs() << format(" %10u", sizeofcmds); 8565 outs() << format(" 0x%08" PRIx32, flags); 8566 } 8567 outs() << "\n"; 8568 } 8569 8570 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize, 8571 StringRef SegName, uint64_t vmaddr, 8572 uint64_t vmsize, uint64_t fileoff, 8573 uint64_t filesize, uint32_t maxprot, 8574 uint32_t initprot, uint32_t nsects, 8575 uint32_t flags, uint32_t object_size, 8576 bool verbose) { 8577 uint64_t expected_cmdsize; 8578 if (cmd == MachO::LC_SEGMENT) { 8579 outs() << " cmd LC_SEGMENT\n"; 8580 expected_cmdsize = nsects; 8581 expected_cmdsize *= sizeof(struct MachO::section); 8582 expected_cmdsize += sizeof(struct MachO::segment_command); 8583 } else { 8584 outs() << " cmd LC_SEGMENT_64\n"; 8585 expected_cmdsize = nsects; 8586 expected_cmdsize *= sizeof(struct MachO::section_64); 8587 expected_cmdsize += sizeof(struct MachO::segment_command_64); 8588 } 8589 outs() << " cmdsize " << cmdsize; 8590 if (cmdsize != expected_cmdsize) 8591 outs() << " Inconsistent size\n"; 8592 else 8593 outs() << "\n"; 8594 outs() << " segname " << SegName << "\n"; 8595 if (cmd == MachO::LC_SEGMENT_64) { 8596 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n"; 8597 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n"; 8598 } else { 8599 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n"; 8600 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n"; 8601 } 8602 outs() << " fileoff " << fileoff; 8603 if (fileoff > object_size) 8604 outs() << " (past end of file)\n"; 8605 else 8606 outs() << "\n"; 8607 outs() << " filesize " << filesize; 8608 if (fileoff + filesize > object_size) 8609 outs() << " (past end of file)\n"; 8610 else 8611 outs() << "\n"; 8612 if (verbose) { 8613 if ((maxprot & 8614 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | 8615 MachO::VM_PROT_EXECUTE)) != 0) 8616 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n"; 8617 else { 8618 outs() << " maxprot "; 8619 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-"); 8620 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-"); 8621 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n"); 8622 } 8623 if ((initprot & 8624 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE | 8625 MachO::VM_PROT_EXECUTE)) != 0) 8626 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n"; 8627 else { 8628 outs() << " initprot "; 8629 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-"); 8630 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-"); 8631 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n"); 8632 } 8633 } else { 8634 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n"; 8635 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n"; 8636 } 8637 outs() << " nsects " << nsects << "\n"; 8638 if (verbose) { 8639 outs() << " flags"; 8640 if (flags == 0) 8641 outs() << " (none)\n"; 8642 else { 8643 if (flags & MachO::SG_HIGHVM) { 8644 outs() << " HIGHVM"; 8645 flags &= ~MachO::SG_HIGHVM; 8646 } 8647 if (flags & MachO::SG_FVMLIB) { 8648 outs() << " FVMLIB"; 8649 flags &= ~MachO::SG_FVMLIB; 8650 } 8651 if (flags & MachO::SG_NORELOC) { 8652 outs() << " NORELOC"; 8653 flags &= ~MachO::SG_NORELOC; 8654 } 8655 if (flags & MachO::SG_PROTECTED_VERSION_1) { 8656 outs() << " PROTECTED_VERSION_1"; 8657 flags &= ~MachO::SG_PROTECTED_VERSION_1; 8658 } 8659 if (flags) 8660 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n"; 8661 else 8662 outs() << "\n"; 8663 } 8664 } else { 8665 outs() << " flags " << format("0x%" PRIx32, flags) << "\n"; 8666 } 8667 } 8668 8669 static void PrintSection(const char *sectname, const char *segname, 8670 uint64_t addr, uint64_t size, uint32_t offset, 8671 uint32_t align, uint32_t reloff, uint32_t nreloc, 8672 uint32_t flags, uint32_t reserved1, uint32_t reserved2, 8673 uint32_t cmd, const char *sg_segname, 8674 uint32_t filetype, uint32_t object_size, 8675 bool verbose) { 8676 outs() << "Section\n"; 8677 outs() << " sectname " << format("%.16s\n", sectname); 8678 outs() << " segname " << format("%.16s", segname); 8679 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0) 8680 outs() << " (does not match segment)\n"; 8681 else 8682 outs() << "\n"; 8683 if (cmd == MachO::LC_SEGMENT_64) { 8684 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n"; 8685 outs() << " size " << format("0x%016" PRIx64, size); 8686 } else { 8687 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n"; 8688 outs() << " size " << format("0x%08" PRIx64, size); 8689 } 8690 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size) 8691 outs() << " (past end of file)\n"; 8692 else 8693 outs() << "\n"; 8694 outs() << " offset " << offset; 8695 if (offset > object_size) 8696 outs() << " (past end of file)\n"; 8697 else 8698 outs() << "\n"; 8699 uint32_t align_shifted = 1 << align; 8700 outs() << " align 2^" << align << " (" << align_shifted << ")\n"; 8701 outs() << " reloff " << reloff; 8702 if (reloff > object_size) 8703 outs() << " (past end of file)\n"; 8704 else 8705 outs() << "\n"; 8706 outs() << " nreloc " << nreloc; 8707 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size) 8708 outs() << " (past end of file)\n"; 8709 else 8710 outs() << "\n"; 8711 uint32_t section_type = flags & MachO::SECTION_TYPE; 8712 if (verbose) { 8713 outs() << " type"; 8714 if (section_type == MachO::S_REGULAR) 8715 outs() << " S_REGULAR\n"; 8716 else if (section_type == MachO::S_ZEROFILL) 8717 outs() << " S_ZEROFILL\n"; 8718 else if (section_type == MachO::S_CSTRING_LITERALS) 8719 outs() << " S_CSTRING_LITERALS\n"; 8720 else if (section_type == MachO::S_4BYTE_LITERALS) 8721 outs() << " S_4BYTE_LITERALS\n"; 8722 else if (section_type == MachO::S_8BYTE_LITERALS) 8723 outs() << " S_8BYTE_LITERALS\n"; 8724 else if (section_type == MachO::S_16BYTE_LITERALS) 8725 outs() << " S_16BYTE_LITERALS\n"; 8726 else if (section_type == MachO::S_LITERAL_POINTERS) 8727 outs() << " S_LITERAL_POINTERS\n"; 8728 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS) 8729 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n"; 8730 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS) 8731 outs() << " S_LAZY_SYMBOL_POINTERS\n"; 8732 else if (section_type == MachO::S_SYMBOL_STUBS) 8733 outs() << " S_SYMBOL_STUBS\n"; 8734 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS) 8735 outs() << " S_MOD_INIT_FUNC_POINTERS\n"; 8736 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS) 8737 outs() << " S_MOD_TERM_FUNC_POINTERS\n"; 8738 else if (section_type == MachO::S_COALESCED) 8739 outs() << " S_COALESCED\n"; 8740 else if (section_type == MachO::S_INTERPOSING) 8741 outs() << " S_INTERPOSING\n"; 8742 else if (section_type == MachO::S_DTRACE_DOF) 8743 outs() << " S_DTRACE_DOF\n"; 8744 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS) 8745 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n"; 8746 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR) 8747 outs() << " S_THREAD_LOCAL_REGULAR\n"; 8748 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL) 8749 outs() << " S_THREAD_LOCAL_ZEROFILL\n"; 8750 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES) 8751 outs() << " S_THREAD_LOCAL_VARIABLES\n"; 8752 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 8753 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n"; 8754 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS) 8755 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n"; 8756 else 8757 outs() << format("0x%08" PRIx32, section_type) << "\n"; 8758 outs() << "attributes"; 8759 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES; 8760 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS) 8761 outs() << " PURE_INSTRUCTIONS"; 8762 if (section_attributes & MachO::S_ATTR_NO_TOC) 8763 outs() << " NO_TOC"; 8764 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS) 8765 outs() << " STRIP_STATIC_SYMS"; 8766 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP) 8767 outs() << " NO_DEAD_STRIP"; 8768 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT) 8769 outs() << " LIVE_SUPPORT"; 8770 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE) 8771 outs() << " SELF_MODIFYING_CODE"; 8772 if (section_attributes & MachO::S_ATTR_DEBUG) 8773 outs() << " DEBUG"; 8774 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS) 8775 outs() << " SOME_INSTRUCTIONS"; 8776 if (section_attributes & MachO::S_ATTR_EXT_RELOC) 8777 outs() << " EXT_RELOC"; 8778 if (section_attributes & MachO::S_ATTR_LOC_RELOC) 8779 outs() << " LOC_RELOC"; 8780 if (section_attributes == 0) 8781 outs() << " (none)"; 8782 outs() << "\n"; 8783 } else 8784 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n"; 8785 outs() << " reserved1 " << reserved1; 8786 if (section_type == MachO::S_SYMBOL_STUBS || 8787 section_type == MachO::S_LAZY_SYMBOL_POINTERS || 8788 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS || 8789 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS || 8790 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS) 8791 outs() << " (index into indirect symbol table)\n"; 8792 else 8793 outs() << "\n"; 8794 outs() << " reserved2 " << reserved2; 8795 if (section_type == MachO::S_SYMBOL_STUBS) 8796 outs() << " (size of stubs)\n"; 8797 else 8798 outs() << "\n"; 8799 } 8800 8801 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit, 8802 uint32_t object_size) { 8803 outs() << " cmd LC_SYMTAB\n"; 8804 outs() << " cmdsize " << st.cmdsize; 8805 if (st.cmdsize != sizeof(struct MachO::symtab_command)) 8806 outs() << " Incorrect size\n"; 8807 else 8808 outs() << "\n"; 8809 outs() << " symoff " << st.symoff; 8810 if (st.symoff > object_size) 8811 outs() << " (past end of file)\n"; 8812 else 8813 outs() << "\n"; 8814 outs() << " nsyms " << st.nsyms; 8815 uint64_t big_size; 8816 if (Is64Bit) { 8817 big_size = st.nsyms; 8818 big_size *= sizeof(struct MachO::nlist_64); 8819 big_size += st.symoff; 8820 if (big_size > object_size) 8821 outs() << " (past end of file)\n"; 8822 else 8823 outs() << "\n"; 8824 } else { 8825 big_size = st.nsyms; 8826 big_size *= sizeof(struct MachO::nlist); 8827 big_size += st.symoff; 8828 if (big_size > object_size) 8829 outs() << " (past end of file)\n"; 8830 else 8831 outs() << "\n"; 8832 } 8833 outs() << " stroff " << st.stroff; 8834 if (st.stroff > object_size) 8835 outs() << " (past end of file)\n"; 8836 else 8837 outs() << "\n"; 8838 outs() << " strsize " << st.strsize; 8839 big_size = st.stroff; 8840 big_size += st.strsize; 8841 if (big_size > object_size) 8842 outs() << " (past end of file)\n"; 8843 else 8844 outs() << "\n"; 8845 } 8846 8847 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst, 8848 uint32_t nsyms, uint32_t object_size, 8849 bool Is64Bit) { 8850 outs() << " cmd LC_DYSYMTAB\n"; 8851 outs() << " cmdsize " << dyst.cmdsize; 8852 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command)) 8853 outs() << " Incorrect size\n"; 8854 else 8855 outs() << "\n"; 8856 outs() << " ilocalsym " << dyst.ilocalsym; 8857 if (dyst.ilocalsym > nsyms) 8858 outs() << " (greater than the number of symbols)\n"; 8859 else 8860 outs() << "\n"; 8861 outs() << " nlocalsym " << dyst.nlocalsym; 8862 uint64_t big_size; 8863 big_size = dyst.ilocalsym; 8864 big_size += dyst.nlocalsym; 8865 if (big_size > nsyms) 8866 outs() << " (past the end of the symbol table)\n"; 8867 else 8868 outs() << "\n"; 8869 outs() << " iextdefsym " << dyst.iextdefsym; 8870 if (dyst.iextdefsym > nsyms) 8871 outs() << " (greater than the number of symbols)\n"; 8872 else 8873 outs() << "\n"; 8874 outs() << " nextdefsym " << dyst.nextdefsym; 8875 big_size = dyst.iextdefsym; 8876 big_size += dyst.nextdefsym; 8877 if (big_size > nsyms) 8878 outs() << " (past the end of the symbol table)\n"; 8879 else 8880 outs() << "\n"; 8881 outs() << " iundefsym " << dyst.iundefsym; 8882 if (dyst.iundefsym > nsyms) 8883 outs() << " (greater than the number of symbols)\n"; 8884 else 8885 outs() << "\n"; 8886 outs() << " nundefsym " << dyst.nundefsym; 8887 big_size = dyst.iundefsym; 8888 big_size += dyst.nundefsym; 8889 if (big_size > nsyms) 8890 outs() << " (past the end of the symbol table)\n"; 8891 else 8892 outs() << "\n"; 8893 outs() << " tocoff " << dyst.tocoff; 8894 if (dyst.tocoff > object_size) 8895 outs() << " (past end of file)\n"; 8896 else 8897 outs() << "\n"; 8898 outs() << " ntoc " << dyst.ntoc; 8899 big_size = dyst.ntoc; 8900 big_size *= sizeof(struct MachO::dylib_table_of_contents); 8901 big_size += dyst.tocoff; 8902 if (big_size > object_size) 8903 outs() << " (past end of file)\n"; 8904 else 8905 outs() << "\n"; 8906 outs() << " modtaboff " << dyst.modtaboff; 8907 if (dyst.modtaboff > object_size) 8908 outs() << " (past end of file)\n"; 8909 else 8910 outs() << "\n"; 8911 outs() << " nmodtab " << dyst.nmodtab; 8912 uint64_t modtabend; 8913 if (Is64Bit) { 8914 modtabend = dyst.nmodtab; 8915 modtabend *= sizeof(struct MachO::dylib_module_64); 8916 modtabend += dyst.modtaboff; 8917 } else { 8918 modtabend = dyst.nmodtab; 8919 modtabend *= sizeof(struct MachO::dylib_module); 8920 modtabend += dyst.modtaboff; 8921 } 8922 if (modtabend > object_size) 8923 outs() << " (past end of file)\n"; 8924 else 8925 outs() << "\n"; 8926 outs() << " extrefsymoff " << dyst.extrefsymoff; 8927 if (dyst.extrefsymoff > object_size) 8928 outs() << " (past end of file)\n"; 8929 else 8930 outs() << "\n"; 8931 outs() << " nextrefsyms " << dyst.nextrefsyms; 8932 big_size = dyst.nextrefsyms; 8933 big_size *= sizeof(struct MachO::dylib_reference); 8934 big_size += dyst.extrefsymoff; 8935 if (big_size > object_size) 8936 outs() << " (past end of file)\n"; 8937 else 8938 outs() << "\n"; 8939 outs() << " indirectsymoff " << dyst.indirectsymoff; 8940 if (dyst.indirectsymoff > object_size) 8941 outs() << " (past end of file)\n"; 8942 else 8943 outs() << "\n"; 8944 outs() << " nindirectsyms " << dyst.nindirectsyms; 8945 big_size = dyst.nindirectsyms; 8946 big_size *= sizeof(uint32_t); 8947 big_size += dyst.indirectsymoff; 8948 if (big_size > object_size) 8949 outs() << " (past end of file)\n"; 8950 else 8951 outs() << "\n"; 8952 outs() << " extreloff " << dyst.extreloff; 8953 if (dyst.extreloff > object_size) 8954 outs() << " (past end of file)\n"; 8955 else 8956 outs() << "\n"; 8957 outs() << " nextrel " << dyst.nextrel; 8958 big_size = dyst.nextrel; 8959 big_size *= sizeof(struct MachO::relocation_info); 8960 big_size += dyst.extreloff; 8961 if (big_size > object_size) 8962 outs() << " (past end of file)\n"; 8963 else 8964 outs() << "\n"; 8965 outs() << " locreloff " << dyst.locreloff; 8966 if (dyst.locreloff > object_size) 8967 outs() << " (past end of file)\n"; 8968 else 8969 outs() << "\n"; 8970 outs() << " nlocrel " << dyst.nlocrel; 8971 big_size = dyst.nlocrel; 8972 big_size *= sizeof(struct MachO::relocation_info); 8973 big_size += dyst.locreloff; 8974 if (big_size > object_size) 8975 outs() << " (past end of file)\n"; 8976 else 8977 outs() << "\n"; 8978 } 8979 8980 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc, 8981 uint32_t object_size) { 8982 if (dc.cmd == MachO::LC_DYLD_INFO) 8983 outs() << " cmd LC_DYLD_INFO\n"; 8984 else 8985 outs() << " cmd LC_DYLD_INFO_ONLY\n"; 8986 outs() << " cmdsize " << dc.cmdsize; 8987 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command)) 8988 outs() << " Incorrect size\n"; 8989 else 8990 outs() << "\n"; 8991 outs() << " rebase_off " << dc.rebase_off; 8992 if (dc.rebase_off > object_size) 8993 outs() << " (past end of file)\n"; 8994 else 8995 outs() << "\n"; 8996 outs() << " rebase_size " << dc.rebase_size; 8997 uint64_t big_size; 8998 big_size = dc.rebase_off; 8999 big_size += dc.rebase_size; 9000 if (big_size > object_size) 9001 outs() << " (past end of file)\n"; 9002 else 9003 outs() << "\n"; 9004 outs() << " bind_off " << dc.bind_off; 9005 if (dc.bind_off > object_size) 9006 outs() << " (past end of file)\n"; 9007 else 9008 outs() << "\n"; 9009 outs() << " bind_size " << dc.bind_size; 9010 big_size = dc.bind_off; 9011 big_size += dc.bind_size; 9012 if (big_size > object_size) 9013 outs() << " (past end of file)\n"; 9014 else 9015 outs() << "\n"; 9016 outs() << " weak_bind_off " << dc.weak_bind_off; 9017 if (dc.weak_bind_off > object_size) 9018 outs() << " (past end of file)\n"; 9019 else 9020 outs() << "\n"; 9021 outs() << " weak_bind_size " << dc.weak_bind_size; 9022 big_size = dc.weak_bind_off; 9023 big_size += dc.weak_bind_size; 9024 if (big_size > object_size) 9025 outs() << " (past end of file)\n"; 9026 else 9027 outs() << "\n"; 9028 outs() << " lazy_bind_off " << dc.lazy_bind_off; 9029 if (dc.lazy_bind_off > object_size) 9030 outs() << " (past end of file)\n"; 9031 else 9032 outs() << "\n"; 9033 outs() << " lazy_bind_size " << dc.lazy_bind_size; 9034 big_size = dc.lazy_bind_off; 9035 big_size += dc.lazy_bind_size; 9036 if (big_size > object_size) 9037 outs() << " (past end of file)\n"; 9038 else 9039 outs() << "\n"; 9040 outs() << " export_off " << dc.export_off; 9041 if (dc.export_off > object_size) 9042 outs() << " (past end of file)\n"; 9043 else 9044 outs() << "\n"; 9045 outs() << " export_size " << dc.export_size; 9046 big_size = dc.export_off; 9047 big_size += dc.export_size; 9048 if (big_size > object_size) 9049 outs() << " (past end of file)\n"; 9050 else 9051 outs() << "\n"; 9052 } 9053 9054 static void PrintDyldLoadCommand(MachO::dylinker_command dyld, 9055 const char *Ptr) { 9056 if (dyld.cmd == MachO::LC_ID_DYLINKER) 9057 outs() << " cmd LC_ID_DYLINKER\n"; 9058 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER) 9059 outs() << " cmd LC_LOAD_DYLINKER\n"; 9060 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT) 9061 outs() << " cmd LC_DYLD_ENVIRONMENT\n"; 9062 else 9063 outs() << " cmd ?(" << dyld.cmd << ")\n"; 9064 outs() << " cmdsize " << dyld.cmdsize; 9065 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command)) 9066 outs() << " Incorrect size\n"; 9067 else 9068 outs() << "\n"; 9069 if (dyld.name >= dyld.cmdsize) 9070 outs() << " name ?(bad offset " << dyld.name << ")\n"; 9071 else { 9072 const char *P = (const char *)(Ptr) + dyld.name; 9073 outs() << " name " << P << " (offset " << dyld.name << ")\n"; 9074 } 9075 } 9076 9077 static void PrintUuidLoadCommand(MachO::uuid_command uuid) { 9078 outs() << " cmd LC_UUID\n"; 9079 outs() << " cmdsize " << uuid.cmdsize; 9080 if (uuid.cmdsize != sizeof(struct MachO::uuid_command)) 9081 outs() << " Incorrect size\n"; 9082 else 9083 outs() << "\n"; 9084 outs() << " uuid "; 9085 for (int i = 0; i < 16; ++i) { 9086 outs() << format("%02" PRIX32, uuid.uuid[i]); 9087 if (i == 3 || i == 5 || i == 7 || i == 9) 9088 outs() << "-"; 9089 } 9090 outs() << "\n"; 9091 } 9092 9093 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) { 9094 outs() << " cmd LC_RPATH\n"; 9095 outs() << " cmdsize " << rpath.cmdsize; 9096 if (rpath.cmdsize < sizeof(struct MachO::rpath_command)) 9097 outs() << " Incorrect size\n"; 9098 else 9099 outs() << "\n"; 9100 if (rpath.path >= rpath.cmdsize) 9101 outs() << " path ?(bad offset " << rpath.path << ")\n"; 9102 else { 9103 const char *P = (const char *)(Ptr) + rpath.path; 9104 outs() << " path " << P << " (offset " << rpath.path << ")\n"; 9105 } 9106 } 9107 9108 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) { 9109 StringRef LoadCmdName; 9110 switch (vd.cmd) { 9111 case MachO::LC_VERSION_MIN_MACOSX: 9112 LoadCmdName = "LC_VERSION_MIN_MACOSX"; 9113 break; 9114 case MachO::LC_VERSION_MIN_IPHONEOS: 9115 LoadCmdName = "LC_VERSION_MIN_IPHONEOS"; 9116 break; 9117 case MachO::LC_VERSION_MIN_TVOS: 9118 LoadCmdName = "LC_VERSION_MIN_TVOS"; 9119 break; 9120 case MachO::LC_VERSION_MIN_WATCHOS: 9121 LoadCmdName = "LC_VERSION_MIN_WATCHOS"; 9122 break; 9123 default: 9124 llvm_unreachable("Unknown version min load command"); 9125 } 9126 9127 outs() << " cmd " << LoadCmdName << '\n'; 9128 outs() << " cmdsize " << vd.cmdsize; 9129 if (vd.cmdsize != sizeof(struct MachO::version_min_command)) 9130 outs() << " Incorrect size\n"; 9131 else 9132 outs() << "\n"; 9133 outs() << " version " 9134 << MachOObjectFile::getVersionMinMajor(vd, false) << "." 9135 << MachOObjectFile::getVersionMinMinor(vd, false); 9136 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false); 9137 if (Update != 0) 9138 outs() << "." << Update; 9139 outs() << "\n"; 9140 if (vd.sdk == 0) 9141 outs() << " sdk n/a"; 9142 else { 9143 outs() << " sdk " 9144 << MachOObjectFile::getVersionMinMajor(vd, true) << "." 9145 << MachOObjectFile::getVersionMinMinor(vd, true); 9146 } 9147 Update = MachOObjectFile::getVersionMinUpdate(vd, true); 9148 if (Update != 0) 9149 outs() << "." << Update; 9150 outs() << "\n"; 9151 } 9152 9153 static void PrintNoteLoadCommand(MachO::note_command Nt) { 9154 outs() << " cmd LC_NOTE\n"; 9155 outs() << " cmdsize " << Nt.cmdsize; 9156 if (Nt.cmdsize != sizeof(struct MachO::note_command)) 9157 outs() << " Incorrect size\n"; 9158 else 9159 outs() << "\n"; 9160 const char *d = Nt.data_owner; 9161 outs() << "data_owner " << format("%.16s\n", d); 9162 outs() << " offset " << Nt.offset << "\n"; 9163 outs() << " size " << Nt.size << "\n"; 9164 } 9165 9166 static void PrintBuildToolVersion(MachO::build_tool_version bv) { 9167 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n"; 9168 outs() << " version " << MachOObjectFile::getVersionString(bv.version) 9169 << "\n"; 9170 } 9171 9172 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj, 9173 MachO::build_version_command bd) { 9174 outs() << " cmd LC_BUILD_VERSION\n"; 9175 outs() << " cmdsize " << bd.cmdsize; 9176 if (bd.cmdsize != 9177 sizeof(struct MachO::build_version_command) + 9178 bd.ntools * sizeof(struct MachO::build_tool_version)) 9179 outs() << " Incorrect size\n"; 9180 else 9181 outs() << "\n"; 9182 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform) 9183 << "\n"; 9184 if (bd.sdk) 9185 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk) 9186 << "\n"; 9187 else 9188 outs() << " sdk n/a\n"; 9189 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos) 9190 << "\n"; 9191 outs() << " ntools " << bd.ntools << "\n"; 9192 for (unsigned i = 0; i < bd.ntools; ++i) { 9193 MachO::build_tool_version bv = obj->getBuildToolVersion(i); 9194 PrintBuildToolVersion(bv); 9195 } 9196 } 9197 9198 static void PrintSourceVersionCommand(MachO::source_version_command sd) { 9199 outs() << " cmd LC_SOURCE_VERSION\n"; 9200 outs() << " cmdsize " << sd.cmdsize; 9201 if (sd.cmdsize != sizeof(struct MachO::source_version_command)) 9202 outs() << " Incorrect size\n"; 9203 else 9204 outs() << "\n"; 9205 uint64_t a = (sd.version >> 40) & 0xffffff; 9206 uint64_t b = (sd.version >> 30) & 0x3ff; 9207 uint64_t c = (sd.version >> 20) & 0x3ff; 9208 uint64_t d = (sd.version >> 10) & 0x3ff; 9209 uint64_t e = sd.version & 0x3ff; 9210 outs() << " version " << a << "." << b; 9211 if (e != 0) 9212 outs() << "." << c << "." << d << "." << e; 9213 else if (d != 0) 9214 outs() << "." << c << "." << d; 9215 else if (c != 0) 9216 outs() << "." << c; 9217 outs() << "\n"; 9218 } 9219 9220 static void PrintEntryPointCommand(MachO::entry_point_command ep) { 9221 outs() << " cmd LC_MAIN\n"; 9222 outs() << " cmdsize " << ep.cmdsize; 9223 if (ep.cmdsize != sizeof(struct MachO::entry_point_command)) 9224 outs() << " Incorrect size\n"; 9225 else 9226 outs() << "\n"; 9227 outs() << " entryoff " << ep.entryoff << "\n"; 9228 outs() << " stacksize " << ep.stacksize << "\n"; 9229 } 9230 9231 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec, 9232 uint32_t object_size) { 9233 outs() << " cmd LC_ENCRYPTION_INFO\n"; 9234 outs() << " cmdsize " << ec.cmdsize; 9235 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command)) 9236 outs() << " Incorrect size\n"; 9237 else 9238 outs() << "\n"; 9239 outs() << " cryptoff " << ec.cryptoff; 9240 if (ec.cryptoff > object_size) 9241 outs() << " (past end of file)\n"; 9242 else 9243 outs() << "\n"; 9244 outs() << " cryptsize " << ec.cryptsize; 9245 if (ec.cryptsize > object_size) 9246 outs() << " (past end of file)\n"; 9247 else 9248 outs() << "\n"; 9249 outs() << " cryptid " << ec.cryptid << "\n"; 9250 } 9251 9252 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec, 9253 uint32_t object_size) { 9254 outs() << " cmd LC_ENCRYPTION_INFO_64\n"; 9255 outs() << " cmdsize " << ec.cmdsize; 9256 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64)) 9257 outs() << " Incorrect size\n"; 9258 else 9259 outs() << "\n"; 9260 outs() << " cryptoff " << ec.cryptoff; 9261 if (ec.cryptoff > object_size) 9262 outs() << " (past end of file)\n"; 9263 else 9264 outs() << "\n"; 9265 outs() << " cryptsize " << ec.cryptsize; 9266 if (ec.cryptsize > object_size) 9267 outs() << " (past end of file)\n"; 9268 else 9269 outs() << "\n"; 9270 outs() << " cryptid " << ec.cryptid << "\n"; 9271 outs() << " pad " << ec.pad << "\n"; 9272 } 9273 9274 static void PrintLinkerOptionCommand(MachO::linker_option_command lo, 9275 const char *Ptr) { 9276 outs() << " cmd LC_LINKER_OPTION\n"; 9277 outs() << " cmdsize " << lo.cmdsize; 9278 if (lo.cmdsize < sizeof(struct MachO::linker_option_command)) 9279 outs() << " Incorrect size\n"; 9280 else 9281 outs() << "\n"; 9282 outs() << " count " << lo.count << "\n"; 9283 const char *string = Ptr + sizeof(struct MachO::linker_option_command); 9284 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command); 9285 uint32_t i = 0; 9286 while (left > 0) { 9287 while (*string == '\0' && left > 0) { 9288 string++; 9289 left--; 9290 } 9291 if (left > 0) { 9292 i++; 9293 outs() << " string #" << i << " " << format("%.*s\n", left, string); 9294 uint32_t NullPos = StringRef(string, left).find('\0'); 9295 uint32_t len = std::min(NullPos, left) + 1; 9296 string += len; 9297 left -= len; 9298 } 9299 } 9300 if (lo.count != i) 9301 outs() << " count " << lo.count << " does not match number of strings " 9302 << i << "\n"; 9303 } 9304 9305 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub, 9306 const char *Ptr) { 9307 outs() << " cmd LC_SUB_FRAMEWORK\n"; 9308 outs() << " cmdsize " << sub.cmdsize; 9309 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command)) 9310 outs() << " Incorrect size\n"; 9311 else 9312 outs() << "\n"; 9313 if (sub.umbrella < sub.cmdsize) { 9314 const char *P = Ptr + sub.umbrella; 9315 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n"; 9316 } else { 9317 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n"; 9318 } 9319 } 9320 9321 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub, 9322 const char *Ptr) { 9323 outs() << " cmd LC_SUB_UMBRELLA\n"; 9324 outs() << " cmdsize " << sub.cmdsize; 9325 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command)) 9326 outs() << " Incorrect size\n"; 9327 else 9328 outs() << "\n"; 9329 if (sub.sub_umbrella < sub.cmdsize) { 9330 const char *P = Ptr + sub.sub_umbrella; 9331 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n"; 9332 } else { 9333 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n"; 9334 } 9335 } 9336 9337 static void PrintSubLibraryCommand(MachO::sub_library_command sub, 9338 const char *Ptr) { 9339 outs() << " cmd LC_SUB_LIBRARY\n"; 9340 outs() << " cmdsize " << sub.cmdsize; 9341 if (sub.cmdsize < sizeof(struct MachO::sub_library_command)) 9342 outs() << " Incorrect size\n"; 9343 else 9344 outs() << "\n"; 9345 if (sub.sub_library < sub.cmdsize) { 9346 const char *P = Ptr + sub.sub_library; 9347 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n"; 9348 } else { 9349 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n"; 9350 } 9351 } 9352 9353 static void PrintSubClientCommand(MachO::sub_client_command sub, 9354 const char *Ptr) { 9355 outs() << " cmd LC_SUB_CLIENT\n"; 9356 outs() << " cmdsize " << sub.cmdsize; 9357 if (sub.cmdsize < sizeof(struct MachO::sub_client_command)) 9358 outs() << " Incorrect size\n"; 9359 else 9360 outs() << "\n"; 9361 if (sub.client < sub.cmdsize) { 9362 const char *P = Ptr + sub.client; 9363 outs() << " client " << P << " (offset " << sub.client << ")\n"; 9364 } else { 9365 outs() << " client ?(bad offset " << sub.client << ")\n"; 9366 } 9367 } 9368 9369 static void PrintRoutinesCommand(MachO::routines_command r) { 9370 outs() << " cmd LC_ROUTINES\n"; 9371 outs() << " cmdsize " << r.cmdsize; 9372 if (r.cmdsize != sizeof(struct MachO::routines_command)) 9373 outs() << " Incorrect size\n"; 9374 else 9375 outs() << "\n"; 9376 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n"; 9377 outs() << " init_module " << r.init_module << "\n"; 9378 outs() << " reserved1 " << r.reserved1 << "\n"; 9379 outs() << " reserved2 " << r.reserved2 << "\n"; 9380 outs() << " reserved3 " << r.reserved3 << "\n"; 9381 outs() << " reserved4 " << r.reserved4 << "\n"; 9382 outs() << " reserved5 " << r.reserved5 << "\n"; 9383 outs() << " reserved6 " << r.reserved6 << "\n"; 9384 } 9385 9386 static void PrintRoutinesCommand64(MachO::routines_command_64 r) { 9387 outs() << " cmd LC_ROUTINES_64\n"; 9388 outs() << " cmdsize " << r.cmdsize; 9389 if (r.cmdsize != sizeof(struct MachO::routines_command_64)) 9390 outs() << " Incorrect size\n"; 9391 else 9392 outs() << "\n"; 9393 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n"; 9394 outs() << " init_module " << r.init_module << "\n"; 9395 outs() << " reserved1 " << r.reserved1 << "\n"; 9396 outs() << " reserved2 " << r.reserved2 << "\n"; 9397 outs() << " reserved3 " << r.reserved3 << "\n"; 9398 outs() << " reserved4 " << r.reserved4 << "\n"; 9399 outs() << " reserved5 " << r.reserved5 << "\n"; 9400 outs() << " reserved6 " << r.reserved6 << "\n"; 9401 } 9402 9403 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) { 9404 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax); 9405 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx); 9406 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx); 9407 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n"; 9408 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi); 9409 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi); 9410 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp); 9411 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n"; 9412 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss); 9413 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags); 9414 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip); 9415 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n"; 9416 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds); 9417 outs() << " es " << format("0x%08" PRIx32, cpu32.es); 9418 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs); 9419 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n"; 9420 } 9421 9422 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) { 9423 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax); 9424 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx); 9425 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n"; 9426 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx); 9427 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi); 9428 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n"; 9429 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp); 9430 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp); 9431 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n"; 9432 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9); 9433 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10); 9434 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n"; 9435 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12); 9436 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13); 9437 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n"; 9438 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15); 9439 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n"; 9440 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags); 9441 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs); 9442 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n"; 9443 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n"; 9444 } 9445 9446 static void Print_mmst_reg(MachO::mmst_reg_t &r) { 9447 uint32_t f; 9448 outs() << "\t mmst_reg "; 9449 for (f = 0; f < 10; f++) 9450 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " "; 9451 outs() << "\n"; 9452 outs() << "\t mmst_rsrv "; 9453 for (f = 0; f < 6; f++) 9454 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " "; 9455 outs() << "\n"; 9456 } 9457 9458 static void Print_xmm_reg(MachO::xmm_reg_t &r) { 9459 uint32_t f; 9460 outs() << "\t xmm_reg "; 9461 for (f = 0; f < 16; f++) 9462 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " "; 9463 outs() << "\n"; 9464 } 9465 9466 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) { 9467 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0]; 9468 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n"; 9469 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid; 9470 outs() << " denorm " << fpu.fpu_fcw.denorm; 9471 outs() << " zdiv " << fpu.fpu_fcw.zdiv; 9472 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl; 9473 outs() << " undfl " << fpu.fpu_fcw.undfl; 9474 outs() << " precis " << fpu.fpu_fcw.precis << "\n"; 9475 outs() << "\t\t pc "; 9476 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B) 9477 outs() << "FP_PREC_24B "; 9478 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B) 9479 outs() << "FP_PREC_53B "; 9480 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B) 9481 outs() << "FP_PREC_64B "; 9482 else 9483 outs() << fpu.fpu_fcw.pc << " "; 9484 outs() << "rc "; 9485 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR) 9486 outs() << "FP_RND_NEAR "; 9487 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN) 9488 outs() << "FP_RND_DOWN "; 9489 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP) 9490 outs() << "FP_RND_UP "; 9491 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP) 9492 outs() << "FP_CHOP "; 9493 outs() << "\n"; 9494 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid; 9495 outs() << " denorm " << fpu.fpu_fsw.denorm; 9496 outs() << " zdiv " << fpu.fpu_fsw.zdiv; 9497 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl; 9498 outs() << " undfl " << fpu.fpu_fsw.undfl; 9499 outs() << " precis " << fpu.fpu_fsw.precis; 9500 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n"; 9501 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm; 9502 outs() << " c0 " << fpu.fpu_fsw.c0; 9503 outs() << " c1 " << fpu.fpu_fsw.c1; 9504 outs() << " c2 " << fpu.fpu_fsw.c2; 9505 outs() << " tos " << fpu.fpu_fsw.tos; 9506 outs() << " c3 " << fpu.fpu_fsw.c3; 9507 outs() << " busy " << fpu.fpu_fsw.busy << "\n"; 9508 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw); 9509 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1); 9510 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop); 9511 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n"; 9512 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs); 9513 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2); 9514 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp); 9515 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n"; 9516 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3); 9517 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr); 9518 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask); 9519 outs() << "\n"; 9520 outs() << "\t fpu_stmm0:\n"; 9521 Print_mmst_reg(fpu.fpu_stmm0); 9522 outs() << "\t fpu_stmm1:\n"; 9523 Print_mmst_reg(fpu.fpu_stmm1); 9524 outs() << "\t fpu_stmm2:\n"; 9525 Print_mmst_reg(fpu.fpu_stmm2); 9526 outs() << "\t fpu_stmm3:\n"; 9527 Print_mmst_reg(fpu.fpu_stmm3); 9528 outs() << "\t fpu_stmm4:\n"; 9529 Print_mmst_reg(fpu.fpu_stmm4); 9530 outs() << "\t fpu_stmm5:\n"; 9531 Print_mmst_reg(fpu.fpu_stmm5); 9532 outs() << "\t fpu_stmm6:\n"; 9533 Print_mmst_reg(fpu.fpu_stmm6); 9534 outs() << "\t fpu_stmm7:\n"; 9535 Print_mmst_reg(fpu.fpu_stmm7); 9536 outs() << "\t fpu_xmm0:\n"; 9537 Print_xmm_reg(fpu.fpu_xmm0); 9538 outs() << "\t fpu_xmm1:\n"; 9539 Print_xmm_reg(fpu.fpu_xmm1); 9540 outs() << "\t fpu_xmm2:\n"; 9541 Print_xmm_reg(fpu.fpu_xmm2); 9542 outs() << "\t fpu_xmm3:\n"; 9543 Print_xmm_reg(fpu.fpu_xmm3); 9544 outs() << "\t fpu_xmm4:\n"; 9545 Print_xmm_reg(fpu.fpu_xmm4); 9546 outs() << "\t fpu_xmm5:\n"; 9547 Print_xmm_reg(fpu.fpu_xmm5); 9548 outs() << "\t fpu_xmm6:\n"; 9549 Print_xmm_reg(fpu.fpu_xmm6); 9550 outs() << "\t fpu_xmm7:\n"; 9551 Print_xmm_reg(fpu.fpu_xmm7); 9552 outs() << "\t fpu_xmm8:\n"; 9553 Print_xmm_reg(fpu.fpu_xmm8); 9554 outs() << "\t fpu_xmm9:\n"; 9555 Print_xmm_reg(fpu.fpu_xmm9); 9556 outs() << "\t fpu_xmm10:\n"; 9557 Print_xmm_reg(fpu.fpu_xmm10); 9558 outs() << "\t fpu_xmm11:\n"; 9559 Print_xmm_reg(fpu.fpu_xmm11); 9560 outs() << "\t fpu_xmm12:\n"; 9561 Print_xmm_reg(fpu.fpu_xmm12); 9562 outs() << "\t fpu_xmm13:\n"; 9563 Print_xmm_reg(fpu.fpu_xmm13); 9564 outs() << "\t fpu_xmm14:\n"; 9565 Print_xmm_reg(fpu.fpu_xmm14); 9566 outs() << "\t fpu_xmm15:\n"; 9567 Print_xmm_reg(fpu.fpu_xmm15); 9568 outs() << "\t fpu_rsrv4:\n"; 9569 for (uint32_t f = 0; f < 6; f++) { 9570 outs() << "\t "; 9571 for (uint32_t g = 0; g < 16; g++) 9572 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " "; 9573 outs() << "\n"; 9574 } 9575 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1); 9576 outs() << "\n"; 9577 } 9578 9579 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) { 9580 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno); 9581 outs() << " err " << format("0x%08" PRIx32, exc64.err); 9582 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n"; 9583 } 9584 9585 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) { 9586 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]); 9587 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]); 9588 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]); 9589 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n"; 9590 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]); 9591 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]); 9592 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]); 9593 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n"; 9594 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]); 9595 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]); 9596 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]); 9597 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n"; 9598 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]); 9599 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp); 9600 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr); 9601 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n"; 9602 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n"; 9603 } 9604 9605 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) { 9606 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]); 9607 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]); 9608 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n"; 9609 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]); 9610 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]); 9611 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n"; 9612 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]); 9613 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]); 9614 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n"; 9615 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]); 9616 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]); 9617 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n"; 9618 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]); 9619 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]); 9620 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n"; 9621 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]); 9622 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]); 9623 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n"; 9624 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]); 9625 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]); 9626 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n"; 9627 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]); 9628 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]); 9629 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n"; 9630 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]); 9631 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]); 9632 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n"; 9633 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]); 9634 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]); 9635 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n"; 9636 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr); 9637 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp); 9638 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n"; 9639 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n"; 9640 } 9641 9642 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr, 9643 bool isLittleEndian, uint32_t cputype) { 9644 if (t.cmd == MachO::LC_THREAD) 9645 outs() << " cmd LC_THREAD\n"; 9646 else if (t.cmd == MachO::LC_UNIXTHREAD) 9647 outs() << " cmd LC_UNIXTHREAD\n"; 9648 else 9649 outs() << " cmd " << t.cmd << " (unknown)\n"; 9650 outs() << " cmdsize " << t.cmdsize; 9651 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t)) 9652 outs() << " Incorrect size\n"; 9653 else 9654 outs() << "\n"; 9655 9656 const char *begin = Ptr + sizeof(struct MachO::thread_command); 9657 const char *end = Ptr + t.cmdsize; 9658 uint32_t flavor, count, left; 9659 if (cputype == MachO::CPU_TYPE_I386) { 9660 while (begin < end) { 9661 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9662 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9663 begin += sizeof(uint32_t); 9664 } else { 9665 flavor = 0; 9666 begin = end; 9667 } 9668 if (isLittleEndian != sys::IsLittleEndianHost) 9669 sys::swapByteOrder(flavor); 9670 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9671 memcpy((char *)&count, begin, sizeof(uint32_t)); 9672 begin += sizeof(uint32_t); 9673 } else { 9674 count = 0; 9675 begin = end; 9676 } 9677 if (isLittleEndian != sys::IsLittleEndianHost) 9678 sys::swapByteOrder(count); 9679 if (flavor == MachO::x86_THREAD_STATE32) { 9680 outs() << " flavor i386_THREAD_STATE\n"; 9681 if (count == MachO::x86_THREAD_STATE32_COUNT) 9682 outs() << " count i386_THREAD_STATE_COUNT\n"; 9683 else 9684 outs() << " count " << count 9685 << " (not x86_THREAD_STATE32_COUNT)\n"; 9686 MachO::x86_thread_state32_t cpu32; 9687 left = end - begin; 9688 if (left >= sizeof(MachO::x86_thread_state32_t)) { 9689 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t)); 9690 begin += sizeof(MachO::x86_thread_state32_t); 9691 } else { 9692 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t)); 9693 memcpy(&cpu32, begin, left); 9694 begin += left; 9695 } 9696 if (isLittleEndian != sys::IsLittleEndianHost) 9697 swapStruct(cpu32); 9698 Print_x86_thread_state32_t(cpu32); 9699 } else if (flavor == MachO::x86_THREAD_STATE) { 9700 outs() << " flavor x86_THREAD_STATE\n"; 9701 if (count == MachO::x86_THREAD_STATE_COUNT) 9702 outs() << " count x86_THREAD_STATE_COUNT\n"; 9703 else 9704 outs() << " count " << count 9705 << " (not x86_THREAD_STATE_COUNT)\n"; 9706 struct MachO::x86_thread_state_t ts; 9707 left = end - begin; 9708 if (left >= sizeof(MachO::x86_thread_state_t)) { 9709 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); 9710 begin += sizeof(MachO::x86_thread_state_t); 9711 } else { 9712 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); 9713 memcpy(&ts, begin, left); 9714 begin += left; 9715 } 9716 if (isLittleEndian != sys::IsLittleEndianHost) 9717 swapStruct(ts); 9718 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) { 9719 outs() << "\t tsh.flavor x86_THREAD_STATE32 "; 9720 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT) 9721 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n"; 9722 else 9723 outs() << "tsh.count " << ts.tsh.count 9724 << " (not x86_THREAD_STATE32_COUNT\n"; 9725 Print_x86_thread_state32_t(ts.uts.ts32); 9726 } else { 9727 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " 9728 << ts.tsh.count << "\n"; 9729 } 9730 } else { 9731 outs() << " flavor " << flavor << " (unknown)\n"; 9732 outs() << " count " << count << "\n"; 9733 outs() << " state (unknown)\n"; 9734 begin += count * sizeof(uint32_t); 9735 } 9736 } 9737 } else if (cputype == MachO::CPU_TYPE_X86_64) { 9738 while (begin < end) { 9739 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9740 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9741 begin += sizeof(uint32_t); 9742 } else { 9743 flavor = 0; 9744 begin = end; 9745 } 9746 if (isLittleEndian != sys::IsLittleEndianHost) 9747 sys::swapByteOrder(flavor); 9748 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9749 memcpy((char *)&count, begin, sizeof(uint32_t)); 9750 begin += sizeof(uint32_t); 9751 } else { 9752 count = 0; 9753 begin = end; 9754 } 9755 if (isLittleEndian != sys::IsLittleEndianHost) 9756 sys::swapByteOrder(count); 9757 if (flavor == MachO::x86_THREAD_STATE64) { 9758 outs() << " flavor x86_THREAD_STATE64\n"; 9759 if (count == MachO::x86_THREAD_STATE64_COUNT) 9760 outs() << " count x86_THREAD_STATE64_COUNT\n"; 9761 else 9762 outs() << " count " << count 9763 << " (not x86_THREAD_STATE64_COUNT)\n"; 9764 MachO::x86_thread_state64_t cpu64; 9765 left = end - begin; 9766 if (left >= sizeof(MachO::x86_thread_state64_t)) { 9767 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t)); 9768 begin += sizeof(MachO::x86_thread_state64_t); 9769 } else { 9770 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t)); 9771 memcpy(&cpu64, begin, left); 9772 begin += left; 9773 } 9774 if (isLittleEndian != sys::IsLittleEndianHost) 9775 swapStruct(cpu64); 9776 Print_x86_thread_state64_t(cpu64); 9777 } else if (flavor == MachO::x86_THREAD_STATE) { 9778 outs() << " flavor x86_THREAD_STATE\n"; 9779 if (count == MachO::x86_THREAD_STATE_COUNT) 9780 outs() << " count x86_THREAD_STATE_COUNT\n"; 9781 else 9782 outs() << " count " << count 9783 << " (not x86_THREAD_STATE_COUNT)\n"; 9784 struct MachO::x86_thread_state_t ts; 9785 left = end - begin; 9786 if (left >= sizeof(MachO::x86_thread_state_t)) { 9787 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t)); 9788 begin += sizeof(MachO::x86_thread_state_t); 9789 } else { 9790 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t)); 9791 memcpy(&ts, begin, left); 9792 begin += left; 9793 } 9794 if (isLittleEndian != sys::IsLittleEndianHost) 9795 swapStruct(ts); 9796 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) { 9797 outs() << "\t tsh.flavor x86_THREAD_STATE64 "; 9798 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT) 9799 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n"; 9800 else 9801 outs() << "tsh.count " << ts.tsh.count 9802 << " (not x86_THREAD_STATE64_COUNT\n"; 9803 Print_x86_thread_state64_t(ts.uts.ts64); 9804 } else { 9805 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count " 9806 << ts.tsh.count << "\n"; 9807 } 9808 } else if (flavor == MachO::x86_FLOAT_STATE) { 9809 outs() << " flavor x86_FLOAT_STATE\n"; 9810 if (count == MachO::x86_FLOAT_STATE_COUNT) 9811 outs() << " count x86_FLOAT_STATE_COUNT\n"; 9812 else 9813 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n"; 9814 struct MachO::x86_float_state_t fs; 9815 left = end - begin; 9816 if (left >= sizeof(MachO::x86_float_state_t)) { 9817 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t)); 9818 begin += sizeof(MachO::x86_float_state_t); 9819 } else { 9820 memset(&fs, '\0', sizeof(MachO::x86_float_state_t)); 9821 memcpy(&fs, begin, left); 9822 begin += left; 9823 } 9824 if (isLittleEndian != sys::IsLittleEndianHost) 9825 swapStruct(fs); 9826 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) { 9827 outs() << "\t fsh.flavor x86_FLOAT_STATE64 "; 9828 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT) 9829 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n"; 9830 else 9831 outs() << "fsh.count " << fs.fsh.count 9832 << " (not x86_FLOAT_STATE64_COUNT\n"; 9833 Print_x86_float_state_t(fs.ufs.fs64); 9834 } else { 9835 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count " 9836 << fs.fsh.count << "\n"; 9837 } 9838 } else if (flavor == MachO::x86_EXCEPTION_STATE) { 9839 outs() << " flavor x86_EXCEPTION_STATE\n"; 9840 if (count == MachO::x86_EXCEPTION_STATE_COUNT) 9841 outs() << " count x86_EXCEPTION_STATE_COUNT\n"; 9842 else 9843 outs() << " count " << count 9844 << " (not x86_EXCEPTION_STATE_COUNT)\n"; 9845 struct MachO::x86_exception_state_t es; 9846 left = end - begin; 9847 if (left >= sizeof(MachO::x86_exception_state_t)) { 9848 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t)); 9849 begin += sizeof(MachO::x86_exception_state_t); 9850 } else { 9851 memset(&es, '\0', sizeof(MachO::x86_exception_state_t)); 9852 memcpy(&es, begin, left); 9853 begin += left; 9854 } 9855 if (isLittleEndian != sys::IsLittleEndianHost) 9856 swapStruct(es); 9857 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) { 9858 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n"; 9859 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT) 9860 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n"; 9861 else 9862 outs() << "\t esh.count " << es.esh.count 9863 << " (not x86_EXCEPTION_STATE64_COUNT\n"; 9864 Print_x86_exception_state_t(es.ues.es64); 9865 } else { 9866 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count " 9867 << es.esh.count << "\n"; 9868 } 9869 } else if (flavor == MachO::x86_EXCEPTION_STATE64) { 9870 outs() << " flavor x86_EXCEPTION_STATE64\n"; 9871 if (count == MachO::x86_EXCEPTION_STATE64_COUNT) 9872 outs() << " count x86_EXCEPTION_STATE64_COUNT\n"; 9873 else 9874 outs() << " count " << count 9875 << " (not x86_EXCEPTION_STATE64_COUNT)\n"; 9876 struct MachO::x86_exception_state64_t es64; 9877 left = end - begin; 9878 if (left >= sizeof(MachO::x86_exception_state64_t)) { 9879 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t)); 9880 begin += sizeof(MachO::x86_exception_state64_t); 9881 } else { 9882 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t)); 9883 memcpy(&es64, begin, left); 9884 begin += left; 9885 } 9886 if (isLittleEndian != sys::IsLittleEndianHost) 9887 swapStruct(es64); 9888 Print_x86_exception_state_t(es64); 9889 } else { 9890 outs() << " flavor " << flavor << " (unknown)\n"; 9891 outs() << " count " << count << "\n"; 9892 outs() << " state (unknown)\n"; 9893 begin += count * sizeof(uint32_t); 9894 } 9895 } 9896 } else if (cputype == MachO::CPU_TYPE_ARM) { 9897 while (begin < end) { 9898 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9899 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9900 begin += sizeof(uint32_t); 9901 } else { 9902 flavor = 0; 9903 begin = end; 9904 } 9905 if (isLittleEndian != sys::IsLittleEndianHost) 9906 sys::swapByteOrder(flavor); 9907 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9908 memcpy((char *)&count, begin, sizeof(uint32_t)); 9909 begin += sizeof(uint32_t); 9910 } else { 9911 count = 0; 9912 begin = end; 9913 } 9914 if (isLittleEndian != sys::IsLittleEndianHost) 9915 sys::swapByteOrder(count); 9916 if (flavor == MachO::ARM_THREAD_STATE) { 9917 outs() << " flavor ARM_THREAD_STATE\n"; 9918 if (count == MachO::ARM_THREAD_STATE_COUNT) 9919 outs() << " count ARM_THREAD_STATE_COUNT\n"; 9920 else 9921 outs() << " count " << count 9922 << " (not ARM_THREAD_STATE_COUNT)\n"; 9923 MachO::arm_thread_state32_t cpu32; 9924 left = end - begin; 9925 if (left >= sizeof(MachO::arm_thread_state32_t)) { 9926 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t)); 9927 begin += sizeof(MachO::arm_thread_state32_t); 9928 } else { 9929 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t)); 9930 memcpy(&cpu32, begin, left); 9931 begin += left; 9932 } 9933 if (isLittleEndian != sys::IsLittleEndianHost) 9934 swapStruct(cpu32); 9935 Print_arm_thread_state32_t(cpu32); 9936 } else { 9937 outs() << " flavor " << flavor << " (unknown)\n"; 9938 outs() << " count " << count << "\n"; 9939 outs() << " state (unknown)\n"; 9940 begin += count * sizeof(uint32_t); 9941 } 9942 } 9943 } else if (cputype == MachO::CPU_TYPE_ARM64 || 9944 cputype == MachO::CPU_TYPE_ARM64_32) { 9945 while (begin < end) { 9946 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9947 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9948 begin += sizeof(uint32_t); 9949 } else { 9950 flavor = 0; 9951 begin = end; 9952 } 9953 if (isLittleEndian != sys::IsLittleEndianHost) 9954 sys::swapByteOrder(flavor); 9955 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9956 memcpy((char *)&count, begin, sizeof(uint32_t)); 9957 begin += sizeof(uint32_t); 9958 } else { 9959 count = 0; 9960 begin = end; 9961 } 9962 if (isLittleEndian != sys::IsLittleEndianHost) 9963 sys::swapByteOrder(count); 9964 if (flavor == MachO::ARM_THREAD_STATE64) { 9965 outs() << " flavor ARM_THREAD_STATE64\n"; 9966 if (count == MachO::ARM_THREAD_STATE64_COUNT) 9967 outs() << " count ARM_THREAD_STATE64_COUNT\n"; 9968 else 9969 outs() << " count " << count 9970 << " (not ARM_THREAD_STATE64_COUNT)\n"; 9971 MachO::arm_thread_state64_t cpu64; 9972 left = end - begin; 9973 if (left >= sizeof(MachO::arm_thread_state64_t)) { 9974 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t)); 9975 begin += sizeof(MachO::arm_thread_state64_t); 9976 } else { 9977 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t)); 9978 memcpy(&cpu64, begin, left); 9979 begin += left; 9980 } 9981 if (isLittleEndian != sys::IsLittleEndianHost) 9982 swapStruct(cpu64); 9983 Print_arm_thread_state64_t(cpu64); 9984 } else { 9985 outs() << " flavor " << flavor << " (unknown)\n"; 9986 outs() << " count " << count << "\n"; 9987 outs() << " state (unknown)\n"; 9988 begin += count * sizeof(uint32_t); 9989 } 9990 } 9991 } else { 9992 while (begin < end) { 9993 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 9994 memcpy((char *)&flavor, begin, sizeof(uint32_t)); 9995 begin += sizeof(uint32_t); 9996 } else { 9997 flavor = 0; 9998 begin = end; 9999 } 10000 if (isLittleEndian != sys::IsLittleEndianHost) 10001 sys::swapByteOrder(flavor); 10002 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) { 10003 memcpy((char *)&count, begin, sizeof(uint32_t)); 10004 begin += sizeof(uint32_t); 10005 } else { 10006 count = 0; 10007 begin = end; 10008 } 10009 if (isLittleEndian != sys::IsLittleEndianHost) 10010 sys::swapByteOrder(count); 10011 outs() << " flavor " << flavor << "\n"; 10012 outs() << " count " << count << "\n"; 10013 outs() << " state (Unknown cputype/cpusubtype)\n"; 10014 begin += count * sizeof(uint32_t); 10015 } 10016 } 10017 } 10018 10019 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) { 10020 if (dl.cmd == MachO::LC_ID_DYLIB) 10021 outs() << " cmd LC_ID_DYLIB\n"; 10022 else if (dl.cmd == MachO::LC_LOAD_DYLIB) 10023 outs() << " cmd LC_LOAD_DYLIB\n"; 10024 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB) 10025 outs() << " cmd LC_LOAD_WEAK_DYLIB\n"; 10026 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB) 10027 outs() << " cmd LC_REEXPORT_DYLIB\n"; 10028 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB) 10029 outs() << " cmd LC_LAZY_LOAD_DYLIB\n"; 10030 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB) 10031 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n"; 10032 else 10033 outs() << " cmd " << dl.cmd << " (unknown)\n"; 10034 outs() << " cmdsize " << dl.cmdsize; 10035 if (dl.cmdsize < sizeof(struct MachO::dylib_command)) 10036 outs() << " Incorrect size\n"; 10037 else 10038 outs() << "\n"; 10039 if (dl.dylib.name < dl.cmdsize) { 10040 const char *P = (const char *)(Ptr) + dl.dylib.name; 10041 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n"; 10042 } else { 10043 outs() << " name ?(bad offset " << dl.dylib.name << ")\n"; 10044 } 10045 outs() << " time stamp " << dl.dylib.timestamp << " "; 10046 time_t t = dl.dylib.timestamp; 10047 outs() << ctime(&t); 10048 outs() << " current version "; 10049 if (dl.dylib.current_version == 0xffffffff) 10050 outs() << "n/a\n"; 10051 else 10052 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "." 10053 << ((dl.dylib.current_version >> 8) & 0xff) << "." 10054 << (dl.dylib.current_version & 0xff) << "\n"; 10055 outs() << "compatibility version "; 10056 if (dl.dylib.compatibility_version == 0xffffffff) 10057 outs() << "n/a\n"; 10058 else 10059 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "." 10060 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "." 10061 << (dl.dylib.compatibility_version & 0xff) << "\n"; 10062 } 10063 10064 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld, 10065 uint32_t object_size) { 10066 if (ld.cmd == MachO::LC_CODE_SIGNATURE) 10067 outs() << " cmd LC_CODE_SIGNATURE\n"; 10068 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO) 10069 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n"; 10070 else if (ld.cmd == MachO::LC_FUNCTION_STARTS) 10071 outs() << " cmd LC_FUNCTION_STARTS\n"; 10072 else if (ld.cmd == MachO::LC_DATA_IN_CODE) 10073 outs() << " cmd LC_DATA_IN_CODE\n"; 10074 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS) 10075 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n"; 10076 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) 10077 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n"; 10078 else if (ld.cmd == MachO::LC_DYLD_EXPORTS_TRIE) 10079 outs() << " cmd LC_DYLD_EXPORTS_TRIE\n"; 10080 else if (ld.cmd == MachO::LC_DYLD_CHAINED_FIXUPS) 10081 outs() << " cmd LC_DYLD_CHAINED_FIXUPS\n"; 10082 else 10083 outs() << " cmd " << ld.cmd << " (?)\n"; 10084 outs() << " cmdsize " << ld.cmdsize; 10085 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command)) 10086 outs() << " Incorrect size\n"; 10087 else 10088 outs() << "\n"; 10089 outs() << " dataoff " << ld.dataoff; 10090 if (ld.dataoff > object_size) 10091 outs() << " (past end of file)\n"; 10092 else 10093 outs() << "\n"; 10094 outs() << " datasize " << ld.datasize; 10095 uint64_t big_size = ld.dataoff; 10096 big_size += ld.datasize; 10097 if (big_size > object_size) 10098 outs() << " (past end of file)\n"; 10099 else 10100 outs() << "\n"; 10101 } 10102 10103 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype, 10104 uint32_t cputype, bool verbose) { 10105 StringRef Buf = Obj->getData(); 10106 unsigned Index = 0; 10107 for (const auto &Command : Obj->load_commands()) { 10108 outs() << "Load command " << Index++ << "\n"; 10109 if (Command.C.cmd == MachO::LC_SEGMENT) { 10110 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command); 10111 const char *sg_segname = SLC.segname; 10112 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr, 10113 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot, 10114 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(), 10115 verbose); 10116 for (unsigned j = 0; j < SLC.nsects; j++) { 10117 MachO::section S = Obj->getSection(Command, j); 10118 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align, 10119 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2, 10120 SLC.cmd, sg_segname, filetype, Buf.size(), verbose); 10121 } 10122 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 10123 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command); 10124 const char *sg_segname = SLC_64.segname; 10125 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname, 10126 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff, 10127 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot, 10128 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose); 10129 for (unsigned j = 0; j < SLC_64.nsects; j++) { 10130 MachO::section_64 S_64 = Obj->getSection64(Command, j); 10131 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size, 10132 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc, 10133 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd, 10134 sg_segname, filetype, Buf.size(), verbose); 10135 } 10136 } else if (Command.C.cmd == MachO::LC_SYMTAB) { 10137 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); 10138 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size()); 10139 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) { 10140 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand(); 10141 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand(); 10142 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(), 10143 Obj->is64Bit()); 10144 } else if (Command.C.cmd == MachO::LC_DYLD_INFO || 10145 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) { 10146 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command); 10147 PrintDyldInfoLoadCommand(DyldInfo, Buf.size()); 10148 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER || 10149 Command.C.cmd == MachO::LC_ID_DYLINKER || 10150 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) { 10151 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command); 10152 PrintDyldLoadCommand(Dyld, Command.Ptr); 10153 } else if (Command.C.cmd == MachO::LC_UUID) { 10154 MachO::uuid_command Uuid = Obj->getUuidCommand(Command); 10155 PrintUuidLoadCommand(Uuid); 10156 } else if (Command.C.cmd == MachO::LC_RPATH) { 10157 MachO::rpath_command Rpath = Obj->getRpathCommand(Command); 10158 PrintRpathLoadCommand(Rpath, Command.Ptr); 10159 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX || 10160 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS || 10161 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS || 10162 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) { 10163 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command); 10164 PrintVersionMinLoadCommand(Vd); 10165 } else if (Command.C.cmd == MachO::LC_NOTE) { 10166 MachO::note_command Nt = Obj->getNoteLoadCommand(Command); 10167 PrintNoteLoadCommand(Nt); 10168 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) { 10169 MachO::build_version_command Bv = 10170 Obj->getBuildVersionLoadCommand(Command); 10171 PrintBuildVersionLoadCommand(Obj, Bv); 10172 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) { 10173 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command); 10174 PrintSourceVersionCommand(Sd); 10175 } else if (Command.C.cmd == MachO::LC_MAIN) { 10176 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command); 10177 PrintEntryPointCommand(Ep); 10178 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) { 10179 MachO::encryption_info_command Ei = 10180 Obj->getEncryptionInfoCommand(Command); 10181 PrintEncryptionInfoCommand(Ei, Buf.size()); 10182 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) { 10183 MachO::encryption_info_command_64 Ei = 10184 Obj->getEncryptionInfoCommand64(Command); 10185 PrintEncryptionInfoCommand64(Ei, Buf.size()); 10186 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) { 10187 MachO::linker_option_command Lo = 10188 Obj->getLinkerOptionLoadCommand(Command); 10189 PrintLinkerOptionCommand(Lo, Command.Ptr); 10190 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) { 10191 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command); 10192 PrintSubFrameworkCommand(Sf, Command.Ptr); 10193 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) { 10194 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command); 10195 PrintSubUmbrellaCommand(Sf, Command.Ptr); 10196 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) { 10197 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command); 10198 PrintSubLibraryCommand(Sl, Command.Ptr); 10199 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) { 10200 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command); 10201 PrintSubClientCommand(Sc, Command.Ptr); 10202 } else if (Command.C.cmd == MachO::LC_ROUTINES) { 10203 MachO::routines_command Rc = Obj->getRoutinesCommand(Command); 10204 PrintRoutinesCommand(Rc); 10205 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) { 10206 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command); 10207 PrintRoutinesCommand64(Rc); 10208 } else if (Command.C.cmd == MachO::LC_THREAD || 10209 Command.C.cmd == MachO::LC_UNIXTHREAD) { 10210 MachO::thread_command Tc = Obj->getThreadCommand(Command); 10211 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype); 10212 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB || 10213 Command.C.cmd == MachO::LC_ID_DYLIB || 10214 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB || 10215 Command.C.cmd == MachO::LC_REEXPORT_DYLIB || 10216 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB || 10217 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) { 10218 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command); 10219 PrintDylibCommand(Dl, Command.Ptr); 10220 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE || 10221 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO || 10222 Command.C.cmd == MachO::LC_FUNCTION_STARTS || 10223 Command.C.cmd == MachO::LC_DATA_IN_CODE || 10224 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS || 10225 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT || 10226 Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE || 10227 Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS) { 10228 MachO::linkedit_data_command Ld = 10229 Obj->getLinkeditDataLoadCommand(Command); 10230 PrintLinkEditDataCommand(Ld, Buf.size()); 10231 } else { 10232 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd) 10233 << ")\n"; 10234 outs() << " cmdsize " << Command.C.cmdsize << "\n"; 10235 // TODO: get and print the raw bytes of the load command. 10236 } 10237 // TODO: print all the other kinds of load commands. 10238 } 10239 } 10240 10241 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) { 10242 if (Obj->is64Bit()) { 10243 MachO::mach_header_64 H_64; 10244 H_64 = Obj->getHeader64(); 10245 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype, 10246 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose); 10247 } else { 10248 MachO::mach_header H; 10249 H = Obj->getHeader(); 10250 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds, 10251 H.sizeofcmds, H.flags, verbose); 10252 } 10253 } 10254 10255 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) { 10256 const MachOObjectFile *file = cast<const MachOObjectFile>(Obj); 10257 PrintMachHeader(file, Verbose); 10258 } 10259 10260 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) { 10261 const MachOObjectFile *file = cast<const MachOObjectFile>(Obj); 10262 uint32_t filetype = 0; 10263 uint32_t cputype = 0; 10264 if (file->is64Bit()) { 10265 MachO::mach_header_64 H_64; 10266 H_64 = file->getHeader64(); 10267 filetype = H_64.filetype; 10268 cputype = H_64.cputype; 10269 } else { 10270 MachO::mach_header H; 10271 H = file->getHeader(); 10272 filetype = H.filetype; 10273 cputype = H.cputype; 10274 } 10275 PrintLoadCommands(file, filetype, cputype, Verbose); 10276 } 10277 10278 //===----------------------------------------------------------------------===// 10279 // export trie dumping 10280 //===----------------------------------------------------------------------===// 10281 10282 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) { 10283 uint64_t BaseSegmentAddress = 0; 10284 for (const auto &Command : Obj->load_commands()) { 10285 if (Command.C.cmd == MachO::LC_SEGMENT) { 10286 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command); 10287 if (Seg.fileoff == 0 && Seg.filesize != 0) { 10288 BaseSegmentAddress = Seg.vmaddr; 10289 break; 10290 } 10291 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) { 10292 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command); 10293 if (Seg.fileoff == 0 && Seg.filesize != 0) { 10294 BaseSegmentAddress = Seg.vmaddr; 10295 break; 10296 } 10297 } 10298 } 10299 Error Err = Error::success(); 10300 for (const object::ExportEntry &Entry : Obj->exports(Err)) { 10301 uint64_t Flags = Entry.flags(); 10302 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT); 10303 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION); 10304 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 10305 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL); 10306 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) == 10307 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE); 10308 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER); 10309 if (ReExport) 10310 outs() << "[re-export] "; 10311 else 10312 outs() << format("0x%08llX ", 10313 Entry.address() + BaseSegmentAddress); 10314 outs() << Entry.name(); 10315 if (WeakDef || ThreadLocal || Resolver || Abs) { 10316 ListSeparator LS; 10317 outs() << " ["; 10318 if (WeakDef) 10319 outs() << LS << "weak_def"; 10320 if (ThreadLocal) 10321 outs() << LS << "per-thread"; 10322 if (Abs) 10323 outs() << LS << "absolute"; 10324 if (Resolver) 10325 outs() << LS << format("resolver=0x%08llX", Entry.other()); 10326 outs() << "]"; 10327 } 10328 if (ReExport) { 10329 StringRef DylibName = "unknown"; 10330 int Ordinal = Entry.other() - 1; 10331 Obj->getLibraryShortNameByIndex(Ordinal, DylibName); 10332 if (Entry.otherName().empty()) 10333 outs() << " (from " << DylibName << ")"; 10334 else 10335 outs() << " (" << Entry.otherName() << " from " << DylibName << ")"; 10336 } 10337 outs() << "\n"; 10338 } 10339 if (Err) 10340 reportError(std::move(Err), Obj->getFileName()); 10341 } 10342 10343 //===----------------------------------------------------------------------===// 10344 // rebase table dumping 10345 //===----------------------------------------------------------------------===// 10346 10347 static void printMachORebaseTable(object::MachOObjectFile *Obj) { 10348 outs() << "segment section address type\n"; 10349 Error Err = Error::success(); 10350 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) { 10351 StringRef SegmentName = Entry.segmentName(); 10352 StringRef SectionName = Entry.sectionName(); 10353 uint64_t Address = Entry.address(); 10354 10355 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer 10356 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n", 10357 SegmentName.str().c_str(), SectionName.str().c_str(), 10358 Address, Entry.typeName().str().c_str()); 10359 } 10360 if (Err) 10361 reportError(std::move(Err), Obj->getFileName()); 10362 } 10363 10364 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) { 10365 StringRef DylibName; 10366 switch (Ordinal) { 10367 case MachO::BIND_SPECIAL_DYLIB_SELF: 10368 return "this-image"; 10369 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE: 10370 return "main-executable"; 10371 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP: 10372 return "flat-namespace"; 10373 default: 10374 if (Ordinal > 0) { 10375 std::error_code EC = 10376 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName); 10377 if (EC) 10378 return "<<bad library ordinal>>"; 10379 return DylibName; 10380 } 10381 } 10382 return "<<unknown special ordinal>>"; 10383 } 10384 10385 //===----------------------------------------------------------------------===// 10386 // bind table dumping 10387 //===----------------------------------------------------------------------===// 10388 10389 static void printMachOBindTable(object::MachOObjectFile *Obj) { 10390 // Build table of sections so names can used in final output. 10391 outs() << "segment section address type " 10392 "addend dylib symbol\n"; 10393 Error Err = Error::success(); 10394 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) { 10395 StringRef SegmentName = Entry.segmentName(); 10396 StringRef SectionName = Entry.sectionName(); 10397 uint64_t Address = Entry.address(); 10398 10399 // Table lines look like: 10400 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard 10401 StringRef Attr; 10402 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT) 10403 Attr = " (weak_import)"; 10404 outs() << left_justify(SegmentName, 8) << " " 10405 << left_justify(SectionName, 18) << " " 10406 << format_hex(Address, 10, true) << " " 10407 << left_justify(Entry.typeName(), 8) << " " 10408 << format_decimal(Entry.addend(), 8) << " " 10409 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " 10410 << Entry.symbolName() << Attr << "\n"; 10411 } 10412 if (Err) 10413 reportError(std::move(Err), Obj->getFileName()); 10414 } 10415 10416 //===----------------------------------------------------------------------===// 10417 // lazy bind table dumping 10418 //===----------------------------------------------------------------------===// 10419 10420 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) { 10421 outs() << "segment section address " 10422 "dylib symbol\n"; 10423 Error Err = Error::success(); 10424 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) { 10425 StringRef SegmentName = Entry.segmentName(); 10426 StringRef SectionName = Entry.sectionName(); 10427 uint64_t Address = Entry.address(); 10428 10429 // Table lines look like: 10430 // __DATA __got 0x00012010 libSystem ___stack_chk_guard 10431 outs() << left_justify(SegmentName, 8) << " " 10432 << left_justify(SectionName, 18) << " " 10433 << format_hex(Address, 10, true) << " " 10434 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " " 10435 << Entry.symbolName() << "\n"; 10436 } 10437 if (Err) 10438 reportError(std::move(Err), Obj->getFileName()); 10439 } 10440 10441 //===----------------------------------------------------------------------===// 10442 // weak bind table dumping 10443 //===----------------------------------------------------------------------===// 10444 10445 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) { 10446 outs() << "segment section address " 10447 "type addend symbol\n"; 10448 Error Err = Error::success(); 10449 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) { 10450 // Strong symbols don't have a location to update. 10451 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) { 10452 outs() << " strong " 10453 << Entry.symbolName() << "\n"; 10454 continue; 10455 } 10456 StringRef SegmentName = Entry.segmentName(); 10457 StringRef SectionName = Entry.sectionName(); 10458 uint64_t Address = Entry.address(); 10459 10460 // Table lines look like: 10461 // __DATA __data 0x00001000 pointer 0 _foo 10462 outs() << left_justify(SegmentName, 8) << " " 10463 << left_justify(SectionName, 18) << " " 10464 << format_hex(Address, 10, true) << " " 10465 << left_justify(Entry.typeName(), 8) << " " 10466 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName() 10467 << "\n"; 10468 } 10469 if (Err) 10470 reportError(std::move(Err), Obj->getFileName()); 10471 } 10472 10473 // get_dyld_bind_info_symbolname() is used for disassembly and passed an 10474 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind 10475 // information for that address. If the address is found its binding symbol 10476 // name is returned. If not nullptr is returned. 10477 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue, 10478 struct DisassembleInfo *info) { 10479 if (info->bindtable == nullptr) { 10480 info->bindtable = std::make_unique<SymbolAddressMap>(); 10481 Error Err = Error::success(); 10482 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) { 10483 uint64_t Address = Entry.address(); 10484 StringRef name = Entry.symbolName(); 10485 if (!name.empty()) 10486 (*info->bindtable)[Address] = name; 10487 } 10488 if (Err) 10489 reportError(std::move(Err), info->O->getFileName()); 10490 } 10491 auto name = info->bindtable->lookup(ReferenceValue); 10492 return !name.empty() ? name.data() : nullptr; 10493 } 10494 10495 void objdump::printLazyBindTable(ObjectFile *o) { 10496 outs() << "\nLazy bind table:\n"; 10497 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10498 printMachOLazyBindTable(MachO); 10499 else 10500 WithColor::error() 10501 << "This operation is only currently supported " 10502 "for Mach-O executable files.\n"; 10503 } 10504 10505 void objdump::printWeakBindTable(ObjectFile *o) { 10506 outs() << "\nWeak bind table:\n"; 10507 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10508 printMachOWeakBindTable(MachO); 10509 else 10510 WithColor::error() 10511 << "This operation is only currently supported " 10512 "for Mach-O executable files.\n"; 10513 } 10514 10515 void objdump::printExportsTrie(const ObjectFile *o) { 10516 outs() << "\nExports trie:\n"; 10517 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10518 printMachOExportsTrie(MachO); 10519 else 10520 WithColor::error() 10521 << "This operation is only currently supported " 10522 "for Mach-O executable files.\n"; 10523 } 10524 10525 void objdump::printRebaseTable(ObjectFile *o) { 10526 outs() << "\nRebase table:\n"; 10527 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10528 printMachORebaseTable(MachO); 10529 else 10530 WithColor::error() 10531 << "This operation is only currently supported " 10532 "for Mach-O executable files.\n"; 10533 } 10534 10535 void objdump::printBindTable(ObjectFile *o) { 10536 outs() << "\nBind table:\n"; 10537 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o)) 10538 printMachOBindTable(MachO); 10539 else 10540 WithColor::error() 10541 << "This operation is only currently supported " 10542 "for Mach-O executable files.\n"; 10543 } 10544