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 "llvm-objdump.h"
16 #include "llvm-c/Disassembler.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/BinaryFormat/MachO.h"
21 #include "llvm/Config/config.h"
22 #include "llvm/DebugInfo/DIContext.h"
23 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
24 #include "llvm/Demangle/Demangle.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCContext.h"
27 #include "llvm/MC/MCDisassembler/MCDisassembler.h"
28 #include "llvm/MC/MCInst.h"
29 #include "llvm/MC/MCInstPrinter.h"
30 #include "llvm/MC/MCInstrDesc.h"
31 #include "llvm/MC/MCInstrInfo.h"
32 #include "llvm/MC/MCRegisterInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/MC/MCTargetOptions.h"
35 #include "llvm/Object/MachO.h"
36 #include "llvm/Object/MachOUniversal.h"
37 #include "llvm/Support/Casting.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/Endian.h"
41 #include "llvm/Support/Format.h"
42 #include "llvm/Support/FormattedStream.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/LEB128.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/ToolOutputFile.h"
49 #include "llvm/Support/WithColor.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include <algorithm>
52 #include <cstring>
53 #include <system_error>
54
55 #ifdef HAVE_LIBXAR
56 extern "C" {
57 #include <xar/xar.h>
58 }
59 #endif
60
61 using namespace llvm;
62 using namespace llvm::object;
63 using namespace llvm::objdump;
64
65 cl::OptionCategory objdump::MachOCat("llvm-objdump MachO Specific Options");
66
67 cl::opt<bool> objdump::FirstPrivateHeader(
68 "private-header",
69 cl::desc("Display only the first format specific file header"),
70 cl::cat(MachOCat));
71
72 cl::opt<bool> objdump::ExportsTrie("exports-trie",
73 cl::desc("Display mach-o exported symbols"),
74 cl::cat(MachOCat));
75
76 cl::opt<bool> objdump::Rebase("rebase",
77 cl::desc("Display mach-o rebasing info"),
78 cl::cat(MachOCat));
79
80 cl::opt<bool> objdump::Bind("bind", cl::desc("Display mach-o binding info"),
81 cl::cat(MachOCat));
82
83 cl::opt<bool> objdump::LazyBind("lazy-bind",
84 cl::desc("Display mach-o lazy binding info"),
85 cl::cat(MachOCat));
86
87 cl::opt<bool> objdump::WeakBind("weak-bind",
88 cl::desc("Display mach-o weak binding info"),
89 cl::cat(MachOCat));
90
91 static cl::opt<bool>
92 UseDbg("g", cl::Grouping,
93 cl::desc("Print line information from debug info if available"),
94 cl::cat(MachOCat));
95
96 static cl::opt<std::string> DSYMFile("dsym",
97 cl::desc("Use .dSYM file for debug info"),
98 cl::cat(MachOCat));
99
100 static cl::opt<bool> FullLeadingAddr("full-leading-addr",
101 cl::desc("Print full leading address"),
102 cl::cat(MachOCat));
103
104 static cl::opt<bool> NoLeadingHeaders("no-leading-headers",
105 cl::desc("Print no leading headers"),
106 cl::cat(MachOCat));
107
108 cl::opt<bool> objdump::UniversalHeaders(
109 "universal-headers",
110 cl::desc("Print Mach-O universal headers (requires -macho)"),
111 cl::cat(MachOCat));
112
113 static cl::opt<bool> ArchiveMemberOffsets(
114 "archive-member-offsets",
115 cl::desc("Print the offset to each archive member for Mach-O archives "
116 "(requires -macho and -archive-headers)"),
117 cl::cat(MachOCat));
118
119 cl::opt<bool> objdump::IndirectSymbols(
120 "indirect-symbols",
121 cl::desc(
122 "Print indirect symbol table for Mach-O objects (requires -macho)"),
123 cl::cat(MachOCat));
124
125 cl::opt<bool> objdump::DataInCode(
126 "data-in-code",
127 cl::desc(
128 "Print the data in code table for Mach-O objects (requires -macho)"),
129 cl::cat(MachOCat));
130
131 cl::opt<bool>
132 objdump::LinkOptHints("link-opt-hints",
133 cl::desc("Print the linker optimization hints for "
134 "Mach-O objects (requires -macho)"),
135 cl::cat(MachOCat));
136
137 cl::opt<bool>
138 objdump::InfoPlist("info-plist",
139 cl::desc("Print the info plist section as strings for "
140 "Mach-O objects (requires -macho)"),
141 cl::cat(MachOCat));
142
143 cl::opt<bool>
144 objdump::DylibsUsed("dylibs-used",
145 cl::desc("Print the shared libraries used for linked "
146 "Mach-O files (requires -macho)"),
147 cl::cat(MachOCat));
148
149 cl::opt<bool> objdump::DylibId("dylib-id",
150 cl::desc("Print the shared library's id for the "
151 "dylib Mach-O file (requires -macho)"),
152 cl::cat(MachOCat));
153
154 static cl::opt<bool>
155 NonVerbose("non-verbose",
156 cl::desc("Print the info for Mach-O objects in non-verbose or "
157 "numeric form (requires -macho)"),
158 cl::cat(MachOCat));
159
160 cl::opt<bool>
161 objdump::ObjcMetaData("objc-meta-data",
162 cl::desc("Print the Objective-C runtime meta data "
163 "for Mach-O files (requires -macho)"),
164 cl::cat(MachOCat));
165
166 static cl::opt<std::string> DisSymName(
167 "dis-symname",
168 cl::desc("disassemble just this symbol's instructions (requires -macho)"),
169 cl::cat(MachOCat));
170
171 static cl::opt<bool> NoSymbolicOperands(
172 "no-symbolic-operands",
173 cl::desc("do not symbolic operands when disassembling (requires -macho)"),
174 cl::cat(MachOCat));
175
176 static cl::list<std::string>
177 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
178 cl::ZeroOrMore, cl::cat(MachOCat));
179
180 static bool ArchAll = false;
181
182 static std::string ThumbTripleName;
183
GetTarget(const MachOObjectFile * MachOObj,const char ** McpuDefault,const Target ** ThumbTarget)184 static const Target *GetTarget(const MachOObjectFile *MachOObj,
185 const char **McpuDefault,
186 const Target **ThumbTarget) {
187 // Figure out the target triple.
188 Triple TT(TripleName);
189 if (TripleName.empty()) {
190 TT = MachOObj->getArchTriple(McpuDefault);
191 TripleName = TT.str();
192 }
193
194 if (TT.getArch() == Triple::arm) {
195 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
196 // that support ARM are also capable of Thumb mode.
197 Triple ThumbTriple = TT;
198 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
199 ThumbTriple.setArchName(ThumbName);
200 ThumbTripleName = ThumbTriple.str();
201 }
202
203 // Get the target specific parser.
204 std::string Error;
205 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
206 if (TheTarget && ThumbTripleName.empty())
207 return TheTarget;
208
209 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
210 if (*ThumbTarget)
211 return TheTarget;
212
213 WithColor::error(errs(), "llvm-objdump") << "unable to get target for '";
214 if (!TheTarget)
215 errs() << TripleName;
216 else
217 errs() << ThumbTripleName;
218 errs() << "', see --version and --triple.\n";
219 return nullptr;
220 }
221
222 namespace {
223 struct SymbolSorter {
operator ()__anon30756ae00111::SymbolSorter224 bool operator()(const SymbolRef &A, const SymbolRef &B) {
225 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
226 if (!ATypeOrErr)
227 reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
228 SymbolRef::Type AType = *ATypeOrErr;
229 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
230 if (!BTypeOrErr)
231 reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
232 SymbolRef::Type BType = *BTypeOrErr;
233 uint64_t AAddr =
234 (AType != SymbolRef::ST_Function) ? 0 : cantFail(A.getValue());
235 uint64_t BAddr =
236 (BType != SymbolRef::ST_Function) ? 0 : cantFail(B.getValue());
237 return AAddr < BAddr;
238 }
239 };
240 } // namespace
241
242 // Types for the storted data in code table that is built before disassembly
243 // and the predicate function to sort them.
244 typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
245 typedef std::vector<DiceTableEntry> DiceTable;
246 typedef DiceTable::iterator dice_table_iterator;
247
248 #ifdef HAVE_LIBXAR
249 namespace {
250 struct ScopedXarFile {
251 xar_t xar;
ScopedXarFile__anon30756ae00211::ScopedXarFile252 ScopedXarFile(const char *filename, int32_t flags)
253 : xar(xar_open(filename, flags)) {}
~ScopedXarFile__anon30756ae00211::ScopedXarFile254 ~ScopedXarFile() {
255 if (xar)
256 xar_close(xar);
257 }
258 ScopedXarFile(const ScopedXarFile &) = delete;
259 ScopedXarFile &operator=(const ScopedXarFile &) = delete;
operator xar_t__anon30756ae00211::ScopedXarFile260 operator xar_t() { return xar; }
261 };
262
263 struct ScopedXarIter {
264 xar_iter_t iter;
ScopedXarIter__anon30756ae00211::ScopedXarIter265 ScopedXarIter() : iter(xar_iter_new()) {}
~ScopedXarIter__anon30756ae00211::ScopedXarIter266 ~ScopedXarIter() {
267 if (iter)
268 xar_iter_free(iter);
269 }
270 ScopedXarIter(const ScopedXarIter &) = delete;
271 ScopedXarIter &operator=(const ScopedXarIter &) = delete;
operator xar_iter_t__anon30756ae00211::ScopedXarIter272 operator xar_iter_t() { return iter; }
273 };
274 } // namespace
275 #endif // defined(HAVE_LIBXAR)
276
277 // This is used to search for a data in code table entry for the PC being
278 // disassembled. The j parameter has the PC in j.first. A single data in code
279 // table entry can cover many bytes for each of its Kind's. So if the offset,
280 // aka the i.first value, of the data in code table entry plus its Length
281 // covers the PC being searched for this will return true. If not it will
282 // return false.
compareDiceTableEntries(const DiceTableEntry & i,const DiceTableEntry & j)283 static bool compareDiceTableEntries(const DiceTableEntry &i,
284 const DiceTableEntry &j) {
285 uint16_t Length;
286 i.second.getLength(Length);
287
288 return j.first >= i.first && j.first < i.first + Length;
289 }
290
DumpDataInCode(const uint8_t * bytes,uint64_t Length,unsigned short Kind)291 static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
292 unsigned short Kind) {
293 uint32_t Value, Size = 1;
294
295 switch (Kind) {
296 default:
297 case MachO::DICE_KIND_DATA:
298 if (Length >= 4) {
299 if (!NoShowRawInsn)
300 dumpBytes(makeArrayRef(bytes, 4), outs());
301 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
302 outs() << "\t.long " << Value;
303 Size = 4;
304 } else if (Length >= 2) {
305 if (!NoShowRawInsn)
306 dumpBytes(makeArrayRef(bytes, 2), outs());
307 Value = bytes[1] << 8 | bytes[0];
308 outs() << "\t.short " << Value;
309 Size = 2;
310 } else {
311 if (!NoShowRawInsn)
312 dumpBytes(makeArrayRef(bytes, 2), outs());
313 Value = bytes[0];
314 outs() << "\t.byte " << Value;
315 Size = 1;
316 }
317 if (Kind == MachO::DICE_KIND_DATA)
318 outs() << "\t@ KIND_DATA\n";
319 else
320 outs() << "\t@ data in code kind = " << Kind << "\n";
321 break;
322 case MachO::DICE_KIND_JUMP_TABLE8:
323 if (!NoShowRawInsn)
324 dumpBytes(makeArrayRef(bytes, 1), outs());
325 Value = bytes[0];
326 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
327 Size = 1;
328 break;
329 case MachO::DICE_KIND_JUMP_TABLE16:
330 if (!NoShowRawInsn)
331 dumpBytes(makeArrayRef(bytes, 2), outs());
332 Value = bytes[1] << 8 | bytes[0];
333 outs() << "\t.short " << format("%5u", Value & 0xffff)
334 << "\t@ KIND_JUMP_TABLE16\n";
335 Size = 2;
336 break;
337 case MachO::DICE_KIND_JUMP_TABLE32:
338 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
339 if (!NoShowRawInsn)
340 dumpBytes(makeArrayRef(bytes, 4), outs());
341 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
342 outs() << "\t.long " << Value;
343 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
344 outs() << "\t@ KIND_JUMP_TABLE32\n";
345 else
346 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
347 Size = 4;
348 break;
349 }
350 return Size;
351 }
352
getSectionsAndSymbols(MachOObjectFile * MachOObj,std::vector<SectionRef> & Sections,std::vector<SymbolRef> & Symbols,SmallVectorImpl<uint64_t> & FoundFns,uint64_t & BaseSegmentAddress)353 static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
354 std::vector<SectionRef> &Sections,
355 std::vector<SymbolRef> &Symbols,
356 SmallVectorImpl<uint64_t> &FoundFns,
357 uint64_t &BaseSegmentAddress) {
358 const StringRef FileName = MachOObj->getFileName();
359 for (const SymbolRef &Symbol : MachOObj->symbols()) {
360 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
361 if (!SymName.startswith("ltmp"))
362 Symbols.push_back(Symbol);
363 }
364
365 for (const SectionRef &Section : MachOObj->sections())
366 Sections.push_back(Section);
367
368 bool BaseSegmentAddressSet = false;
369 for (const auto &Command : MachOObj->load_commands()) {
370 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
371 // We found a function starts segment, parse the addresses for later
372 // consumption.
373 MachO::linkedit_data_command LLC =
374 MachOObj->getLinkeditDataLoadCommand(Command);
375
376 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
377 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
378 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
379 StringRef SegName = SLC.segname;
380 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
381 BaseSegmentAddressSet = true;
382 BaseSegmentAddress = SLC.vmaddr;
383 }
384 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
385 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(Command);
386 StringRef SegName = SLC.segname;
387 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
388 BaseSegmentAddressSet = true;
389 BaseSegmentAddress = SLC.vmaddr;
390 }
391 }
392 }
393 }
394
DumpAndSkipDataInCode(uint64_t PC,const uint8_t * bytes,DiceTable & Dices,uint64_t & InstSize)395 static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
396 DiceTable &Dices, uint64_t &InstSize) {
397 // Check the data in code table here to see if this is data not an
398 // instruction to be disassembled.
399 DiceTable Dice;
400 Dice.push_back(std::make_pair(PC, DiceRef()));
401 dice_table_iterator DTI =
402 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
403 compareDiceTableEntries);
404 if (DTI != Dices.end()) {
405 uint16_t Length;
406 DTI->second.getLength(Length);
407 uint16_t Kind;
408 DTI->second.getKind(Kind);
409 InstSize = DumpDataInCode(bytes, Length, Kind);
410 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
411 (PC == (DTI->first + Length - 1)) && (Length & 1))
412 InstSize++;
413 return true;
414 }
415 return false;
416 }
417
printRelocationTargetName(const MachOObjectFile * O,const MachO::any_relocation_info & RE,raw_string_ostream & Fmt)418 static void printRelocationTargetName(const MachOObjectFile *O,
419 const MachO::any_relocation_info &RE,
420 raw_string_ostream &Fmt) {
421 // Target of a scattered relocation is an address. In the interest of
422 // generating pretty output, scan through the symbol table looking for a
423 // symbol that aligns with that address. If we find one, print it.
424 // Otherwise, we just print the hex address of the target.
425 const StringRef FileName = O->getFileName();
426 if (O->isRelocationScattered(RE)) {
427 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
428
429 for (const SymbolRef &Symbol : O->symbols()) {
430 uint64_t Addr = unwrapOrError(Symbol.getAddress(), FileName);
431 if (Addr != Val)
432 continue;
433 Fmt << unwrapOrError(Symbol.getName(), FileName);
434 return;
435 }
436
437 // If we couldn't find a symbol that this relocation refers to, try
438 // to find a section beginning instead.
439 for (const SectionRef &Section : ToolSectionFilter(*O)) {
440 uint64_t Addr = Section.getAddress();
441 if (Addr != Val)
442 continue;
443 StringRef NameOrErr = unwrapOrError(Section.getName(), O->getFileName());
444 Fmt << NameOrErr;
445 return;
446 }
447
448 Fmt << format("0x%x", Val);
449 return;
450 }
451
452 StringRef S;
453 bool isExtern = O->getPlainRelocationExternal(RE);
454 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
455
456 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
457 (O->getArch() == Triple::aarch64 || O->getArch() == Triple::aarch64_be)) {
458 Fmt << format("0x%0" PRIx64, Val);
459 return;
460 }
461
462 if (isExtern) {
463 symbol_iterator SI = O->symbol_begin();
464 advance(SI, Val);
465 S = unwrapOrError(SI->getName(), FileName);
466 } else {
467 section_iterator SI = O->section_begin();
468 // Adjust for the fact that sections are 1-indexed.
469 if (Val == 0) {
470 Fmt << "0 (?,?)";
471 return;
472 }
473 uint32_t I = Val - 1;
474 while (I != 0 && SI != O->section_end()) {
475 --I;
476 advance(SI, 1);
477 }
478 if (SI == O->section_end()) {
479 Fmt << Val << " (?,?)";
480 } else {
481 if (Expected<StringRef> NameOrErr = SI->getName())
482 S = *NameOrErr;
483 else
484 consumeError(NameOrErr.takeError());
485 }
486 }
487
488 Fmt << S;
489 }
490
getMachORelocationValueString(const MachOObjectFile * Obj,const RelocationRef & RelRef,SmallVectorImpl<char> & Result)491 Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
492 const RelocationRef &RelRef,
493 SmallVectorImpl<char> &Result) {
494 DataRefImpl Rel = RelRef.getRawDataRefImpl();
495 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
496
497 unsigned Arch = Obj->getArch();
498
499 std::string FmtBuf;
500 raw_string_ostream Fmt(FmtBuf);
501 unsigned Type = Obj->getAnyRelocationType(RE);
502 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
503
504 // Determine any addends that should be displayed with the relocation.
505 // These require decoding the relocation type, which is triple-specific.
506
507 // X86_64 has entirely custom relocation types.
508 if (Arch == Triple::x86_64) {
509 switch (Type) {
510 case MachO::X86_64_RELOC_GOT_LOAD:
511 case MachO::X86_64_RELOC_GOT: {
512 printRelocationTargetName(Obj, RE, Fmt);
513 Fmt << "@GOT";
514 if (IsPCRel)
515 Fmt << "PCREL";
516 break;
517 }
518 case MachO::X86_64_RELOC_SUBTRACTOR: {
519 DataRefImpl RelNext = Rel;
520 Obj->moveRelocationNext(RelNext);
521 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
522
523 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
524 // X86_64_RELOC_UNSIGNED.
525 // NOTE: Scattered relocations don't exist on x86_64.
526 unsigned RType = Obj->getAnyRelocationType(RENext);
527 if (RType != MachO::X86_64_RELOC_UNSIGNED)
528 reportError(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
529 "X86_64_RELOC_SUBTRACTOR.");
530
531 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
532 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
533 printRelocationTargetName(Obj, RENext, Fmt);
534 Fmt << "-";
535 printRelocationTargetName(Obj, RE, Fmt);
536 break;
537 }
538 case MachO::X86_64_RELOC_TLV:
539 printRelocationTargetName(Obj, RE, Fmt);
540 Fmt << "@TLV";
541 if (IsPCRel)
542 Fmt << "P";
543 break;
544 case MachO::X86_64_RELOC_SIGNED_1:
545 printRelocationTargetName(Obj, RE, Fmt);
546 Fmt << "-1";
547 break;
548 case MachO::X86_64_RELOC_SIGNED_2:
549 printRelocationTargetName(Obj, RE, Fmt);
550 Fmt << "-2";
551 break;
552 case MachO::X86_64_RELOC_SIGNED_4:
553 printRelocationTargetName(Obj, RE, Fmt);
554 Fmt << "-4";
555 break;
556 default:
557 printRelocationTargetName(Obj, RE, Fmt);
558 break;
559 }
560 // X86 and ARM share some relocation types in common.
561 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
562 Arch == Triple::ppc) {
563 // Generic relocation types...
564 switch (Type) {
565 case MachO::GENERIC_RELOC_PAIR: // prints no info
566 return Error::success();
567 case MachO::GENERIC_RELOC_SECTDIFF: {
568 DataRefImpl RelNext = Rel;
569 Obj->moveRelocationNext(RelNext);
570 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
571
572 // X86 sect diff's must be followed by a relocation of type
573 // GENERIC_RELOC_PAIR.
574 unsigned RType = Obj->getAnyRelocationType(RENext);
575
576 if (RType != MachO::GENERIC_RELOC_PAIR)
577 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
578 "GENERIC_RELOC_SECTDIFF.");
579
580 printRelocationTargetName(Obj, RE, Fmt);
581 Fmt << "-";
582 printRelocationTargetName(Obj, RENext, Fmt);
583 break;
584 }
585 }
586
587 if (Arch == Triple::x86 || Arch == Triple::ppc) {
588 switch (Type) {
589 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
590 DataRefImpl RelNext = Rel;
591 Obj->moveRelocationNext(RelNext);
592 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
593
594 // X86 sect diff's must be followed by a relocation of type
595 // GENERIC_RELOC_PAIR.
596 unsigned RType = Obj->getAnyRelocationType(RENext);
597 if (RType != MachO::GENERIC_RELOC_PAIR)
598 reportError(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
599 "GENERIC_RELOC_LOCAL_SECTDIFF.");
600
601 printRelocationTargetName(Obj, RE, Fmt);
602 Fmt << "-";
603 printRelocationTargetName(Obj, RENext, Fmt);
604 break;
605 }
606 case MachO::GENERIC_RELOC_TLV: {
607 printRelocationTargetName(Obj, RE, Fmt);
608 Fmt << "@TLV";
609 if (IsPCRel)
610 Fmt << "P";
611 break;
612 }
613 default:
614 printRelocationTargetName(Obj, RE, Fmt);
615 }
616 } else { // ARM-specific relocations
617 switch (Type) {
618 case MachO::ARM_RELOC_HALF:
619 case MachO::ARM_RELOC_HALF_SECTDIFF: {
620 // Half relocations steal a bit from the length field to encode
621 // whether this is an upper16 or a lower16 relocation.
622 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
623
624 if (isUpper)
625 Fmt << ":upper16:(";
626 else
627 Fmt << ":lower16:(";
628 printRelocationTargetName(Obj, RE, Fmt);
629
630 DataRefImpl RelNext = Rel;
631 Obj->moveRelocationNext(RelNext);
632 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
633
634 // ARM half relocs must be followed by a relocation of type
635 // ARM_RELOC_PAIR.
636 unsigned RType = Obj->getAnyRelocationType(RENext);
637 if (RType != MachO::ARM_RELOC_PAIR)
638 reportError(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
639 "ARM_RELOC_HALF");
640
641 // NOTE: The half of the target virtual address is stashed in the
642 // address field of the secondary relocation, but we can't reverse
643 // engineer the constant offset from it without decoding the movw/movt
644 // instruction to find the other half in its immediate field.
645
646 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
647 // symbol/section pointer of the follow-on relocation.
648 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
649 Fmt << "-";
650 printRelocationTargetName(Obj, RENext, Fmt);
651 }
652
653 Fmt << ")";
654 break;
655 }
656 default: {
657 printRelocationTargetName(Obj, RE, Fmt);
658 }
659 }
660 }
661 } else
662 printRelocationTargetName(Obj, RE, Fmt);
663
664 Fmt.flush();
665 Result.append(FmtBuf.begin(), FmtBuf.end());
666 return Error::success();
667 }
668
PrintIndirectSymbolTable(MachOObjectFile * O,bool verbose,uint32_t n,uint32_t count,uint32_t stride,uint64_t addr)669 static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
670 uint32_t n, uint32_t count,
671 uint32_t stride, uint64_t addr) {
672 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
673 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
674 if (n > nindirectsyms)
675 outs() << " (entries start past the end of the indirect symbol "
676 "table) (reserved1 field greater than the table size)";
677 else if (n + count > nindirectsyms)
678 outs() << " (entries extends past the end of the indirect symbol "
679 "table)";
680 outs() << "\n";
681 uint32_t cputype = O->getHeader().cputype;
682 if (cputype & MachO::CPU_ARCH_ABI64)
683 outs() << "address index";
684 else
685 outs() << "address index";
686 if (verbose)
687 outs() << " name\n";
688 else
689 outs() << "\n";
690 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
691 if (cputype & MachO::CPU_ARCH_ABI64)
692 outs() << format("0x%016" PRIx64, addr + j * stride) << " ";
693 else
694 outs() << format("0x%08" PRIx32, (uint32_t)addr + j * stride) << " ";
695 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
696 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
697 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
698 outs() << "LOCAL\n";
699 continue;
700 }
701 if (indirect_symbol ==
702 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
703 outs() << "LOCAL ABSOLUTE\n";
704 continue;
705 }
706 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
707 outs() << "ABSOLUTE\n";
708 continue;
709 }
710 outs() << format("%5u ", indirect_symbol);
711 if (verbose) {
712 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
713 if (indirect_symbol < Symtab.nsyms) {
714 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
715 SymbolRef Symbol = *Sym;
716 outs() << unwrapOrError(Symbol.getName(), O->getFileName());
717 } else {
718 outs() << "?";
719 }
720 }
721 outs() << "\n";
722 }
723 }
724
PrintIndirectSymbols(MachOObjectFile * O,bool verbose)725 static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
726 for (const auto &Load : O->load_commands()) {
727 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
728 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
729 for (unsigned J = 0; J < Seg.nsects; ++J) {
730 MachO::section_64 Sec = O->getSection64(Load, J);
731 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
732 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
733 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
734 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
735 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
736 section_type == MachO::S_SYMBOL_STUBS) {
737 uint32_t stride;
738 if (section_type == MachO::S_SYMBOL_STUBS)
739 stride = Sec.reserved2;
740 else
741 stride = 8;
742 if (stride == 0) {
743 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
744 << Sec.sectname << ") "
745 << "(size of stubs in reserved2 field is zero)\n";
746 continue;
747 }
748 uint32_t count = Sec.size / stride;
749 outs() << "Indirect symbols for (" << Sec.segname << ","
750 << Sec.sectname << ") " << count << " entries";
751 uint32_t n = Sec.reserved1;
752 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
753 }
754 }
755 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
756 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
757 for (unsigned J = 0; J < Seg.nsects; ++J) {
758 MachO::section Sec = O->getSection(Load, J);
759 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
760 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
761 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
762 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
763 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
764 section_type == MachO::S_SYMBOL_STUBS) {
765 uint32_t stride;
766 if (section_type == MachO::S_SYMBOL_STUBS)
767 stride = Sec.reserved2;
768 else
769 stride = 4;
770 if (stride == 0) {
771 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
772 << Sec.sectname << ") "
773 << "(size of stubs in reserved2 field is zero)\n";
774 continue;
775 }
776 uint32_t count = Sec.size / stride;
777 outs() << "Indirect symbols for (" << Sec.segname << ","
778 << Sec.sectname << ") " << count << " entries";
779 uint32_t n = Sec.reserved1;
780 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
781 }
782 }
783 }
784 }
785 }
786
PrintRType(const uint64_t cputype,const unsigned r_type)787 static void PrintRType(const uint64_t cputype, const unsigned r_type) {
788 static char const *generic_r_types[] = {
789 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
790 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
791 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
792 };
793 static char const *x86_64_r_types[] = {
794 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
795 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
796 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
797 };
798 static char const *arm_r_types[] = {
799 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
800 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
801 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
802 };
803 static char const *arm64_r_types[] = {
804 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
805 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
806 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
807 };
808
809 if (r_type > 0xf){
810 outs() << format("%-7u", r_type) << " ";
811 return;
812 }
813 switch (cputype) {
814 case MachO::CPU_TYPE_I386:
815 outs() << generic_r_types[r_type];
816 break;
817 case MachO::CPU_TYPE_X86_64:
818 outs() << x86_64_r_types[r_type];
819 break;
820 case MachO::CPU_TYPE_ARM:
821 outs() << arm_r_types[r_type];
822 break;
823 case MachO::CPU_TYPE_ARM64:
824 case MachO::CPU_TYPE_ARM64_32:
825 outs() << arm64_r_types[r_type];
826 break;
827 default:
828 outs() << format("%-7u ", r_type);
829 }
830 }
831
PrintRLength(const uint64_t cputype,const unsigned r_type,const unsigned r_length,const bool previous_arm_half)832 static void PrintRLength(const uint64_t cputype, const unsigned r_type,
833 const unsigned r_length, const bool previous_arm_half){
834 if (cputype == MachO::CPU_TYPE_ARM &&
835 (r_type == MachO::ARM_RELOC_HALF ||
836 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
837 if ((r_length & 0x1) == 0)
838 outs() << "lo/";
839 else
840 outs() << "hi/";
841 if ((r_length & 0x1) == 0)
842 outs() << "arm ";
843 else
844 outs() << "thm ";
845 } else {
846 switch (r_length) {
847 case 0:
848 outs() << "byte ";
849 break;
850 case 1:
851 outs() << "word ";
852 break;
853 case 2:
854 outs() << "long ";
855 break;
856 case 3:
857 if (cputype == MachO::CPU_TYPE_X86_64)
858 outs() << "quad ";
859 else
860 outs() << format("?(%2d) ", r_length);
861 break;
862 default:
863 outs() << format("?(%2d) ", r_length);
864 }
865 }
866 }
867
PrintRelocationEntries(const MachOObjectFile * O,const relocation_iterator Begin,const relocation_iterator End,const uint64_t cputype,const bool verbose)868 static void PrintRelocationEntries(const MachOObjectFile *O,
869 const relocation_iterator Begin,
870 const relocation_iterator End,
871 const uint64_t cputype,
872 const bool verbose) {
873 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
874 bool previous_arm_half = false;
875 bool previous_sectdiff = false;
876 uint32_t sectdiff_r_type = 0;
877
878 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
879 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
880 const MachO::any_relocation_info RE = O->getRelocation(Rel);
881 const unsigned r_type = O->getAnyRelocationType(RE);
882 const bool r_scattered = O->isRelocationScattered(RE);
883 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
884 const unsigned r_length = O->getAnyRelocationLength(RE);
885 const unsigned r_address = O->getAnyRelocationAddress(RE);
886 const bool r_extern = (r_scattered ? false :
887 O->getPlainRelocationExternal(RE));
888 const uint32_t r_value = (r_scattered ?
889 O->getScatteredRelocationValue(RE) : 0);
890 const unsigned r_symbolnum = (r_scattered ? 0 :
891 O->getPlainRelocationSymbolNum(RE));
892
893 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
894 if (verbose) {
895 // scattered: address
896 if ((cputype == MachO::CPU_TYPE_I386 &&
897 r_type == MachO::GENERIC_RELOC_PAIR) ||
898 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
899 outs() << " ";
900 else
901 outs() << format("%08x ", (unsigned int)r_address);
902
903 // scattered: pcrel
904 if (r_pcrel)
905 outs() << "True ";
906 else
907 outs() << "False ";
908
909 // scattered: length
910 PrintRLength(cputype, r_type, r_length, previous_arm_half);
911
912 // scattered: extern & type
913 outs() << "n/a ";
914 PrintRType(cputype, r_type);
915
916 // scattered: scattered & value
917 outs() << format("True 0x%08x", (unsigned int)r_value);
918 if (previous_sectdiff == false) {
919 if ((cputype == MachO::CPU_TYPE_ARM &&
920 r_type == MachO::ARM_RELOC_PAIR))
921 outs() << format(" half = 0x%04x ", (unsigned int)r_address);
922 } else if (cputype == MachO::CPU_TYPE_ARM &&
923 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
924 outs() << format(" other_half = 0x%04x ", (unsigned int)r_address);
925 if ((cputype == MachO::CPU_TYPE_I386 &&
926 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
927 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
928 (cputype == MachO::CPU_TYPE_ARM &&
929 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
930 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
931 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
932 previous_sectdiff = true;
933 sectdiff_r_type = r_type;
934 } else {
935 previous_sectdiff = false;
936 sectdiff_r_type = 0;
937 }
938 if (cputype == MachO::CPU_TYPE_ARM &&
939 (r_type == MachO::ARM_RELOC_HALF ||
940 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
941 previous_arm_half = true;
942 else
943 previous_arm_half = false;
944 outs() << "\n";
945 }
946 else {
947 // scattered: address pcrel length extern type scattered value
948 outs() << format("%08x %1d %-2d n/a %-7d 1 0x%08x\n",
949 (unsigned int)r_address, r_pcrel, r_length, r_type,
950 (unsigned int)r_value);
951 }
952 }
953 else {
954 if (verbose) {
955 // plain: address
956 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
957 outs() << " ";
958 else
959 outs() << format("%08x ", (unsigned int)r_address);
960
961 // plain: pcrel
962 if (r_pcrel)
963 outs() << "True ";
964 else
965 outs() << "False ";
966
967 // plain: length
968 PrintRLength(cputype, r_type, r_length, previous_arm_half);
969
970 if (r_extern) {
971 // plain: extern & type & scattered
972 outs() << "True ";
973 PrintRType(cputype, r_type);
974 outs() << "False ";
975
976 // plain: symbolnum/value
977 if (r_symbolnum > Symtab.nsyms)
978 outs() << format("?(%d)\n", r_symbolnum);
979 else {
980 SymbolRef Symbol = *O->getSymbolByIndex(r_symbolnum);
981 Expected<StringRef> SymNameNext = Symbol.getName();
982 const char *name = NULL;
983 if (SymNameNext)
984 name = SymNameNext->data();
985 if (name == NULL)
986 outs() << format("?(%d)\n", r_symbolnum);
987 else
988 outs() << name << "\n";
989 }
990 }
991 else {
992 // plain: extern & type & scattered
993 outs() << "False ";
994 PrintRType(cputype, r_type);
995 outs() << "False ";
996
997 // plain: symbolnum/value
998 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
999 outs() << format("other_half = 0x%04x\n", (unsigned int)r_address);
1000 else if ((cputype == MachO::CPU_TYPE_ARM64 ||
1001 cputype == MachO::CPU_TYPE_ARM64_32) &&
1002 r_type == MachO::ARM64_RELOC_ADDEND)
1003 outs() << format("addend = 0x%06x\n", (unsigned int)r_symbolnum);
1004 else {
1005 outs() << format("%d ", r_symbolnum);
1006 if (r_symbolnum == MachO::R_ABS)
1007 outs() << "R_ABS\n";
1008 else {
1009 // in this case, r_symbolnum is actually a 1-based section number
1010 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
1011 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
1012 object::DataRefImpl DRI;
1013 DRI.d.a = r_symbolnum-1;
1014 StringRef SegName = O->getSectionFinalSegmentName(DRI);
1015 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1016 outs() << "(" << SegName << "," << *NameOrErr << ")\n";
1017 else
1018 outs() << "(?,?)\n";
1019 }
1020 else {
1021 outs() << "(?,?)\n";
1022 }
1023 }
1024 }
1025 }
1026 if (cputype == MachO::CPU_TYPE_ARM &&
1027 (r_type == MachO::ARM_RELOC_HALF ||
1028 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
1029 previous_arm_half = true;
1030 else
1031 previous_arm_half = false;
1032 }
1033 else {
1034 // plain: address pcrel length extern type scattered symbolnum/section
1035 outs() << format("%08x %1d %-2d %1d %-7d 0 %d\n",
1036 (unsigned int)r_address, r_pcrel, r_length, r_extern,
1037 r_type, r_symbolnum);
1038 }
1039 }
1040 }
1041 }
1042
PrintRelocations(const MachOObjectFile * O,const bool verbose)1043 static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
1044 const uint64_t cputype = O->getHeader().cputype;
1045 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
1046 if (Dysymtab.nextrel != 0) {
1047 outs() << "External relocation information " << Dysymtab.nextrel
1048 << " entries";
1049 outs() << "\naddress pcrel length extern type scattered "
1050 "symbolnum/value\n";
1051 PrintRelocationEntries(O, O->extrel_begin(), O->extrel_end(), cputype,
1052 verbose);
1053 }
1054 if (Dysymtab.nlocrel != 0) {
1055 outs() << format("Local relocation information %u entries",
1056 Dysymtab.nlocrel);
1057 outs() << "\naddress pcrel length extern type scattered "
1058 "symbolnum/value\n";
1059 PrintRelocationEntries(O, O->locrel_begin(), O->locrel_end(), cputype,
1060 verbose);
1061 }
1062 for (const auto &Load : O->load_commands()) {
1063 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1064 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
1065 for (unsigned J = 0; J < Seg.nsects; ++J) {
1066 const MachO::section_64 Sec = O->getSection64(Load, J);
1067 if (Sec.nreloc != 0) {
1068 DataRefImpl DRI;
1069 DRI.d.a = J;
1070 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1071 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1072 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1073 << format(") %u entries", Sec.nreloc);
1074 else
1075 outs() << "Relocation information (" << SegName << ",?) "
1076 << format("%u entries", Sec.nreloc);
1077 outs() << "\naddress pcrel length extern type scattered "
1078 "symbolnum/value\n";
1079 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1080 O->section_rel_end(DRI), cputype, verbose);
1081 }
1082 }
1083 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1084 const MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
1085 for (unsigned J = 0; J < Seg.nsects; ++J) {
1086 const MachO::section Sec = O->getSection(Load, J);
1087 if (Sec.nreloc != 0) {
1088 DataRefImpl DRI;
1089 DRI.d.a = J;
1090 const StringRef SegName = O->getSectionFinalSegmentName(DRI);
1091 if (Expected<StringRef> NameOrErr = O->getSectionName(DRI))
1092 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1093 << format(") %u entries", Sec.nreloc);
1094 else
1095 outs() << "Relocation information (" << SegName << ",?) "
1096 << format("%u entries", Sec.nreloc);
1097 outs() << "\naddress pcrel length extern type scattered "
1098 "symbolnum/value\n";
1099 PrintRelocationEntries(O, O->section_rel_begin(DRI),
1100 O->section_rel_end(DRI), cputype, verbose);
1101 }
1102 }
1103 }
1104 }
1105 }
1106
PrintDataInCodeTable(MachOObjectFile * O,bool verbose)1107 static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1108 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1109 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1110 outs() << "Data in code table (" << nentries << " entries)\n";
1111 outs() << "offset length kind\n";
1112 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1113 ++DI) {
1114 uint32_t Offset;
1115 DI->getOffset(Offset);
1116 outs() << format("0x%08" PRIx32, Offset) << " ";
1117 uint16_t Length;
1118 DI->getLength(Length);
1119 outs() << format("%6u", Length) << " ";
1120 uint16_t Kind;
1121 DI->getKind(Kind);
1122 if (verbose) {
1123 switch (Kind) {
1124 case MachO::DICE_KIND_DATA:
1125 outs() << "DATA";
1126 break;
1127 case MachO::DICE_KIND_JUMP_TABLE8:
1128 outs() << "JUMP_TABLE8";
1129 break;
1130 case MachO::DICE_KIND_JUMP_TABLE16:
1131 outs() << "JUMP_TABLE16";
1132 break;
1133 case MachO::DICE_KIND_JUMP_TABLE32:
1134 outs() << "JUMP_TABLE32";
1135 break;
1136 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1137 outs() << "ABS_JUMP_TABLE32";
1138 break;
1139 default:
1140 outs() << format("0x%04" PRIx32, Kind);
1141 break;
1142 }
1143 } else
1144 outs() << format("0x%04" PRIx32, Kind);
1145 outs() << "\n";
1146 }
1147 }
1148
PrintLinkOptHints(MachOObjectFile * O)1149 static void PrintLinkOptHints(MachOObjectFile *O) {
1150 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1151 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
1152 uint32_t nloh = LohLC.datasize;
1153 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1154 for (uint32_t i = 0; i < nloh;) {
1155 unsigned n;
1156 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
1157 i += n;
1158 outs() << " identifier " << identifier << " ";
1159 if (i >= nloh)
1160 return;
1161 switch (identifier) {
1162 case 1:
1163 outs() << "AdrpAdrp\n";
1164 break;
1165 case 2:
1166 outs() << "AdrpLdr\n";
1167 break;
1168 case 3:
1169 outs() << "AdrpAddLdr\n";
1170 break;
1171 case 4:
1172 outs() << "AdrpLdrGotLdr\n";
1173 break;
1174 case 5:
1175 outs() << "AdrpAddStr\n";
1176 break;
1177 case 6:
1178 outs() << "AdrpLdrGotStr\n";
1179 break;
1180 case 7:
1181 outs() << "AdrpAdd\n";
1182 break;
1183 case 8:
1184 outs() << "AdrpLdrGot\n";
1185 break;
1186 default:
1187 outs() << "Unknown identifier value\n";
1188 break;
1189 }
1190 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
1191 i += n;
1192 outs() << " narguments " << narguments << "\n";
1193 if (i >= nloh)
1194 return;
1195
1196 for (uint32_t j = 0; j < narguments; j++) {
1197 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
1198 i += n;
1199 outs() << "\tvalue " << format("0x%" PRIx64, value) << "\n";
1200 if (i >= nloh)
1201 return;
1202 }
1203 }
1204 }
1205
PrintDylibs(MachOObjectFile * O,bool JustId)1206 static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1207 unsigned Index = 0;
1208 for (const auto &Load : O->load_commands()) {
1209 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1210 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1211 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1212 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1213 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1214 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1215 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1216 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
1217 if (dl.dylib.name < dl.cmdsize) {
1218 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1219 if (JustId)
1220 outs() << p << "\n";
1221 else {
1222 outs() << "\t" << p;
1223 outs() << " (compatibility version "
1224 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1225 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1226 << (dl.dylib.compatibility_version & 0xff) << ",";
1227 outs() << " current version "
1228 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1229 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1230 << (dl.dylib.current_version & 0xff);
1231 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1232 outs() << ", weak";
1233 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1234 outs() << ", reexport";
1235 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1236 outs() << ", upward";
1237 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1238 outs() << ", lazy";
1239 outs() << ")\n";
1240 }
1241 } else {
1242 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1243 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1244 outs() << "LC_ID_DYLIB ";
1245 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1246 outs() << "LC_LOAD_DYLIB ";
1247 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1248 outs() << "LC_LOAD_WEAK_DYLIB ";
1249 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1250 outs() << "LC_LAZY_LOAD_DYLIB ";
1251 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1252 outs() << "LC_REEXPORT_DYLIB ";
1253 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1254 outs() << "LC_LOAD_UPWARD_DYLIB ";
1255 else
1256 outs() << "LC_??? ";
1257 outs() << "command " << Index++ << "\n";
1258 }
1259 }
1260 }
1261 }
1262
1263 typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1264
CreateSymbolAddressMap(MachOObjectFile * O,SymbolAddressMap * AddrMap)1265 static void CreateSymbolAddressMap(MachOObjectFile *O,
1266 SymbolAddressMap *AddrMap) {
1267 // Create a map of symbol addresses to symbol names.
1268 const StringRef FileName = O->getFileName();
1269 for (const SymbolRef &Symbol : O->symbols()) {
1270 SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
1271 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1272 ST == SymbolRef::ST_Other) {
1273 uint64_t Address = cantFail(Symbol.getValue());
1274 StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
1275 if (!SymName.startswith(".objc"))
1276 (*AddrMap)[Address] = SymName;
1277 }
1278 }
1279 }
1280
1281 // GuessSymbolName is passed the address of what might be a symbol and a
1282 // pointer to the SymbolAddressMap. It returns the name of a symbol
1283 // with that address or nullptr if no symbol is found with that address.
GuessSymbolName(uint64_t value,SymbolAddressMap * AddrMap)1284 static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1285 const char *SymbolName = nullptr;
1286 // A DenseMap can't lookup up some values.
1287 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1288 StringRef name = AddrMap->lookup(value);
1289 if (!name.empty())
1290 SymbolName = name.data();
1291 }
1292 return SymbolName;
1293 }
1294
DumpCstringChar(const char c)1295 static void DumpCstringChar(const char c) {
1296 char p[2];
1297 p[0] = c;
1298 p[1] = '\0';
1299 outs().write_escaped(p);
1300 }
1301
DumpCstringSection(MachOObjectFile * O,const char * sect,uint32_t sect_size,uint64_t sect_addr,bool print_addresses)1302 static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1303 uint32_t sect_size, uint64_t sect_addr,
1304 bool print_addresses) {
1305 for (uint32_t i = 0; i < sect_size; i++) {
1306 if (print_addresses) {
1307 if (O->is64Bit())
1308 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1309 else
1310 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1311 }
1312 for (; i < sect_size && sect[i] != '\0'; i++)
1313 DumpCstringChar(sect[i]);
1314 if (i < sect_size && sect[i] == '\0')
1315 outs() << "\n";
1316 }
1317 }
1318
DumpLiteral4(uint32_t l,float f)1319 static void DumpLiteral4(uint32_t l, float f) {
1320 outs() << format("0x%08" PRIx32, l);
1321 if ((l & 0x7f800000) != 0x7f800000)
1322 outs() << format(" (%.16e)\n", f);
1323 else {
1324 if (l == 0x7f800000)
1325 outs() << " (+Infinity)\n";
1326 else if (l == 0xff800000)
1327 outs() << " (-Infinity)\n";
1328 else if ((l & 0x00400000) == 0x00400000)
1329 outs() << " (non-signaling Not-a-Number)\n";
1330 else
1331 outs() << " (signaling Not-a-Number)\n";
1332 }
1333 }
1334
DumpLiteral4Section(MachOObjectFile * O,const char * sect,uint32_t sect_size,uint64_t sect_addr,bool print_addresses)1335 static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1336 uint32_t sect_size, uint64_t sect_addr,
1337 bool print_addresses) {
1338 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1339 if (print_addresses) {
1340 if (O->is64Bit())
1341 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1342 else
1343 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1344 }
1345 float f;
1346 memcpy(&f, sect + i, sizeof(float));
1347 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1348 sys::swapByteOrder(f);
1349 uint32_t l;
1350 memcpy(&l, sect + i, sizeof(uint32_t));
1351 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1352 sys::swapByteOrder(l);
1353 DumpLiteral4(l, f);
1354 }
1355 }
1356
DumpLiteral8(MachOObjectFile * O,uint32_t l0,uint32_t l1,double d)1357 static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1358 double d) {
1359 outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
1360 uint32_t Hi, Lo;
1361 Hi = (O->isLittleEndian()) ? l1 : l0;
1362 Lo = (O->isLittleEndian()) ? l0 : l1;
1363
1364 // Hi is the high word, so this is equivalent to if(isfinite(d))
1365 if ((Hi & 0x7ff00000) != 0x7ff00000)
1366 outs() << format(" (%.16e)\n", d);
1367 else {
1368 if (Hi == 0x7ff00000 && Lo == 0)
1369 outs() << " (+Infinity)\n";
1370 else if (Hi == 0xfff00000 && Lo == 0)
1371 outs() << " (-Infinity)\n";
1372 else if ((Hi & 0x00080000) == 0x00080000)
1373 outs() << " (non-signaling Not-a-Number)\n";
1374 else
1375 outs() << " (signaling Not-a-Number)\n";
1376 }
1377 }
1378
DumpLiteral8Section(MachOObjectFile * O,const char * sect,uint32_t sect_size,uint64_t sect_addr,bool print_addresses)1379 static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1380 uint32_t sect_size, uint64_t sect_addr,
1381 bool print_addresses) {
1382 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1383 if (print_addresses) {
1384 if (O->is64Bit())
1385 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1386 else
1387 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1388 }
1389 double d;
1390 memcpy(&d, sect + i, sizeof(double));
1391 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1392 sys::swapByteOrder(d);
1393 uint32_t l0, l1;
1394 memcpy(&l0, sect + i, sizeof(uint32_t));
1395 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1396 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1397 sys::swapByteOrder(l0);
1398 sys::swapByteOrder(l1);
1399 }
1400 DumpLiteral8(O, l0, l1, d);
1401 }
1402 }
1403
DumpLiteral16(uint32_t l0,uint32_t l1,uint32_t l2,uint32_t l3)1404 static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1405 outs() << format("0x%08" PRIx32, l0) << " ";
1406 outs() << format("0x%08" PRIx32, l1) << " ";
1407 outs() << format("0x%08" PRIx32, l2) << " ";
1408 outs() << format("0x%08" PRIx32, l3) << "\n";
1409 }
1410
DumpLiteral16Section(MachOObjectFile * O,const char * sect,uint32_t sect_size,uint64_t sect_addr,bool print_addresses)1411 static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1412 uint32_t sect_size, uint64_t sect_addr,
1413 bool print_addresses) {
1414 for (uint32_t i = 0; i < sect_size; i += 16) {
1415 if (print_addresses) {
1416 if (O->is64Bit())
1417 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1418 else
1419 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1420 }
1421 uint32_t l0, l1, l2, l3;
1422 memcpy(&l0, sect + i, sizeof(uint32_t));
1423 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
1424 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
1425 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
1426 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1427 sys::swapByteOrder(l0);
1428 sys::swapByteOrder(l1);
1429 sys::swapByteOrder(l2);
1430 sys::swapByteOrder(l3);
1431 }
1432 DumpLiteral16(l0, l1, l2, l3);
1433 }
1434 }
1435
DumpLiteralPointerSection(MachOObjectFile * O,const SectionRef & Section,const char * sect,uint32_t sect_size,uint64_t sect_addr,bool print_addresses)1436 static void DumpLiteralPointerSection(MachOObjectFile *O,
1437 const SectionRef &Section,
1438 const char *sect, uint32_t sect_size,
1439 uint64_t sect_addr,
1440 bool print_addresses) {
1441 // Collect the literal sections in this Mach-O file.
1442 std::vector<SectionRef> LiteralSections;
1443 for (const SectionRef &Section : O->sections()) {
1444 DataRefImpl Ref = Section.getRawDataRefImpl();
1445 uint32_t section_type;
1446 if (O->is64Bit()) {
1447 const MachO::section_64 Sec = O->getSection64(Ref);
1448 section_type = Sec.flags & MachO::SECTION_TYPE;
1449 } else {
1450 const MachO::section Sec = O->getSection(Ref);
1451 section_type = Sec.flags & MachO::SECTION_TYPE;
1452 }
1453 if (section_type == MachO::S_CSTRING_LITERALS ||
1454 section_type == MachO::S_4BYTE_LITERALS ||
1455 section_type == MachO::S_8BYTE_LITERALS ||
1456 section_type == MachO::S_16BYTE_LITERALS)
1457 LiteralSections.push_back(Section);
1458 }
1459
1460 // Set the size of the literal pointer.
1461 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1462
1463 // Collect the external relocation symbols for the literal pointers.
1464 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1465 for (const RelocationRef &Reloc : Section.relocations()) {
1466 DataRefImpl Rel;
1467 MachO::any_relocation_info RE;
1468 bool isExtern = false;
1469 Rel = Reloc.getRawDataRefImpl();
1470 RE = O->getRelocation(Rel);
1471 isExtern = O->getPlainRelocationExternal(RE);
1472 if (isExtern) {
1473 uint64_t RelocOffset = Reloc.getOffset();
1474 symbol_iterator RelocSym = Reloc.getSymbol();
1475 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1476 }
1477 }
1478 array_pod_sort(Relocs.begin(), Relocs.end());
1479
1480 // Dump each literal pointer.
1481 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1482 if (print_addresses) {
1483 if (O->is64Bit())
1484 outs() << format("%016" PRIx64, sect_addr + i) << " ";
1485 else
1486 outs() << format("%08" PRIx64, sect_addr + i) << " ";
1487 }
1488 uint64_t lp;
1489 if (O->is64Bit()) {
1490 memcpy(&lp, sect + i, sizeof(uint64_t));
1491 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1492 sys::swapByteOrder(lp);
1493 } else {
1494 uint32_t li;
1495 memcpy(&li, sect + i, sizeof(uint32_t));
1496 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1497 sys::swapByteOrder(li);
1498 lp = li;
1499 }
1500
1501 // First look for an external relocation entry for this literal pointer.
1502 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1503 return P.first == i;
1504 });
1505 if (Reloc != Relocs.end()) {
1506 symbol_iterator RelocSym = Reloc->second;
1507 StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
1508 outs() << "external relocation entry for symbol:" << SymName << "\n";
1509 continue;
1510 }
1511
1512 // For local references see what the section the literal pointer points to.
1513 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
1514 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1515 });
1516 if (Sect == LiteralSections.end()) {
1517 outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
1518 continue;
1519 }
1520
1521 uint64_t SectAddress = Sect->getAddress();
1522 uint64_t SectSize = Sect->getSize();
1523
1524 StringRef SectName;
1525 Expected<StringRef> SectNameOrErr = Sect->getName();
1526 if (SectNameOrErr)
1527 SectName = *SectNameOrErr;
1528 else
1529 consumeError(SectNameOrErr.takeError());
1530
1531 DataRefImpl Ref = Sect->getRawDataRefImpl();
1532 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
1533 outs() << SegmentName << ":" << SectName << ":";
1534
1535 uint32_t section_type;
1536 if (O->is64Bit()) {
1537 const MachO::section_64 Sec = O->getSection64(Ref);
1538 section_type = Sec.flags & MachO::SECTION_TYPE;
1539 } else {
1540 const MachO::section Sec = O->getSection(Ref);
1541 section_type = Sec.flags & MachO::SECTION_TYPE;
1542 }
1543
1544 StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
1545
1546 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
1547
1548 switch (section_type) {
1549 case MachO::S_CSTRING_LITERALS:
1550 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1551 i++) {
1552 DumpCstringChar(Contents[i]);
1553 }
1554 outs() << "\n";
1555 break;
1556 case MachO::S_4BYTE_LITERALS:
1557 float f;
1558 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
1559 uint32_t l;
1560 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
1561 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1562 sys::swapByteOrder(f);
1563 sys::swapByteOrder(l);
1564 }
1565 DumpLiteral4(l, f);
1566 break;
1567 case MachO::S_8BYTE_LITERALS: {
1568 double d;
1569 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
1570 uint32_t l0, l1;
1571 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1572 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1573 sizeof(uint32_t));
1574 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1575 sys::swapByteOrder(f);
1576 sys::swapByteOrder(l0);
1577 sys::swapByteOrder(l1);
1578 }
1579 DumpLiteral8(O, l0, l1, d);
1580 break;
1581 }
1582 case MachO::S_16BYTE_LITERALS: {
1583 uint32_t l0, l1, l2, l3;
1584 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
1585 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
1586 sizeof(uint32_t));
1587 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1588 sizeof(uint32_t));
1589 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1590 sizeof(uint32_t));
1591 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1592 sys::swapByteOrder(l0);
1593 sys::swapByteOrder(l1);
1594 sys::swapByteOrder(l2);
1595 sys::swapByteOrder(l3);
1596 }
1597 DumpLiteral16(l0, l1, l2, l3);
1598 break;
1599 }
1600 }
1601 }
1602 }
1603
DumpInitTermPointerSection(MachOObjectFile * O,const SectionRef & Section,const char * sect,uint32_t sect_size,uint64_t sect_addr,SymbolAddressMap * AddrMap,bool verbose)1604 static void DumpInitTermPointerSection(MachOObjectFile *O,
1605 const SectionRef &Section,
1606 const char *sect,
1607 uint32_t sect_size, uint64_t sect_addr,
1608 SymbolAddressMap *AddrMap,
1609 bool verbose) {
1610 uint32_t stride;
1611 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1612
1613 // Collect the external relocation symbols for the pointers.
1614 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1615 for (const RelocationRef &Reloc : Section.relocations()) {
1616 DataRefImpl Rel;
1617 MachO::any_relocation_info RE;
1618 bool isExtern = false;
1619 Rel = Reloc.getRawDataRefImpl();
1620 RE = O->getRelocation(Rel);
1621 isExtern = O->getPlainRelocationExternal(RE);
1622 if (isExtern) {
1623 uint64_t RelocOffset = Reloc.getOffset();
1624 symbol_iterator RelocSym = Reloc.getSymbol();
1625 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
1626 }
1627 }
1628 array_pod_sort(Relocs.begin(), Relocs.end());
1629
1630 for (uint32_t i = 0; i < sect_size; i += stride) {
1631 const char *SymbolName = nullptr;
1632 uint64_t p;
1633 if (O->is64Bit()) {
1634 outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
1635 uint64_t pointer_value;
1636 memcpy(&pointer_value, sect + i, stride);
1637 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1638 sys::swapByteOrder(pointer_value);
1639 outs() << format("0x%016" PRIx64, pointer_value);
1640 p = pointer_value;
1641 } else {
1642 outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
1643 uint32_t pointer_value;
1644 memcpy(&pointer_value, sect + i, stride);
1645 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1646 sys::swapByteOrder(pointer_value);
1647 outs() << format("0x%08" PRIx32, pointer_value);
1648 p = pointer_value;
1649 }
1650 if (verbose) {
1651 // First look for an external relocation entry for this pointer.
1652 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
1653 return P.first == i;
1654 });
1655 if (Reloc != Relocs.end()) {
1656 symbol_iterator RelocSym = Reloc->second;
1657 outs() << " " << unwrapOrError(RelocSym->getName(), O->getFileName());
1658 } else {
1659 SymbolName = GuessSymbolName(p, AddrMap);
1660 if (SymbolName)
1661 outs() << " " << SymbolName;
1662 }
1663 }
1664 outs() << "\n";
1665 }
1666 }
1667
DumpRawSectionContents(MachOObjectFile * O,const char * sect,uint32_t size,uint64_t addr)1668 static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1669 uint32_t size, uint64_t addr) {
1670 uint32_t cputype = O->getHeader().cputype;
1671 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1672 uint32_t j;
1673 for (uint32_t i = 0; i < size; i += j, addr += j) {
1674 if (O->is64Bit())
1675 outs() << format("%016" PRIx64, addr) << "\t";
1676 else
1677 outs() << format("%08" PRIx64, addr) << "\t";
1678 for (j = 0; j < 16 && i + j < size; j++) {
1679 uint8_t byte_word = *(sect + i + j);
1680 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1681 }
1682 outs() << "\n";
1683 }
1684 } else {
1685 uint32_t j;
1686 for (uint32_t i = 0; i < size; i += j, addr += j) {
1687 if (O->is64Bit())
1688 outs() << format("%016" PRIx64, addr) << "\t";
1689 else
1690 outs() << format("%08" PRIx64, addr) << "\t";
1691 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1692 j += sizeof(int32_t)) {
1693 if (i + j + sizeof(int32_t) <= size) {
1694 uint32_t long_word;
1695 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1696 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1697 sys::swapByteOrder(long_word);
1698 outs() << format("%08" PRIx32, long_word) << " ";
1699 } else {
1700 for (uint32_t k = 0; i + j + k < size; k++) {
1701 uint8_t byte_word = *(sect + i + j + k);
1702 outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
1703 }
1704 }
1705 }
1706 outs() << "\n";
1707 }
1708 }
1709 }
1710
1711 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1712 StringRef DisSegName, StringRef DisSectName);
1713 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1714 uint32_t size, uint32_t addr);
1715 #ifdef HAVE_LIBXAR
1716 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1717 uint32_t size, bool verbose,
1718 bool PrintXarHeader, bool PrintXarFileHeaders,
1719 std::string XarMemberName);
1720 #endif // defined(HAVE_LIBXAR)
1721
DumpSectionContents(StringRef Filename,MachOObjectFile * O,bool verbose)1722 static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1723 bool verbose) {
1724 SymbolAddressMap AddrMap;
1725 if (verbose)
1726 CreateSymbolAddressMap(O, &AddrMap);
1727
1728 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1729 StringRef DumpSection = FilterSections[i];
1730 std::pair<StringRef, StringRef> DumpSegSectName;
1731 DumpSegSectName = DumpSection.split(',');
1732 StringRef DumpSegName, DumpSectName;
1733 if (!DumpSegSectName.second.empty()) {
1734 DumpSegName = DumpSegSectName.first;
1735 DumpSectName = DumpSegSectName.second;
1736 } else {
1737 DumpSegName = "";
1738 DumpSectName = DumpSegSectName.first;
1739 }
1740 for (const SectionRef &Section : O->sections()) {
1741 StringRef SectName;
1742 Expected<StringRef> SecNameOrErr = Section.getName();
1743 if (SecNameOrErr)
1744 SectName = *SecNameOrErr;
1745 else
1746 consumeError(SecNameOrErr.takeError());
1747
1748 if (!DumpSection.empty())
1749 FoundSectionSet.insert(DumpSection);
1750
1751 DataRefImpl Ref = Section.getRawDataRefImpl();
1752 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1753 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1754 (SectName == DumpSectName)) {
1755
1756 uint32_t section_flags;
1757 if (O->is64Bit()) {
1758 const MachO::section_64 Sec = O->getSection64(Ref);
1759 section_flags = Sec.flags;
1760
1761 } else {
1762 const MachO::section Sec = O->getSection(Ref);
1763 section_flags = Sec.flags;
1764 }
1765 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1766
1767 StringRef BytesStr =
1768 unwrapOrError(Section.getContents(), O->getFileName());
1769 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1770 uint32_t sect_size = BytesStr.size();
1771 uint64_t sect_addr = Section.getAddress();
1772
1773 if (!NoLeadingHeaders)
1774 outs() << "Contents of (" << SegName << "," << SectName
1775 << ") section\n";
1776
1777 if (verbose) {
1778 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1779 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1780 DisassembleMachO(Filename, O, SegName, SectName);
1781 continue;
1782 }
1783 if (SegName == "__TEXT" && SectName == "__info_plist") {
1784 outs() << sect;
1785 continue;
1786 }
1787 if (SegName == "__OBJC" && SectName == "__protocol") {
1788 DumpProtocolSection(O, sect, sect_size, sect_addr);
1789 continue;
1790 }
1791 #ifdef HAVE_LIBXAR
1792 if (SegName == "__LLVM" && SectName == "__bundle") {
1793 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1794 ArchiveHeaders, "");
1795 continue;
1796 }
1797 #endif // defined(HAVE_LIBXAR)
1798 switch (section_type) {
1799 case MachO::S_REGULAR:
1800 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1801 break;
1802 case MachO::S_ZEROFILL:
1803 outs() << "zerofill section and has no contents in the file\n";
1804 break;
1805 case MachO::S_CSTRING_LITERALS:
1806 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1807 break;
1808 case MachO::S_4BYTE_LITERALS:
1809 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1810 break;
1811 case MachO::S_8BYTE_LITERALS:
1812 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1813 break;
1814 case MachO::S_16BYTE_LITERALS:
1815 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1816 break;
1817 case MachO::S_LITERAL_POINTERS:
1818 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1819 !NoLeadingAddr);
1820 break;
1821 case MachO::S_MOD_INIT_FUNC_POINTERS:
1822 case MachO::S_MOD_TERM_FUNC_POINTERS:
1823 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
1824 &AddrMap, verbose);
1825 break;
1826 default:
1827 outs() << "Unknown section type ("
1828 << format("0x%08" PRIx32, section_type) << ")\n";
1829 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1830 break;
1831 }
1832 } else {
1833 if (section_type == MachO::S_ZEROFILL)
1834 outs() << "zerofill section and has no contents in the file\n";
1835 else
1836 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1837 }
1838 }
1839 }
1840 }
1841 }
1842
DumpInfoPlistSectionContents(StringRef Filename,MachOObjectFile * O)1843 static void DumpInfoPlistSectionContents(StringRef Filename,
1844 MachOObjectFile *O) {
1845 for (const SectionRef &Section : O->sections()) {
1846 StringRef SectName;
1847 Expected<StringRef> SecNameOrErr = Section.getName();
1848 if (SecNameOrErr)
1849 SectName = *SecNameOrErr;
1850 else
1851 consumeError(SecNameOrErr.takeError());
1852
1853 DataRefImpl Ref = Section.getRawDataRefImpl();
1854 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1855 if (SegName == "__TEXT" && SectName == "__info_plist") {
1856 if (!NoLeadingHeaders)
1857 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1858 StringRef BytesStr =
1859 unwrapOrError(Section.getContents(), O->getFileName());
1860 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1861 outs() << format("%.*s", BytesStr.size(), sect) << "\n";
1862 return;
1863 }
1864 }
1865 }
1866
1867 // checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1868 // and if it is and there is a list of architecture flags is specified then
1869 // check to make sure this Mach-O file is one of those architectures or all
1870 // architectures were specified. If not then an error is generated and this
1871 // routine returns false. Else it returns true.
checkMachOAndArchFlags(ObjectFile * O,StringRef Filename)1872 static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1873 auto *MachO = dyn_cast<MachOObjectFile>(O);
1874
1875 if (!MachO || ArchAll || ArchFlags.empty())
1876 return true;
1877
1878 MachO::mach_header H;
1879 MachO::mach_header_64 H_64;
1880 Triple T;
1881 const char *McpuDefault, *ArchFlag;
1882 if (MachO->is64Bit()) {
1883 H_64 = MachO->MachOObjectFile::getHeader64();
1884 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
1885 &McpuDefault, &ArchFlag);
1886 } else {
1887 H = MachO->MachOObjectFile::getHeader();
1888 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype,
1889 &McpuDefault, &ArchFlag);
1890 }
1891 const std::string ArchFlagName(ArchFlag);
1892 if (none_of(ArchFlags, [&](const std::string &Name) {
1893 return Name == ArchFlagName;
1894 })) {
1895 WithColor::error(errs(), "llvm-objdump")
1896 << Filename << ": no architecture specified.\n";
1897 return false;
1898 }
1899 return true;
1900 }
1901
1902 static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1903
1904 // ProcessMachO() is passed a single opened Mach-O file, which may be an
1905 // archive member and or in a slice of a universal file. It prints the
1906 // the file name and header info and then processes it according to the
1907 // command line options.
ProcessMachO(StringRef Name,MachOObjectFile * MachOOF,StringRef ArchiveMemberName=StringRef (),StringRef ArchitectureName=StringRef ())1908 static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
1909 StringRef ArchiveMemberName = StringRef(),
1910 StringRef ArchitectureName = StringRef()) {
1911 // If we are doing some processing here on the Mach-O file print the header
1912 // info. And don't print it otherwise like in the case of printing the
1913 // UniversalHeaders or ArchiveHeaders.
1914 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
1915 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
1916 DataInCode || LinkOptHints || DylibsUsed || DylibId || ObjcMetaData ||
1917 (!FilterSections.empty())) {
1918 if (!NoLeadingHeaders) {
1919 outs() << Name;
1920 if (!ArchiveMemberName.empty())
1921 outs() << '(' << ArchiveMemberName << ')';
1922 if (!ArchitectureName.empty())
1923 outs() << " (architecture " << ArchitectureName << ")";
1924 outs() << ":\n";
1925 }
1926 }
1927 // To use the report_error() form with an ArchiveName and FileName set
1928 // these up based on what is passed for Name and ArchiveMemberName.
1929 StringRef ArchiveName;
1930 StringRef FileName;
1931 if (!ArchiveMemberName.empty()) {
1932 ArchiveName = Name;
1933 FileName = ArchiveMemberName;
1934 } else {
1935 ArchiveName = StringRef();
1936 FileName = Name;
1937 }
1938
1939 // If we need the symbol table to do the operation then check it here to
1940 // produce a good error message as to where the Mach-O file comes from in
1941 // the error message.
1942 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
1943 if (Error Err = MachOOF->checkSymbolTable())
1944 reportError(std::move(Err), FileName, ArchiveName, ArchitectureName);
1945
1946 if (DisassembleAll) {
1947 for (const SectionRef &Section : MachOOF->sections()) {
1948 StringRef SectName;
1949 if (Expected<StringRef> NameOrErr = Section.getName())
1950 SectName = *NameOrErr;
1951 else
1952 consumeError(NameOrErr.takeError());
1953
1954 if (SectName.equals("__text")) {
1955 DataRefImpl Ref = Section.getRawDataRefImpl();
1956 StringRef SegName = MachOOF->getSectionFinalSegmentName(Ref);
1957 DisassembleMachO(FileName, MachOOF, SegName, SectName);
1958 }
1959 }
1960 }
1961 else if (Disassemble) {
1962 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
1963 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
1964 DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
1965 else
1966 DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
1967 }
1968 if (IndirectSymbols)
1969 PrintIndirectSymbols(MachOOF, !NonVerbose);
1970 if (DataInCode)
1971 PrintDataInCodeTable(MachOOF, !NonVerbose);
1972 if (LinkOptHints)
1973 PrintLinkOptHints(MachOOF);
1974 if (Relocations)
1975 PrintRelocations(MachOOF, !NonVerbose);
1976 if (SectionHeaders)
1977 printSectionHeaders(MachOOF);
1978 if (SectionContents)
1979 printSectionContents(MachOOF);
1980 if (!FilterSections.empty())
1981 DumpSectionContents(FileName, MachOOF, !NonVerbose);
1982 if (InfoPlist)
1983 DumpInfoPlistSectionContents(FileName, MachOOF);
1984 if (DylibsUsed)
1985 PrintDylibs(MachOOF, false);
1986 if (DylibId)
1987 PrintDylibs(MachOOF, true);
1988 if (SymbolTable)
1989 printSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1990 if (UnwindInfo)
1991 printMachOUnwindInfo(MachOOF);
1992 if (PrivateHeaders) {
1993 printMachOFileHeader(MachOOF);
1994 printMachOLoadCommands(MachOOF);
1995 }
1996 if (FirstPrivateHeader)
1997 printMachOFileHeader(MachOOF);
1998 if (ObjcMetaData)
1999 printObjcMetaData(MachOOF, !NonVerbose);
2000 if (ExportsTrie)
2001 printExportsTrie(MachOOF);
2002 if (Rebase)
2003 printRebaseTable(MachOOF);
2004 if (Bind)
2005 printBindTable(MachOOF);
2006 if (LazyBind)
2007 printLazyBindTable(MachOOF);
2008 if (WeakBind)
2009 printWeakBindTable(MachOOF);
2010
2011 if (DwarfDumpType != DIDT_Null) {
2012 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*MachOOF);
2013 // Dump the complete DWARF structure.
2014 DIDumpOptions DumpOpts;
2015 DumpOpts.DumpType = DwarfDumpType;
2016 DICtx->dump(outs(), DumpOpts);
2017 }
2018 }
2019
2020 // printUnknownCPUType() helps print_fat_headers for unknown CPU's.
printUnknownCPUType(uint32_t cputype,uint32_t cpusubtype)2021 static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2022 outs() << " cputype (" << cputype << ")\n";
2023 outs() << " cpusubtype (" << cpusubtype << ")\n";
2024 }
2025
2026 // printCPUType() helps print_fat_headers by printing the cputype and
2027 // pusubtype (symbolically for the one's it knows about).
printCPUType(uint32_t cputype,uint32_t cpusubtype)2028 static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2029 switch (cputype) {
2030 case MachO::CPU_TYPE_I386:
2031 switch (cpusubtype) {
2032 case MachO::CPU_SUBTYPE_I386_ALL:
2033 outs() << " cputype CPU_TYPE_I386\n";
2034 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
2035 break;
2036 default:
2037 printUnknownCPUType(cputype, cpusubtype);
2038 break;
2039 }
2040 break;
2041 case MachO::CPU_TYPE_X86_64:
2042 switch (cpusubtype) {
2043 case MachO::CPU_SUBTYPE_X86_64_ALL:
2044 outs() << " cputype CPU_TYPE_X86_64\n";
2045 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2046 break;
2047 case MachO::CPU_SUBTYPE_X86_64_H:
2048 outs() << " cputype CPU_TYPE_X86_64\n";
2049 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2050 break;
2051 default:
2052 printUnknownCPUType(cputype, cpusubtype);
2053 break;
2054 }
2055 break;
2056 case MachO::CPU_TYPE_ARM:
2057 switch (cpusubtype) {
2058 case MachO::CPU_SUBTYPE_ARM_ALL:
2059 outs() << " cputype CPU_TYPE_ARM\n";
2060 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2061 break;
2062 case MachO::CPU_SUBTYPE_ARM_V4T:
2063 outs() << " cputype CPU_TYPE_ARM\n";
2064 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2065 break;
2066 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2067 outs() << " cputype CPU_TYPE_ARM\n";
2068 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2069 break;
2070 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2071 outs() << " cputype CPU_TYPE_ARM\n";
2072 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2073 break;
2074 case MachO::CPU_SUBTYPE_ARM_V6:
2075 outs() << " cputype CPU_TYPE_ARM\n";
2076 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2077 break;
2078 case MachO::CPU_SUBTYPE_ARM_V6M:
2079 outs() << " cputype CPU_TYPE_ARM\n";
2080 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2081 break;
2082 case MachO::CPU_SUBTYPE_ARM_V7:
2083 outs() << " cputype CPU_TYPE_ARM\n";
2084 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2085 break;
2086 case MachO::CPU_SUBTYPE_ARM_V7EM:
2087 outs() << " cputype CPU_TYPE_ARM\n";
2088 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2089 break;
2090 case MachO::CPU_SUBTYPE_ARM_V7K:
2091 outs() << " cputype CPU_TYPE_ARM\n";
2092 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2093 break;
2094 case MachO::CPU_SUBTYPE_ARM_V7M:
2095 outs() << " cputype CPU_TYPE_ARM\n";
2096 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2097 break;
2098 case MachO::CPU_SUBTYPE_ARM_V7S:
2099 outs() << " cputype CPU_TYPE_ARM\n";
2100 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2101 break;
2102 default:
2103 printUnknownCPUType(cputype, cpusubtype);
2104 break;
2105 }
2106 break;
2107 case MachO::CPU_TYPE_ARM64:
2108 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2109 case MachO::CPU_SUBTYPE_ARM64_ALL:
2110 outs() << " cputype CPU_TYPE_ARM64\n";
2111 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2112 break;
2113 case MachO::CPU_SUBTYPE_ARM64_V8:
2114 outs() << " cputype CPU_TYPE_ARM64\n";
2115 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2116 break;
2117 case MachO::CPU_SUBTYPE_ARM64E:
2118 outs() << " cputype CPU_TYPE_ARM64\n";
2119 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2120 break;
2121 default:
2122 printUnknownCPUType(cputype, cpusubtype);
2123 break;
2124 }
2125 break;
2126 case MachO::CPU_TYPE_ARM64_32:
2127 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2128 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2129 outs() << " cputype CPU_TYPE_ARM64_32\n";
2130 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2131 break;
2132 default:
2133 printUnknownCPUType(cputype, cpusubtype);
2134 break;
2135 }
2136 break;
2137 default:
2138 printUnknownCPUType(cputype, cpusubtype);
2139 break;
2140 }
2141 }
2142
printMachOUniversalHeaders(const object::MachOUniversalBinary * UB,bool verbose)2143 static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2144 bool verbose) {
2145 outs() << "Fat headers\n";
2146 if (verbose) {
2147 if (UB->getMagic() == MachO::FAT_MAGIC)
2148 outs() << "fat_magic FAT_MAGIC\n";
2149 else // UB->getMagic() == MachO::FAT_MAGIC_64
2150 outs() << "fat_magic FAT_MAGIC_64\n";
2151 } else
2152 outs() << "fat_magic " << format("0x%" PRIx32, MachO::FAT_MAGIC) << "\n";
2153
2154 uint32_t nfat_arch = UB->getNumberOfObjects();
2155 StringRef Buf = UB->getData();
2156 uint64_t size = Buf.size();
2157 uint64_t big_size = sizeof(struct MachO::fat_header) +
2158 nfat_arch * sizeof(struct MachO::fat_arch);
2159 outs() << "nfat_arch " << UB->getNumberOfObjects();
2160 if (nfat_arch == 0)
2161 outs() << " (malformed, contains zero architecture types)\n";
2162 else if (big_size > size)
2163 outs() << " (malformed, architectures past end of file)\n";
2164 else
2165 outs() << "\n";
2166
2167 for (uint32_t i = 0; i < nfat_arch; ++i) {
2168 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2169 uint32_t cputype = OFA.getCPUType();
2170 uint32_t cpusubtype = OFA.getCPUSubType();
2171 outs() << "architecture ";
2172 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2173 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2174 uint32_t other_cputype = other_OFA.getCPUType();
2175 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2176 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2177 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2178 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2179 outs() << "(illegal duplicate architecture) ";
2180 break;
2181 }
2182 }
2183 if (verbose) {
2184 outs() << OFA.getArchFlagName() << "\n";
2185 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2186 } else {
2187 outs() << i << "\n";
2188 outs() << " cputype " << cputype << "\n";
2189 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2190 << "\n";
2191 }
2192 if (verbose &&
2193 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
2194 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2195 else
2196 outs() << " capabilities "
2197 << format("0x%" PRIx32,
2198 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2199 outs() << " offset " << OFA.getOffset();
2200 if (OFA.getOffset() > size)
2201 outs() << " (past end of file)";
2202 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2203 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2204 outs() << "\n";
2205 outs() << " size " << OFA.getSize();
2206 big_size = OFA.getOffset() + OFA.getSize();
2207 if (big_size > size)
2208 outs() << " (past end of file)";
2209 outs() << "\n";
2210 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2211 << ")\n";
2212 }
2213 }
2214
printArchiveChild(StringRef Filename,const Archive::Child & C,size_t ChildIndex,bool verbose,bool print_offset,StringRef ArchitectureName=StringRef ())2215 static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2216 size_t ChildIndex, bool verbose,
2217 bool print_offset,
2218 StringRef ArchitectureName = StringRef()) {
2219 if (print_offset)
2220 outs() << C.getChildOffset() << "\t";
2221 sys::fs::perms Mode =
2222 unwrapOrError(C.getAccessMode(), getFileNameForError(C, ChildIndex),
2223 Filename, ArchitectureName);
2224 if (verbose) {
2225 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2226 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2227 outs() << "-";
2228 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2229 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2230 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2231 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2232 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2233 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2234 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2235 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2236 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2237 } else {
2238 outs() << format("0%o ", Mode);
2239 }
2240
2241 outs() << format("%3d/%-3d %5" PRId64 " ",
2242 unwrapOrError(C.getUID(), getFileNameForError(C, ChildIndex),
2243 Filename, ArchitectureName),
2244 unwrapOrError(C.getGID(), getFileNameForError(C, ChildIndex),
2245 Filename, ArchitectureName),
2246 unwrapOrError(C.getRawSize(),
2247 getFileNameForError(C, ChildIndex), Filename,
2248 ArchitectureName));
2249
2250 StringRef RawLastModified = C.getRawLastModified();
2251 if (verbose) {
2252 unsigned Seconds;
2253 if (RawLastModified.getAsInteger(10, Seconds))
2254 outs() << "(date: \"" << RawLastModified
2255 << "\" contains non-decimal chars) ";
2256 else {
2257 // Since cime(3) returns a 26 character string of the form:
2258 // "Sun Sep 16 01:03:52 1973\n\0"
2259 // just print 24 characters.
2260 time_t t = Seconds;
2261 outs() << format("%.24s ", ctime(&t));
2262 }
2263 } else {
2264 outs() << RawLastModified << " ";
2265 }
2266
2267 if (verbose) {
2268 Expected<StringRef> NameOrErr = C.getName();
2269 if (!NameOrErr) {
2270 consumeError(NameOrErr.takeError());
2271 outs() << unwrapOrError(C.getRawName(),
2272 getFileNameForError(C, ChildIndex), Filename,
2273 ArchitectureName)
2274 << "\n";
2275 } else {
2276 StringRef Name = NameOrErr.get();
2277 outs() << Name << "\n";
2278 }
2279 } else {
2280 outs() << unwrapOrError(C.getRawName(), getFileNameForError(C, ChildIndex),
2281 Filename, ArchitectureName)
2282 << "\n";
2283 }
2284 }
2285
printArchiveHeaders(StringRef Filename,Archive * A,bool verbose,bool print_offset,StringRef ArchitectureName=StringRef ())2286 static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2287 bool print_offset,
2288 StringRef ArchitectureName = StringRef()) {
2289 Error Err = Error::success();
2290 size_t I = 0;
2291 for (const auto &C : A->children(Err, false))
2292 printArchiveChild(Filename, C, I++, verbose, print_offset,
2293 ArchitectureName);
2294
2295 if (Err)
2296 reportError(std::move(Err), Filename, "", ArchitectureName);
2297 }
2298
ValidateArchFlags()2299 static bool ValidateArchFlags() {
2300 // Check for -arch all and verifiy the -arch flags are valid.
2301 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2302 if (ArchFlags[i] == "all") {
2303 ArchAll = true;
2304 } else {
2305 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
2306 WithColor::error(errs(), "llvm-objdump")
2307 << "unknown architecture named '" + ArchFlags[i] +
2308 "'for the -arch option\n";
2309 return false;
2310 }
2311 }
2312 }
2313 return true;
2314 }
2315
2316 // ParseInputMachO() parses the named Mach-O file in Filename and handles the
2317 // -arch flags selecting just those slices as specified by them and also parses
2318 // archive files. Then for each individual Mach-O file ProcessMachO() is
2319 // called to process the file based on the command line options.
parseInputMachO(StringRef Filename)2320 void objdump::parseInputMachO(StringRef Filename) {
2321 if (!ValidateArchFlags())
2322 return;
2323
2324 // Attempt to open the binary.
2325 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
2326 if (!BinaryOrErr) {
2327 if (Error E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
2328 reportError(std::move(E), Filename);
2329 else
2330 outs() << Filename << ": is not an object file\n";
2331 return;
2332 }
2333 Binary &Bin = *BinaryOrErr.get().getBinary();
2334
2335 if (Archive *A = dyn_cast<Archive>(&Bin)) {
2336 outs() << "Archive : " << Filename << "\n";
2337 if (ArchiveHeaders)
2338 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
2339
2340 Error Err = Error::success();
2341 unsigned I = -1;
2342 for (auto &C : A->children(Err)) {
2343 ++I;
2344 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2345 if (!ChildOrErr) {
2346 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2347 reportError(std::move(E), getFileNameForError(C, I), Filename);
2348 continue;
2349 }
2350 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2351 if (!checkMachOAndArchFlags(O, Filename))
2352 return;
2353 ProcessMachO(Filename, O, O->getFileName());
2354 }
2355 }
2356 if (Err)
2357 reportError(std::move(Err), Filename);
2358 return;
2359 }
2360 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
2361 parseInputMachO(UB);
2362 return;
2363 }
2364 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
2365 if (!checkMachOAndArchFlags(O, Filename))
2366 return;
2367 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O))
2368 ProcessMachO(Filename, MachOOF);
2369 else
2370 WithColor::error(errs(), "llvm-objdump")
2371 << Filename << "': "
2372 << "object is not a Mach-O file type.\n";
2373 return;
2374 }
2375 llvm_unreachable("Input object can't be invalid at this point");
2376 }
2377
parseInputMachO(MachOUniversalBinary * UB)2378 void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2379 if (!ValidateArchFlags())
2380 return;
2381
2382 auto Filename = UB->getFileName();
2383
2384 if (UniversalHeaders)
2385 printMachOUniversalHeaders(UB, !NonVerbose);
2386
2387 // If we have a list of architecture flags specified dump only those.
2388 if (!ArchAll && !ArchFlags.empty()) {
2389 // Look for a slice in the universal binary that matches each ArchFlag.
2390 bool ArchFound;
2391 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2392 ArchFound = false;
2393 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2394 E = UB->end_objects();
2395 I != E; ++I) {
2396 if (ArchFlags[i] == I->getArchFlagName()) {
2397 ArchFound = true;
2398 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2399 I->getAsObjectFile();
2400 std::string ArchitectureName = "";
2401 if (ArchFlags.size() > 1)
2402 ArchitectureName = I->getArchFlagName();
2403 if (ObjOrErr) {
2404 ObjectFile &O = *ObjOrErr.get();
2405 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2406 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2407 } else if (Error E = isNotObjectErrorInvalidFileType(
2408 ObjOrErr.takeError())) {
2409 reportError(std::move(E), "", Filename, ArchitectureName);
2410 continue;
2411 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2412 I->getAsArchive()) {
2413 std::unique_ptr<Archive> &A = *AOrErr;
2414 outs() << "Archive : " << Filename;
2415 if (!ArchitectureName.empty())
2416 outs() << " (architecture " << ArchitectureName << ")";
2417 outs() << "\n";
2418 if (ArchiveHeaders)
2419 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2420 ArchiveMemberOffsets, ArchitectureName);
2421 Error Err = Error::success();
2422 unsigned I = -1;
2423 for (auto &C : A->children(Err)) {
2424 ++I;
2425 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2426 if (!ChildOrErr) {
2427 if (Error E =
2428 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2429 reportError(std::move(E), getFileNameForError(C, I), Filename,
2430 ArchitectureName);
2431 continue;
2432 }
2433 if (MachOObjectFile *O =
2434 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2435 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
2436 }
2437 if (Err)
2438 reportError(std::move(Err), Filename);
2439 } else {
2440 consumeError(AOrErr.takeError());
2441 reportError(Filename,
2442 "Mach-O universal file for architecture " +
2443 StringRef(I->getArchFlagName()) +
2444 " is not a Mach-O file or an archive file");
2445 }
2446 }
2447 }
2448 if (!ArchFound) {
2449 WithColor::error(errs(), "llvm-objdump")
2450 << "file: " + Filename + " does not contain "
2451 << "architecture: " + ArchFlags[i] + "\n";
2452 return;
2453 }
2454 }
2455 return;
2456 }
2457 // No architecture flags were specified so if this contains a slice that
2458 // matches the host architecture dump only that.
2459 if (!ArchAll) {
2460 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2461 E = UB->end_objects();
2462 I != E; ++I) {
2463 if (MachOObjectFile::getHostArch().getArchName() ==
2464 I->getArchFlagName()) {
2465 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2466 std::string ArchiveName;
2467 ArchiveName.clear();
2468 if (ObjOrErr) {
2469 ObjectFile &O = *ObjOrErr.get();
2470 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
2471 ProcessMachO(Filename, MachOOF);
2472 } else if (Error E =
2473 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2474 reportError(std::move(E), Filename);
2475 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2476 I->getAsArchive()) {
2477 std::unique_ptr<Archive> &A = *AOrErr;
2478 outs() << "Archive : " << Filename << "\n";
2479 if (ArchiveHeaders)
2480 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2481 ArchiveMemberOffsets);
2482 Error Err = Error::success();
2483 unsigned I = -1;
2484 for (auto &C : A->children(Err)) {
2485 ++I;
2486 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2487 if (!ChildOrErr) {
2488 if (Error E =
2489 isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2490 reportError(std::move(E), getFileNameForError(C, I), Filename);
2491 continue;
2492 }
2493 if (MachOObjectFile *O =
2494 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
2495 ProcessMachO(Filename, O, O->getFileName());
2496 }
2497 if (Err)
2498 reportError(std::move(Err), Filename);
2499 } else {
2500 consumeError(AOrErr.takeError());
2501 reportError(Filename, "Mach-O universal file for architecture " +
2502 StringRef(I->getArchFlagName()) +
2503 " is not a Mach-O file or an archive file");
2504 }
2505 return;
2506 }
2507 }
2508 }
2509 // Either all architectures have been specified or none have been specified
2510 // and this does not contain the host architecture so dump all the slices.
2511 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2512 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2513 E = UB->end_objects();
2514 I != E; ++I) {
2515 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2516 std::string ArchitectureName = "";
2517 if (moreThanOneArch)
2518 ArchitectureName = I->getArchFlagName();
2519 if (ObjOrErr) {
2520 ObjectFile &Obj = *ObjOrErr.get();
2521 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
2522 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
2523 } else if (Error E =
2524 isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
2525 reportError(std::move(E), Filename, "", ArchitectureName);
2526 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2527 std::unique_ptr<Archive> &A = *AOrErr;
2528 outs() << "Archive : " << Filename;
2529 if (!ArchitectureName.empty())
2530 outs() << " (architecture " << ArchitectureName << ")";
2531 outs() << "\n";
2532 if (ArchiveHeaders)
2533 printArchiveHeaders(Filename, A.get(), !NonVerbose,
2534 ArchiveMemberOffsets, ArchitectureName);
2535 Error Err = Error::success();
2536 unsigned I = -1;
2537 for (auto &C : A->children(Err)) {
2538 ++I;
2539 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2540 if (!ChildOrErr) {
2541 if (Error E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2542 reportError(std::move(E), getFileNameForError(C, I), Filename,
2543 ArchitectureName);
2544 continue;
2545 }
2546 if (MachOObjectFile *O =
2547 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
2548 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
2549 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
2550 ArchitectureName);
2551 }
2552 }
2553 if (Err)
2554 reportError(std::move(Err), Filename);
2555 } else {
2556 consumeError(AOrErr.takeError());
2557 reportError(Filename, "Mach-O universal file for architecture " +
2558 StringRef(I->getArchFlagName()) +
2559 " is not a Mach-O file or an archive file");
2560 }
2561 }
2562 }
2563
2564 namespace {
2565 // The block of info used by the Symbolizer call backs.
2566 struct DisassembleInfo {
DisassembleInfo__anon30756ae00711::DisassembleInfo2567 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2568 std::vector<SectionRef> *Sections, bool verbose)
2569 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2570 bool verbose;
2571 MachOObjectFile *O;
2572 SectionRef S;
2573 SymbolAddressMap *AddrMap;
2574 std::vector<SectionRef> *Sections;
2575 const char *class_name = nullptr;
2576 const char *selector_name = nullptr;
2577 std::unique_ptr<char[]> method = nullptr;
2578 char *demangled_name = nullptr;
2579 uint64_t adrp_addr = 0;
2580 uint32_t adrp_inst = 0;
2581 std::unique_ptr<SymbolAddressMap> bindtable;
2582 uint32_t depth = 0;
2583 };
2584 } // namespace
2585
2586 // SymbolizerGetOpInfo() is the operand information call back function.
2587 // This is called to get the symbolic information for operand(s) of an
2588 // instruction when it is being done. This routine does this from
2589 // the relocation information, symbol table, etc. That block of information
2590 // is a pointer to the struct DisassembleInfo that was passed when the
2591 // disassembler context was created and passed to back to here when
2592 // called back by the disassembler for instruction operands that could have
2593 // relocation information. The address of the instruction containing operand is
2594 // at the Pc parameter. The immediate value the operand has is passed in
2595 // op_info->Value and is at Offset past the start of the instruction and has a
2596 // byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2597 // LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2598 // names and addends of the symbolic expression to add for the operand. The
2599 // value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2600 // information is returned then this function returns 1 else it returns 0.
SymbolizerGetOpInfo(void * DisInfo,uint64_t Pc,uint64_t Offset,uint64_t Size,int TagType,void * TagBuf)2601 static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2602 uint64_t Size, int TagType, void *TagBuf) {
2603 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2604 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2605 uint64_t value = op_info->Value;
2606
2607 // Make sure all fields returned are zero if we don't set them.
2608 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
2609 op_info->Value = value;
2610
2611 // If the TagType is not the value 1 which it code knows about or if no
2612 // verbose symbolic information is wanted then just return 0, indicating no
2613 // information is being returned.
2614 if (TagType != 1 || !info->verbose)
2615 return 0;
2616
2617 unsigned int Arch = info->O->getArch();
2618 if (Arch == Triple::x86) {
2619 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2620 return 0;
2621 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2622 // TODO:
2623 // Search the external relocation entries of a fully linked image
2624 // (if any) for an entry that matches this segment offset.
2625 // uint32_t seg_offset = (Pc + Offset);
2626 return 0;
2627 }
2628 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2629 // for an entry for this section offset.
2630 uint32_t sect_addr = info->S.getAddress();
2631 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2632 bool reloc_found = false;
2633 DataRefImpl Rel;
2634 MachO::any_relocation_info RE;
2635 bool isExtern = false;
2636 SymbolRef Symbol;
2637 bool r_scattered = false;
2638 uint32_t r_value, pair_r_value, r_type;
2639 for (const RelocationRef &Reloc : info->S.relocations()) {
2640 uint64_t RelocOffset = Reloc.getOffset();
2641 if (RelocOffset == sect_offset) {
2642 Rel = Reloc.getRawDataRefImpl();
2643 RE = info->O->getRelocation(Rel);
2644 r_type = info->O->getAnyRelocationType(RE);
2645 r_scattered = info->O->isRelocationScattered(RE);
2646 if (r_scattered) {
2647 r_value = info->O->getScatteredRelocationValue(RE);
2648 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2649 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2650 DataRefImpl RelNext = Rel;
2651 info->O->moveRelocationNext(RelNext);
2652 MachO::any_relocation_info RENext;
2653 RENext = info->O->getRelocation(RelNext);
2654 if (info->O->isRelocationScattered(RENext))
2655 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2656 else
2657 return 0;
2658 }
2659 } else {
2660 isExtern = info->O->getPlainRelocationExternal(RE);
2661 if (isExtern) {
2662 symbol_iterator RelocSym = Reloc.getSymbol();
2663 Symbol = *RelocSym;
2664 }
2665 }
2666 reloc_found = true;
2667 break;
2668 }
2669 }
2670 if (reloc_found && isExtern) {
2671 op_info->AddSymbol.Present = 1;
2672 op_info->AddSymbol.Name =
2673 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2674 // For i386 extern relocation entries the value in the instruction is
2675 // the offset from the symbol, and value is already set in op_info->Value.
2676 return 1;
2677 }
2678 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2679 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2680 const char *add = GuessSymbolName(r_value, info->AddrMap);
2681 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2682 uint32_t offset = value - (r_value - pair_r_value);
2683 op_info->AddSymbol.Present = 1;
2684 if (add != nullptr)
2685 op_info->AddSymbol.Name = add;
2686 else
2687 op_info->AddSymbol.Value = r_value;
2688 op_info->SubtractSymbol.Present = 1;
2689 if (sub != nullptr)
2690 op_info->SubtractSymbol.Name = sub;
2691 else
2692 op_info->SubtractSymbol.Value = pair_r_value;
2693 op_info->Value = offset;
2694 return 1;
2695 }
2696 return 0;
2697 }
2698 if (Arch == Triple::x86_64) {
2699 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
2700 return 0;
2701 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2702 // relocation entries of a linked image (if any) for an entry that matches
2703 // this segment offset.
2704 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2705 uint64_t seg_offset = Pc + Offset;
2706 bool reloc_found = false;
2707 DataRefImpl Rel;
2708 MachO::any_relocation_info RE;
2709 bool isExtern = false;
2710 SymbolRef Symbol;
2711 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2712 uint64_t RelocOffset = Reloc.getOffset();
2713 if (RelocOffset == seg_offset) {
2714 Rel = Reloc.getRawDataRefImpl();
2715 RE = info->O->getRelocation(Rel);
2716 // external relocation entries should always be external.
2717 isExtern = info->O->getPlainRelocationExternal(RE);
2718 if (isExtern) {
2719 symbol_iterator RelocSym = Reloc.getSymbol();
2720 Symbol = *RelocSym;
2721 }
2722 reloc_found = true;
2723 break;
2724 }
2725 }
2726 if (reloc_found && isExtern) {
2727 // The Value passed in will be adjusted by the Pc if the instruction
2728 // adds the Pc. But for x86_64 external relocation entries the Value
2729 // is the offset from the external symbol.
2730 if (info->O->getAnyRelocationPCRel(RE))
2731 op_info->Value -= Pc + Offset + Size;
2732 const char *name =
2733 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2734 op_info->AddSymbol.Present = 1;
2735 op_info->AddSymbol.Name = name;
2736 return 1;
2737 }
2738 return 0;
2739 }
2740 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2741 // for an entry for this section offset.
2742 uint64_t sect_addr = info->S.getAddress();
2743 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2744 bool reloc_found = false;
2745 DataRefImpl Rel;
2746 MachO::any_relocation_info RE;
2747 bool isExtern = false;
2748 SymbolRef Symbol;
2749 for (const RelocationRef &Reloc : info->S.relocations()) {
2750 uint64_t RelocOffset = Reloc.getOffset();
2751 if (RelocOffset == sect_offset) {
2752 Rel = Reloc.getRawDataRefImpl();
2753 RE = info->O->getRelocation(Rel);
2754 // NOTE: Scattered relocations don't exist on x86_64.
2755 isExtern = info->O->getPlainRelocationExternal(RE);
2756 if (isExtern) {
2757 symbol_iterator RelocSym = Reloc.getSymbol();
2758 Symbol = *RelocSym;
2759 }
2760 reloc_found = true;
2761 break;
2762 }
2763 }
2764 if (reloc_found && isExtern) {
2765 // The Value passed in will be adjusted by the Pc if the instruction
2766 // adds the Pc. But for x86_64 external relocation entries the Value
2767 // is the offset from the external symbol.
2768 if (info->O->getAnyRelocationPCRel(RE))
2769 op_info->Value -= Pc + Offset + Size;
2770 const char *name =
2771 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2772 unsigned Type = info->O->getAnyRelocationType(RE);
2773 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2774 DataRefImpl RelNext = Rel;
2775 info->O->moveRelocationNext(RelNext);
2776 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2777 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
2778 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
2779 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
2780 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
2781 op_info->SubtractSymbol.Present = 1;
2782 op_info->SubtractSymbol.Name = name;
2783 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
2784 Symbol = *RelocSymNext;
2785 name = unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2786 }
2787 }
2788 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2789 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2790 op_info->AddSymbol.Present = 1;
2791 op_info->AddSymbol.Name = name;
2792 return 1;
2793 }
2794 return 0;
2795 }
2796 if (Arch == Triple::arm) {
2797 if (Offset != 0 || (Size != 4 && Size != 2))
2798 return 0;
2799 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2800 // TODO:
2801 // Search the external relocation entries of a fully linked image
2802 // (if any) for an entry that matches this segment offset.
2803 // uint32_t seg_offset = (Pc + Offset);
2804 return 0;
2805 }
2806 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2807 // for an entry for this section offset.
2808 uint32_t sect_addr = info->S.getAddress();
2809 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2810 DataRefImpl Rel;
2811 MachO::any_relocation_info RE;
2812 bool isExtern = false;
2813 SymbolRef Symbol;
2814 bool r_scattered = false;
2815 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
2816 auto Reloc =
2817 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2818 uint64_t RelocOffset = Reloc.getOffset();
2819 return RelocOffset == sect_offset;
2820 });
2821
2822 if (Reloc == info->S.relocations().end())
2823 return 0;
2824
2825 Rel = Reloc->getRawDataRefImpl();
2826 RE = info->O->getRelocation(Rel);
2827 r_length = info->O->getAnyRelocationLength(RE);
2828 r_scattered = info->O->isRelocationScattered(RE);
2829 if (r_scattered) {
2830 r_value = info->O->getScatteredRelocationValue(RE);
2831 r_type = info->O->getScatteredRelocationType(RE);
2832 } else {
2833 r_type = info->O->getAnyRelocationType(RE);
2834 isExtern = info->O->getPlainRelocationExternal(RE);
2835 if (isExtern) {
2836 symbol_iterator RelocSym = Reloc->getSymbol();
2837 Symbol = *RelocSym;
2838 }
2839 }
2840 if (r_type == MachO::ARM_RELOC_HALF ||
2841 r_type == MachO::ARM_RELOC_SECTDIFF ||
2842 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
2843 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2844 DataRefImpl RelNext = Rel;
2845 info->O->moveRelocationNext(RelNext);
2846 MachO::any_relocation_info RENext;
2847 RENext = info->O->getRelocation(RelNext);
2848 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2849 if (info->O->isRelocationScattered(RENext))
2850 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2851 }
2852
2853 if (isExtern) {
2854 const char *name =
2855 unwrapOrError(Symbol.getName(), info->O->getFileName()).data();
2856 op_info->AddSymbol.Present = 1;
2857 op_info->AddSymbol.Name = name;
2858 switch (r_type) {
2859 case MachO::ARM_RELOC_HALF:
2860 if ((r_length & 0x1) == 1) {
2861 op_info->Value = value << 16 | other_half;
2862 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2863 } else {
2864 op_info->Value = other_half << 16 | value;
2865 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2866 }
2867 break;
2868 default:
2869 break;
2870 }
2871 return 1;
2872 }
2873 // If we have a branch that is not an external relocation entry then
2874 // return 0 so the code in tryAddingSymbolicOperand() can use the
2875 // SymbolLookUp call back with the branch target address to look up the
2876 // symbol and possibility add an annotation for a symbol stub.
2877 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
2878 r_type == MachO::ARM_THUMB_RELOC_BR22))
2879 return 0;
2880
2881 uint32_t offset = 0;
2882 if (r_type == MachO::ARM_RELOC_HALF ||
2883 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2884 if ((r_length & 0x1) == 1)
2885 value = value << 16 | other_half;
2886 else
2887 value = other_half << 16 | value;
2888 }
2889 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2890 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2891 offset = value - r_value;
2892 value = r_value;
2893 }
2894
2895 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2896 if ((r_length & 0x1) == 1)
2897 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2898 else
2899 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2900 const char *add = GuessSymbolName(r_value, info->AddrMap);
2901 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2902 int32_t offset = value - (r_value - pair_r_value);
2903 op_info->AddSymbol.Present = 1;
2904 if (add != nullptr)
2905 op_info->AddSymbol.Name = add;
2906 else
2907 op_info->AddSymbol.Value = r_value;
2908 op_info->SubtractSymbol.Present = 1;
2909 if (sub != nullptr)
2910 op_info->SubtractSymbol.Name = sub;
2911 else
2912 op_info->SubtractSymbol.Value = pair_r_value;
2913 op_info->Value = offset;
2914 return 1;
2915 }
2916
2917 op_info->AddSymbol.Present = 1;
2918 op_info->Value = offset;
2919 if (r_type == MachO::ARM_RELOC_HALF) {
2920 if ((r_length & 0x1) == 1)
2921 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
2922 else
2923 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
2924 }
2925 const char *add = GuessSymbolName(value, info->AddrMap);
2926 if (add != nullptr) {
2927 op_info->AddSymbol.Name = add;
2928 return 1;
2929 }
2930 op_info->AddSymbol.Value = value;
2931 return 1;
2932 }
2933 if (Arch == Triple::aarch64) {
2934 if (Offset != 0 || Size != 4)
2935 return 0;
2936 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2937 // TODO:
2938 // Search the external relocation entries of a fully linked image
2939 // (if any) for an entry that matches this segment offset.
2940 // uint64_t seg_offset = (Pc + Offset);
2941 return 0;
2942 }
2943 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2944 // for an entry for this section offset.
2945 uint64_t sect_addr = info->S.getAddress();
2946 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2947 auto Reloc =
2948 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2949 uint64_t RelocOffset = Reloc.getOffset();
2950 return RelocOffset == sect_offset;
2951 });
2952
2953 if (Reloc == info->S.relocations().end())
2954 return 0;
2955
2956 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2957 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2958 uint32_t r_type = info->O->getAnyRelocationType(RE);
2959 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2960 DataRefImpl RelNext = Rel;
2961 info->O->moveRelocationNext(RelNext);
2962 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2963 if (value == 0) {
2964 value = info->O->getPlainRelocationSymbolNum(RENext);
2965 op_info->Value = value;
2966 }
2967 }
2968 // NOTE: Scattered relocations don't exist on arm64.
2969 if (!info->O->getPlainRelocationExternal(RE))
2970 return 0;
2971 const char *name =
2972 unwrapOrError(Reloc->getSymbol()->getName(), info->O->getFileName())
2973 .data();
2974 op_info->AddSymbol.Present = 1;
2975 op_info->AddSymbol.Name = name;
2976
2977 switch (r_type) {
2978 case MachO::ARM64_RELOC_PAGE21:
2979 /* @page */
2980 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
2981 break;
2982 case MachO::ARM64_RELOC_PAGEOFF12:
2983 /* @pageoff */
2984 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
2985 break;
2986 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2987 /* @gotpage */
2988 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
2989 break;
2990 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2991 /* @gotpageoff */
2992 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
2993 break;
2994 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2995 /* @tvlppage is not implemented in llvm-mc */
2996 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
2997 break;
2998 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2999 /* @tvlppageoff is not implemented in llvm-mc */
3000 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3001 break;
3002 default:
3003 case MachO::ARM64_RELOC_BRANCH26:
3004 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3005 break;
3006 }
3007 return 1;
3008 }
3009 return 0;
3010 }
3011
3012 // GuessCstringPointer is passed the address of what might be a pointer to a
3013 // literal string in a cstring section. If that address is in a cstring section
3014 // it returns a pointer to that string. Else it returns nullptr.
GuessCstringPointer(uint64_t ReferenceValue,struct DisassembleInfo * info)3015 static const char *GuessCstringPointer(uint64_t ReferenceValue,
3016 struct DisassembleInfo *info) {
3017 for (const auto &Load : info->O->load_commands()) {
3018 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3019 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3020 for (unsigned J = 0; J < Seg.nsects; ++J) {
3021 MachO::section_64 Sec = info->O->getSection64(Load, J);
3022 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3023 if (section_type == MachO::S_CSTRING_LITERALS &&
3024 ReferenceValue >= Sec.addr &&
3025 ReferenceValue < Sec.addr + Sec.size) {
3026 uint64_t sect_offset = ReferenceValue - Sec.addr;
3027 uint64_t object_offset = Sec.offset + sect_offset;
3028 StringRef MachOContents = info->O->getData();
3029 uint64_t object_size = MachOContents.size();
3030 const char *object_addr = (const char *)MachOContents.data();
3031 if (object_offset < object_size) {
3032 const char *name = object_addr + object_offset;
3033 return name;
3034 } else {
3035 return nullptr;
3036 }
3037 }
3038 }
3039 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3040 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3041 for (unsigned J = 0; J < Seg.nsects; ++J) {
3042 MachO::section Sec = info->O->getSection(Load, J);
3043 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3044 if (section_type == MachO::S_CSTRING_LITERALS &&
3045 ReferenceValue >= Sec.addr &&
3046 ReferenceValue < Sec.addr + Sec.size) {
3047 uint64_t sect_offset = ReferenceValue - Sec.addr;
3048 uint64_t object_offset = Sec.offset + sect_offset;
3049 StringRef MachOContents = info->O->getData();
3050 uint64_t object_size = MachOContents.size();
3051 const char *object_addr = (const char *)MachOContents.data();
3052 if (object_offset < object_size) {
3053 const char *name = object_addr + object_offset;
3054 return name;
3055 } else {
3056 return nullptr;
3057 }
3058 }
3059 }
3060 }
3061 }
3062 return nullptr;
3063 }
3064
3065 // GuessIndirectSymbol returns the name of the indirect symbol for the
3066 // ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
3067 // an address of a symbol stub or a lazy or non-lazy pointer to associate the
3068 // symbol name being referenced by the stub or pointer.
GuessIndirectSymbol(uint64_t ReferenceValue,struct DisassembleInfo * info)3069 static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3070 struct DisassembleInfo *info) {
3071 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3072 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3073 for (const auto &Load : info->O->load_commands()) {
3074 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3075 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3076 for (unsigned J = 0; J < Seg.nsects; ++J) {
3077 MachO::section_64 Sec = info->O->getSection64(Load, J);
3078 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3079 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3080 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3081 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3082 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3083 section_type == MachO::S_SYMBOL_STUBS) &&
3084 ReferenceValue >= Sec.addr &&
3085 ReferenceValue < Sec.addr + Sec.size) {
3086 uint32_t stride;
3087 if (section_type == MachO::S_SYMBOL_STUBS)
3088 stride = Sec.reserved2;
3089 else
3090 stride = 8;
3091 if (stride == 0)
3092 return nullptr;
3093 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3094 if (index < Dysymtab.nindirectsyms) {
3095 uint32_t indirect_symbol =
3096 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3097 if (indirect_symbol < Symtab.nsyms) {
3098 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3099 return unwrapOrError(Sym->getName(), info->O->getFileName())
3100 .data();
3101 }
3102 }
3103 }
3104 }
3105 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3106 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
3107 for (unsigned J = 0; J < Seg.nsects; ++J) {
3108 MachO::section Sec = info->O->getSection(Load, J);
3109 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3110 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3111 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3112 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3113 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3114 section_type == MachO::S_SYMBOL_STUBS) &&
3115 ReferenceValue >= Sec.addr &&
3116 ReferenceValue < Sec.addr + Sec.size) {
3117 uint32_t stride;
3118 if (section_type == MachO::S_SYMBOL_STUBS)
3119 stride = Sec.reserved2;
3120 else
3121 stride = 4;
3122 if (stride == 0)
3123 return nullptr;
3124 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3125 if (index < Dysymtab.nindirectsyms) {
3126 uint32_t indirect_symbol =
3127 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
3128 if (indirect_symbol < Symtab.nsyms) {
3129 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
3130 return unwrapOrError(Sym->getName(), info->O->getFileName())
3131 .data();
3132 }
3133 }
3134 }
3135 }
3136 }
3137 }
3138 return nullptr;
3139 }
3140
3141 // method_reference() is called passing it the ReferenceName that might be
3142 // a reference it to an Objective-C method call. If so then it allocates and
3143 // assembles a method call string with the values last seen and saved in
3144 // the DisassembleInfo's class_name and selector_name fields. This is saved
3145 // into the method field of the info and any previous string is free'ed.
3146 // Then the class_name field in the info is set to nullptr. The method call
3147 // string is set into ReferenceName and ReferenceType is set to
3148 // LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3149 // then both ReferenceType and ReferenceName are left unchanged.
method_reference(struct DisassembleInfo * info,uint64_t * ReferenceType,const char ** ReferenceName)3150 static void method_reference(struct DisassembleInfo *info,
3151 uint64_t *ReferenceType,
3152 const char **ReferenceName) {
3153 unsigned int Arch = info->O->getArch();
3154 if (*ReferenceName != nullptr) {
3155 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
3156 if (info->selector_name != nullptr) {
3157 if (info->class_name != nullptr) {
3158 info->method = std::make_unique<char[]>(
3159 5 + strlen(info->class_name) + strlen(info->selector_name));
3160 char *method = info->method.get();
3161 if (method != nullptr) {
3162 strcpy(method, "+[");
3163 strcat(method, info->class_name);
3164 strcat(method, " ");
3165 strcat(method, info->selector_name);
3166 strcat(method, "]");
3167 *ReferenceName = method;
3168 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3169 }
3170 } else {
3171 info->method =
3172 std::make_unique<char[]>(9 + strlen(info->selector_name));
3173 char *method = info->method.get();
3174 if (method != nullptr) {
3175 if (Arch == Triple::x86_64)
3176 strcpy(method, "-[%rdi ");
3177 else if (Arch == Triple::aarch64)
3178 strcpy(method, "-[x0 ");
3179 else
3180 strcpy(method, "-[r? ");
3181 strcat(method, info->selector_name);
3182 strcat(method, "]");
3183 *ReferenceName = method;
3184 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3185 }
3186 }
3187 info->class_name = nullptr;
3188 }
3189 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
3190 if (info->selector_name != nullptr) {
3191 info->method =
3192 std::make_unique<char[]>(17 + strlen(info->selector_name));
3193 char *method = info->method.get();
3194 if (method != nullptr) {
3195 if (Arch == Triple::x86_64)
3196 strcpy(method, "-[[%rdi super] ");
3197 else if (Arch == Triple::aarch64)
3198 strcpy(method, "-[[x0 super] ");
3199 else
3200 strcpy(method, "-[[r? super] ");
3201 strcat(method, info->selector_name);
3202 strcat(method, "]");
3203 *ReferenceName = method;
3204 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3205 }
3206 info->class_name = nullptr;
3207 }
3208 }
3209 }
3210 }
3211
3212 // GuessPointerPointer() is passed the address of what might be a pointer to
3213 // a reference to an Objective-C class, selector, message ref or cfstring.
3214 // If so the value of the pointer is returned and one of the booleans are set
3215 // to true. If not zero is returned and all the booleans are set to false.
GuessPointerPointer(uint64_t ReferenceValue,struct DisassembleInfo * info,bool & classref,bool & selref,bool & msgref,bool & cfstring)3216 static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3217 struct DisassembleInfo *info,
3218 bool &classref, bool &selref, bool &msgref,
3219 bool &cfstring) {
3220 classref = false;
3221 selref = false;
3222 msgref = false;
3223 cfstring = false;
3224 for (const auto &Load : info->O->load_commands()) {
3225 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3226 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
3227 for (unsigned J = 0; J < Seg.nsects; ++J) {
3228 MachO::section_64 Sec = info->O->getSection64(Load, J);
3229 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
3230 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3231 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
3232 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
3233 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
3234 ReferenceValue >= Sec.addr &&
3235 ReferenceValue < Sec.addr + Sec.size) {
3236 uint64_t sect_offset = ReferenceValue - Sec.addr;
3237 uint64_t object_offset = Sec.offset + sect_offset;
3238 StringRef MachOContents = info->O->getData();
3239 uint64_t object_size = MachOContents.size();
3240 const char *object_addr = (const char *)MachOContents.data();
3241 if (object_offset < object_size) {
3242 uint64_t pointer_value;
3243 memcpy(&pointer_value, object_addr + object_offset,
3244 sizeof(uint64_t));
3245 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3246 sys::swapByteOrder(pointer_value);
3247 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
3248 selref = true;
3249 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
3250 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
3251 classref = true;
3252 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
3253 ReferenceValue + 8 < Sec.addr + Sec.size) {
3254 msgref = true;
3255 memcpy(&pointer_value, object_addr + object_offset + 8,
3256 sizeof(uint64_t));
3257 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3258 sys::swapByteOrder(pointer_value);
3259 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
3260 cfstring = true;
3261 return pointer_value;
3262 } else {
3263 return 0;
3264 }
3265 }
3266 }
3267 }
3268 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3269 }
3270 return 0;
3271 }
3272
3273 // get_pointer_64 returns a pointer to the bytes in the object file at the
3274 // Address from a section in the Mach-O file. And indirectly returns the
3275 // offset into the section, number of bytes left in the section past the offset
3276 // and which section is was being referenced. If the Address is not in a
3277 // section nullptr is returned.
get_pointer_64(uint64_t Address,uint32_t & offset,uint32_t & left,SectionRef & S,DisassembleInfo * info,bool objc_only=false)3278 static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3279 uint32_t &left, SectionRef &S,
3280 DisassembleInfo *info,
3281 bool objc_only = false) {
3282 offset = 0;
3283 left = 0;
3284 S = SectionRef();
3285 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3286 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3287 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3288 if (SectSize == 0)
3289 continue;
3290 if (objc_only) {
3291 StringRef SectName;
3292 Expected<StringRef> SecNameOrErr =
3293 ((*(info->Sections))[SectIdx]).getName();
3294 if (SecNameOrErr)
3295 SectName = *SecNameOrErr;
3296 else
3297 consumeError(SecNameOrErr.takeError());
3298
3299 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3300 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
3301 if (SegName != "__OBJC" && SectName != "__cstring")
3302 continue;
3303 }
3304 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3305 S = (*(info->Sections))[SectIdx];
3306 offset = Address - SectAddress;
3307 left = SectSize - offset;
3308 StringRef SectContents = unwrapOrError(
3309 ((*(info->Sections))[SectIdx]).getContents(), info->O->getFileName());
3310 return SectContents.data() + offset;
3311 }
3312 }
3313 return nullptr;
3314 }
3315
get_pointer_32(uint32_t Address,uint32_t & offset,uint32_t & left,SectionRef & S,DisassembleInfo * info,bool objc_only=false)3316 static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3317 uint32_t &left, SectionRef &S,
3318 DisassembleInfo *info,
3319 bool objc_only = false) {
3320 return get_pointer_64(Address, offset, left, S, info, objc_only);
3321 }
3322
3323 // get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3324 // the symbol indirectly through n_value. Based on the relocation information
3325 // for the specified section offset in the specified section reference.
3326 // If no relocation information is found and a non-zero ReferenceValue for the
3327 // symbol is passed, look up that address in the info's AddrMap.
get_symbol_64(uint32_t sect_offset,SectionRef S,DisassembleInfo * info,uint64_t & n_value,uint64_t ReferenceValue=0)3328 static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3329 DisassembleInfo *info, uint64_t &n_value,
3330 uint64_t ReferenceValue = 0) {
3331 n_value = 0;
3332 if (!info->verbose)
3333 return nullptr;
3334
3335 // See if there is an external relocation entry at the sect_offset.
3336 bool reloc_found = false;
3337 DataRefImpl Rel;
3338 MachO::any_relocation_info RE;
3339 bool isExtern = false;
3340 SymbolRef Symbol;
3341 for (const RelocationRef &Reloc : S.relocations()) {
3342 uint64_t RelocOffset = Reloc.getOffset();
3343 if (RelocOffset == sect_offset) {
3344 Rel = Reloc.getRawDataRefImpl();
3345 RE = info->O->getRelocation(Rel);
3346 if (info->O->isRelocationScattered(RE))
3347 continue;
3348 isExtern = info->O->getPlainRelocationExternal(RE);
3349 if (isExtern) {
3350 symbol_iterator RelocSym = Reloc.getSymbol();
3351 Symbol = *RelocSym;
3352 }
3353 reloc_found = true;
3354 break;
3355 }
3356 }
3357 // If there is an external relocation entry for a symbol in this section
3358 // at this section_offset then use that symbol's value for the n_value
3359 // and return its name.
3360 const char *SymbolName = nullptr;
3361 if (reloc_found && isExtern) {
3362 n_value = cantFail(Symbol.getValue());
3363 StringRef Name = unwrapOrError(Symbol.getName(), info->O->getFileName());
3364 if (!Name.empty()) {
3365 SymbolName = Name.data();
3366 return SymbolName;
3367 }
3368 }
3369
3370 // TODO: For fully linked images, look through the external relocation
3371 // entries off the dynamic symtab command. For these the r_offset is from the
3372 // start of the first writeable segment in the Mach-O file. So the offset
3373 // to this section from that segment is passed to this routine by the caller,
3374 // as the database_offset. Which is the difference of the section's starting
3375 // address and the first writable segment.
3376 //
3377 // NOTE: need add passing the database_offset to this routine.
3378
3379 // We did not find an external relocation entry so look up the ReferenceValue
3380 // as an address of a symbol and if found return that symbol's name.
3381 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
3382
3383 return SymbolName;
3384 }
3385
get_symbol_32(uint32_t sect_offset,SectionRef S,DisassembleInfo * info,uint32_t ReferenceValue)3386 static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3387 DisassembleInfo *info,
3388 uint32_t ReferenceValue) {
3389 uint64_t n_value64;
3390 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
3391 }
3392
3393 namespace {
3394
3395 // These are structs in the Objective-C meta data and read to produce the
3396 // comments for disassembly. While these are part of the ABI they are no
3397 // public defintions. So the are here not in include/llvm/BinaryFormat/MachO.h
3398 // .
3399
3400 // The cfstring object in a 64-bit Mach-O file.
3401 struct cfstring64_t {
3402 uint64_t isa; // class64_t * (64-bit pointer)
3403 uint64_t flags; // flag bits
3404 uint64_t characters; // char * (64-bit pointer)
3405 uint64_t length; // number of non-NULL characters in above
3406 };
3407
3408 // The class object in a 64-bit Mach-O file.
3409 struct class64_t {
3410 uint64_t isa; // class64_t * (64-bit pointer)
3411 uint64_t superclass; // class64_t * (64-bit pointer)
3412 uint64_t cache; // Cache (64-bit pointer)
3413 uint64_t vtable; // IMP * (64-bit pointer)
3414 uint64_t data; // class_ro64_t * (64-bit pointer)
3415 };
3416
3417 struct class32_t {
3418 uint32_t isa; /* class32_t * (32-bit pointer) */
3419 uint32_t superclass; /* class32_t * (32-bit pointer) */
3420 uint32_t cache; /* Cache (32-bit pointer) */
3421 uint32_t vtable; /* IMP * (32-bit pointer) */
3422 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3423 };
3424
3425 struct class_ro64_t {
3426 uint32_t flags;
3427 uint32_t instanceStart;
3428 uint32_t instanceSize;
3429 uint32_t reserved;
3430 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3431 uint64_t name; // const char * (64-bit pointer)
3432 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3433 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3434 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3435 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3436 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3437 };
3438
3439 struct class_ro32_t {
3440 uint32_t flags;
3441 uint32_t instanceStart;
3442 uint32_t instanceSize;
3443 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3444 uint32_t name; /* const char * (32-bit pointer) */
3445 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3446 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3447 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3448 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3449 uint32_t baseProperties; /* const struct objc_property_list *
3450 (32-bit pointer) */
3451 };
3452
3453 /* Values for class_ro{64,32}_t->flags */
3454 #define RO_META (1 << 0)
3455 #define RO_ROOT (1 << 1)
3456 #define RO_HAS_CXX_STRUCTORS (1 << 2)
3457
3458 struct method_list64_t {
3459 uint32_t entsize;
3460 uint32_t count;
3461 /* struct method64_t first; These structures follow inline */
3462 };
3463
3464 struct method_list32_t {
3465 uint32_t entsize;
3466 uint32_t count;
3467 /* struct method32_t first; These structures follow inline */
3468 };
3469
3470 struct method64_t {
3471 uint64_t name; /* SEL (64-bit pointer) */
3472 uint64_t types; /* const char * (64-bit pointer) */
3473 uint64_t imp; /* IMP (64-bit pointer) */
3474 };
3475
3476 struct method32_t {
3477 uint32_t name; /* SEL (32-bit pointer) */
3478 uint32_t types; /* const char * (32-bit pointer) */
3479 uint32_t imp; /* IMP (32-bit pointer) */
3480 };
3481
3482 struct protocol_list64_t {
3483 uint64_t count; /* uintptr_t (a 64-bit value) */
3484 /* struct protocol64_t * list[0]; These pointers follow inline */
3485 };
3486
3487 struct protocol_list32_t {
3488 uint32_t count; /* uintptr_t (a 32-bit value) */
3489 /* struct protocol32_t * list[0]; These pointers follow inline */
3490 };
3491
3492 struct protocol64_t {
3493 uint64_t isa; /* id * (64-bit pointer) */
3494 uint64_t name; /* const char * (64-bit pointer) */
3495 uint64_t protocols; /* struct protocol_list64_t *
3496 (64-bit pointer) */
3497 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3498 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3499 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3500 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3501 uint64_t instanceProperties; /* struct objc_property_list *
3502 (64-bit pointer) */
3503 };
3504
3505 struct protocol32_t {
3506 uint32_t isa; /* id * (32-bit pointer) */
3507 uint32_t name; /* const char * (32-bit pointer) */
3508 uint32_t protocols; /* struct protocol_list_t *
3509 (32-bit pointer) */
3510 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3511 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3512 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3513 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3514 uint32_t instanceProperties; /* struct objc_property_list *
3515 (32-bit pointer) */
3516 };
3517
3518 struct ivar_list64_t {
3519 uint32_t entsize;
3520 uint32_t count;
3521 /* struct ivar64_t first; These structures follow inline */
3522 };
3523
3524 struct ivar_list32_t {
3525 uint32_t entsize;
3526 uint32_t count;
3527 /* struct ivar32_t first; These structures follow inline */
3528 };
3529
3530 struct ivar64_t {
3531 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3532 uint64_t name; /* const char * (64-bit pointer) */
3533 uint64_t type; /* const char * (64-bit pointer) */
3534 uint32_t alignment;
3535 uint32_t size;
3536 };
3537
3538 struct ivar32_t {
3539 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3540 uint32_t name; /* const char * (32-bit pointer) */
3541 uint32_t type; /* const char * (32-bit pointer) */
3542 uint32_t alignment;
3543 uint32_t size;
3544 };
3545
3546 struct objc_property_list64 {
3547 uint32_t entsize;
3548 uint32_t count;
3549 /* struct objc_property64 first; These structures follow inline */
3550 };
3551
3552 struct objc_property_list32 {
3553 uint32_t entsize;
3554 uint32_t count;
3555 /* struct objc_property32 first; These structures follow inline */
3556 };
3557
3558 struct objc_property64 {
3559 uint64_t name; /* const char * (64-bit pointer) */
3560 uint64_t attributes; /* const char * (64-bit pointer) */
3561 };
3562
3563 struct objc_property32 {
3564 uint32_t name; /* const char * (32-bit pointer) */
3565 uint32_t attributes; /* const char * (32-bit pointer) */
3566 };
3567
3568 struct category64_t {
3569 uint64_t name; /* const char * (64-bit pointer) */
3570 uint64_t cls; /* struct class_t * (64-bit pointer) */
3571 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3572 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3573 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3574 uint64_t instanceProperties; /* struct objc_property_list *
3575 (64-bit pointer) */
3576 };
3577
3578 struct category32_t {
3579 uint32_t name; /* const char * (32-bit pointer) */
3580 uint32_t cls; /* struct class_t * (32-bit pointer) */
3581 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3582 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3583 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3584 uint32_t instanceProperties; /* struct objc_property_list *
3585 (32-bit pointer) */
3586 };
3587
3588 struct objc_image_info64 {
3589 uint32_t version;
3590 uint32_t flags;
3591 };
3592 struct objc_image_info32 {
3593 uint32_t version;
3594 uint32_t flags;
3595 };
3596 struct imageInfo_t {
3597 uint32_t version;
3598 uint32_t flags;
3599 };
3600 /* masks for objc_image_info.flags */
3601 #define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3602 #define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3603 #define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3604 #define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3605
3606 struct message_ref64 {
3607 uint64_t imp; /* IMP (64-bit pointer) */
3608 uint64_t sel; /* SEL (64-bit pointer) */
3609 };
3610
3611 struct message_ref32 {
3612 uint32_t imp; /* IMP (32-bit pointer) */
3613 uint32_t sel; /* SEL (32-bit pointer) */
3614 };
3615
3616 // Objective-C 1 (32-bit only) meta data structs.
3617
3618 struct objc_module_t {
3619 uint32_t version;
3620 uint32_t size;
3621 uint32_t name; /* char * (32-bit pointer) */
3622 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3623 };
3624
3625 struct objc_symtab_t {
3626 uint32_t sel_ref_cnt;
3627 uint32_t refs; /* SEL * (32-bit pointer) */
3628 uint16_t cls_def_cnt;
3629 uint16_t cat_def_cnt;
3630 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3631 };
3632
3633 struct objc_class_t {
3634 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3635 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3636 uint32_t name; /* const char * (32-bit pointer) */
3637 int32_t version;
3638 int32_t info;
3639 int32_t instance_size;
3640 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3641 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3642 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3643 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3644 };
3645
3646 #define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3647 // class is not a metaclass
3648 #define CLS_CLASS 0x1
3649 // class is a metaclass
3650 #define CLS_META 0x2
3651
3652 struct objc_category_t {
3653 uint32_t category_name; /* char * (32-bit pointer) */
3654 uint32_t class_name; /* char * (32-bit pointer) */
3655 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3656 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3657 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3658 };
3659
3660 struct objc_ivar_t {
3661 uint32_t ivar_name; /* char * (32-bit pointer) */
3662 uint32_t ivar_type; /* char * (32-bit pointer) */
3663 int32_t ivar_offset;
3664 };
3665
3666 struct objc_ivar_list_t {
3667 int32_t ivar_count;
3668 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3669 };
3670
3671 struct objc_method_list_t {
3672 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3673 int32_t method_count;
3674 // struct objc_method_t method_list[1]; /* variable length structure */
3675 };
3676
3677 struct objc_method_t {
3678 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3679 uint32_t method_types; /* char * (32-bit pointer) */
3680 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3681 (32-bit pointer) */
3682 };
3683
3684 struct objc_protocol_list_t {
3685 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3686 int32_t count;
3687 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3688 // (32-bit pointer) */
3689 };
3690
3691 struct objc_protocol_t {
3692 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3693 uint32_t protocol_name; /* char * (32-bit pointer) */
3694 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3695 uint32_t instance_methods; /* struct objc_method_description_list *
3696 (32-bit pointer) */
3697 uint32_t class_methods; /* struct objc_method_description_list *
3698 (32-bit pointer) */
3699 };
3700
3701 struct objc_method_description_list_t {
3702 int32_t count;
3703 // struct objc_method_description_t list[1];
3704 };
3705
3706 struct objc_method_description_t {
3707 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3708 uint32_t types; /* char * (32-bit pointer) */
3709 };
3710
swapStruct(struct cfstring64_t & cfs)3711 inline void swapStruct(struct cfstring64_t &cfs) {
3712 sys::swapByteOrder(cfs.isa);
3713 sys::swapByteOrder(cfs.flags);
3714 sys::swapByteOrder(cfs.characters);
3715 sys::swapByteOrder(cfs.length);
3716 }
3717
swapStruct(struct class64_t & c)3718 inline void swapStruct(struct class64_t &c) {
3719 sys::swapByteOrder(c.isa);
3720 sys::swapByteOrder(c.superclass);
3721 sys::swapByteOrder(c.cache);
3722 sys::swapByteOrder(c.vtable);
3723 sys::swapByteOrder(c.data);
3724 }
3725
swapStruct(struct class32_t & c)3726 inline void swapStruct(struct class32_t &c) {
3727 sys::swapByteOrder(c.isa);
3728 sys::swapByteOrder(c.superclass);
3729 sys::swapByteOrder(c.cache);
3730 sys::swapByteOrder(c.vtable);
3731 sys::swapByteOrder(c.data);
3732 }
3733
swapStruct(struct class_ro64_t & cro)3734 inline void swapStruct(struct class_ro64_t &cro) {
3735 sys::swapByteOrder(cro.flags);
3736 sys::swapByteOrder(cro.instanceStart);
3737 sys::swapByteOrder(cro.instanceSize);
3738 sys::swapByteOrder(cro.reserved);
3739 sys::swapByteOrder(cro.ivarLayout);
3740 sys::swapByteOrder(cro.name);
3741 sys::swapByteOrder(cro.baseMethods);
3742 sys::swapByteOrder(cro.baseProtocols);
3743 sys::swapByteOrder(cro.ivars);
3744 sys::swapByteOrder(cro.weakIvarLayout);
3745 sys::swapByteOrder(cro.baseProperties);
3746 }
3747
swapStruct(struct class_ro32_t & cro)3748 inline void swapStruct(struct class_ro32_t &cro) {
3749 sys::swapByteOrder(cro.flags);
3750 sys::swapByteOrder(cro.instanceStart);
3751 sys::swapByteOrder(cro.instanceSize);
3752 sys::swapByteOrder(cro.ivarLayout);
3753 sys::swapByteOrder(cro.name);
3754 sys::swapByteOrder(cro.baseMethods);
3755 sys::swapByteOrder(cro.baseProtocols);
3756 sys::swapByteOrder(cro.ivars);
3757 sys::swapByteOrder(cro.weakIvarLayout);
3758 sys::swapByteOrder(cro.baseProperties);
3759 }
3760
swapStruct(struct method_list64_t & ml)3761 inline void swapStruct(struct method_list64_t &ml) {
3762 sys::swapByteOrder(ml.entsize);
3763 sys::swapByteOrder(ml.count);
3764 }
3765
swapStruct(struct method_list32_t & ml)3766 inline void swapStruct(struct method_list32_t &ml) {
3767 sys::swapByteOrder(ml.entsize);
3768 sys::swapByteOrder(ml.count);
3769 }
3770
swapStruct(struct method64_t & m)3771 inline void swapStruct(struct method64_t &m) {
3772 sys::swapByteOrder(m.name);
3773 sys::swapByteOrder(m.types);
3774 sys::swapByteOrder(m.imp);
3775 }
3776
swapStruct(struct method32_t & m)3777 inline void swapStruct(struct method32_t &m) {
3778 sys::swapByteOrder(m.name);
3779 sys::swapByteOrder(m.types);
3780 sys::swapByteOrder(m.imp);
3781 }
3782
swapStruct(struct protocol_list64_t & pl)3783 inline void swapStruct(struct protocol_list64_t &pl) {
3784 sys::swapByteOrder(pl.count);
3785 }
3786
swapStruct(struct protocol_list32_t & pl)3787 inline void swapStruct(struct protocol_list32_t &pl) {
3788 sys::swapByteOrder(pl.count);
3789 }
3790
swapStruct(struct protocol64_t & p)3791 inline void swapStruct(struct protocol64_t &p) {
3792 sys::swapByteOrder(p.isa);
3793 sys::swapByteOrder(p.name);
3794 sys::swapByteOrder(p.protocols);
3795 sys::swapByteOrder(p.instanceMethods);
3796 sys::swapByteOrder(p.classMethods);
3797 sys::swapByteOrder(p.optionalInstanceMethods);
3798 sys::swapByteOrder(p.optionalClassMethods);
3799 sys::swapByteOrder(p.instanceProperties);
3800 }
3801
swapStruct(struct protocol32_t & p)3802 inline void swapStruct(struct protocol32_t &p) {
3803 sys::swapByteOrder(p.isa);
3804 sys::swapByteOrder(p.name);
3805 sys::swapByteOrder(p.protocols);
3806 sys::swapByteOrder(p.instanceMethods);
3807 sys::swapByteOrder(p.classMethods);
3808 sys::swapByteOrder(p.optionalInstanceMethods);
3809 sys::swapByteOrder(p.optionalClassMethods);
3810 sys::swapByteOrder(p.instanceProperties);
3811 }
3812
swapStruct(struct ivar_list64_t & il)3813 inline void swapStruct(struct ivar_list64_t &il) {
3814 sys::swapByteOrder(il.entsize);
3815 sys::swapByteOrder(il.count);
3816 }
3817
swapStruct(struct ivar_list32_t & il)3818 inline void swapStruct(struct ivar_list32_t &il) {
3819 sys::swapByteOrder(il.entsize);
3820 sys::swapByteOrder(il.count);
3821 }
3822
swapStruct(struct ivar64_t & i)3823 inline void swapStruct(struct ivar64_t &i) {
3824 sys::swapByteOrder(i.offset);
3825 sys::swapByteOrder(i.name);
3826 sys::swapByteOrder(i.type);
3827 sys::swapByteOrder(i.alignment);
3828 sys::swapByteOrder(i.size);
3829 }
3830
swapStruct(struct ivar32_t & i)3831 inline void swapStruct(struct ivar32_t &i) {
3832 sys::swapByteOrder(i.offset);
3833 sys::swapByteOrder(i.name);
3834 sys::swapByteOrder(i.type);
3835 sys::swapByteOrder(i.alignment);
3836 sys::swapByteOrder(i.size);
3837 }
3838
swapStruct(struct objc_property_list64 & pl)3839 inline void swapStruct(struct objc_property_list64 &pl) {
3840 sys::swapByteOrder(pl.entsize);
3841 sys::swapByteOrder(pl.count);
3842 }
3843
swapStruct(struct objc_property_list32 & pl)3844 inline void swapStruct(struct objc_property_list32 &pl) {
3845 sys::swapByteOrder(pl.entsize);
3846 sys::swapByteOrder(pl.count);
3847 }
3848
swapStruct(struct objc_property64 & op)3849 inline void swapStruct(struct objc_property64 &op) {
3850 sys::swapByteOrder(op.name);
3851 sys::swapByteOrder(op.attributes);
3852 }
3853
swapStruct(struct objc_property32 & op)3854 inline void swapStruct(struct objc_property32 &op) {
3855 sys::swapByteOrder(op.name);
3856 sys::swapByteOrder(op.attributes);
3857 }
3858
swapStruct(struct category64_t & c)3859 inline void swapStruct(struct category64_t &c) {
3860 sys::swapByteOrder(c.name);
3861 sys::swapByteOrder(c.cls);
3862 sys::swapByteOrder(c.instanceMethods);
3863 sys::swapByteOrder(c.classMethods);
3864 sys::swapByteOrder(c.protocols);
3865 sys::swapByteOrder(c.instanceProperties);
3866 }
3867
swapStruct(struct category32_t & c)3868 inline void swapStruct(struct category32_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
swapStruct(struct objc_image_info64 & o)3877 inline void swapStruct(struct objc_image_info64 &o) {
3878 sys::swapByteOrder(o.version);
3879 sys::swapByteOrder(o.flags);
3880 }
3881
swapStruct(struct objc_image_info32 & o)3882 inline void swapStruct(struct objc_image_info32 &o) {
3883 sys::swapByteOrder(o.version);
3884 sys::swapByteOrder(o.flags);
3885 }
3886
swapStruct(struct imageInfo_t & o)3887 inline void swapStruct(struct imageInfo_t &o) {
3888 sys::swapByteOrder(o.version);
3889 sys::swapByteOrder(o.flags);
3890 }
3891
swapStruct(struct message_ref64 & mr)3892 inline void swapStruct(struct message_ref64 &mr) {
3893 sys::swapByteOrder(mr.imp);
3894 sys::swapByteOrder(mr.sel);
3895 }
3896
swapStruct(struct message_ref32 & mr)3897 inline void swapStruct(struct message_ref32 &mr) {
3898 sys::swapByteOrder(mr.imp);
3899 sys::swapByteOrder(mr.sel);
3900 }
3901
swapStruct(struct objc_module_t & module)3902 inline void swapStruct(struct objc_module_t &module) {
3903 sys::swapByteOrder(module.version);
3904 sys::swapByteOrder(module.size);
3905 sys::swapByteOrder(module.name);
3906 sys::swapByteOrder(module.symtab);
3907 }
3908
swapStruct(struct objc_symtab_t & symtab)3909 inline void swapStruct(struct objc_symtab_t &symtab) {
3910 sys::swapByteOrder(symtab.sel_ref_cnt);
3911 sys::swapByteOrder(symtab.refs);
3912 sys::swapByteOrder(symtab.cls_def_cnt);
3913 sys::swapByteOrder(symtab.cat_def_cnt);
3914 }
3915
swapStruct(struct objc_class_t & objc_class)3916 inline void swapStruct(struct objc_class_t &objc_class) {
3917 sys::swapByteOrder(objc_class.isa);
3918 sys::swapByteOrder(objc_class.super_class);
3919 sys::swapByteOrder(objc_class.name);
3920 sys::swapByteOrder(objc_class.version);
3921 sys::swapByteOrder(objc_class.info);
3922 sys::swapByteOrder(objc_class.instance_size);
3923 sys::swapByteOrder(objc_class.ivars);
3924 sys::swapByteOrder(objc_class.methodLists);
3925 sys::swapByteOrder(objc_class.cache);
3926 sys::swapByteOrder(objc_class.protocols);
3927 }
3928
swapStruct(struct objc_category_t & objc_category)3929 inline void swapStruct(struct objc_category_t &objc_category) {
3930 sys::swapByteOrder(objc_category.category_name);
3931 sys::swapByteOrder(objc_category.class_name);
3932 sys::swapByteOrder(objc_category.instance_methods);
3933 sys::swapByteOrder(objc_category.class_methods);
3934 sys::swapByteOrder(objc_category.protocols);
3935 }
3936
swapStruct(struct objc_ivar_list_t & objc_ivar_list)3937 inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3938 sys::swapByteOrder(objc_ivar_list.ivar_count);
3939 }
3940
swapStruct(struct objc_ivar_t & objc_ivar)3941 inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3942 sys::swapByteOrder(objc_ivar.ivar_name);
3943 sys::swapByteOrder(objc_ivar.ivar_type);
3944 sys::swapByteOrder(objc_ivar.ivar_offset);
3945 }
3946
swapStruct(struct objc_method_list_t & method_list)3947 inline void swapStruct(struct objc_method_list_t &method_list) {
3948 sys::swapByteOrder(method_list.obsolete);
3949 sys::swapByteOrder(method_list.method_count);
3950 }
3951
swapStruct(struct objc_method_t & method)3952 inline void swapStruct(struct objc_method_t &method) {
3953 sys::swapByteOrder(method.method_name);
3954 sys::swapByteOrder(method.method_types);
3955 sys::swapByteOrder(method.method_imp);
3956 }
3957
swapStruct(struct objc_protocol_list_t & protocol_list)3958 inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3959 sys::swapByteOrder(protocol_list.next);
3960 sys::swapByteOrder(protocol_list.count);
3961 }
3962
swapStruct(struct objc_protocol_t & protocol)3963 inline void swapStruct(struct objc_protocol_t &protocol) {
3964 sys::swapByteOrder(protocol.isa);
3965 sys::swapByteOrder(protocol.protocol_name);
3966 sys::swapByteOrder(protocol.protocol_list);
3967 sys::swapByteOrder(protocol.instance_methods);
3968 sys::swapByteOrder(protocol.class_methods);
3969 }
3970
swapStruct(struct objc_method_description_list_t & mdl)3971 inline void swapStruct(struct objc_method_description_list_t &mdl) {
3972 sys::swapByteOrder(mdl.count);
3973 }
3974
swapStruct(struct objc_method_description_t & md)3975 inline void swapStruct(struct objc_method_description_t &md) {
3976 sys::swapByteOrder(md.name);
3977 sys::swapByteOrder(md.types);
3978 }
3979
3980 } // namespace
3981
3982 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3983 struct DisassembleInfo *info);
3984
3985 // get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3986 // to an Objective-C class and returns the class name. It is also passed the
3987 // address of the pointer, so when the pointer is zero as it can be in an .o
3988 // file, that is used to look for an external relocation entry with a symbol
3989 // name.
get_objc2_64bit_class_name(uint64_t pointer_value,uint64_t ReferenceValue,struct DisassembleInfo * info)3990 static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3991 uint64_t ReferenceValue,
3992 struct DisassembleInfo *info) {
3993 const char *r;
3994 uint32_t offset, left;
3995 SectionRef S;
3996
3997 // The pointer_value can be 0 in an object file and have a relocation
3998 // entry for the class symbol at the ReferenceValue (the address of the
3999 // pointer).
4000 if (pointer_value == 0) {
4001 r = get_pointer_64(ReferenceValue, offset, left, S, info);
4002 if (r == nullptr || left < sizeof(uint64_t))
4003 return nullptr;
4004 uint64_t n_value;
4005 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4006 if (symbol_name == nullptr)
4007 return nullptr;
4008 const char *class_name = strrchr(symbol_name, '$');
4009 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4010 return class_name + 2;
4011 else
4012 return nullptr;
4013 }
4014
4015 // The case were the pointer_value is non-zero and points to a class defined
4016 // in this Mach-O file.
4017 r = get_pointer_64(pointer_value, offset, left, S, info);
4018 if (r == nullptr || left < sizeof(struct class64_t))
4019 return nullptr;
4020 struct class64_t c;
4021 memcpy(&c, r, sizeof(struct class64_t));
4022 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4023 swapStruct(c);
4024 if (c.data == 0)
4025 return nullptr;
4026 r = get_pointer_64(c.data, offset, left, S, info);
4027 if (r == nullptr || left < sizeof(struct class_ro64_t))
4028 return nullptr;
4029 struct class_ro64_t cro;
4030 memcpy(&cro, r, sizeof(struct class_ro64_t));
4031 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4032 swapStruct(cro);
4033 if (cro.name == 0)
4034 return nullptr;
4035 const char *name = get_pointer_64(cro.name, offset, left, S, info);
4036 return name;
4037 }
4038
4039 // get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4040 // pointer to a cfstring and returns its name or nullptr.
get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,struct DisassembleInfo * info)4041 static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4042 struct DisassembleInfo *info) {
4043 const char *r, *name;
4044 uint32_t offset, left;
4045 SectionRef S;
4046 struct cfstring64_t cfs;
4047 uint64_t cfs_characters;
4048
4049 r = get_pointer_64(ReferenceValue, offset, left, S, info);
4050 if (r == nullptr || left < sizeof(struct cfstring64_t))
4051 return nullptr;
4052 memcpy(&cfs, r, sizeof(struct cfstring64_t));
4053 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4054 swapStruct(cfs);
4055 if (cfs.characters == 0) {
4056 uint64_t n_value;
4057 const char *symbol_name = get_symbol_64(
4058 offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4059 if (symbol_name == nullptr)
4060 return nullptr;
4061 cfs_characters = n_value;
4062 } else
4063 cfs_characters = cfs.characters;
4064 name = get_pointer_64(cfs_characters, offset, left, S, info);
4065
4066 return name;
4067 }
4068
4069 // get_objc2_64bit_selref() is used for disassembly and is passed a the address
4070 // of a pointer to an Objective-C selector reference when the pointer value is
4071 // zero as in a .o file and is likely to have a external relocation entry with
4072 // who's symbol's n_value is the real pointer to the selector name. If that is
4073 // the case the real pointer to the selector name is returned else 0 is
4074 // returned
get_objc2_64bit_selref(uint64_t ReferenceValue,struct DisassembleInfo * info)4075 static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4076 struct DisassembleInfo *info) {
4077 uint32_t offset, left;
4078 SectionRef S;
4079
4080 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
4081 if (r == nullptr || left < sizeof(uint64_t))
4082 return 0;
4083 uint64_t n_value;
4084 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
4085 if (symbol_name == nullptr)
4086 return 0;
4087 return n_value;
4088 }
4089
get_section(MachOObjectFile * O,const char * segname,const char * sectname)4090 static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4091 const char *sectname) {
4092 for (const SectionRef &Section : O->sections()) {
4093 StringRef SectName;
4094 Expected<StringRef> SecNameOrErr = Section.getName();
4095 if (SecNameOrErr)
4096 SectName = *SecNameOrErr;
4097 else
4098 consumeError(SecNameOrErr.takeError());
4099
4100 DataRefImpl Ref = Section.getRawDataRefImpl();
4101 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4102 if (SegName == segname && SectName == sectname)
4103 return Section;
4104 }
4105 return SectionRef();
4106 }
4107
4108 static void
walk_pointer_list_64(const char * listname,const SectionRef S,MachOObjectFile * O,struct DisassembleInfo * info,void (* func)(uint64_t,struct DisassembleInfo * info))4109 walk_pointer_list_64(const char *listname, const SectionRef S,
4110 MachOObjectFile *O, struct DisassembleInfo *info,
4111 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4112 if (S == SectionRef())
4113 return;
4114
4115 StringRef SectName;
4116 Expected<StringRef> SecNameOrErr = S.getName();
4117 if (SecNameOrErr)
4118 SectName = *SecNameOrErr;
4119 else
4120 consumeError(SecNameOrErr.takeError());
4121
4122 DataRefImpl Ref = S.getRawDataRefImpl();
4123 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4124 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4125
4126 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4127 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4128
4129 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4130 uint32_t left = S.getSize() - i;
4131 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4132 uint64_t p = 0;
4133 memcpy(&p, Contents + i, size);
4134 if (i + sizeof(uint64_t) > S.getSize())
4135 outs() << listname << " list pointer extends past end of (" << SegName
4136 << "," << SectName << ") section\n";
4137 outs() << format("%016" PRIx64, S.getAddress() + i) << " ";
4138
4139 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4140 sys::swapByteOrder(p);
4141
4142 uint64_t n_value = 0;
4143 const char *name = get_symbol_64(i, S, info, n_value, p);
4144 if (name == nullptr)
4145 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
4146
4147 if (n_value != 0) {
4148 outs() << format("0x%" PRIx64, n_value);
4149 if (p != 0)
4150 outs() << " + " << format("0x%" PRIx64, p);
4151 } else
4152 outs() << format("0x%" PRIx64, p);
4153 if (name != nullptr)
4154 outs() << " " << name;
4155 outs() << "\n";
4156
4157 p += n_value;
4158 if (func)
4159 func(p, info);
4160 }
4161 }
4162
4163 static void
walk_pointer_list_32(const char * listname,const SectionRef S,MachOObjectFile * O,struct DisassembleInfo * info,void (* func)(uint32_t,struct DisassembleInfo * info))4164 walk_pointer_list_32(const char *listname, const SectionRef S,
4165 MachOObjectFile *O, struct DisassembleInfo *info,
4166 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4167 if (S == SectionRef())
4168 return;
4169
4170 StringRef SectName = unwrapOrError(S.getName(), O->getFileName());
4171 DataRefImpl Ref = S.getRawDataRefImpl();
4172 StringRef SegName = O->getSectionFinalSegmentName(Ref);
4173 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4174
4175 StringRef BytesStr = unwrapOrError(S.getContents(), O->getFileName());
4176 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
4177
4178 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4179 uint32_t left = S.getSize() - i;
4180 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4181 uint32_t p = 0;
4182 memcpy(&p, Contents + i, size);
4183 if (i + sizeof(uint32_t) > S.getSize())
4184 outs() << listname << " list pointer extends past end of (" << SegName
4185 << "," << SectName << ") section\n";
4186 uint32_t Address = S.getAddress() + i;
4187 outs() << format("%08" PRIx32, Address) << " ";
4188
4189 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4190 sys::swapByteOrder(p);
4191 outs() << format("0x%" PRIx32, p);
4192
4193 const char *name = get_symbol_32(i, S, info, p);
4194 if (name != nullptr)
4195 outs() << " " << name;
4196 outs() << "\n";
4197
4198 if (func)
4199 func(p, info);
4200 }
4201 }
4202
print_layout_map(const char * layout_map,uint32_t left)4203 static void print_layout_map(const char *layout_map, uint32_t left) {
4204 if (layout_map == nullptr)
4205 return;
4206 outs() << " layout map: ";
4207 do {
4208 outs() << format("0x%02" PRIx32, (*layout_map) & 0xff) << " ";
4209 left--;
4210 layout_map++;
4211 } while (*layout_map != '\0' && left != 0);
4212 outs() << "\n";
4213 }
4214
print_layout_map64(uint64_t p,struct DisassembleInfo * info)4215 static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4216 uint32_t offset, left;
4217 SectionRef S;
4218 const char *layout_map;
4219
4220 if (p == 0)
4221 return;
4222 layout_map = get_pointer_64(p, offset, left, S, info);
4223 print_layout_map(layout_map, left);
4224 }
4225
print_layout_map32(uint32_t p,struct DisassembleInfo * info)4226 static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4227 uint32_t offset, left;
4228 SectionRef S;
4229 const char *layout_map;
4230
4231 if (p == 0)
4232 return;
4233 layout_map = get_pointer_32(p, offset, left, S, info);
4234 print_layout_map(layout_map, left);
4235 }
4236
print_method_list64_t(uint64_t p,struct DisassembleInfo * info,const char * indent)4237 static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4238 const char *indent) {
4239 struct method_list64_t ml;
4240 struct method64_t m;
4241 const char *r;
4242 uint32_t offset, xoffset, left, i;
4243 SectionRef S, xS;
4244 const char *name, *sym_name;
4245 uint64_t n_value;
4246
4247 r = get_pointer_64(p, offset, left, S, info);
4248 if (r == nullptr)
4249 return;
4250 memset(&ml, '\0', sizeof(struct method_list64_t));
4251 if (left < sizeof(struct method_list64_t)) {
4252 memcpy(&ml, r, left);
4253 outs() << " (method_list_t entends past the end of the section)\n";
4254 } else
4255 memcpy(&ml, r, sizeof(struct method_list64_t));
4256 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4257 swapStruct(ml);
4258 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4259 outs() << indent << "\t\t count " << ml.count << "\n";
4260
4261 p += sizeof(struct method_list64_t);
4262 offset += sizeof(struct method_list64_t);
4263 for (i = 0; i < ml.count; i++) {
4264 r = get_pointer_64(p, offset, left, S, info);
4265 if (r == nullptr)
4266 return;
4267 memset(&m, '\0', sizeof(struct method64_t));
4268 if (left < sizeof(struct method64_t)) {
4269 memcpy(&m, r, left);
4270 outs() << indent << " (method_t extends past the end of the section)\n";
4271 } else
4272 memcpy(&m, r, sizeof(struct method64_t));
4273 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4274 swapStruct(m);
4275
4276 outs() << indent << "\t\t name ";
4277 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name), S,
4278 info, n_value, m.name);
4279 if (n_value != 0) {
4280 if (info->verbose && sym_name != nullptr)
4281 outs() << sym_name;
4282 else
4283 outs() << format("0x%" PRIx64, n_value);
4284 if (m.name != 0)
4285 outs() << " + " << format("0x%" PRIx64, m.name);
4286 } else
4287 outs() << format("0x%" PRIx64, m.name);
4288 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
4289 if (name != nullptr)
4290 outs() << format(" %.*s", left, name);
4291 outs() << "\n";
4292
4293 outs() << indent << "\t\t types ";
4294 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types), S,
4295 info, n_value, m.types);
4296 if (n_value != 0) {
4297 if (info->verbose && sym_name != nullptr)
4298 outs() << sym_name;
4299 else
4300 outs() << format("0x%" PRIx64, n_value);
4301 if (m.types != 0)
4302 outs() << " + " << format("0x%" PRIx64, m.types);
4303 } else
4304 outs() << format("0x%" PRIx64, m.types);
4305 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
4306 if (name != nullptr)
4307 outs() << format(" %.*s", left, name);
4308 outs() << "\n";
4309
4310 outs() << indent << "\t\t imp ";
4311 name = get_symbol_64(offset + offsetof(struct method64_t, imp), S, info,
4312 n_value, m.imp);
4313 if (info->verbose && name == nullptr) {
4314 if (n_value != 0) {
4315 outs() << format("0x%" PRIx64, n_value) << " ";
4316 if (m.imp != 0)
4317 outs() << "+ " << format("0x%" PRIx64, m.imp) << " ";
4318 } else
4319 outs() << format("0x%" PRIx64, m.imp) << " ";
4320 }
4321 if (name != nullptr)
4322 outs() << name;
4323 outs() << "\n";
4324
4325 p += sizeof(struct method64_t);
4326 offset += sizeof(struct method64_t);
4327 }
4328 }
4329
print_method_list32_t(uint64_t p,struct DisassembleInfo * info,const char * indent)4330 static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4331 const char *indent) {
4332 struct method_list32_t ml;
4333 struct method32_t m;
4334 const char *r, *name;
4335 uint32_t offset, xoffset, left, i;
4336 SectionRef S, xS;
4337
4338 r = get_pointer_32(p, offset, left, S, info);
4339 if (r == nullptr)
4340 return;
4341 memset(&ml, '\0', sizeof(struct method_list32_t));
4342 if (left < sizeof(struct method_list32_t)) {
4343 memcpy(&ml, r, left);
4344 outs() << " (method_list_t entends past the end of the section)\n";
4345 } else
4346 memcpy(&ml, r, sizeof(struct method_list32_t));
4347 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4348 swapStruct(ml);
4349 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4350 outs() << indent << "\t\t count " << ml.count << "\n";
4351
4352 p += sizeof(struct method_list32_t);
4353 offset += sizeof(struct method_list32_t);
4354 for (i = 0; i < ml.count; i++) {
4355 r = get_pointer_32(p, offset, left, S, info);
4356 if (r == nullptr)
4357 return;
4358 memset(&m, '\0', sizeof(struct method32_t));
4359 if (left < sizeof(struct method32_t)) {
4360 memcpy(&ml, r, left);
4361 outs() << indent << " (method_t entends past the end of the section)\n";
4362 } else
4363 memcpy(&m, r, sizeof(struct method32_t));
4364 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4365 swapStruct(m);
4366
4367 outs() << indent << "\t\t name " << format("0x%" PRIx32, m.name);
4368 name = get_pointer_32(m.name, xoffset, left, xS, info);
4369 if (name != nullptr)
4370 outs() << format(" %.*s", left, name);
4371 outs() << "\n";
4372
4373 outs() << indent << "\t\t types " << format("0x%" PRIx32, m.types);
4374 name = get_pointer_32(m.types, xoffset, left, xS, info);
4375 if (name != nullptr)
4376 outs() << format(" %.*s", left, name);
4377 outs() << "\n";
4378
4379 outs() << indent << "\t\t imp " << format("0x%" PRIx32, m.imp);
4380 name = get_symbol_32(offset + offsetof(struct method32_t, imp), S, info,
4381 m.imp);
4382 if (name != nullptr)
4383 outs() << " " << name;
4384 outs() << "\n";
4385
4386 p += sizeof(struct method32_t);
4387 offset += sizeof(struct method32_t);
4388 }
4389 }
4390
print_method_list(uint32_t p,struct DisassembleInfo * info)4391 static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4392 uint32_t offset, left, xleft;
4393 SectionRef S;
4394 struct objc_method_list_t method_list;
4395 struct objc_method_t method;
4396 const char *r, *methods, *name, *SymbolName;
4397 int32_t i;
4398
4399 r = get_pointer_32(p, offset, left, S, info, true);
4400 if (r == nullptr)
4401 return true;
4402
4403 outs() << "\n";
4404 if (left > sizeof(struct objc_method_list_t)) {
4405 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
4406 } else {
4407 outs() << "\t\t objc_method_list extends past end of the section\n";
4408 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
4409 memcpy(&method_list, r, left);
4410 }
4411 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4412 swapStruct(method_list);
4413
4414 outs() << "\t\t obsolete "
4415 << format("0x%08" PRIx32, method_list.obsolete) << "\n";
4416 outs() << "\t\t method_count " << method_list.method_count << "\n";
4417
4418 methods = r + sizeof(struct objc_method_list_t);
4419 for (i = 0; i < method_list.method_count; i++) {
4420 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4421 outs() << "\t\t remaining method's extend past the of the section\n";
4422 break;
4423 }
4424 memcpy(&method, methods + i * sizeof(struct objc_method_t),
4425 sizeof(struct objc_method_t));
4426 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4427 swapStruct(method);
4428
4429 outs() << "\t\t method_name "
4430 << format("0x%08" PRIx32, method.method_name);
4431 if (info->verbose) {
4432 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
4433 if (name != nullptr)
4434 outs() << format(" %.*s", xleft, name);
4435 else
4436 outs() << " (not in an __OBJC section)";
4437 }
4438 outs() << "\n";
4439
4440 outs() << "\t\t method_types "
4441 << format("0x%08" PRIx32, method.method_types);
4442 if (info->verbose) {
4443 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
4444 if (name != nullptr)
4445 outs() << format(" %.*s", xleft, name);
4446 else
4447 outs() << " (not in an __OBJC section)";
4448 }
4449 outs() << "\n";
4450
4451 outs() << "\t\t method_imp "
4452 << format("0x%08" PRIx32, method.method_imp) << " ";
4453 if (info->verbose) {
4454 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
4455 if (SymbolName != nullptr)
4456 outs() << SymbolName;
4457 }
4458 outs() << "\n";
4459 }
4460 return false;
4461 }
4462
print_protocol_list64_t(uint64_t p,struct DisassembleInfo * info)4463 static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4464 struct protocol_list64_t pl;
4465 uint64_t q, n_value;
4466 struct protocol64_t pc;
4467 const char *r;
4468 uint32_t offset, xoffset, left, i;
4469 SectionRef S, xS;
4470 const char *name, *sym_name;
4471
4472 r = get_pointer_64(p, offset, left, S, info);
4473 if (r == nullptr)
4474 return;
4475 memset(&pl, '\0', sizeof(struct protocol_list64_t));
4476 if (left < sizeof(struct protocol_list64_t)) {
4477 memcpy(&pl, r, left);
4478 outs() << " (protocol_list_t entends past the end of the section)\n";
4479 } else
4480 memcpy(&pl, r, sizeof(struct protocol_list64_t));
4481 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4482 swapStruct(pl);
4483 outs() << " count " << pl.count << "\n";
4484
4485 p += sizeof(struct protocol_list64_t);
4486 offset += sizeof(struct protocol_list64_t);
4487 for (i = 0; i < pl.count; i++) {
4488 r = get_pointer_64(p, offset, left, S, info);
4489 if (r == nullptr)
4490 return;
4491 q = 0;
4492 if (left < sizeof(uint64_t)) {
4493 memcpy(&q, r, left);
4494 outs() << " (protocol_t * entends past the end of the section)\n";
4495 } else
4496 memcpy(&q, r, sizeof(uint64_t));
4497 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4498 sys::swapByteOrder(q);
4499
4500 outs() << "\t\t list[" << i << "] ";
4501 sym_name = get_symbol_64(offset, S, info, n_value, q);
4502 if (n_value != 0) {
4503 if (info->verbose && sym_name != nullptr)
4504 outs() << sym_name;
4505 else
4506 outs() << format("0x%" PRIx64, n_value);
4507 if (q != 0)
4508 outs() << " + " << format("0x%" PRIx64, q);
4509 } else
4510 outs() << format("0x%" PRIx64, q);
4511 outs() << " (struct protocol_t *)\n";
4512
4513 r = get_pointer_64(q + n_value, offset, left, S, info);
4514 if (r == nullptr)
4515 return;
4516 memset(&pc, '\0', sizeof(struct protocol64_t));
4517 if (left < sizeof(struct protocol64_t)) {
4518 memcpy(&pc, r, left);
4519 outs() << " (protocol_t entends past the end of the section)\n";
4520 } else
4521 memcpy(&pc, r, sizeof(struct protocol64_t));
4522 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4523 swapStruct(pc);
4524
4525 outs() << "\t\t\t isa " << format("0x%" PRIx64, pc.isa) << "\n";
4526
4527 outs() << "\t\t\t name ";
4528 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name), S,
4529 info, n_value, pc.name);
4530 if (n_value != 0) {
4531 if (info->verbose && sym_name != nullptr)
4532 outs() << sym_name;
4533 else
4534 outs() << format("0x%" PRIx64, n_value);
4535 if (pc.name != 0)
4536 outs() << " + " << format("0x%" PRIx64, pc.name);
4537 } else
4538 outs() << format("0x%" PRIx64, pc.name);
4539 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
4540 if (name != nullptr)
4541 outs() << format(" %.*s", left, name);
4542 outs() << "\n";
4543
4544 outs() << "\t\t\tprotocols " << format("0x%" PRIx64, pc.protocols) << "\n";
4545
4546 outs() << "\t\t instanceMethods ";
4547 sym_name =
4548 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods),
4549 S, info, n_value, pc.instanceMethods);
4550 if (n_value != 0) {
4551 if (info->verbose && sym_name != nullptr)
4552 outs() << sym_name;
4553 else
4554 outs() << format("0x%" PRIx64, n_value);
4555 if (pc.instanceMethods != 0)
4556 outs() << " + " << format("0x%" PRIx64, pc.instanceMethods);
4557 } else
4558 outs() << format("0x%" PRIx64, pc.instanceMethods);
4559 outs() << " (struct method_list_t *)\n";
4560 if (pc.instanceMethods + n_value != 0)
4561 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
4562
4563 outs() << "\t\t classMethods ";
4564 sym_name =
4565 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods), S,
4566 info, n_value, pc.classMethods);
4567 if (n_value != 0) {
4568 if (info->verbose && sym_name != nullptr)
4569 outs() << sym_name;
4570 else
4571 outs() << format("0x%" PRIx64, n_value);
4572 if (pc.classMethods != 0)
4573 outs() << " + " << format("0x%" PRIx64, pc.classMethods);
4574 } else
4575 outs() << format("0x%" PRIx64, pc.classMethods);
4576 outs() << " (struct method_list_t *)\n";
4577 if (pc.classMethods + n_value != 0)
4578 print_method_list64_t(pc.classMethods + n_value, info, "\t");
4579
4580 outs() << "\t optionalInstanceMethods "
4581 << format("0x%" PRIx64, pc.optionalInstanceMethods) << "\n";
4582 outs() << "\t optionalClassMethods "
4583 << format("0x%" PRIx64, pc.optionalClassMethods) << "\n";
4584 outs() << "\t instanceProperties "
4585 << format("0x%" PRIx64, pc.instanceProperties) << "\n";
4586
4587 p += sizeof(uint64_t);
4588 offset += sizeof(uint64_t);
4589 }
4590 }
4591
print_protocol_list32_t(uint32_t p,struct DisassembleInfo * info)4592 static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4593 struct protocol_list32_t pl;
4594 uint32_t q;
4595 struct protocol32_t pc;
4596 const char *r;
4597 uint32_t offset, xoffset, left, i;
4598 SectionRef S, xS;
4599 const char *name;
4600
4601 r = get_pointer_32(p, offset, left, S, info);
4602 if (r == nullptr)
4603 return;
4604 memset(&pl, '\0', sizeof(struct protocol_list32_t));
4605 if (left < sizeof(struct protocol_list32_t)) {
4606 memcpy(&pl, r, left);
4607 outs() << " (protocol_list_t entends past the end of the section)\n";
4608 } else
4609 memcpy(&pl, r, sizeof(struct protocol_list32_t));
4610 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4611 swapStruct(pl);
4612 outs() << " count " << pl.count << "\n";
4613
4614 p += sizeof(struct protocol_list32_t);
4615 offset += sizeof(struct protocol_list32_t);
4616 for (i = 0; i < pl.count; i++) {
4617 r = get_pointer_32(p, offset, left, S, info);
4618 if (r == nullptr)
4619 return;
4620 q = 0;
4621 if (left < sizeof(uint32_t)) {
4622 memcpy(&q, r, left);
4623 outs() << " (protocol_t * entends past the end of the section)\n";
4624 } else
4625 memcpy(&q, r, sizeof(uint32_t));
4626 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4627 sys::swapByteOrder(q);
4628 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32, q)
4629 << " (struct protocol_t *)\n";
4630 r = get_pointer_32(q, offset, left, S, info);
4631 if (r == nullptr)
4632 return;
4633 memset(&pc, '\0', sizeof(struct protocol32_t));
4634 if (left < sizeof(struct protocol32_t)) {
4635 memcpy(&pc, r, left);
4636 outs() << " (protocol_t entends past the end of the section)\n";
4637 } else
4638 memcpy(&pc, r, sizeof(struct protocol32_t));
4639 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4640 swapStruct(pc);
4641 outs() << "\t\t\t isa " << format("0x%" PRIx32, pc.isa) << "\n";
4642 outs() << "\t\t\t name " << format("0x%" PRIx32, pc.name);
4643 name = get_pointer_32(pc.name, xoffset, left, xS, info);
4644 if (name != nullptr)
4645 outs() << format(" %.*s", left, name);
4646 outs() << "\n";
4647 outs() << "\t\t\tprotocols " << format("0x%" PRIx32, pc.protocols) << "\n";
4648 outs() << "\t\t instanceMethods "
4649 << format("0x%" PRIx32, pc.instanceMethods)
4650 << " (struct method_list_t *)\n";
4651 if (pc.instanceMethods != 0)
4652 print_method_list32_t(pc.instanceMethods, info, "\t");
4653 outs() << "\t\t classMethods " << format("0x%" PRIx32, pc.classMethods)
4654 << " (struct method_list_t *)\n";
4655 if (pc.classMethods != 0)
4656 print_method_list32_t(pc.classMethods, info, "\t");
4657 outs() << "\t optionalInstanceMethods "
4658 << format("0x%" PRIx32, pc.optionalInstanceMethods) << "\n";
4659 outs() << "\t optionalClassMethods "
4660 << format("0x%" PRIx32, pc.optionalClassMethods) << "\n";
4661 outs() << "\t instanceProperties "
4662 << format("0x%" PRIx32, pc.instanceProperties) << "\n";
4663 p += sizeof(uint32_t);
4664 offset += sizeof(uint32_t);
4665 }
4666 }
4667
print_indent(uint32_t indent)4668 static void print_indent(uint32_t indent) {
4669 for (uint32_t i = 0; i < indent;) {
4670 if (indent - i >= 8) {
4671 outs() << "\t";
4672 i += 8;
4673 } else {
4674 for (uint32_t j = i; j < indent; j++)
4675 outs() << " ";
4676 return;
4677 }
4678 }
4679 }
4680
print_method_description_list(uint32_t p,uint32_t indent,struct DisassembleInfo * info)4681 static bool print_method_description_list(uint32_t p, uint32_t indent,
4682 struct DisassembleInfo *info) {
4683 uint32_t offset, left, xleft;
4684 SectionRef S;
4685 struct objc_method_description_list_t mdl;
4686 struct objc_method_description_t md;
4687 const char *r, *list, *name;
4688 int32_t i;
4689
4690 r = get_pointer_32(p, offset, left, S, info, true);
4691 if (r == nullptr)
4692 return true;
4693
4694 outs() << "\n";
4695 if (left > sizeof(struct objc_method_description_list_t)) {
4696 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
4697 } else {
4698 print_indent(indent);
4699 outs() << " objc_method_description_list extends past end of the section\n";
4700 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
4701 memcpy(&mdl, r, left);
4702 }
4703 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4704 swapStruct(mdl);
4705
4706 print_indent(indent);
4707 outs() << " count " << mdl.count << "\n";
4708
4709 list = r + sizeof(struct objc_method_description_list_t);
4710 for (i = 0; i < mdl.count; i++) {
4711 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
4712 print_indent(indent);
4713 outs() << " remaining list entries extend past the of the section\n";
4714 break;
4715 }
4716 print_indent(indent);
4717 outs() << " list[" << i << "]\n";
4718 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
4719 sizeof(struct objc_method_description_t));
4720 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4721 swapStruct(md);
4722
4723 print_indent(indent);
4724 outs() << " name " << format("0x%08" PRIx32, md.name);
4725 if (info->verbose) {
4726 name = get_pointer_32(md.name, offset, xleft, S, info, true);
4727 if (name != nullptr)
4728 outs() << format(" %.*s", xleft, name);
4729 else
4730 outs() << " (not in an __OBJC section)";
4731 }
4732 outs() << "\n";
4733
4734 print_indent(indent);
4735 outs() << " types " << format("0x%08" PRIx32, md.types);
4736 if (info->verbose) {
4737 name = get_pointer_32(md.types, offset, xleft, S, info, true);
4738 if (name != nullptr)
4739 outs() << format(" %.*s", xleft, name);
4740 else
4741 outs() << " (not in an __OBJC section)";
4742 }
4743 outs() << "\n";
4744 }
4745 return false;
4746 }
4747
4748 static bool print_protocol_list(uint32_t p, uint32_t indent,
4749 struct DisassembleInfo *info);
4750
print_protocol(uint32_t p,uint32_t indent,struct DisassembleInfo * info)4751 static bool print_protocol(uint32_t p, uint32_t indent,
4752 struct DisassembleInfo *info) {
4753 uint32_t offset, left;
4754 SectionRef S;
4755 struct objc_protocol_t protocol;
4756 const char *r, *name;
4757
4758 r = get_pointer_32(p, offset, left, S, info, true);
4759 if (r == nullptr)
4760 return true;
4761
4762 outs() << "\n";
4763 if (left >= sizeof(struct objc_protocol_t)) {
4764 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4765 } else {
4766 print_indent(indent);
4767 outs() << " Protocol extends past end of the section\n";
4768 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4769 memcpy(&protocol, r, left);
4770 }
4771 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4772 swapStruct(protocol);
4773
4774 print_indent(indent);
4775 outs() << " isa " << format("0x%08" PRIx32, protocol.isa)
4776 << "\n";
4777
4778 print_indent(indent);
4779 outs() << " protocol_name "
4780 << format("0x%08" PRIx32, protocol.protocol_name);
4781 if (info->verbose) {
4782 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4783 if (name != nullptr)
4784 outs() << format(" %.*s", left, name);
4785 else
4786 outs() << " (not in an __OBJC section)";
4787 }
4788 outs() << "\n";
4789
4790 print_indent(indent);
4791 outs() << " protocol_list "
4792 << format("0x%08" PRIx32, protocol.protocol_list);
4793 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4794 outs() << " (not in an __OBJC section)\n";
4795
4796 print_indent(indent);
4797 outs() << " instance_methods "
4798 << format("0x%08" PRIx32, protocol.instance_methods);
4799 if (print_method_description_list(protocol.instance_methods, indent, info))
4800 outs() << " (not in an __OBJC section)\n";
4801
4802 print_indent(indent);
4803 outs() << " class_methods "
4804 << format("0x%08" PRIx32, protocol.class_methods);
4805 if (print_method_description_list(protocol.class_methods, indent, info))
4806 outs() << " (not in an __OBJC section)\n";
4807
4808 return false;
4809 }
4810
print_protocol_list(uint32_t p,uint32_t indent,struct DisassembleInfo * info)4811 static bool print_protocol_list(uint32_t p, uint32_t indent,
4812 struct DisassembleInfo *info) {
4813 uint32_t offset, left, l;
4814 SectionRef S;
4815 struct objc_protocol_list_t protocol_list;
4816 const char *r, *list;
4817 int32_t i;
4818
4819 r = get_pointer_32(p, offset, left, S, info, true);
4820 if (r == nullptr)
4821 return true;
4822
4823 outs() << "\n";
4824 if (left > sizeof(struct objc_protocol_list_t)) {
4825 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4826 } else {
4827 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4828 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4829 memcpy(&protocol_list, r, left);
4830 }
4831 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4832 swapStruct(protocol_list);
4833
4834 print_indent(indent);
4835 outs() << " next " << format("0x%08" PRIx32, protocol_list.next)
4836 << "\n";
4837 print_indent(indent);
4838 outs() << " count " << protocol_list.count << "\n";
4839
4840 list = r + sizeof(struct objc_protocol_list_t);
4841 for (i = 0; i < protocol_list.count; i++) {
4842 if ((i + 1) * sizeof(uint32_t) > left) {
4843 outs() << "\t\t remaining list entries extend past the of the section\n";
4844 break;
4845 }
4846 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4847 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4848 sys::swapByteOrder(l);
4849
4850 print_indent(indent);
4851 outs() << " list[" << i << "] " << format("0x%08" PRIx32, l);
4852 if (print_protocol(l, indent, info))
4853 outs() << "(not in an __OBJC section)\n";
4854 }
4855 return false;
4856 }
4857
print_ivar_list64_t(uint64_t p,struct DisassembleInfo * info)4858 static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4859 struct ivar_list64_t il;
4860 struct ivar64_t i;
4861 const char *r;
4862 uint32_t offset, xoffset, left, j;
4863 SectionRef S, xS;
4864 const char *name, *sym_name, *ivar_offset_p;
4865 uint64_t ivar_offset, n_value;
4866
4867 r = get_pointer_64(p, offset, left, S, info);
4868 if (r == nullptr)
4869 return;
4870 memset(&il, '\0', sizeof(struct ivar_list64_t));
4871 if (left < sizeof(struct ivar_list64_t)) {
4872 memcpy(&il, r, left);
4873 outs() << " (ivar_list_t entends past the end of the section)\n";
4874 } else
4875 memcpy(&il, r, sizeof(struct ivar_list64_t));
4876 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4877 swapStruct(il);
4878 outs() << " entsize " << il.entsize << "\n";
4879 outs() << " count " << il.count << "\n";
4880
4881 p += sizeof(struct ivar_list64_t);
4882 offset += sizeof(struct ivar_list64_t);
4883 for (j = 0; j < il.count; j++) {
4884 r = get_pointer_64(p, offset, left, S, info);
4885 if (r == nullptr)
4886 return;
4887 memset(&i, '\0', sizeof(struct ivar64_t));
4888 if (left < sizeof(struct ivar64_t)) {
4889 memcpy(&i, r, left);
4890 outs() << " (ivar_t entends past the end of the section)\n";
4891 } else
4892 memcpy(&i, r, sizeof(struct ivar64_t));
4893 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4894 swapStruct(i);
4895
4896 outs() << "\t\t\t offset ";
4897 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset), S,
4898 info, n_value, i.offset);
4899 if (n_value != 0) {
4900 if (info->verbose && sym_name != nullptr)
4901 outs() << sym_name;
4902 else
4903 outs() << format("0x%" PRIx64, n_value);
4904 if (i.offset != 0)
4905 outs() << " + " << format("0x%" PRIx64, i.offset);
4906 } else
4907 outs() << format("0x%" PRIx64, i.offset);
4908 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4909 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4910 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4911 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4912 sys::swapByteOrder(ivar_offset);
4913 outs() << " " << ivar_offset << "\n";
4914 } else
4915 outs() << "\n";
4916
4917 outs() << "\t\t\t name ";
4918 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name), S, info,
4919 n_value, i.name);
4920 if (n_value != 0) {
4921 if (info->verbose && sym_name != nullptr)
4922 outs() << sym_name;
4923 else
4924 outs() << format("0x%" PRIx64, n_value);
4925 if (i.name != 0)
4926 outs() << " + " << format("0x%" PRIx64, i.name);
4927 } else
4928 outs() << format("0x%" PRIx64, i.name);
4929 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4930 if (name != nullptr)
4931 outs() << format(" %.*s", left, name);
4932 outs() << "\n";
4933
4934 outs() << "\t\t\t type ";
4935 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type), S, info,
4936 n_value, i.name);
4937 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4938 if (n_value != 0) {
4939 if (info->verbose && sym_name != nullptr)
4940 outs() << sym_name;
4941 else
4942 outs() << format("0x%" PRIx64, n_value);
4943 if (i.type != 0)
4944 outs() << " + " << format("0x%" PRIx64, i.type);
4945 } else
4946 outs() << format("0x%" PRIx64, i.type);
4947 if (name != nullptr)
4948 outs() << format(" %.*s", left, name);
4949 outs() << "\n";
4950
4951 outs() << "\t\t\talignment " << i.alignment << "\n";
4952 outs() << "\t\t\t size " << i.size << "\n";
4953
4954 p += sizeof(struct ivar64_t);
4955 offset += sizeof(struct ivar64_t);
4956 }
4957 }
4958
print_ivar_list32_t(uint32_t p,struct DisassembleInfo * info)4959 static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4960 struct ivar_list32_t il;
4961 struct ivar32_t i;
4962 const char *r;
4963 uint32_t offset, xoffset, left, j;
4964 SectionRef S, xS;
4965 const char *name, *ivar_offset_p;
4966 uint32_t ivar_offset;
4967
4968 r = get_pointer_32(p, offset, left, S, info);
4969 if (r == nullptr)
4970 return;
4971 memset(&il, '\0', sizeof(struct ivar_list32_t));
4972 if (left < sizeof(struct ivar_list32_t)) {
4973 memcpy(&il, r, left);
4974 outs() << " (ivar_list_t entends past the end of the section)\n";
4975 } else
4976 memcpy(&il, r, sizeof(struct ivar_list32_t));
4977 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4978 swapStruct(il);
4979 outs() << " entsize " << il.entsize << "\n";
4980 outs() << " count " << il.count << "\n";
4981
4982 p += sizeof(struct ivar_list32_t);
4983 offset += sizeof(struct ivar_list32_t);
4984 for (j = 0; j < il.count; j++) {
4985 r = get_pointer_32(p, offset, left, S, info);
4986 if (r == nullptr)
4987 return;
4988 memset(&i, '\0', sizeof(struct ivar32_t));
4989 if (left < sizeof(struct ivar32_t)) {
4990 memcpy(&i, r, left);
4991 outs() << " (ivar_t entends past the end of the section)\n";
4992 } else
4993 memcpy(&i, r, sizeof(struct ivar32_t));
4994 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4995 swapStruct(i);
4996
4997 outs() << "\t\t\t offset " << format("0x%" PRIx32, i.offset);
4998 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4999 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5000 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
5001 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5002 sys::swapByteOrder(ivar_offset);
5003 outs() << " " << ivar_offset << "\n";
5004 } else
5005 outs() << "\n";
5006
5007 outs() << "\t\t\t name " << format("0x%" PRIx32, i.name);
5008 name = get_pointer_32(i.name, xoffset, left, xS, info);
5009 if (name != nullptr)
5010 outs() << format(" %.*s", left, name);
5011 outs() << "\n";
5012
5013 outs() << "\t\t\t type " << format("0x%" PRIx32, i.type);
5014 name = get_pointer_32(i.type, xoffset, left, xS, info);
5015 if (name != nullptr)
5016 outs() << format(" %.*s", left, name);
5017 outs() << "\n";
5018
5019 outs() << "\t\t\talignment " << i.alignment << "\n";
5020 outs() << "\t\t\t size " << i.size << "\n";
5021
5022 p += sizeof(struct ivar32_t);
5023 offset += sizeof(struct ivar32_t);
5024 }
5025 }
5026
print_objc_property_list64(uint64_t p,struct DisassembleInfo * info)5027 static void print_objc_property_list64(uint64_t p,
5028 struct DisassembleInfo *info) {
5029 struct objc_property_list64 opl;
5030 struct objc_property64 op;
5031 const char *r;
5032 uint32_t offset, xoffset, left, j;
5033 SectionRef S, xS;
5034 const char *name, *sym_name;
5035 uint64_t n_value;
5036
5037 r = get_pointer_64(p, offset, left, S, info);
5038 if (r == nullptr)
5039 return;
5040 memset(&opl, '\0', sizeof(struct objc_property_list64));
5041 if (left < sizeof(struct objc_property_list64)) {
5042 memcpy(&opl, r, left);
5043 outs() << " (objc_property_list entends past the end of the section)\n";
5044 } else
5045 memcpy(&opl, r, sizeof(struct objc_property_list64));
5046 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5047 swapStruct(opl);
5048 outs() << " entsize " << opl.entsize << "\n";
5049 outs() << " count " << opl.count << "\n";
5050
5051 p += sizeof(struct objc_property_list64);
5052 offset += sizeof(struct objc_property_list64);
5053 for (j = 0; j < opl.count; j++) {
5054 r = get_pointer_64(p, offset, left, S, info);
5055 if (r == nullptr)
5056 return;
5057 memset(&op, '\0', sizeof(struct objc_property64));
5058 if (left < sizeof(struct objc_property64)) {
5059 memcpy(&op, r, left);
5060 outs() << " (objc_property entends past the end of the section)\n";
5061 } else
5062 memcpy(&op, r, sizeof(struct objc_property64));
5063 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5064 swapStruct(op);
5065
5066 outs() << "\t\t\t name ";
5067 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name), S,
5068 info, n_value, op.name);
5069 if (n_value != 0) {
5070 if (info->verbose && sym_name != nullptr)
5071 outs() << sym_name;
5072 else
5073 outs() << format("0x%" PRIx64, n_value);
5074 if (op.name != 0)
5075 outs() << " + " << format("0x%" PRIx64, op.name);
5076 } else
5077 outs() << format("0x%" PRIx64, op.name);
5078 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
5079 if (name != nullptr)
5080 outs() << format(" %.*s", left, name);
5081 outs() << "\n";
5082
5083 outs() << "\t\t\tattributes ";
5084 sym_name =
5085 get_symbol_64(offset + offsetof(struct objc_property64, attributes), S,
5086 info, n_value, op.attributes);
5087 if (n_value != 0) {
5088 if (info->verbose && sym_name != nullptr)
5089 outs() << sym_name;
5090 else
5091 outs() << format("0x%" PRIx64, n_value);
5092 if (op.attributes != 0)
5093 outs() << " + " << format("0x%" PRIx64, op.attributes);
5094 } else
5095 outs() << format("0x%" PRIx64, op.attributes);
5096 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
5097 if (name != nullptr)
5098 outs() << format(" %.*s", left, name);
5099 outs() << "\n";
5100
5101 p += sizeof(struct objc_property64);
5102 offset += sizeof(struct objc_property64);
5103 }
5104 }
5105
print_objc_property_list32(uint32_t p,struct DisassembleInfo * info)5106 static void print_objc_property_list32(uint32_t p,
5107 struct DisassembleInfo *info) {
5108 struct objc_property_list32 opl;
5109 struct objc_property32 op;
5110 const char *r;
5111 uint32_t offset, xoffset, left, j;
5112 SectionRef S, xS;
5113 const char *name;
5114
5115 r = get_pointer_32(p, offset, left, S, info);
5116 if (r == nullptr)
5117 return;
5118 memset(&opl, '\0', sizeof(struct objc_property_list32));
5119 if (left < sizeof(struct objc_property_list32)) {
5120 memcpy(&opl, r, left);
5121 outs() << " (objc_property_list entends past the end of the section)\n";
5122 } else
5123 memcpy(&opl, r, sizeof(struct objc_property_list32));
5124 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5125 swapStruct(opl);
5126 outs() << " entsize " << opl.entsize << "\n";
5127 outs() << " count " << opl.count << "\n";
5128
5129 p += sizeof(struct objc_property_list32);
5130 offset += sizeof(struct objc_property_list32);
5131 for (j = 0; j < opl.count; j++) {
5132 r = get_pointer_32(p, offset, left, S, info);
5133 if (r == nullptr)
5134 return;
5135 memset(&op, '\0', sizeof(struct objc_property32));
5136 if (left < sizeof(struct objc_property32)) {
5137 memcpy(&op, r, left);
5138 outs() << " (objc_property entends past the end of the section)\n";
5139 } else
5140 memcpy(&op, r, sizeof(struct objc_property32));
5141 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5142 swapStruct(op);
5143
5144 outs() << "\t\t\t name " << format("0x%" PRIx32, op.name);
5145 name = get_pointer_32(op.name, xoffset, left, xS, info);
5146 if (name != nullptr)
5147 outs() << format(" %.*s", left, name);
5148 outs() << "\n";
5149
5150 outs() << "\t\t\tattributes " << format("0x%" PRIx32, op.attributes);
5151 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
5152 if (name != nullptr)
5153 outs() << format(" %.*s", left, name);
5154 outs() << "\n";
5155
5156 p += sizeof(struct objc_property32);
5157 offset += sizeof(struct objc_property32);
5158 }
5159 }
5160
print_class_ro64_t(uint64_t p,struct DisassembleInfo * info,bool & is_meta_class)5161 static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5162 bool &is_meta_class) {
5163 struct class_ro64_t cro;
5164 const char *r;
5165 uint32_t offset, xoffset, left;
5166 SectionRef S, xS;
5167 const char *name, *sym_name;
5168 uint64_t n_value;
5169
5170 r = get_pointer_64(p, offset, left, S, info);
5171 if (r == nullptr || left < sizeof(struct class_ro64_t))
5172 return false;
5173 memcpy(&cro, r, sizeof(struct class_ro64_t));
5174 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5175 swapStruct(cro);
5176 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5177 if (cro.flags & RO_META)
5178 outs() << " RO_META";
5179 if (cro.flags & RO_ROOT)
5180 outs() << " RO_ROOT";
5181 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5182 outs() << " RO_HAS_CXX_STRUCTORS";
5183 outs() << "\n";
5184 outs() << " instanceStart " << cro.instanceStart << "\n";
5185 outs() << " instanceSize " << cro.instanceSize << "\n";
5186 outs() << " reserved " << format("0x%" PRIx32, cro.reserved)
5187 << "\n";
5188 outs() << " ivarLayout " << format("0x%" PRIx64, cro.ivarLayout)
5189 << "\n";
5190 print_layout_map64(cro.ivarLayout, info);
5191
5192 outs() << " name ";
5193 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name), S,
5194 info, n_value, cro.name);
5195 if (n_value != 0) {
5196 if (info->verbose && sym_name != nullptr)
5197 outs() << sym_name;
5198 else
5199 outs() << format("0x%" PRIx64, n_value);
5200 if (cro.name != 0)
5201 outs() << " + " << format("0x%" PRIx64, cro.name);
5202 } else
5203 outs() << format("0x%" PRIx64, cro.name);
5204 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
5205 if (name != nullptr)
5206 outs() << format(" %.*s", left, name);
5207 outs() << "\n";
5208
5209 outs() << " baseMethods ";
5210 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods),
5211 S, info, n_value, cro.baseMethods);
5212 if (n_value != 0) {
5213 if (info->verbose && sym_name != nullptr)
5214 outs() << sym_name;
5215 else
5216 outs() << format("0x%" PRIx64, n_value);
5217 if (cro.baseMethods != 0)
5218 outs() << " + " << format("0x%" PRIx64, cro.baseMethods);
5219 } else
5220 outs() << format("0x%" PRIx64, cro.baseMethods);
5221 outs() << " (struct method_list_t *)\n";
5222 if (cro.baseMethods + n_value != 0)
5223 print_method_list64_t(cro.baseMethods + n_value, info, "");
5224
5225 outs() << " baseProtocols ";
5226 sym_name =
5227 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols), S,
5228 info, n_value, cro.baseProtocols);
5229 if (n_value != 0) {
5230 if (info->verbose && sym_name != nullptr)
5231 outs() << sym_name;
5232 else
5233 outs() << format("0x%" PRIx64, n_value);
5234 if (cro.baseProtocols != 0)
5235 outs() << " + " << format("0x%" PRIx64, cro.baseProtocols);
5236 } else
5237 outs() << format("0x%" PRIx64, cro.baseProtocols);
5238 outs() << "\n";
5239 if (cro.baseProtocols + n_value != 0)
5240 print_protocol_list64_t(cro.baseProtocols + n_value, info);
5241
5242 outs() << " ivars ";
5243 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars), S,
5244 info, n_value, cro.ivars);
5245 if (n_value != 0) {
5246 if (info->verbose && sym_name != nullptr)
5247 outs() << sym_name;
5248 else
5249 outs() << format("0x%" PRIx64, n_value);
5250 if (cro.ivars != 0)
5251 outs() << " + " << format("0x%" PRIx64, cro.ivars);
5252 } else
5253 outs() << format("0x%" PRIx64, cro.ivars);
5254 outs() << "\n";
5255 if (cro.ivars + n_value != 0)
5256 print_ivar_list64_t(cro.ivars + n_value, info);
5257
5258 outs() << " weakIvarLayout ";
5259 sym_name =
5260 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5261 info, n_value, cro.weakIvarLayout);
5262 if (n_value != 0) {
5263 if (info->verbose && sym_name != nullptr)
5264 outs() << sym_name;
5265 else
5266 outs() << format("0x%" PRIx64, n_value);
5267 if (cro.weakIvarLayout != 0)
5268 outs() << " + " << format("0x%" PRIx64, cro.weakIvarLayout);
5269 } else
5270 outs() << format("0x%" PRIx64, cro.weakIvarLayout);
5271 outs() << "\n";
5272 print_layout_map64(cro.weakIvarLayout + n_value, info);
5273
5274 outs() << " baseProperties ";
5275 sym_name =
5276 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties), S,
5277 info, n_value, cro.baseProperties);
5278 if (n_value != 0) {
5279 if (info->verbose && sym_name != nullptr)
5280 outs() << sym_name;
5281 else
5282 outs() << format("0x%" PRIx64, n_value);
5283 if (cro.baseProperties != 0)
5284 outs() << " + " << format("0x%" PRIx64, cro.baseProperties);
5285 } else
5286 outs() << format("0x%" PRIx64, cro.baseProperties);
5287 outs() << "\n";
5288 if (cro.baseProperties + n_value != 0)
5289 print_objc_property_list64(cro.baseProperties + n_value, info);
5290
5291 is_meta_class = (cro.flags & RO_META) != 0;
5292 return true;
5293 }
5294
print_class_ro32_t(uint32_t p,struct DisassembleInfo * info,bool & is_meta_class)5295 static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5296 bool &is_meta_class) {
5297 struct class_ro32_t cro;
5298 const char *r;
5299 uint32_t offset, xoffset, left;
5300 SectionRef S, xS;
5301 const char *name;
5302
5303 r = get_pointer_32(p, offset, left, S, info);
5304 if (r == nullptr)
5305 return false;
5306 memset(&cro, '\0', sizeof(struct class_ro32_t));
5307 if (left < sizeof(struct class_ro32_t)) {
5308 memcpy(&cro, r, left);
5309 outs() << " (class_ro_t entends past the end of the section)\n";
5310 } else
5311 memcpy(&cro, r, sizeof(struct class_ro32_t));
5312 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5313 swapStruct(cro);
5314 outs() << " flags " << format("0x%" PRIx32, cro.flags);
5315 if (cro.flags & RO_META)
5316 outs() << " RO_META";
5317 if (cro.flags & RO_ROOT)
5318 outs() << " RO_ROOT";
5319 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5320 outs() << " RO_HAS_CXX_STRUCTORS";
5321 outs() << "\n";
5322 outs() << " instanceStart " << cro.instanceStart << "\n";
5323 outs() << " instanceSize " << cro.instanceSize << "\n";
5324 outs() << " ivarLayout " << format("0x%" PRIx32, cro.ivarLayout)
5325 << "\n";
5326 print_layout_map32(cro.ivarLayout, info);
5327
5328 outs() << " name " << format("0x%" PRIx32, cro.name);
5329 name = get_pointer_32(cro.name, xoffset, left, xS, info);
5330 if (name != nullptr)
5331 outs() << format(" %.*s", left, name);
5332 outs() << "\n";
5333
5334 outs() << " baseMethods "
5335 << format("0x%" PRIx32, cro.baseMethods)
5336 << " (struct method_list_t *)\n";
5337 if (cro.baseMethods != 0)
5338 print_method_list32_t(cro.baseMethods, info, "");
5339
5340 outs() << " baseProtocols "
5341 << format("0x%" PRIx32, cro.baseProtocols) << "\n";
5342 if (cro.baseProtocols != 0)
5343 print_protocol_list32_t(cro.baseProtocols, info);
5344 outs() << " ivars " << format("0x%" PRIx32, cro.ivars)
5345 << "\n";
5346 if (cro.ivars != 0)
5347 print_ivar_list32_t(cro.ivars, info);
5348 outs() << " weakIvarLayout "
5349 << format("0x%" PRIx32, cro.weakIvarLayout) << "\n";
5350 print_layout_map32(cro.weakIvarLayout, info);
5351 outs() << " baseProperties "
5352 << format("0x%" PRIx32, cro.baseProperties) << "\n";
5353 if (cro.baseProperties != 0)
5354 print_objc_property_list32(cro.baseProperties, info);
5355 is_meta_class = (cro.flags & RO_META) != 0;
5356 return true;
5357 }
5358
print_class64_t(uint64_t p,struct DisassembleInfo * info)5359 static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5360 struct class64_t c;
5361 const char *r;
5362 uint32_t offset, left;
5363 SectionRef S;
5364 const char *name;
5365 uint64_t isa_n_value, n_value;
5366
5367 r = get_pointer_64(p, offset, left, S, info);
5368 if (r == nullptr || left < sizeof(struct class64_t))
5369 return;
5370 memcpy(&c, r, sizeof(struct class64_t));
5371 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5372 swapStruct(c);
5373
5374 outs() << " isa " << format("0x%" PRIx64, c.isa);
5375 name = get_symbol_64(offset + offsetof(struct class64_t, isa), S, info,
5376 isa_n_value, c.isa);
5377 if (name != nullptr)
5378 outs() << " " << name;
5379 outs() << "\n";
5380
5381 outs() << " superclass " << format("0x%" PRIx64, c.superclass);
5382 name = get_symbol_64(offset + offsetof(struct class64_t, superclass), S, info,
5383 n_value, c.superclass);
5384 if (name != nullptr)
5385 outs() << " " << name;
5386 else {
5387 name = get_dyld_bind_info_symbolname(S.getAddress() +
5388 offset + offsetof(struct class64_t, superclass), info);
5389 if (name != nullptr)
5390 outs() << " " << name;
5391 }
5392 outs() << "\n";
5393
5394 outs() << " cache " << format("0x%" PRIx64, c.cache);
5395 name = get_symbol_64(offset + offsetof(struct class64_t, cache), S, info,
5396 n_value, c.cache);
5397 if (name != nullptr)
5398 outs() << " " << name;
5399 outs() << "\n";
5400
5401 outs() << " vtable " << format("0x%" PRIx64, c.vtable);
5402 name = get_symbol_64(offset + offsetof(struct class64_t, vtable), S, info,
5403 n_value, c.vtable);
5404 if (name != nullptr)
5405 outs() << " " << name;
5406 outs() << "\n";
5407
5408 name = get_symbol_64(offset + offsetof(struct class64_t, data), S, info,
5409 n_value, c.data);
5410 outs() << " data ";
5411 if (n_value != 0) {
5412 if (info->verbose && name != nullptr)
5413 outs() << name;
5414 else
5415 outs() << format("0x%" PRIx64, n_value);
5416 if (c.data != 0)
5417 outs() << " + " << format("0x%" PRIx64, c.data);
5418 } else
5419 outs() << format("0x%" PRIx64, c.data);
5420 outs() << " (struct class_ro_t *)";
5421
5422 // This is a Swift class if some of the low bits of the pointer are set.
5423 if ((c.data + n_value) & 0x7)
5424 outs() << " Swift class";
5425 outs() << "\n";
5426 bool is_meta_class;
5427 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
5428 return;
5429
5430 if (!is_meta_class &&
5431 c.isa + isa_n_value != p &&
5432 c.isa + isa_n_value != 0 &&
5433 info->depth < 100) {
5434 info->depth++;
5435 outs() << "Meta Class\n";
5436 print_class64_t(c.isa + isa_n_value, info);
5437 }
5438 }
5439
print_class32_t(uint32_t p,struct DisassembleInfo * info)5440 static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5441 struct class32_t c;
5442 const char *r;
5443 uint32_t offset, left;
5444 SectionRef S;
5445 const char *name;
5446
5447 r = get_pointer_32(p, offset, left, S, info);
5448 if (r == nullptr)
5449 return;
5450 memset(&c, '\0', sizeof(struct class32_t));
5451 if (left < sizeof(struct class32_t)) {
5452 memcpy(&c, r, left);
5453 outs() << " (class_t entends past the end of the section)\n";
5454 } else
5455 memcpy(&c, r, sizeof(struct class32_t));
5456 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5457 swapStruct(c);
5458
5459 outs() << " isa " << format("0x%" PRIx32, c.isa);
5460 name =
5461 get_symbol_32(offset + offsetof(struct class32_t, isa), S, info, c.isa);
5462 if (name != nullptr)
5463 outs() << " " << name;
5464 outs() << "\n";
5465
5466 outs() << " superclass " << format("0x%" PRIx32, c.superclass);
5467 name = get_symbol_32(offset + offsetof(struct class32_t, superclass), S, info,
5468 c.superclass);
5469 if (name != nullptr)
5470 outs() << " " << name;
5471 outs() << "\n";
5472
5473 outs() << " cache " << format("0x%" PRIx32, c.cache);
5474 name = get_symbol_32(offset + offsetof(struct class32_t, cache), S, info,
5475 c.cache);
5476 if (name != nullptr)
5477 outs() << " " << name;
5478 outs() << "\n";
5479
5480 outs() << " vtable " << format("0x%" PRIx32, c.vtable);
5481 name = get_symbol_32(offset + offsetof(struct class32_t, vtable), S, info,
5482 c.vtable);
5483 if (name != nullptr)
5484 outs() << " " << name;
5485 outs() << "\n";
5486
5487 name =
5488 get_symbol_32(offset + offsetof(struct class32_t, data), S, info, c.data);
5489 outs() << " data " << format("0x%" PRIx32, c.data)
5490 << " (struct class_ro_t *)";
5491
5492 // This is a Swift class if some of the low bits of the pointer are set.
5493 if (c.data & 0x3)
5494 outs() << " Swift class";
5495 outs() << "\n";
5496 bool is_meta_class;
5497 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
5498 return;
5499
5500 if (!is_meta_class) {
5501 outs() << "Meta Class\n";
5502 print_class32_t(c.isa, info);
5503 }
5504 }
5505
print_objc_class_t(struct objc_class_t * objc_class,struct DisassembleInfo * info)5506 static void print_objc_class_t(struct objc_class_t *objc_class,
5507 struct DisassembleInfo *info) {
5508 uint32_t offset, left, xleft;
5509 const char *name, *p, *ivar_list;
5510 SectionRef S;
5511 int32_t i;
5512 struct objc_ivar_list_t objc_ivar_list;
5513 struct objc_ivar_t ivar;
5514
5515 outs() << "\t\t isa " << format("0x%08" PRIx32, objc_class->isa);
5516 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5517 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
5518 if (name != nullptr)
5519 outs() << format(" %.*s", left, name);
5520 else
5521 outs() << " (not in an __OBJC section)";
5522 }
5523 outs() << "\n";
5524
5525 outs() << "\t super_class "
5526 << format("0x%08" PRIx32, objc_class->super_class);
5527 if (info->verbose) {
5528 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
5529 if (name != nullptr)
5530 outs() << format(" %.*s", left, name);
5531 else
5532 outs() << " (not in an __OBJC section)";
5533 }
5534 outs() << "\n";
5535
5536 outs() << "\t\t name " << format("0x%08" PRIx32, objc_class->name);
5537 if (info->verbose) {
5538 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
5539 if (name != nullptr)
5540 outs() << format(" %.*s", left, name);
5541 else
5542 outs() << " (not in an __OBJC section)";
5543 }
5544 outs() << "\n";
5545
5546 outs() << "\t\t version " << format("0x%08" PRIx32, objc_class->version)
5547 << "\n";
5548
5549 outs() << "\t\t info " << format("0x%08" PRIx32, objc_class->info);
5550 if (info->verbose) {
5551 if (CLS_GETINFO(objc_class, CLS_CLASS))
5552 outs() << " CLS_CLASS";
5553 else if (CLS_GETINFO(objc_class, CLS_META))
5554 outs() << " CLS_META";
5555 }
5556 outs() << "\n";
5557
5558 outs() << "\t instance_size "
5559 << format("0x%08" PRIx32, objc_class->instance_size) << "\n";
5560
5561 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
5562 outs() << "\t\t ivars " << format("0x%08" PRIx32, objc_class->ivars);
5563 if (p != nullptr) {
5564 if (left > sizeof(struct objc_ivar_list_t)) {
5565 outs() << "\n";
5566 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
5567 } else {
5568 outs() << " (entends past the end of the section)\n";
5569 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
5570 memcpy(&objc_ivar_list, p, left);
5571 }
5572 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5573 swapStruct(objc_ivar_list);
5574 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5575 ivar_list = p + sizeof(struct objc_ivar_list_t);
5576 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5577 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5578 outs() << "\t\t remaining ivar's extend past the of the section\n";
5579 break;
5580 }
5581 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
5582 sizeof(struct objc_ivar_t));
5583 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5584 swapStruct(ivar);
5585
5586 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32, ivar.ivar_name);
5587 if (info->verbose) {
5588 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
5589 if (name != nullptr)
5590 outs() << format(" %.*s", xleft, name);
5591 else
5592 outs() << " (not in an __OBJC section)";
5593 }
5594 outs() << "\n";
5595
5596 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32, ivar.ivar_type);
5597 if (info->verbose) {
5598 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
5599 if (name != nullptr)
5600 outs() << format(" %.*s", xleft, name);
5601 else
5602 outs() << " (not in an __OBJC section)";
5603 }
5604 outs() << "\n";
5605
5606 outs() << "\t\t ivar_offset "
5607 << format("0x%08" PRIx32, ivar.ivar_offset) << "\n";
5608 }
5609 } else {
5610 outs() << " (not in an __OBJC section)\n";
5611 }
5612
5613 outs() << "\t\t methods " << format("0x%08" PRIx32, objc_class->methodLists);
5614 if (print_method_list(objc_class->methodLists, info))
5615 outs() << " (not in an __OBJC section)\n";
5616
5617 outs() << "\t\t cache " << format("0x%08" PRIx32, objc_class->cache)
5618 << "\n";
5619
5620 outs() << "\t\tprotocols " << format("0x%08" PRIx32, objc_class->protocols);
5621 if (print_protocol_list(objc_class->protocols, 16, info))
5622 outs() << " (not in an __OBJC section)\n";
5623 }
5624
print_objc_objc_category_t(struct objc_category_t * objc_category,struct DisassembleInfo * info)5625 static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5626 struct DisassembleInfo *info) {
5627 uint32_t offset, left;
5628 const char *name;
5629 SectionRef S;
5630
5631 outs() << "\t category name "
5632 << format("0x%08" PRIx32, objc_category->category_name);
5633 if (info->verbose) {
5634 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
5635 true);
5636 if (name != nullptr)
5637 outs() << format(" %.*s", left, name);
5638 else
5639 outs() << " (not in an __OBJC section)";
5640 }
5641 outs() << "\n";
5642
5643 outs() << "\t\t class name "
5644 << format("0x%08" PRIx32, objc_category->class_name);
5645 if (info->verbose) {
5646 name =
5647 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
5648 if (name != nullptr)
5649 outs() << format(" %.*s", left, name);
5650 else
5651 outs() << " (not in an __OBJC section)";
5652 }
5653 outs() << "\n";
5654
5655 outs() << "\t instance methods "
5656 << format("0x%08" PRIx32, objc_category->instance_methods);
5657 if (print_method_list(objc_category->instance_methods, info))
5658 outs() << " (not in an __OBJC section)\n";
5659
5660 outs() << "\t class methods "
5661 << format("0x%08" PRIx32, objc_category->class_methods);
5662 if (print_method_list(objc_category->class_methods, info))
5663 outs() << " (not in an __OBJC section)\n";
5664 }
5665
print_category64_t(uint64_t p,struct DisassembleInfo * info)5666 static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5667 struct category64_t c;
5668 const char *r;
5669 uint32_t offset, xoffset, left;
5670 SectionRef S, xS;
5671 const char *name, *sym_name;
5672 uint64_t n_value;
5673
5674 r = get_pointer_64(p, offset, left, S, info);
5675 if (r == nullptr)
5676 return;
5677 memset(&c, '\0', sizeof(struct category64_t));
5678 if (left < sizeof(struct category64_t)) {
5679 memcpy(&c, r, left);
5680 outs() << " (category_t entends past the end of the section)\n";
5681 } else
5682 memcpy(&c, r, sizeof(struct category64_t));
5683 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5684 swapStruct(c);
5685
5686 outs() << " name ";
5687 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name), S,
5688 info, n_value, c.name);
5689 if (n_value != 0) {
5690 if (info->verbose && sym_name != nullptr)
5691 outs() << sym_name;
5692 else
5693 outs() << format("0x%" PRIx64, n_value);
5694 if (c.name != 0)
5695 outs() << " + " << format("0x%" PRIx64, c.name);
5696 } else
5697 outs() << format("0x%" PRIx64, c.name);
5698 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
5699 if (name != nullptr)
5700 outs() << format(" %.*s", left, name);
5701 outs() << "\n";
5702
5703 outs() << " cls ";
5704 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls), S, info,
5705 n_value, c.cls);
5706 if (n_value != 0) {
5707 if (info->verbose && sym_name != nullptr)
5708 outs() << sym_name;
5709 else
5710 outs() << format("0x%" PRIx64, n_value);
5711 if (c.cls != 0)
5712 outs() << " + " << format("0x%" PRIx64, c.cls);
5713 } else
5714 outs() << format("0x%" PRIx64, c.cls);
5715 outs() << "\n";
5716 if (c.cls + n_value != 0)
5717 print_class64_t(c.cls + n_value, info);
5718
5719 outs() << " instanceMethods ";
5720 sym_name =
5721 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods), S,
5722 info, n_value, c.instanceMethods);
5723 if (n_value != 0) {
5724 if (info->verbose && sym_name != nullptr)
5725 outs() << sym_name;
5726 else
5727 outs() << format("0x%" PRIx64, n_value);
5728 if (c.instanceMethods != 0)
5729 outs() << " + " << format("0x%" PRIx64, c.instanceMethods);
5730 } else
5731 outs() << format("0x%" PRIx64, c.instanceMethods);
5732 outs() << "\n";
5733 if (c.instanceMethods + n_value != 0)
5734 print_method_list64_t(c.instanceMethods + n_value, info, "");
5735
5736 outs() << " classMethods ";
5737 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods),
5738 S, info, n_value, c.classMethods);
5739 if (n_value != 0) {
5740 if (info->verbose && sym_name != nullptr)
5741 outs() << sym_name;
5742 else
5743 outs() << format("0x%" PRIx64, n_value);
5744 if (c.classMethods != 0)
5745 outs() << " + " << format("0x%" PRIx64, c.classMethods);
5746 } else
5747 outs() << format("0x%" PRIx64, c.classMethods);
5748 outs() << "\n";
5749 if (c.classMethods + n_value != 0)
5750 print_method_list64_t(c.classMethods + n_value, info, "");
5751
5752 outs() << " protocols ";
5753 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols), S,
5754 info, n_value, c.protocols);
5755 if (n_value != 0) {
5756 if (info->verbose && sym_name != nullptr)
5757 outs() << sym_name;
5758 else
5759 outs() << format("0x%" PRIx64, n_value);
5760 if (c.protocols != 0)
5761 outs() << " + " << format("0x%" PRIx64, c.protocols);
5762 } else
5763 outs() << format("0x%" PRIx64, c.protocols);
5764 outs() << "\n";
5765 if (c.protocols + n_value != 0)
5766 print_protocol_list64_t(c.protocols + n_value, info);
5767
5768 outs() << "instanceProperties ";
5769 sym_name =
5770 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties),
5771 S, info, n_value, c.instanceProperties);
5772 if (n_value != 0) {
5773 if (info->verbose && sym_name != nullptr)
5774 outs() << sym_name;
5775 else
5776 outs() << format("0x%" PRIx64, n_value);
5777 if (c.instanceProperties != 0)
5778 outs() << " + " << format("0x%" PRIx64, c.instanceProperties);
5779 } else
5780 outs() << format("0x%" PRIx64, c.instanceProperties);
5781 outs() << "\n";
5782 if (c.instanceProperties + n_value != 0)
5783 print_objc_property_list64(c.instanceProperties + n_value, info);
5784 }
5785
print_category32_t(uint32_t p,struct DisassembleInfo * info)5786 static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5787 struct category32_t c;
5788 const char *r;
5789 uint32_t offset, left;
5790 SectionRef S, xS;
5791 const char *name;
5792
5793 r = get_pointer_32(p, offset, left, S, info);
5794 if (r == nullptr)
5795 return;
5796 memset(&c, '\0', sizeof(struct category32_t));
5797 if (left < sizeof(struct category32_t)) {
5798 memcpy(&c, r, left);
5799 outs() << " (category_t entends past the end of the section)\n";
5800 } else
5801 memcpy(&c, r, sizeof(struct category32_t));
5802 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5803 swapStruct(c);
5804
5805 outs() << " name " << format("0x%" PRIx32, c.name);
5806 name = get_symbol_32(offset + offsetof(struct category32_t, name), S, info,
5807 c.name);
5808 if (name)
5809 outs() << " " << name;
5810 outs() << "\n";
5811
5812 outs() << " cls " << format("0x%" PRIx32, c.cls) << "\n";
5813 if (c.cls != 0)
5814 print_class32_t(c.cls, info);
5815 outs() << " instanceMethods " << format("0x%" PRIx32, c.instanceMethods)
5816 << "\n";
5817 if (c.instanceMethods != 0)
5818 print_method_list32_t(c.instanceMethods, info, "");
5819 outs() << " classMethods " << format("0x%" PRIx32, c.classMethods)
5820 << "\n";
5821 if (c.classMethods != 0)
5822 print_method_list32_t(c.classMethods, info, "");
5823 outs() << " protocols " << format("0x%" PRIx32, c.protocols) << "\n";
5824 if (c.protocols != 0)
5825 print_protocol_list32_t(c.protocols, info);
5826 outs() << "instanceProperties " << format("0x%" PRIx32, c.instanceProperties)
5827 << "\n";
5828 if (c.instanceProperties != 0)
5829 print_objc_property_list32(c.instanceProperties, info);
5830 }
5831
print_message_refs64(SectionRef S,struct DisassembleInfo * info)5832 static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5833 uint32_t i, left, offset, xoffset;
5834 uint64_t p, n_value;
5835 struct message_ref64 mr;
5836 const char *name, *sym_name;
5837 const char *r;
5838 SectionRef xS;
5839
5840 if (S == SectionRef())
5841 return;
5842
5843 StringRef SectName;
5844 Expected<StringRef> SecNameOrErr = S.getName();
5845 if (SecNameOrErr)
5846 SectName = *SecNameOrErr;
5847 else
5848 consumeError(SecNameOrErr.takeError());
5849
5850 DataRefImpl Ref = S.getRawDataRefImpl();
5851 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5852 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5853 offset = 0;
5854 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5855 p = S.getAddress() + i;
5856 r = get_pointer_64(p, offset, left, S, info);
5857 if (r == nullptr)
5858 return;
5859 memset(&mr, '\0', sizeof(struct message_ref64));
5860 if (left < sizeof(struct message_ref64)) {
5861 memcpy(&mr, r, left);
5862 outs() << " (message_ref entends past the end of the section)\n";
5863 } else
5864 memcpy(&mr, r, sizeof(struct message_ref64));
5865 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5866 swapStruct(mr);
5867
5868 outs() << " imp ";
5869 name = get_symbol_64(offset + offsetof(struct message_ref64, imp), S, info,
5870 n_value, mr.imp);
5871 if (n_value != 0) {
5872 outs() << format("0x%" PRIx64, n_value) << " ";
5873 if (mr.imp != 0)
5874 outs() << "+ " << format("0x%" PRIx64, mr.imp) << " ";
5875 } else
5876 outs() << format("0x%" PRIx64, mr.imp) << " ";
5877 if (name != nullptr)
5878 outs() << " " << name;
5879 outs() << "\n";
5880
5881 outs() << " sel ";
5882 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel), S,
5883 info, n_value, mr.sel);
5884 if (n_value != 0) {
5885 if (info->verbose && sym_name != nullptr)
5886 outs() << sym_name;
5887 else
5888 outs() << format("0x%" PRIx64, n_value);
5889 if (mr.sel != 0)
5890 outs() << " + " << format("0x%" PRIx64, mr.sel);
5891 } else
5892 outs() << format("0x%" PRIx64, mr.sel);
5893 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5894 if (name != nullptr)
5895 outs() << format(" %.*s", left, name);
5896 outs() << "\n";
5897
5898 offset += sizeof(struct message_ref64);
5899 }
5900 }
5901
print_message_refs32(SectionRef S,struct DisassembleInfo * info)5902 static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5903 uint32_t i, left, offset, xoffset, p;
5904 struct message_ref32 mr;
5905 const char *name, *r;
5906 SectionRef xS;
5907
5908 if (S == SectionRef())
5909 return;
5910
5911 StringRef SectName;
5912 Expected<StringRef> SecNameOrErr = S.getName();
5913 if (SecNameOrErr)
5914 SectName = *SecNameOrErr;
5915 else
5916 consumeError(SecNameOrErr.takeError());
5917
5918 DataRefImpl Ref = S.getRawDataRefImpl();
5919 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5920 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5921 offset = 0;
5922 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5923 p = S.getAddress() + i;
5924 r = get_pointer_32(p, offset, left, S, info);
5925 if (r == nullptr)
5926 return;
5927 memset(&mr, '\0', sizeof(struct message_ref32));
5928 if (left < sizeof(struct message_ref32)) {
5929 memcpy(&mr, r, left);
5930 outs() << " (message_ref entends past the end of the section)\n";
5931 } else
5932 memcpy(&mr, r, sizeof(struct message_ref32));
5933 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5934 swapStruct(mr);
5935
5936 outs() << " imp " << format("0x%" PRIx32, mr.imp);
5937 name = get_symbol_32(offset + offsetof(struct message_ref32, imp), S, info,
5938 mr.imp);
5939 if (name != nullptr)
5940 outs() << " " << name;
5941 outs() << "\n";
5942
5943 outs() << " sel " << format("0x%" PRIx32, mr.sel);
5944 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5945 if (name != nullptr)
5946 outs() << " " << name;
5947 outs() << "\n";
5948
5949 offset += sizeof(struct message_ref32);
5950 }
5951 }
5952
print_image_info64(SectionRef S,struct DisassembleInfo * info)5953 static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5954 uint32_t left, offset, swift_version;
5955 uint64_t p;
5956 struct objc_image_info64 o;
5957 const char *r;
5958
5959 if (S == SectionRef())
5960 return;
5961
5962 StringRef SectName;
5963 Expected<StringRef> SecNameOrErr = S.getName();
5964 if (SecNameOrErr)
5965 SectName = *SecNameOrErr;
5966 else
5967 consumeError(SecNameOrErr.takeError());
5968
5969 DataRefImpl Ref = S.getRawDataRefImpl();
5970 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5971 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5972 p = S.getAddress();
5973 r = get_pointer_64(p, offset, left, S, info);
5974 if (r == nullptr)
5975 return;
5976 memset(&o, '\0', sizeof(struct objc_image_info64));
5977 if (left < sizeof(struct objc_image_info64)) {
5978 memcpy(&o, r, left);
5979 outs() << " (objc_image_info entends past the end of the section)\n";
5980 } else
5981 memcpy(&o, r, sizeof(struct objc_image_info64));
5982 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5983 swapStruct(o);
5984 outs() << " version " << o.version << "\n";
5985 outs() << " flags " << format("0x%" PRIx32, o.flags);
5986 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
5987 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5988 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
5989 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5990 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
5991 outs() << " OBJC_IMAGE_IS_SIMULATED";
5992 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
5993 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
5994 swift_version = (o.flags >> 8) & 0xff;
5995 if (swift_version != 0) {
5996 if (swift_version == 1)
5997 outs() << " Swift 1.0";
5998 else if (swift_version == 2)
5999 outs() << " Swift 1.1";
6000 else if(swift_version == 3)
6001 outs() << " Swift 2.0";
6002 else if(swift_version == 4)
6003 outs() << " Swift 3.0";
6004 else if(swift_version == 5)
6005 outs() << " Swift 4.0";
6006 else if(swift_version == 6)
6007 outs() << " Swift 4.1/Swift 4.2";
6008 else if(swift_version == 7)
6009 outs() << " Swift 5 or later";
6010 else
6011 outs() << " unknown future Swift version (" << swift_version << ")";
6012 }
6013 outs() << "\n";
6014 }
6015
print_image_info32(SectionRef S,struct DisassembleInfo * info)6016 static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6017 uint32_t left, offset, swift_version, p;
6018 struct objc_image_info32 o;
6019 const char *r;
6020
6021 if (S == SectionRef())
6022 return;
6023
6024 StringRef SectName;
6025 Expected<StringRef> SecNameOrErr = S.getName();
6026 if (SecNameOrErr)
6027 SectName = *SecNameOrErr;
6028 else
6029 consumeError(SecNameOrErr.takeError());
6030
6031 DataRefImpl Ref = S.getRawDataRefImpl();
6032 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6033 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6034 p = S.getAddress();
6035 r = get_pointer_32(p, offset, left, S, info);
6036 if (r == nullptr)
6037 return;
6038 memset(&o, '\0', sizeof(struct objc_image_info32));
6039 if (left < sizeof(struct objc_image_info32)) {
6040 memcpy(&o, r, left);
6041 outs() << " (objc_image_info entends past the end of the section)\n";
6042 } else
6043 memcpy(&o, r, sizeof(struct objc_image_info32));
6044 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6045 swapStruct(o);
6046 outs() << " version " << o.version << "\n";
6047 outs() << " flags " << format("0x%" PRIx32, o.flags);
6048 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6049 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6050 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6051 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6052 swift_version = (o.flags >> 8) & 0xff;
6053 if (swift_version != 0) {
6054 if (swift_version == 1)
6055 outs() << " Swift 1.0";
6056 else if (swift_version == 2)
6057 outs() << " Swift 1.1";
6058 else if(swift_version == 3)
6059 outs() << " Swift 2.0";
6060 else if(swift_version == 4)
6061 outs() << " Swift 3.0";
6062 else if(swift_version == 5)
6063 outs() << " Swift 4.0";
6064 else if(swift_version == 6)
6065 outs() << " Swift 4.1/Swift 4.2";
6066 else if(swift_version == 7)
6067 outs() << " Swift 5 or later";
6068 else
6069 outs() << " unknown future Swift version (" << swift_version << ")";
6070 }
6071 outs() << "\n";
6072 }
6073
print_image_info(SectionRef S,struct DisassembleInfo * info)6074 static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6075 uint32_t left, offset, p;
6076 struct imageInfo_t o;
6077 const char *r;
6078
6079 StringRef SectName;
6080 Expected<StringRef> SecNameOrErr = S.getName();
6081 if (SecNameOrErr)
6082 SectName = *SecNameOrErr;
6083 else
6084 consumeError(SecNameOrErr.takeError());
6085
6086 DataRefImpl Ref = S.getRawDataRefImpl();
6087 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
6088 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6089 p = S.getAddress();
6090 r = get_pointer_32(p, offset, left, S, info);
6091 if (r == nullptr)
6092 return;
6093 memset(&o, '\0', sizeof(struct imageInfo_t));
6094 if (left < sizeof(struct imageInfo_t)) {
6095 memcpy(&o, r, left);
6096 outs() << " (imageInfo entends past the end of the section)\n";
6097 } else
6098 memcpy(&o, r, sizeof(struct imageInfo_t));
6099 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6100 swapStruct(o);
6101 outs() << " version " << o.version << "\n";
6102 outs() << " flags " << format("0x%" PRIx32, o.flags);
6103 if (o.flags & 0x1)
6104 outs() << " F&C";
6105 if (o.flags & 0x2)
6106 outs() << " GC";
6107 if (o.flags & 0x4)
6108 outs() << " GC-only";
6109 else
6110 outs() << " RR";
6111 outs() << "\n";
6112 }
6113
printObjc2_64bit_MetaData(MachOObjectFile * O,bool verbose)6114 static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6115 SymbolAddressMap AddrMap;
6116 if (verbose)
6117 CreateSymbolAddressMap(O, &AddrMap);
6118
6119 std::vector<SectionRef> Sections;
6120 for (const SectionRef &Section : O->sections())
6121 Sections.push_back(Section);
6122
6123 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6124
6125 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6126 if (CL == SectionRef())
6127 CL = get_section(O, "__DATA", "__objc_classlist");
6128 if (CL == SectionRef())
6129 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6130 if (CL == SectionRef())
6131 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6132 info.S = CL;
6133 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
6134
6135 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6136 if (CR == SectionRef())
6137 CR = get_section(O, "__DATA", "__objc_classrefs");
6138 if (CR == SectionRef())
6139 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6140 if (CR == SectionRef())
6141 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6142 info.S = CR;
6143 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
6144
6145 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6146 if (SR == SectionRef())
6147 SR = get_section(O, "__DATA", "__objc_superrefs");
6148 if (SR == SectionRef())
6149 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6150 if (SR == SectionRef())
6151 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6152 info.S = SR;
6153 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
6154
6155 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6156 if (CA == SectionRef())
6157 CA = get_section(O, "__DATA", "__objc_catlist");
6158 if (CA == SectionRef())
6159 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6160 if (CA == SectionRef())
6161 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6162 info.S = CA;
6163 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
6164
6165 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6166 if (PL == SectionRef())
6167 PL = get_section(O, "__DATA", "__objc_protolist");
6168 if (PL == SectionRef())
6169 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6170 if (PL == SectionRef())
6171 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6172 info.S = PL;
6173 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
6174
6175 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6176 if (MR == SectionRef())
6177 MR = get_section(O, "__DATA", "__objc_msgrefs");
6178 if (MR == SectionRef())
6179 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6180 if (MR == SectionRef())
6181 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6182 info.S = MR;
6183 print_message_refs64(MR, &info);
6184
6185 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6186 if (II == SectionRef())
6187 II = get_section(O, "__DATA", "__objc_imageinfo");
6188 if (II == SectionRef())
6189 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6190 if (II == SectionRef())
6191 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6192 info.S = II;
6193 print_image_info64(II, &info);
6194 }
6195
printObjc2_32bit_MetaData(MachOObjectFile * O,bool verbose)6196 static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6197 SymbolAddressMap AddrMap;
6198 if (verbose)
6199 CreateSymbolAddressMap(O, &AddrMap);
6200
6201 std::vector<SectionRef> Sections;
6202 for (const SectionRef &Section : O->sections())
6203 Sections.push_back(Section);
6204
6205 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6206
6207 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
6208 if (CL == SectionRef())
6209 CL = get_section(O, "__DATA", "__objc_classlist");
6210 if (CL == SectionRef())
6211 CL = get_section(O, "__DATA_CONST", "__objc_classlist");
6212 if (CL == SectionRef())
6213 CL = get_section(O, "__DATA_DIRTY", "__objc_classlist");
6214 info.S = CL;
6215 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
6216
6217 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
6218 if (CR == SectionRef())
6219 CR = get_section(O, "__DATA", "__objc_classrefs");
6220 if (CR == SectionRef())
6221 CR = get_section(O, "__DATA_CONST", "__objc_classrefs");
6222 if (CR == SectionRef())
6223 CR = get_section(O, "__DATA_DIRTY", "__objc_classrefs");
6224 info.S = CR;
6225 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
6226
6227 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
6228 if (SR == SectionRef())
6229 SR = get_section(O, "__DATA", "__objc_superrefs");
6230 if (SR == SectionRef())
6231 SR = get_section(O, "__DATA_CONST", "__objc_superrefs");
6232 if (SR == SectionRef())
6233 SR = get_section(O, "__DATA_DIRTY", "__objc_superrefs");
6234 info.S = SR;
6235 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
6236
6237 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
6238 if (CA == SectionRef())
6239 CA = get_section(O, "__DATA", "__objc_catlist");
6240 if (CA == SectionRef())
6241 CA = get_section(O, "__DATA_CONST", "__objc_catlist");
6242 if (CA == SectionRef())
6243 CA = get_section(O, "__DATA_DIRTY", "__objc_catlist");
6244 info.S = CA;
6245 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
6246
6247 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
6248 if (PL == SectionRef())
6249 PL = get_section(O, "__DATA", "__objc_protolist");
6250 if (PL == SectionRef())
6251 PL = get_section(O, "__DATA_CONST", "__objc_protolist");
6252 if (PL == SectionRef())
6253 PL = get_section(O, "__DATA_DIRTY", "__objc_protolist");
6254 info.S = PL;
6255 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
6256
6257 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
6258 if (MR == SectionRef())
6259 MR = get_section(O, "__DATA", "__objc_msgrefs");
6260 if (MR == SectionRef())
6261 MR = get_section(O, "__DATA_CONST", "__objc_msgrefs");
6262 if (MR == SectionRef())
6263 MR = get_section(O, "__DATA_DIRTY", "__objc_msgrefs");
6264 info.S = MR;
6265 print_message_refs32(MR, &info);
6266
6267 SectionRef II = get_section(O, "__OBJC2", "__image_info");
6268 if (II == SectionRef())
6269 II = get_section(O, "__DATA", "__objc_imageinfo");
6270 if (II == SectionRef())
6271 II = get_section(O, "__DATA_CONST", "__objc_imageinfo");
6272 if (II == SectionRef())
6273 II = get_section(O, "__DATA_DIRTY", "__objc_imageinfo");
6274 info.S = II;
6275 print_image_info32(II, &info);
6276 }
6277
printObjc1_32bit_MetaData(MachOObjectFile * O,bool verbose)6278 static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6279 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6280 const char *r, *name, *defs;
6281 struct objc_module_t module;
6282 SectionRef S, xS;
6283 struct objc_symtab_t symtab;
6284 struct objc_class_t objc_class;
6285 struct objc_category_t objc_category;
6286
6287 outs() << "Objective-C segment\n";
6288 S = get_section(O, "__OBJC", "__module_info");
6289 if (S == SectionRef())
6290 return false;
6291
6292 SymbolAddressMap AddrMap;
6293 if (verbose)
6294 CreateSymbolAddressMap(O, &AddrMap);
6295
6296 std::vector<SectionRef> Sections;
6297 for (const SectionRef &Section : O->sections())
6298 Sections.push_back(Section);
6299
6300 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6301
6302 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6303 p = S.getAddress() + i;
6304 r = get_pointer_32(p, offset, left, S, &info, true);
6305 if (r == nullptr)
6306 return true;
6307 memset(&module, '\0', sizeof(struct objc_module_t));
6308 if (left < sizeof(struct objc_module_t)) {
6309 memcpy(&module, r, left);
6310 outs() << " (module extends past end of __module_info section)\n";
6311 } else
6312 memcpy(&module, r, sizeof(struct objc_module_t));
6313 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6314 swapStruct(module);
6315
6316 outs() << "Module " << format("0x%" PRIx32, p) << "\n";
6317 outs() << " version " << module.version << "\n";
6318 outs() << " size " << module.size << "\n";
6319 outs() << " name ";
6320 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
6321 if (name != nullptr)
6322 outs() << format("%.*s", left, name);
6323 else
6324 outs() << format("0x%08" PRIx32, module.name)
6325 << "(not in an __OBJC section)";
6326 outs() << "\n";
6327
6328 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
6329 if (module.symtab == 0 || r == nullptr) {
6330 outs() << " symtab " << format("0x%08" PRIx32, module.symtab)
6331 << " (not in an __OBJC section)\n";
6332 continue;
6333 }
6334 outs() << " symtab " << format("0x%08" PRIx32, module.symtab) << "\n";
6335 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
6336 defs_left = 0;
6337 defs = nullptr;
6338 if (left < sizeof(struct objc_symtab_t)) {
6339 memcpy(&symtab, r, left);
6340 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6341 } else {
6342 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
6343 if (left > sizeof(struct objc_symtab_t)) {
6344 defs_left = left - sizeof(struct objc_symtab_t);
6345 defs = r + sizeof(struct objc_symtab_t);
6346 }
6347 }
6348 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6349 swapStruct(symtab);
6350
6351 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6352 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
6353 outs() << "\trefs " << format("0x%08" PRIx32, symtab.refs);
6354 if (r == nullptr)
6355 outs() << " (not in an __OBJC section)";
6356 outs() << "\n";
6357 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6358 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6359 if (symtab.cls_def_cnt > 0)
6360 outs() << "\tClass Definitions\n";
6361 for (j = 0; j < symtab.cls_def_cnt; j++) {
6362 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6363 outs() << "\t(remaining class defs entries entends past the end of the "
6364 << "section)\n";
6365 break;
6366 }
6367 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
6368 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6369 sys::swapByteOrder(def);
6370
6371 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6372 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32, def);
6373 if (r != nullptr) {
6374 if (left > sizeof(struct objc_class_t)) {
6375 outs() << "\n";
6376 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6377 } else {
6378 outs() << " (entends past the end of the section)\n";
6379 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6380 memcpy(&objc_class, r, left);
6381 }
6382 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6383 swapStruct(objc_class);
6384 print_objc_class_t(&objc_class, &info);
6385 } else {
6386 outs() << "(not in an __OBJC section)\n";
6387 }
6388
6389 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6390 outs() << "\tMeta Class";
6391 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
6392 if (r != nullptr) {
6393 if (left > sizeof(struct objc_class_t)) {
6394 outs() << "\n";
6395 memcpy(&objc_class, r, sizeof(struct objc_class_t));
6396 } else {
6397 outs() << " (entends past the end of the section)\n";
6398 memset(&objc_class, '\0', sizeof(struct objc_class_t));
6399 memcpy(&objc_class, r, left);
6400 }
6401 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6402 swapStruct(objc_class);
6403 print_objc_class_t(&objc_class, &info);
6404 } else {
6405 outs() << "(not in an __OBJC section)\n";
6406 }
6407 }
6408 }
6409 if (symtab.cat_def_cnt > 0)
6410 outs() << "\tCategory Definitions\n";
6411 for (j = 0; j < symtab.cat_def_cnt; j++) {
6412 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6413 outs() << "\t(remaining category defs entries entends past the end of "
6414 << "the section)\n";
6415 break;
6416 }
6417 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6418 sizeof(uint32_t));
6419 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6420 sys::swapByteOrder(def);
6421
6422 r = get_pointer_32(def, xoffset, left, xS, &info, true);
6423 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6424 << format("0x%08" PRIx32, def);
6425 if (r != nullptr) {
6426 if (left > sizeof(struct objc_category_t)) {
6427 outs() << "\n";
6428 memcpy(&objc_category, r, sizeof(struct objc_category_t));
6429 } else {
6430 outs() << " (entends past the end of the section)\n";
6431 memset(&objc_category, '\0', sizeof(struct objc_category_t));
6432 memcpy(&objc_category, r, left);
6433 }
6434 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6435 swapStruct(objc_category);
6436 print_objc_objc_category_t(&objc_category, &info);
6437 } else {
6438 outs() << "(not in an __OBJC section)\n";
6439 }
6440 }
6441 }
6442 const SectionRef II = get_section(O, "__OBJC", "__image_info");
6443 if (II != SectionRef())
6444 print_image_info(II, &info);
6445
6446 return true;
6447 }
6448
DumpProtocolSection(MachOObjectFile * O,const char * sect,uint32_t size,uint32_t addr)6449 static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6450 uint32_t size, uint32_t addr) {
6451 SymbolAddressMap AddrMap;
6452 CreateSymbolAddressMap(O, &AddrMap);
6453
6454 std::vector<SectionRef> Sections;
6455 for (const SectionRef &Section : O->sections())
6456 Sections.push_back(Section);
6457
6458 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6459
6460 const char *p;
6461 struct objc_protocol_t protocol;
6462 uint32_t left, paddr;
6463 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6464 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
6465 left = size - (p - sect);
6466 if (left < sizeof(struct objc_protocol_t)) {
6467 outs() << "Protocol extends past end of __protocol section\n";
6468 memcpy(&protocol, p, left);
6469 } else
6470 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
6471 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6472 swapStruct(protocol);
6473 paddr = addr + (p - sect);
6474 outs() << "Protocol " << format("0x%" PRIx32, paddr);
6475 if (print_protocol(paddr, 0, &info))
6476 outs() << "(not in an __OBJC section)\n";
6477 }
6478 }
6479
6480 #ifdef HAVE_LIBXAR
swapStruct(struct xar_header & xar)6481 static inline void swapStruct(struct xar_header &xar) {
6482 sys::swapByteOrder(xar.magic);
6483 sys::swapByteOrder(xar.size);
6484 sys::swapByteOrder(xar.version);
6485 sys::swapByteOrder(xar.toc_length_compressed);
6486 sys::swapByteOrder(xar.toc_length_uncompressed);
6487 sys::swapByteOrder(xar.cksum_alg);
6488 }
6489
PrintModeVerbose(uint32_t mode)6490 static void PrintModeVerbose(uint32_t mode) {
6491 switch(mode & S_IFMT){
6492 case S_IFDIR:
6493 outs() << "d";
6494 break;
6495 case S_IFCHR:
6496 outs() << "c";
6497 break;
6498 case S_IFBLK:
6499 outs() << "b";
6500 break;
6501 case S_IFREG:
6502 outs() << "-";
6503 break;
6504 case S_IFLNK:
6505 outs() << "l";
6506 break;
6507 case S_IFSOCK:
6508 outs() << "s";
6509 break;
6510 default:
6511 outs() << "?";
6512 break;
6513 }
6514
6515 /* owner permissions */
6516 if(mode & S_IREAD)
6517 outs() << "r";
6518 else
6519 outs() << "-";
6520 if(mode & S_IWRITE)
6521 outs() << "w";
6522 else
6523 outs() << "-";
6524 if(mode & S_ISUID)
6525 outs() << "s";
6526 else if(mode & S_IEXEC)
6527 outs() << "x";
6528 else
6529 outs() << "-";
6530
6531 /* group permissions */
6532 if(mode & (S_IREAD >> 3))
6533 outs() << "r";
6534 else
6535 outs() << "-";
6536 if(mode & (S_IWRITE >> 3))
6537 outs() << "w";
6538 else
6539 outs() << "-";
6540 if(mode & S_ISGID)
6541 outs() << "s";
6542 else if(mode & (S_IEXEC >> 3))
6543 outs() << "x";
6544 else
6545 outs() << "-";
6546
6547 /* other permissions */
6548 if(mode & (S_IREAD >> 6))
6549 outs() << "r";
6550 else
6551 outs() << "-";
6552 if(mode & (S_IWRITE >> 6))
6553 outs() << "w";
6554 else
6555 outs() << "-";
6556 if(mode & S_ISVTX)
6557 outs() << "t";
6558 else if(mode & (S_IEXEC >> 6))
6559 outs() << "x";
6560 else
6561 outs() << "-";
6562 }
6563
PrintXarFilesSummary(const char * XarFilename,xar_t xar)6564 static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
6565 xar_file_t xf;
6566 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
6567 char *endp;
6568 uint32_t mode_value;
6569
6570 ScopedXarIter xi;
6571 if (!xi) {
6572 WithColor::error(errs(), "llvm-objdump")
6573 << "can't obtain an xar iterator for xar archive " << XarFilename
6574 << "\n";
6575 return;
6576 }
6577
6578 // Go through the xar's files.
6579 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
6580 ScopedXarIter xp;
6581 if(!xp){
6582 WithColor::error(errs(), "llvm-objdump")
6583 << "can't obtain an xar iterator for xar archive " << XarFilename
6584 << "\n";
6585 return;
6586 }
6587 type = nullptr;
6588 mode = nullptr;
6589 user = nullptr;
6590 group = nullptr;
6591 size = nullptr;
6592 mtime = nullptr;
6593 name = nullptr;
6594 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6595 const char *val = nullptr;
6596 xar_prop_get(xf, key, &val);
6597 #if 0 // Useful for debugging.
6598 outs() << "key: " << key << " value: " << val << "\n";
6599 #endif
6600 if(strcmp(key, "type") == 0)
6601 type = val;
6602 if(strcmp(key, "mode") == 0)
6603 mode = val;
6604 if(strcmp(key, "user") == 0)
6605 user = val;
6606 if(strcmp(key, "group") == 0)
6607 group = val;
6608 if(strcmp(key, "data/size") == 0)
6609 size = val;
6610 if(strcmp(key, "mtime") == 0)
6611 mtime = val;
6612 if(strcmp(key, "name") == 0)
6613 name = val;
6614 }
6615 if(mode != nullptr){
6616 mode_value = strtoul(mode, &endp, 8);
6617 if(*endp != '\0')
6618 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
6619 if(strcmp(type, "file") == 0)
6620 mode_value |= S_IFREG;
6621 PrintModeVerbose(mode_value);
6622 outs() << " ";
6623 }
6624 if(user != nullptr)
6625 outs() << format("%10s/", user);
6626 if(group != nullptr)
6627 outs() << format("%-10s ", group);
6628 if(size != nullptr)
6629 outs() << format("%7s ", size);
6630 if(mtime != nullptr){
6631 for(m = mtime; *m != 'T' && *m != '\0'; m++)
6632 outs() << *m;
6633 if(*m == 'T')
6634 m++;
6635 outs() << " ";
6636 for( ; *m != 'Z' && *m != '\0'; m++)
6637 outs() << *m;
6638 outs() << " ";
6639 }
6640 if(name != nullptr)
6641 outs() << name;
6642 outs() << "\n";
6643 }
6644 }
6645
DumpBitcodeSection(MachOObjectFile * O,const char * sect,uint32_t size,bool verbose,bool PrintXarHeader,bool PrintXarFileHeaders,std::string XarMemberName)6646 static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
6647 uint32_t size, bool verbose,
6648 bool PrintXarHeader, bool PrintXarFileHeaders,
6649 std::string XarMemberName) {
6650 if(size < sizeof(struct xar_header)) {
6651 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
6652 "of struct xar_header)\n";
6653 return;
6654 }
6655 struct xar_header XarHeader;
6656 memcpy(&XarHeader, sect, sizeof(struct xar_header));
6657 if (sys::IsLittleEndianHost)
6658 swapStruct(XarHeader);
6659 if (PrintXarHeader) {
6660 if (!XarMemberName.empty())
6661 outs() << "In xar member " << XarMemberName << ": ";
6662 else
6663 outs() << "For (__LLVM,__bundle) section: ";
6664 outs() << "xar header\n";
6665 if (XarHeader.magic == XAR_HEADER_MAGIC)
6666 outs() << " magic XAR_HEADER_MAGIC\n";
6667 else
6668 outs() << " magic "
6669 << format_hex(XarHeader.magic, 10, true)
6670 << " (not XAR_HEADER_MAGIC)\n";
6671 outs() << " size " << XarHeader.size << "\n";
6672 outs() << " version " << XarHeader.version << "\n";
6673 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
6674 << "\n";
6675 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
6676 << "\n";
6677 outs() << " cksum_alg ";
6678 switch (XarHeader.cksum_alg) {
6679 case XAR_CKSUM_NONE:
6680 outs() << "XAR_CKSUM_NONE\n";
6681 break;
6682 case XAR_CKSUM_SHA1:
6683 outs() << "XAR_CKSUM_SHA1\n";
6684 break;
6685 case XAR_CKSUM_MD5:
6686 outs() << "XAR_CKSUM_MD5\n";
6687 break;
6688 #ifdef XAR_CKSUM_SHA256
6689 case XAR_CKSUM_SHA256:
6690 outs() << "XAR_CKSUM_SHA256\n";
6691 break;
6692 #endif
6693 #ifdef XAR_CKSUM_SHA512
6694 case XAR_CKSUM_SHA512:
6695 outs() << "XAR_CKSUM_SHA512\n";
6696 break;
6697 #endif
6698 default:
6699 outs() << XarHeader.cksum_alg << "\n";
6700 }
6701 }
6702
6703 SmallString<128> XarFilename;
6704 int FD;
6705 std::error_code XarEC =
6706 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
6707 if (XarEC) {
6708 WithColor::error(errs(), "llvm-objdump") << XarEC.message() << "\n";
6709 return;
6710 }
6711 ToolOutputFile XarFile(XarFilename, FD);
6712 raw_fd_ostream &XarOut = XarFile.os();
6713 StringRef XarContents(sect, size);
6714 XarOut << XarContents;
6715 XarOut.close();
6716 if (XarOut.has_error())
6717 return;
6718
6719 ScopedXarFile xar(XarFilename.c_str(), READ);
6720 if (!xar) {
6721 WithColor::error(errs(), "llvm-objdump")
6722 << "can't create temporary xar archive " << XarFilename << "\n";
6723 return;
6724 }
6725
6726 SmallString<128> TocFilename;
6727 std::error_code TocEC =
6728 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
6729 if (TocEC) {
6730 WithColor::error(errs(), "llvm-objdump") << TocEC.message() << "\n";
6731 return;
6732 }
6733 xar_serialize(xar, TocFilename.c_str());
6734
6735 if (PrintXarFileHeaders) {
6736 if (!XarMemberName.empty())
6737 outs() << "In xar member " << XarMemberName << ": ";
6738 else
6739 outs() << "For (__LLVM,__bundle) section: ";
6740 outs() << "xar archive files:\n";
6741 PrintXarFilesSummary(XarFilename.c_str(), xar);
6742 }
6743
6744 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
6745 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
6746 if (std::error_code EC = FileOrErr.getError()) {
6747 WithColor::error(errs(), "llvm-objdump") << EC.message() << "\n";
6748 return;
6749 }
6750 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
6751
6752 if (!XarMemberName.empty())
6753 outs() << "In xar member " << XarMemberName << ": ";
6754 else
6755 outs() << "For (__LLVM,__bundle) section: ";
6756 outs() << "xar table of contents:\n";
6757 outs() << Buffer->getBuffer() << "\n";
6758
6759 // TODO: Go through the xar's files.
6760 ScopedXarIter xi;
6761 if(!xi){
6762 WithColor::error(errs(), "llvm-objdump")
6763 << "can't obtain an xar iterator for xar archive "
6764 << XarFilename.c_str() << "\n";
6765 return;
6766 }
6767 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
6768 const char *key;
6769 const char *member_name, *member_type, *member_size_string;
6770 size_t member_size;
6771
6772 ScopedXarIter xp;
6773 if(!xp){
6774 WithColor::error(errs(), "llvm-objdump")
6775 << "can't obtain an xar iterator for xar archive "
6776 << XarFilename.c_str() << "\n";
6777 return;
6778 }
6779 member_name = NULL;
6780 member_type = NULL;
6781 member_size_string = NULL;
6782 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
6783 const char *val = nullptr;
6784 xar_prop_get(xf, key, &val);
6785 #if 0 // Useful for debugging.
6786 outs() << "key: " << key << " value: " << val << "\n";
6787 #endif
6788 if (strcmp(key, "name") == 0)
6789 member_name = val;
6790 if (strcmp(key, "type") == 0)
6791 member_type = val;
6792 if (strcmp(key, "data/size") == 0)
6793 member_size_string = val;
6794 }
6795 /*
6796 * If we find a file with a name, date/size and type properties
6797 * and with the type being "file" see if that is a xar file.
6798 */
6799 if (member_name != NULL && member_type != NULL &&
6800 strcmp(member_type, "file") == 0 &&
6801 member_size_string != NULL){
6802 // Extract the file into a buffer.
6803 char *endptr;
6804 member_size = strtoul(member_size_string, &endptr, 10);
6805 if (*endptr == '\0' && member_size != 0) {
6806 char *buffer;
6807 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6808 #if 0 // Useful for debugging.
6809 outs() << "xar member: " << member_name << " extracted\n";
6810 #endif
6811 // Set the XarMemberName we want to see printed in the header.
6812 std::string OldXarMemberName;
6813 // If XarMemberName is already set this is nested. So
6814 // save the old name and create the nested name.
6815 if (!XarMemberName.empty()) {
6816 OldXarMemberName = XarMemberName;
6817 XarMemberName =
6818 (Twine("[") + XarMemberName + "]" + member_name).str();
6819 } else {
6820 OldXarMemberName = "";
6821 XarMemberName = member_name;
6822 }
6823 // See if this is could be a xar file (nested).
6824 if (member_size >= sizeof(struct xar_header)) {
6825 #if 0 // Useful for debugging.
6826 outs() << "could be a xar file: " << member_name << "\n";
6827 #endif
6828 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6829 if (sys::IsLittleEndianHost)
6830 swapStruct(XarHeader);
6831 if (XarHeader.magic == XAR_HEADER_MAGIC)
6832 DumpBitcodeSection(O, buffer, member_size, verbose,
6833 PrintXarHeader, PrintXarFileHeaders,
6834 XarMemberName);
6835 }
6836 XarMemberName = OldXarMemberName;
6837 delete buffer;
6838 }
6839 }
6840 }
6841 }
6842 }
6843 #endif // defined(HAVE_LIBXAR)
6844
printObjcMetaData(MachOObjectFile * O,bool verbose)6845 static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6846 if (O->is64Bit())
6847 printObjc2_64bit_MetaData(O, verbose);
6848 else {
6849 MachO::mach_header H;
6850 H = O->getHeader();
6851 if (H.cputype == MachO::CPU_TYPE_ARM)
6852 printObjc2_32bit_MetaData(O, verbose);
6853 else {
6854 // This is the 32-bit non-arm cputype case. Which is normally
6855 // the first Objective-C ABI. But it may be the case of a
6856 // binary for the iOS simulator which is the second Objective-C
6857 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6858 // and return false.
6859 if (!printObjc1_32bit_MetaData(O, verbose))
6860 printObjc2_32bit_MetaData(O, verbose);
6861 }
6862 }
6863 }
6864
6865 // GuessLiteralPointer returns a string which for the item in the Mach-O file
6866 // for the address passed in as ReferenceValue for printing as a comment with
6867 // the instruction and also returns the corresponding type of that item
6868 // indirectly through ReferenceType.
6869 //
6870 // If ReferenceValue is an address of literal cstring then a pointer to the
6871 // cstring is returned and ReferenceType is set to
6872 // LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6873 //
6874 // If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6875 // Class ref that name is returned and the ReferenceType is set accordingly.
6876 //
6877 // Lastly, literals which are Symbol address in a literal pool are looked for
6878 // and if found the symbol name is returned and ReferenceType is set to
6879 // LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6880 //
6881 // If there is no item in the Mach-O file for the address passed in as
6882 // ReferenceValue nullptr is returned and ReferenceType is unchanged.
GuessLiteralPointer(uint64_t ReferenceValue,uint64_t ReferencePC,uint64_t * ReferenceType,struct DisassembleInfo * info)6883 static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6884 uint64_t ReferencePC,
6885 uint64_t *ReferenceType,
6886 struct DisassembleInfo *info) {
6887 // First see if there is an external relocation entry at the ReferencePC.
6888 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6889 uint64_t sect_addr = info->S.getAddress();
6890 uint64_t sect_offset = ReferencePC - sect_addr;
6891 bool reloc_found = false;
6892 DataRefImpl Rel;
6893 MachO::any_relocation_info RE;
6894 bool isExtern = false;
6895 SymbolRef Symbol;
6896 for (const RelocationRef &Reloc : info->S.relocations()) {
6897 uint64_t RelocOffset = Reloc.getOffset();
6898 if (RelocOffset == sect_offset) {
6899 Rel = Reloc.getRawDataRefImpl();
6900 RE = info->O->getRelocation(Rel);
6901 if (info->O->isRelocationScattered(RE))
6902 continue;
6903 isExtern = info->O->getPlainRelocationExternal(RE);
6904 if (isExtern) {
6905 symbol_iterator RelocSym = Reloc.getSymbol();
6906 Symbol = *RelocSym;
6907 }
6908 reloc_found = true;
6909 break;
6910 }
6911 }
6912 // If there is an external relocation entry for a symbol in a section
6913 // then used that symbol's value for the value of the reference.
6914 if (reloc_found && isExtern) {
6915 if (info->O->getAnyRelocationPCRel(RE)) {
6916 unsigned Type = info->O->getAnyRelocationType(RE);
6917 if (Type == MachO::X86_64_RELOC_SIGNED) {
6918 ReferenceValue = cantFail(Symbol.getValue());
6919 }
6920 }
6921 }
6922 }
6923
6924 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6925 // Message refs and Class refs.
6926 bool classref, selref, msgref, cfstring;
6927 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6928 selref, msgref, cfstring);
6929 if (classref && pointer_value == 0) {
6930 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6931 // And the pointer_value in that section is typically zero as it will be
6932 // set by dyld as part of the "bind information".
6933 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6934 if (name != nullptr) {
6935 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6936 const char *class_name = strrchr(name, '$');
6937 if (class_name != nullptr && class_name[1] == '_' &&
6938 class_name[2] != '\0') {
6939 info->class_name = class_name + 2;
6940 return name;
6941 }
6942 }
6943 }
6944
6945 if (classref) {
6946 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6947 const char *name =
6948 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6949 if (name != nullptr)
6950 info->class_name = name;
6951 else
6952 name = "bad class ref";
6953 return name;
6954 }
6955
6956 if (cfstring) {
6957 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6958 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6959 return name;
6960 }
6961
6962 if (selref && pointer_value == 0)
6963 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6964
6965 if (pointer_value != 0)
6966 ReferenceValue = pointer_value;
6967
6968 const char *name = GuessCstringPointer(ReferenceValue, info);
6969 if (name) {
6970 if (pointer_value != 0 && selref) {
6971 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6972 info->selector_name = name;
6973 } else if (pointer_value != 0 && msgref) {
6974 info->class_name = nullptr;
6975 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6976 info->selector_name = name;
6977 } else
6978 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6979 return name;
6980 }
6981
6982 // Lastly look for an indirect symbol with this ReferenceValue which is in
6983 // a literal pool. If found return that symbol name.
6984 name = GuessIndirectSymbol(ReferenceValue, info);
6985 if (name) {
6986 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6987 return name;
6988 }
6989
6990 return nullptr;
6991 }
6992
6993 // SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6994 // the Symbolizer. It looks up the ReferenceValue using the info passed via the
6995 // pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6996 // is created and returns the symbol name that matches the ReferenceValue or
6997 // nullptr if none. The ReferenceType is passed in for the IN type of
6998 // reference the instruction is making from the values in defined in the header
6999 // "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
7000 // Out type and the ReferenceName will also be set which is added as a comment
7001 // to the disassembled instruction.
7002 //
7003 // If the symbol name is a C++ mangled name then the demangled name is
7004 // returned through ReferenceName and ReferenceType is set to
7005 // LLVMDisassembler_ReferenceType_DeMangled_Name .
7006 //
7007 // When this is called to get a symbol name for a branch target then the
7008 // ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7009 // SymbolValue will be looked for in the indirect symbol table to determine if
7010 // it is an address for a symbol stub. If so then the symbol name for that
7011 // stub is returned indirectly through ReferenceName and then ReferenceType is
7012 // set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7013 //
7014 // When this is called with an value loaded via a PC relative load then
7015 // ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7016 // SymbolValue is checked to be an address of literal pointer, symbol pointer,
7017 // or an Objective-C meta data reference. If so the output ReferenceType is
7018 // set to correspond to that as well as setting the ReferenceName.
SymbolizerSymbolLookUp(void * DisInfo,uint64_t ReferenceValue,uint64_t * ReferenceType,uint64_t ReferencePC,const char ** ReferenceName)7019 static const char *SymbolizerSymbolLookUp(void *DisInfo,
7020 uint64_t ReferenceValue,
7021 uint64_t *ReferenceType,
7022 uint64_t ReferencePC,
7023 const char **ReferenceName) {
7024 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7025 // If no verbose symbolic information is wanted then just return nullptr.
7026 if (!info->verbose) {
7027 *ReferenceName = nullptr;
7028 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7029 return nullptr;
7030 }
7031
7032 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
7033
7034 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7035 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7036 if (*ReferenceName != nullptr) {
7037 method_reference(info, ReferenceType, ReferenceName);
7038 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7039 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7040 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7041 if (info->demangled_name != nullptr)
7042 free(info->demangled_name);
7043 int status;
7044 info->demangled_name =
7045 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7046 if (info->demangled_name != nullptr) {
7047 *ReferenceName = info->demangled_name;
7048 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7049 } else
7050 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7051 } else
7052 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7053 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7054 *ReferenceName =
7055 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7056 if (*ReferenceName)
7057 method_reference(info, ReferenceType, ReferenceName);
7058 else
7059 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7060 // If this is arm64 and the reference is an adrp instruction save the
7061 // instruction, passed in ReferenceValue and the address of the instruction
7062 // for use later if we see and add immediate instruction.
7063 } else if (info->O->getArch() == Triple::aarch64 &&
7064 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7065 info->adrp_inst = ReferenceValue;
7066 info->adrp_addr = ReferencePC;
7067 SymbolName = nullptr;
7068 *ReferenceName = nullptr;
7069 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7070 // If this is arm64 and reference is an add immediate instruction and we
7071 // have
7072 // seen an adrp instruction just before it and the adrp's Xd register
7073 // matches
7074 // this add's Xn register reconstruct the value being referenced and look to
7075 // see if it is a literal pointer. Note the add immediate instruction is
7076 // passed in ReferenceValue.
7077 } else if (info->O->getArch() == Triple::aarch64 &&
7078 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7079 ReferencePC - 4 == info->adrp_addr &&
7080 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7081 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7082 uint32_t addxri_inst;
7083 uint64_t adrp_imm, addxri_imm;
7084
7085 adrp_imm =
7086 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7087 if (info->adrp_inst & 0x0200000)
7088 adrp_imm |= 0xfffffffffc000000LL;
7089
7090 addxri_inst = ReferenceValue;
7091 addxri_imm = (addxri_inst >> 10) & 0xfff;
7092 if (((addxri_inst >> 22) & 0x3) == 1)
7093 addxri_imm <<= 12;
7094
7095 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7096 (adrp_imm << 12) + addxri_imm;
7097
7098 *ReferenceName =
7099 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7100 if (*ReferenceName == nullptr)
7101 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7102 // If this is arm64 and the reference is a load register instruction and we
7103 // have seen an adrp instruction just before it and the adrp's Xd register
7104 // matches this add's Xn register reconstruct the value being referenced and
7105 // look to see if it is a literal pointer. Note the load register
7106 // instruction is passed in ReferenceValue.
7107 } else if (info->O->getArch() == Triple::aarch64 &&
7108 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7109 ReferencePC - 4 == info->adrp_addr &&
7110 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7111 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7112 uint32_t ldrxui_inst;
7113 uint64_t adrp_imm, ldrxui_imm;
7114
7115 adrp_imm =
7116 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7117 if (info->adrp_inst & 0x0200000)
7118 adrp_imm |= 0xfffffffffc000000LL;
7119
7120 ldrxui_inst = ReferenceValue;
7121 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7122
7123 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7124 (adrp_imm << 12) + (ldrxui_imm << 3);
7125
7126 *ReferenceName =
7127 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7128 if (*ReferenceName == nullptr)
7129 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7130 }
7131 // If this arm64 and is an load register (PC-relative) instruction the
7132 // ReferenceValue is the PC plus the immediate value.
7133 else if (info->O->getArch() == Triple::aarch64 &&
7134 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7135 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7136 *ReferenceName =
7137 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7138 if (*ReferenceName == nullptr)
7139 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7140 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
7141 if (info->demangled_name != nullptr)
7142 free(info->demangled_name);
7143 int status;
7144 info->demangled_name =
7145 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
7146 if (info->demangled_name != nullptr) {
7147 *ReferenceName = info->demangled_name;
7148 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7149 }
7150 }
7151 else {
7152 *ReferenceName = nullptr;
7153 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7154 }
7155
7156 return SymbolName;
7157 }
7158
7159 /// Emits the comments that are stored in the CommentStream.
7160 /// Each comment in the CommentStream must end with a newline.
emitComments(raw_svector_ostream & CommentStream,SmallString<128> & CommentsToEmit,formatted_raw_ostream & FormattedOS,const MCAsmInfo & MAI)7161 static void emitComments(raw_svector_ostream &CommentStream,
7162 SmallString<128> &CommentsToEmit,
7163 formatted_raw_ostream &FormattedOS,
7164 const MCAsmInfo &MAI) {
7165 // Flush the stream before taking its content.
7166 StringRef Comments = CommentsToEmit.str();
7167 // Get the default information for printing a comment.
7168 StringRef CommentBegin = MAI.getCommentString();
7169 unsigned CommentColumn = MAI.getCommentColumn();
7170 bool IsFirst = true;
7171 while (!Comments.empty()) {
7172 if (!IsFirst)
7173 FormattedOS << '\n';
7174 // Emit a line of comments.
7175 FormattedOS.PadToColumn(CommentColumn);
7176 size_t Position = Comments.find('\n');
7177 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
7178 // Move after the newline character.
7179 Comments = Comments.substr(Position + 1);
7180 IsFirst = false;
7181 }
7182 FormattedOS.flush();
7183
7184 // Tell the comment stream that the vector changed underneath it.
7185 CommentsToEmit.clear();
7186 }
7187
DisassembleMachO(StringRef Filename,MachOObjectFile * MachOOF,StringRef DisSegName,StringRef DisSectName)7188 static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7189 StringRef DisSegName, StringRef DisSectName) {
7190 const char *McpuDefault = nullptr;
7191 const Target *ThumbTarget = nullptr;
7192 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
7193 if (!TheTarget) {
7194 // GetTarget prints out stuff.
7195 return;
7196 }
7197 std::string MachOMCPU;
7198 if (MCPU.empty() && McpuDefault)
7199 MachOMCPU = McpuDefault;
7200 else
7201 MachOMCPU = MCPU;
7202
7203 #define CHECK_TARGET_INFO_CREATION(NAME) \
7204 do { \
7205 if (!NAME) { \
7206 WithColor::error(errs(), "llvm-objdump") \
7207 << "couldn't initialize disassembler for target " << TripleName \
7208 << '\n'; \
7209 return; \
7210 } \
7211 } while (false)
7212 #define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \
7213 do { \
7214 if (!NAME) { \
7215 WithColor::error(errs(), "llvm-objdump") \
7216 << "couldn't initialize disassembler for target " << ThumbTripleName \
7217 << '\n'; \
7218 return; \
7219 } \
7220 } while (false)
7221
7222 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7223 CHECK_TARGET_INFO_CREATION(InstrInfo);
7224 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7225 if (ThumbTarget) {
7226 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
7227 CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7228 }
7229
7230 // Package up features to be passed to target/subtarget
7231 std::string FeaturesStr;
7232 if (!MAttrs.empty()) {
7233 SubtargetFeatures Features;
7234 for (unsigned i = 0; i != MAttrs.size(); ++i)
7235 Features.AddFeature(MAttrs[i]);
7236 FeaturesStr = Features.getString();
7237 }
7238
7239 MCTargetOptions MCOptions;
7240 // Set up disassembler.
7241 std::unique_ptr<const MCRegisterInfo> MRI(
7242 TheTarget->createMCRegInfo(TripleName));
7243 CHECK_TARGET_INFO_CREATION(MRI);
7244 std::unique_ptr<const MCAsmInfo> AsmInfo(
7245 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
7246 CHECK_TARGET_INFO_CREATION(AsmInfo);
7247 std::unique_ptr<const MCSubtargetInfo> STI(
7248 TheTarget->createMCSubtargetInfo(TripleName, MachOMCPU, FeaturesStr));
7249 CHECK_TARGET_INFO_CREATION(STI);
7250 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
7251 std::unique_ptr<MCDisassembler> DisAsm(
7252 TheTarget->createMCDisassembler(*STI, Ctx));
7253 CHECK_TARGET_INFO_CREATION(DisAsm);
7254 std::unique_ptr<MCSymbolizer> Symbolizer;
7255 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7256 std::unique_ptr<MCRelocationInfo> RelInfo(
7257 TheTarget->createMCRelocationInfo(TripleName, Ctx));
7258 if (RelInfo) {
7259 Symbolizer.reset(TheTarget->createMCSymbolizer(
7260 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7261 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
7262 DisAsm->setSymbolizer(std::move(Symbolizer));
7263 }
7264 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7265 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7266 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
7267 CHECK_TARGET_INFO_CREATION(IP);
7268 // Set the display preference for hex vs. decimal immediates.
7269 IP->setPrintImmHex(PrintImmHex);
7270 // Comment stream and backing vector.
7271 SmallString<128> CommentsToEmit;
7272 raw_svector_ostream CommentStream(CommentsToEmit);
7273 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7274 // if it is done then arm64 comments for string literals don't get printed
7275 // and some constant get printed instead and not setting it causes intel
7276 // (32-bit and 64-bit) comments printed with different spacing before the
7277 // comment causing different diffs with the 'C' disassembler library API.
7278 // IP->setCommentStream(CommentStream);
7279
7280 // Set up separate thumb disassembler if needed.
7281 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7282 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7283 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7284 std::unique_ptr<MCDisassembler> ThumbDisAsm;
7285 std::unique_ptr<MCInstPrinter> ThumbIP;
7286 std::unique_ptr<MCContext> ThumbCtx;
7287 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7288 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7289 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7290 if (ThumbTarget) {
7291 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
7292 CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7293 ThumbAsmInfo.reset(
7294 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName, MCOptions));
7295 CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7296 ThumbSTI.reset(
7297 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MachOMCPU,
7298 FeaturesStr));
7299 CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7300 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
7301 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
7302 CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7303 MCContext *PtrThumbCtx = ThumbCtx.get();
7304 ThumbRelInfo.reset(
7305 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
7306 if (ThumbRelInfo) {
7307 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
7308 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
7309 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
7310 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7311 }
7312 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7313 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
7314 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
7315 *ThumbInstrInfo, *ThumbMRI));
7316 CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7317 // Set the display preference for hex vs. decimal immediates.
7318 ThumbIP->setPrintImmHex(PrintImmHex);
7319 }
7320
7321 #undef CHECK_TARGET_INFO_CREATION
7322 #undef CHECK_THUMB_TARGET_INFO_CREATION
7323
7324 MachO::mach_header Header = MachOOF->getHeader();
7325
7326 // FIXME: Using the -cfg command line option, this code used to be able to
7327 // annotate relocations with the referenced symbol's name, and if this was
7328 // inside a __[cf]string section, the data it points to. This is now replaced
7329 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7330 std::vector<SectionRef> Sections;
7331 std::vector<SymbolRef> Symbols;
7332 SmallVector<uint64_t, 8> FoundFns;
7333 uint64_t BaseSegmentAddress = 0;
7334
7335 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
7336 BaseSegmentAddress);
7337
7338 // Sort the symbols by address, just in case they didn't come in that way.
7339 llvm::sort(Symbols, SymbolSorter());
7340
7341 // Build a data in code table that is sorted on by the address of each entry.
7342 uint64_t BaseAddress = 0;
7343 if (Header.filetype == MachO::MH_OBJECT)
7344 BaseAddress = Sections[0].getAddress();
7345 else
7346 BaseAddress = BaseSegmentAddress;
7347 DiceTable Dices;
7348 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7349 DI != DE; ++DI) {
7350 uint32_t Offset;
7351 DI->getOffset(Offset);
7352 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
7353 }
7354 array_pod_sort(Dices.begin(), Dices.end());
7355
7356 // Try to find debug info and set up the DIContext for it.
7357 std::unique_ptr<DIContext> diContext;
7358 std::unique_ptr<Binary> DSYMBinary;
7359 std::unique_ptr<MemoryBuffer> DSYMBuf;
7360 if (UseDbg) {
7361 ObjectFile *DbgObj = MachOOF;
7362
7363 // A separate DSym file path was specified, parse it as a macho file,
7364 // get the sections and supply it to the section name parsing machinery.
7365 if (!DSYMFile.empty()) {
7366 std::string DSYMPath(DSYMFile);
7367
7368 // If DSYMPath is a .dSYM directory, append the Mach-O file.
7369 if (llvm::sys::fs::is_directory(DSYMPath) &&
7370 llvm::sys::path::extension(DSYMPath) == ".dSYM") {
7371 SmallString<128> ShortName(llvm::sys::path::filename(DSYMPath));
7372 llvm::sys::path::replace_extension(ShortName, "");
7373 SmallString<1024> FullPath(DSYMPath);
7374 llvm::sys::path::append(FullPath, "Contents", "Resources", "DWARF",
7375 ShortName);
7376 DSYMPath = std::string(FullPath.str());
7377 }
7378
7379 // Load the file.
7380 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7381 MemoryBuffer::getFileOrSTDIN(DSYMPath);
7382 if (std::error_code EC = BufOrErr.getError()) {
7383 reportError(errorCodeToError(EC), DSYMPath);
7384 return;
7385 }
7386
7387 // We need to keep the file alive, because we're replacing DbgObj with it.
7388 DSYMBuf = std::move(BufOrErr.get());
7389
7390 Expected<std::unique_ptr<Binary>> BinaryOrErr =
7391 createBinary(DSYMBuf.get()->getMemBufferRef());
7392 if (!BinaryOrErr) {
7393 reportError(BinaryOrErr.takeError(), DSYMPath);
7394 return;
7395 }
7396
7397 // We need to keep the Binary alive with the buffer
7398 DSYMBinary = std::move(BinaryOrErr.get());
7399 if (ObjectFile *O = dyn_cast<ObjectFile>(DSYMBinary.get())) {
7400 // this is a Mach-O object file, use it
7401 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(&*O)) {
7402 DbgObj = MachDSYM;
7403 }
7404 else {
7405 WithColor::error(errs(), "llvm-objdump")
7406 << DSYMPath << " is not a Mach-O file type.\n";
7407 return;
7408 }
7409 }
7410 else if (auto UB = dyn_cast<MachOUniversalBinary>(DSYMBinary.get())){
7411 // this is a Universal Binary, find a Mach-O for this architecture
7412 uint32_t CPUType, CPUSubType;
7413 const char *ArchFlag;
7414 if (MachOOF->is64Bit()) {
7415 const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7416 CPUType = H_64.cputype;
7417 CPUSubType = H_64.cpusubtype;
7418 } else {
7419 const MachO::mach_header H = MachOOF->getHeader();
7420 CPUType = H.cputype;
7421 CPUSubType = H.cpusubtype;
7422 }
7423 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, nullptr,
7424 &ArchFlag);
7425 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7426 UB->getMachOObjectForArch(ArchFlag);
7427 if (!MachDSYM) {
7428 reportError(MachDSYM.takeError(), DSYMPath);
7429 return;
7430 }
7431
7432 // We need to keep the Binary alive with the buffer
7433 DbgObj = &*MachDSYM.get();
7434 DSYMBinary = std::move(*MachDSYM);
7435 }
7436 else {
7437 WithColor::error(errs(), "llvm-objdump")
7438 << DSYMPath << " is not a Mach-O or Universal file type.\n";
7439 return;
7440 }
7441 }
7442
7443 // Setup the DIContext
7444 diContext = DWARFContext::create(*DbgObj);
7445 }
7446
7447 if (FilterSections.empty())
7448 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7449
7450 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7451 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7452 if (!SecNameOrErr) {
7453 consumeError(SecNameOrErr.takeError());
7454 continue;
7455 }
7456 if (*SecNameOrErr != DisSectName)
7457 continue;
7458
7459 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7460
7461 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
7462 if (SegmentName != DisSegName)
7463 continue;
7464
7465 StringRef BytesStr =
7466 unwrapOrError(Sections[SectIdx].getContents(), Filename);
7467 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(BytesStr);
7468 uint64_t SectAddress = Sections[SectIdx].getAddress();
7469
7470 bool symbolTableWorked = false;
7471
7472 // Create a map of symbol addresses to symbol names for use by
7473 // the SymbolizerSymbolLookUp() routine.
7474 SymbolAddressMap AddrMap;
7475 bool DisSymNameFound = false;
7476 for (const SymbolRef &Symbol : MachOOF->symbols()) {
7477 SymbolRef::Type ST =
7478 unwrapOrError(Symbol.getType(), MachOOF->getFileName());
7479 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7480 ST == SymbolRef::ST_Other) {
7481 uint64_t Address = cantFail(Symbol.getValue());
7482 StringRef SymName =
7483 unwrapOrError(Symbol.getName(), MachOOF->getFileName());
7484 AddrMap[Address] = SymName;
7485 if (!DisSymName.empty() && DisSymName == SymName)
7486 DisSymNameFound = true;
7487 }
7488 }
7489 if (!DisSymName.empty() && !DisSymNameFound) {
7490 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7491 return;
7492 }
7493 // Set up the block of info used by the Symbolizer call backs.
7494 SymbolizerInfo.verbose = !NoSymbolicOperands;
7495 SymbolizerInfo.O = MachOOF;
7496 SymbolizerInfo.S = Sections[SectIdx];
7497 SymbolizerInfo.AddrMap = &AddrMap;
7498 SymbolizerInfo.Sections = &Sections;
7499 // Same for the ThumbSymbolizer
7500 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
7501 ThumbSymbolizerInfo.O = MachOOF;
7502 ThumbSymbolizerInfo.S = Sections[SectIdx];
7503 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7504 ThumbSymbolizerInfo.Sections = &Sections;
7505
7506 unsigned int Arch = MachOOF->getArch();
7507
7508 // Skip all symbols if this is a stubs file.
7509 if (Bytes.empty())
7510 return;
7511
7512 // If the section has symbols but no symbol at the start of the section
7513 // these are used to make sure the bytes before the first symbol are
7514 // disassembled.
7515 bool FirstSymbol = true;
7516 bool FirstSymbolAtSectionStart = true;
7517
7518 // Disassemble symbol by symbol.
7519 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7520 StringRef SymName =
7521 unwrapOrError(Symbols[SymIdx].getName(), MachOOF->getFileName());
7522 SymbolRef::Type ST =
7523 unwrapOrError(Symbols[SymIdx].getType(), MachOOF->getFileName());
7524 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7525 continue;
7526
7527 // Make sure the symbol is defined in this section.
7528 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
7529 if (!containsSym) {
7530 if (!DisSymName.empty() && DisSymName == SymName) {
7531 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7532 return;
7533 }
7534 continue;
7535 }
7536 // The __mh_execute_header is special and we need to deal with that fact
7537 // this symbol is before the start of the (__TEXT,__text) section and at the
7538 // address of the start of the __TEXT segment. This is because this symbol
7539 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7540 // start of the section in a standard MH_EXECUTE filetype.
7541 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7542 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7543 return;
7544 }
7545 // When this code is trying to disassemble a symbol at a time and in the
7546 // case there is only the __mh_execute_header symbol left as in a stripped
7547 // executable, we need to deal with this by ignoring this symbol so the
7548 // whole section is disassembled and this symbol is then not displayed.
7549 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7550 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7551 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7552 continue;
7553
7554 // If we are only disassembling one symbol see if this is that symbol.
7555 if (!DisSymName.empty() && DisSymName != SymName)
7556 continue;
7557
7558 // Start at the address of the symbol relative to the section's address.
7559 uint64_t SectSize = Sections[SectIdx].getSize();
7560 uint64_t Start = cantFail(Symbols[SymIdx].getValue());
7561 uint64_t SectionAddress = Sections[SectIdx].getAddress();
7562 Start -= SectionAddress;
7563
7564 if (Start > SectSize) {
7565 outs() << "section data ends, " << SymName
7566 << " lies outside valid range\n";
7567 return;
7568 }
7569
7570 // Stop disassembling either at the beginning of the next symbol or at
7571 // the end of the section.
7572 bool containsNextSym = false;
7573 uint64_t NextSym = 0;
7574 uint64_t NextSymIdx = SymIdx + 1;
7575 while (Symbols.size() > NextSymIdx) {
7576 SymbolRef::Type NextSymType = unwrapOrError(
7577 Symbols[NextSymIdx].getType(), MachOOF->getFileName());
7578 if (NextSymType == SymbolRef::ST_Function) {
7579 containsNextSym =
7580 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
7581 NextSym = cantFail(Symbols[NextSymIdx].getValue());
7582 NextSym -= SectionAddress;
7583 break;
7584 }
7585 ++NextSymIdx;
7586 }
7587
7588 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
7589 uint64_t Size;
7590
7591 symbolTableWorked = true;
7592
7593 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7594 uint32_t SymbolFlags = cantFail(MachOOF->getSymbolFlags(Symb));
7595 bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7596
7597 // We only need the dedicated Thumb target if there's a real choice
7598 // (i.e. we're not targeting M-class) and the function is Thumb.
7599 bool UseThumbTarget = IsThumb && ThumbTarget;
7600
7601 // If we are not specifying a symbol to start disassembly with and this
7602 // is the first symbol in the section but not at the start of the section
7603 // then move the disassembly index to the start of the section and
7604 // don't print the symbol name just yet. This is so the bytes before the
7605 // first symbol are disassembled.
7606 uint64_t SymbolStart = Start;
7607 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7608 FirstSymbolAtSectionStart = false;
7609 Start = 0;
7610 }
7611 else
7612 outs() << SymName << ":\n";
7613
7614 DILineInfo lastLine;
7615 for (uint64_t Index = Start; Index < End; Index += Size) {
7616 MCInst Inst;
7617
7618 // If this is the first symbol in the section and it was not at the
7619 // start of the section, see if we are at its Index now and if so print
7620 // the symbol name.
7621 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7622 outs() << SymName << ":\n";
7623
7624 uint64_t PC = SectAddress + Index;
7625 if (!NoLeadingAddr) {
7626 if (FullLeadingAddr) {
7627 if (MachOOF->is64Bit())
7628 outs() << format("%016" PRIx64, PC);
7629 else
7630 outs() << format("%08" PRIx64, PC);
7631 } else {
7632 outs() << format("%8" PRIx64 ":", PC);
7633 }
7634 }
7635 if (!NoShowRawInsn || Arch == Triple::arm)
7636 outs() << "\t";
7637
7638 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, Size))
7639 continue;
7640
7641 SmallVector<char, 64> AnnotationsBytes;
7642 raw_svector_ostream Annotations(AnnotationsBytes);
7643
7644 bool gotInst;
7645 if (UseThumbTarget)
7646 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
7647 PC, Annotations);
7648 else
7649 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
7650 Annotations);
7651 if (gotInst) {
7652 if (!NoShowRawInsn || Arch == Triple::arm) {
7653 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
7654 }
7655 formatted_raw_ostream FormattedOS(outs());
7656 StringRef AnnotationsStr = Annotations.str();
7657 if (UseThumbTarget)
7658 ThumbIP->printInst(&Inst, PC, AnnotationsStr, *ThumbSTI,
7659 FormattedOS);
7660 else
7661 IP->printInst(&Inst, PC, AnnotationsStr, *STI, FormattedOS);
7662 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
7663
7664 // Print debug info.
7665 if (diContext) {
7666 DILineInfo dli = diContext->getLineInfoForAddress({PC, SectIdx});
7667 // Print valid line info if it changed.
7668 if (dli != lastLine && dli.Line != 0)
7669 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7670 << dli.Column;
7671 lastLine = dli;
7672 }
7673 outs() << "\n";
7674 } else {
7675 if (MachOOF->getArchTriple().isX86()) {
7676 outs() << format("\t.byte 0x%02x #bad opcode\n",
7677 *(Bytes.data() + Index) & 0xff);
7678 Size = 1; // skip exactly one illegible byte and move on.
7679 } else if (Arch == Triple::aarch64 ||
7680 (Arch == Triple::arm && !IsThumb)) {
7681 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7682 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7683 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7684 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7685 outs() << format("\t.long\t0x%08x\n", opcode);
7686 Size = 4;
7687 } else if (Arch == Triple::arm) {
7688 assert(IsThumb && "ARM mode should have been dealt with above");
7689 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7690 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7691 outs() << format("\t.short\t0x%04x\n", opcode);
7692 Size = 2;
7693 } else{
7694 WithColor::warning(errs(), "llvm-objdump")
7695 << "invalid instruction encoding\n";
7696 if (Size == 0)
7697 Size = 1; // skip illegible bytes
7698 }
7699 }
7700 }
7701 // Now that we are done disassembled the first symbol set the bool that
7702 // were doing this to false.
7703 FirstSymbol = false;
7704 }
7705 if (!symbolTableWorked) {
7706 // Reading the symbol table didn't work, disassemble the whole section.
7707 uint64_t SectAddress = Sections[SectIdx].getAddress();
7708 uint64_t SectSize = Sections[SectIdx].getSize();
7709 uint64_t InstSize;
7710 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7711 MCInst Inst;
7712
7713 uint64_t PC = SectAddress + Index;
7714
7715 if (DumpAndSkipDataInCode(PC, Bytes.data() + Index, Dices, InstSize))
7716 continue;
7717
7718 SmallVector<char, 64> AnnotationsBytes;
7719 raw_svector_ostream Annotations(AnnotationsBytes);
7720 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
7721 Annotations)) {
7722 if (!NoLeadingAddr) {
7723 if (FullLeadingAddr) {
7724 if (MachOOF->is64Bit())
7725 outs() << format("%016" PRIx64, PC);
7726 else
7727 outs() << format("%08" PRIx64, PC);
7728 } else {
7729 outs() << format("%8" PRIx64 ":", PC);
7730 }
7731 }
7732 if (!NoShowRawInsn || Arch == Triple::arm) {
7733 outs() << "\t";
7734 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
7735 }
7736 StringRef AnnotationsStr = Annotations.str();
7737 IP->printInst(&Inst, PC, AnnotationsStr, *STI, outs());
7738 outs() << "\n";
7739 } else {
7740 if (MachOOF->getArchTriple().isX86()) {
7741 outs() << format("\t.byte 0x%02x #bad opcode\n",
7742 *(Bytes.data() + Index) & 0xff);
7743 InstSize = 1; // skip exactly one illegible byte and move on.
7744 } else {
7745 WithColor::warning(errs(), "llvm-objdump")
7746 << "invalid instruction encoding\n";
7747 if (InstSize == 0)
7748 InstSize = 1; // skip illegible bytes
7749 }
7750 }
7751 }
7752 }
7753 // The TripleName's need to be reset if we are called again for a different
7754 // architecture.
7755 TripleName = "";
7756 ThumbTripleName = "";
7757
7758 if (SymbolizerInfo.demangled_name != nullptr)
7759 free(SymbolizerInfo.demangled_name);
7760 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7761 free(ThumbSymbolizerInfo.demangled_name);
7762 }
7763 }
7764
7765 //===----------------------------------------------------------------------===//
7766 // __compact_unwind section dumping
7767 //===----------------------------------------------------------------------===//
7768
7769 namespace {
7770
7771 template <typename T>
read(StringRef Contents,ptrdiff_t Offset)7772 static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7773 using llvm::support::little;
7774 using llvm::support::unaligned;
7775
7776 if (Offset + sizeof(T) > Contents.size()) {
7777 outs() << "warning: attempt to read past end of buffer\n";
7778 return T();
7779 }
7780
7781 uint64_t Val =
7782 support::endian::read<T, little, unaligned>(Contents.data() + Offset);
7783 return Val;
7784 }
7785
7786 template <typename T>
readNext(StringRef Contents,ptrdiff_t & Offset)7787 static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7788 T Val = read<T>(Contents, Offset);
7789 Offset += sizeof(T);
7790 return Val;
7791 }
7792
7793 struct CompactUnwindEntry {
7794 uint32_t OffsetInSection;
7795
7796 uint64_t FunctionAddr;
7797 uint32_t Length;
7798 uint32_t CompactEncoding;
7799 uint64_t PersonalityAddr;
7800 uint64_t LSDAAddr;
7801
7802 RelocationRef FunctionReloc;
7803 RelocationRef PersonalityReloc;
7804 RelocationRef LSDAReloc;
7805
CompactUnwindEntry__anon30756ae00b11::CompactUnwindEntry7806 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7807 : OffsetInSection(Offset) {
7808 if (Is64)
7809 read<uint64_t>(Contents, Offset);
7810 else
7811 read<uint32_t>(Contents, Offset);
7812 }
7813
7814 private:
read__anon30756ae00b11::CompactUnwindEntry7815 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7816 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7817 Length = readNext<uint32_t>(Contents, Offset);
7818 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7819 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7820 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7821 }
7822 };
7823 }
7824
7825 /// Given a relocation from __compact_unwind, consisting of the RelocationRef
7826 /// and data being relocated, determine the best base Name and Addend to use for
7827 /// display purposes.
7828 ///
7829 /// 1. An Extern relocation will directly reference a symbol (and the data is
7830 /// then already an addend), so use that.
7831 /// 2. Otherwise the data is an offset in the object file's layout; try to find
7832 // a symbol before it in the same section, and use the offset from there.
7833 /// 3. Finally, if all that fails, fall back to an offset from the start of the
7834 /// referenced section.
findUnwindRelocNameAddend(const MachOObjectFile * Obj,std::map<uint64_t,SymbolRef> & Symbols,const RelocationRef & Reloc,uint64_t Addr,StringRef & Name,uint64_t & Addend)7835 static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7836 std::map<uint64_t, SymbolRef> &Symbols,
7837 const RelocationRef &Reloc, uint64_t Addr,
7838 StringRef &Name, uint64_t &Addend) {
7839 if (Reloc.getSymbol() != Obj->symbol_end()) {
7840 Name = unwrapOrError(Reloc.getSymbol()->getName(), Obj->getFileName());
7841 Addend = Addr;
7842 return;
7843 }
7844
7845 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7846 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7847
7848 uint64_t SectionAddr = RelocSection.getAddress();
7849
7850 auto Sym = Symbols.upper_bound(Addr);
7851 if (Sym == Symbols.begin()) {
7852 // The first symbol in the object is after this reference, the best we can
7853 // do is section-relative notation.
7854 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7855 Name = *NameOrErr;
7856 else
7857 consumeError(NameOrErr.takeError());
7858
7859 Addend = Addr - SectionAddr;
7860 return;
7861 }
7862
7863 // Go back one so that SymbolAddress <= Addr.
7864 --Sym;
7865
7866 section_iterator SymSection =
7867 unwrapOrError(Sym->second.getSection(), Obj->getFileName());
7868 if (RelocSection == *SymSection) {
7869 // There's a valid symbol in the same section before this reference.
7870 Name = unwrapOrError(Sym->second.getName(), Obj->getFileName());
7871 Addend = Addr - Sym->first;
7872 return;
7873 }
7874
7875 // There is a symbol before this reference, but it's in a different
7876 // section. Probably not helpful to mention it, so use the section name.
7877 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7878 Name = *NameOrErr;
7879 else
7880 consumeError(NameOrErr.takeError());
7881
7882 Addend = Addr - SectionAddr;
7883 }
7884
printUnwindRelocDest(const MachOObjectFile * Obj,std::map<uint64_t,SymbolRef> & Symbols,const RelocationRef & Reloc,uint64_t Addr)7885 static void printUnwindRelocDest(const MachOObjectFile *Obj,
7886 std::map<uint64_t, SymbolRef> &Symbols,
7887 const RelocationRef &Reloc, uint64_t Addr) {
7888 StringRef Name;
7889 uint64_t Addend;
7890
7891 if (!Reloc.getObject())
7892 return;
7893
7894 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7895
7896 outs() << Name;
7897 if (Addend)
7898 outs() << " + " << format("0x%" PRIx64, Addend);
7899 }
7900
7901 static void
printMachOCompactUnwindSection(const MachOObjectFile * Obj,std::map<uint64_t,SymbolRef> & Symbols,const SectionRef & CompactUnwind)7902 printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7903 std::map<uint64_t, SymbolRef> &Symbols,
7904 const SectionRef &CompactUnwind) {
7905
7906 if (!Obj->isLittleEndian()) {
7907 outs() << "Skipping big-endian __compact_unwind section\n";
7908 return;
7909 }
7910
7911 bool Is64 = Obj->is64Bit();
7912 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7913 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7914
7915 StringRef Contents =
7916 unwrapOrError(CompactUnwind.getContents(), Obj->getFileName());
7917 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7918
7919 // First populate the initial raw offsets, encodings and so on from the entry.
7920 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7921 CompactUnwindEntry Entry(Contents, Offset, Is64);
7922 CompactUnwinds.push_back(Entry);
7923 }
7924
7925 // Next we need to look at the relocations to find out what objects are
7926 // actually being referred to.
7927 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7928 uint64_t RelocAddress = Reloc.getOffset();
7929
7930 uint32_t EntryIdx = RelocAddress / EntrySize;
7931 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7932 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7933
7934 if (OffsetInEntry == 0)
7935 Entry.FunctionReloc = Reloc;
7936 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7937 Entry.PersonalityReloc = Reloc;
7938 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7939 Entry.LSDAReloc = Reloc;
7940 else {
7941 outs() << "Invalid relocation in __compact_unwind section\n";
7942 return;
7943 }
7944 }
7945
7946 // Finally, we're ready to print the data we've gathered.
7947 outs() << "Contents of __compact_unwind section:\n";
7948 for (auto &Entry : CompactUnwinds) {
7949 outs() << " Entry at offset "
7950 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
7951
7952 // 1. Start of the region this entry applies to.
7953 outs() << " start: " << format("0x%" PRIx64,
7954 Entry.FunctionAddr) << ' ';
7955 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7956 outs() << '\n';
7957
7958 // 2. Length of the region this entry applies to.
7959 outs() << " length: " << format("0x%" PRIx32, Entry.Length)
7960 << '\n';
7961 // 3. The 32-bit compact encoding.
7962 outs() << " compact encoding: "
7963 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
7964
7965 // 4. The personality function, if present.
7966 if (Entry.PersonalityReloc.getObject()) {
7967 outs() << " personality function: "
7968 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
7969 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7970 Entry.PersonalityAddr);
7971 outs() << '\n';
7972 }
7973
7974 // 5. This entry's language-specific data area.
7975 if (Entry.LSDAReloc.getObject()) {
7976 outs() << " LSDA: " << format("0x%" PRIx64,
7977 Entry.LSDAAddr) << ' ';
7978 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7979 outs() << '\n';
7980 }
7981 }
7982 }
7983
7984 //===----------------------------------------------------------------------===//
7985 // __unwind_info section dumping
7986 //===----------------------------------------------------------------------===//
7987
printRegularSecondLevelUnwindPage(StringRef PageData)7988 static void printRegularSecondLevelUnwindPage(StringRef PageData) {
7989 ptrdiff_t Pos = 0;
7990 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
7991 (void)Kind;
7992 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
7993
7994 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
7995 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
7996
7997 Pos = EntriesStart;
7998 for (unsigned i = 0; i < NumEntries; ++i) {
7999 uint32_t FunctionOffset = readNext<uint32_t>(PageData, Pos);
8000 uint32_t Encoding = readNext<uint32_t>(PageData, Pos);
8001
8002 outs() << " [" << i << "]: "
8003 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8004 << ", "
8005 << "encoding=" << format("0x%08" PRIx32, Encoding) << '\n';
8006 }
8007 }
8008
printCompressedSecondLevelUnwindPage(StringRef PageData,uint32_t FunctionBase,const SmallVectorImpl<uint32_t> & CommonEncodings)8009 static void printCompressedSecondLevelUnwindPage(
8010 StringRef PageData, uint32_t FunctionBase,
8011 const SmallVectorImpl<uint32_t> &CommonEncodings) {
8012 ptrdiff_t Pos = 0;
8013 uint32_t Kind = readNext<uint32_t>(PageData, Pos);
8014 (void)Kind;
8015 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8016
8017 uint16_t EntriesStart = readNext<uint16_t>(PageData, Pos);
8018 uint16_t NumEntries = readNext<uint16_t>(PageData, Pos);
8019
8020 uint16_t EncodingsStart = readNext<uint16_t>(PageData, Pos);
8021 readNext<uint16_t>(PageData, Pos);
8022 StringRef PageEncodings = PageData.substr(EncodingsStart, StringRef::npos);
8023
8024 Pos = EntriesStart;
8025 for (unsigned i = 0; i < NumEntries; ++i) {
8026 uint32_t Entry = readNext<uint32_t>(PageData, Pos);
8027 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8028 uint32_t EncodingIdx = Entry >> 24;
8029
8030 uint32_t Encoding;
8031 if (EncodingIdx < CommonEncodings.size())
8032 Encoding = CommonEncodings[EncodingIdx];
8033 else
8034 Encoding = read<uint32_t>(PageEncodings,
8035 sizeof(uint32_t) *
8036 (EncodingIdx - CommonEncodings.size()));
8037
8038 outs() << " [" << i << "]: "
8039 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8040 << ", "
8041 << "encoding[" << EncodingIdx
8042 << "]=" << format("0x%08" PRIx32, Encoding) << '\n';
8043 }
8044 }
8045
printMachOUnwindInfoSection(const MachOObjectFile * Obj,std::map<uint64_t,SymbolRef> & Symbols,const SectionRef & UnwindInfo)8046 static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8047 std::map<uint64_t, SymbolRef> &Symbols,
8048 const SectionRef &UnwindInfo) {
8049
8050 if (!Obj->isLittleEndian()) {
8051 outs() << "Skipping big-endian __unwind_info section\n";
8052 return;
8053 }
8054
8055 outs() << "Contents of __unwind_info section:\n";
8056
8057 StringRef Contents =
8058 unwrapOrError(UnwindInfo.getContents(), Obj->getFileName());
8059 ptrdiff_t Pos = 0;
8060
8061 //===----------------------------------
8062 // Section header
8063 //===----------------------------------
8064
8065 uint32_t Version = readNext<uint32_t>(Contents, Pos);
8066 outs() << " Version: "
8067 << format("0x%" PRIx32, Version) << '\n';
8068 if (Version != 1) {
8069 outs() << " Skipping section with unknown version\n";
8070 return;
8071 }
8072
8073 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Pos);
8074 outs() << " Common encodings array section offset: "
8075 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
8076 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Pos);
8077 outs() << " Number of common encodings in array: "
8078 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
8079
8080 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Pos);
8081 outs() << " Personality function array section offset: "
8082 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
8083 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Pos);
8084 outs() << " Number of personality functions in array: "
8085 << format("0x%" PRIx32, NumPersonalities) << '\n';
8086
8087 uint32_t IndicesStart = readNext<uint32_t>(Contents, Pos);
8088 outs() << " Index array section offset: "
8089 << format("0x%" PRIx32, IndicesStart) << '\n';
8090 uint32_t NumIndices = readNext<uint32_t>(Contents, Pos);
8091 outs() << " Number of indices in array: "
8092 << format("0x%" PRIx32, NumIndices) << '\n';
8093
8094 //===----------------------------------
8095 // A shared list of common encodings
8096 //===----------------------------------
8097
8098 // These occupy indices in the range [0, N] whenever an encoding is referenced
8099 // from a compressed 2nd level index table. In practice the linker only
8100 // creates ~128 of these, so that indices are available to embed encodings in
8101 // the 2nd level index.
8102
8103 SmallVector<uint32_t, 64> CommonEncodings;
8104 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
8105 Pos = CommonEncodingsStart;
8106 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8107 uint32_t Encoding = readNext<uint32_t>(Contents, Pos);
8108 CommonEncodings.push_back(Encoding);
8109
8110 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
8111 << '\n';
8112 }
8113
8114 //===----------------------------------
8115 // Personality functions used in this executable
8116 //===----------------------------------
8117
8118 // There should be only a handful of these (one per source language,
8119 // roughly). Particularly since they only get 2 bits in the compact encoding.
8120
8121 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
8122 Pos = PersonalitiesStart;
8123 for (unsigned i = 0; i < NumPersonalities; ++i) {
8124 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Pos);
8125 outs() << " personality[" << i + 1
8126 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
8127 }
8128
8129 //===----------------------------------
8130 // The level 1 index entries
8131 //===----------------------------------
8132
8133 // These specify an approximate place to start searching for the more detailed
8134 // information, sorted by PC.
8135
8136 struct IndexEntry {
8137 uint32_t FunctionOffset;
8138 uint32_t SecondLevelPageStart;
8139 uint32_t LSDAStart;
8140 };
8141
8142 SmallVector<IndexEntry, 4> IndexEntries;
8143
8144 outs() << " Top level indices: (count = " << NumIndices << ")\n";
8145 Pos = IndicesStart;
8146 for (unsigned i = 0; i < NumIndices; ++i) {
8147 IndexEntry Entry;
8148
8149 Entry.FunctionOffset = readNext<uint32_t>(Contents, Pos);
8150 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Pos);
8151 Entry.LSDAStart = readNext<uint32_t>(Contents, Pos);
8152 IndexEntries.push_back(Entry);
8153
8154 outs() << " [" << i << "]: "
8155 << "function offset=" << format("0x%08" PRIx32, Entry.FunctionOffset)
8156 << ", "
8157 << "2nd level page offset="
8158 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
8159 << "LSDA offset=" << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
8160 }
8161
8162 //===----------------------------------
8163 // Next come the LSDA tables
8164 //===----------------------------------
8165
8166 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8167 // the first top-level index's LSDAOffset to the last (sentinel).
8168
8169 outs() << " LSDA descriptors:\n";
8170 Pos = IndexEntries[0].LSDAStart;
8171 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8172 int NumLSDAs =
8173 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8174
8175 for (int i = 0; i < NumLSDAs; ++i) {
8176 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Pos);
8177 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Pos);
8178 outs() << " [" << i << "]: "
8179 << "function offset=" << format("0x%08" PRIx32, FunctionOffset)
8180 << ", "
8181 << "LSDA offset=" << format("0x%08" PRIx32, LSDAOffset) << '\n';
8182 }
8183
8184 //===----------------------------------
8185 // Finally, the 2nd level indices
8186 //===----------------------------------
8187
8188 // Generally these are 4K in size, and have 2 possible forms:
8189 // + Regular stores up to 511 entries with disparate encodings
8190 // + Compressed stores up to 1021 entries if few enough compact encoding
8191 // values are used.
8192 outs() << " Second level indices:\n";
8193 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8194 // The final sentinel top-level index has no associated 2nd level page
8195 if (IndexEntries[i].SecondLevelPageStart == 0)
8196 break;
8197
8198 outs() << " Second level index[" << i << "]: "
8199 << "offset in section="
8200 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
8201 << ", "
8202 << "base function offset="
8203 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
8204
8205 Pos = IndexEntries[i].SecondLevelPageStart;
8206 if (Pos + sizeof(uint32_t) > Contents.size()) {
8207 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8208 continue;
8209 }
8210
8211 uint32_t Kind =
8212 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8213 if (Kind == 2)
8214 printRegularSecondLevelUnwindPage(Contents.substr(Pos, 4096));
8215 else if (Kind == 3)
8216 printCompressedSecondLevelUnwindPage(Contents.substr(Pos, 4096),
8217 IndexEntries[i].FunctionOffset,
8218 CommonEncodings);
8219 else
8220 outs() << " Skipping 2nd level page with unknown kind " << Kind
8221 << '\n';
8222 }
8223 }
8224
printMachOUnwindInfo(const MachOObjectFile * Obj)8225 void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8226 std::map<uint64_t, SymbolRef> Symbols;
8227 for (const SymbolRef &SymRef : Obj->symbols()) {
8228 // Discard any undefined or absolute symbols. They're not going to take part
8229 // in the convenience lookup for unwind info and just take up resources.
8230 auto SectOrErr = SymRef.getSection();
8231 if (!SectOrErr) {
8232 // TODO: Actually report errors helpfully.
8233 consumeError(SectOrErr.takeError());
8234 continue;
8235 }
8236 section_iterator Section = *SectOrErr;
8237 if (Section == Obj->section_end())
8238 continue;
8239
8240 uint64_t Addr = cantFail(SymRef.getValue());
8241 Symbols.insert(std::make_pair(Addr, SymRef));
8242 }
8243
8244 for (const SectionRef &Section : Obj->sections()) {
8245 StringRef SectName;
8246 if (Expected<StringRef> NameOrErr = Section.getName())
8247 SectName = *NameOrErr;
8248 else
8249 consumeError(NameOrErr.takeError());
8250
8251 if (SectName == "__compact_unwind")
8252 printMachOCompactUnwindSection(Obj, Symbols, Section);
8253 else if (SectName == "__unwind_info")
8254 printMachOUnwindInfoSection(Obj, Symbols, Section);
8255 }
8256 }
8257
PrintMachHeader(uint32_t magic,uint32_t cputype,uint32_t cpusubtype,uint32_t filetype,uint32_t ncmds,uint32_t sizeofcmds,uint32_t flags,bool verbose)8258 static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8259 uint32_t cpusubtype, uint32_t filetype,
8260 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8261 bool verbose) {
8262 outs() << "Mach header\n";
8263 outs() << " magic cputype cpusubtype caps filetype ncmds "
8264 "sizeofcmds flags\n";
8265 if (verbose) {
8266 if (magic == MachO::MH_MAGIC)
8267 outs() << " MH_MAGIC";
8268 else if (magic == MachO::MH_MAGIC_64)
8269 outs() << "MH_MAGIC_64";
8270 else
8271 outs() << format(" 0x%08" PRIx32, magic);
8272 switch (cputype) {
8273 case MachO::CPU_TYPE_I386:
8274 outs() << " I386";
8275 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8276 case MachO::CPU_SUBTYPE_I386_ALL:
8277 outs() << " ALL";
8278 break;
8279 default:
8280 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8281 break;
8282 }
8283 break;
8284 case MachO::CPU_TYPE_X86_64:
8285 outs() << " X86_64";
8286 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8287 case MachO::CPU_SUBTYPE_X86_64_ALL:
8288 outs() << " ALL";
8289 break;
8290 case MachO::CPU_SUBTYPE_X86_64_H:
8291 outs() << " Haswell";
8292 break;
8293 default:
8294 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8295 break;
8296 }
8297 break;
8298 case MachO::CPU_TYPE_ARM:
8299 outs() << " ARM";
8300 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8301 case MachO::CPU_SUBTYPE_ARM_ALL:
8302 outs() << " ALL";
8303 break;
8304 case MachO::CPU_SUBTYPE_ARM_V4T:
8305 outs() << " V4T";
8306 break;
8307 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8308 outs() << " V5TEJ";
8309 break;
8310 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8311 outs() << " XSCALE";
8312 break;
8313 case MachO::CPU_SUBTYPE_ARM_V6:
8314 outs() << " V6";
8315 break;
8316 case MachO::CPU_SUBTYPE_ARM_V6M:
8317 outs() << " V6M";
8318 break;
8319 case MachO::CPU_SUBTYPE_ARM_V7:
8320 outs() << " V7";
8321 break;
8322 case MachO::CPU_SUBTYPE_ARM_V7EM:
8323 outs() << " V7EM";
8324 break;
8325 case MachO::CPU_SUBTYPE_ARM_V7K:
8326 outs() << " V7K";
8327 break;
8328 case MachO::CPU_SUBTYPE_ARM_V7M:
8329 outs() << " V7M";
8330 break;
8331 case MachO::CPU_SUBTYPE_ARM_V7S:
8332 outs() << " V7S";
8333 break;
8334 default:
8335 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8336 break;
8337 }
8338 break;
8339 case MachO::CPU_TYPE_ARM64:
8340 outs() << " ARM64";
8341 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8342 case MachO::CPU_SUBTYPE_ARM64_ALL:
8343 outs() << " ALL";
8344 break;
8345 case MachO::CPU_SUBTYPE_ARM64_V8:
8346 outs() << " V8";
8347 break;
8348 case MachO::CPU_SUBTYPE_ARM64E:
8349 outs() << " E";
8350 break;
8351 default:
8352 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8353 break;
8354 }
8355 break;
8356 case MachO::CPU_TYPE_ARM64_32:
8357 outs() << " ARM64_32";
8358 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8359 case MachO::CPU_SUBTYPE_ARM64_32_V8:
8360 outs() << " V8";
8361 break;
8362 default:
8363 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8364 break;
8365 }
8366 break;
8367 case MachO::CPU_TYPE_POWERPC:
8368 outs() << " PPC";
8369 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8370 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8371 outs() << " ALL";
8372 break;
8373 default:
8374 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8375 break;
8376 }
8377 break;
8378 case MachO::CPU_TYPE_POWERPC64:
8379 outs() << " PPC64";
8380 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8381 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8382 outs() << " ALL";
8383 break;
8384 default:
8385 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8386 break;
8387 }
8388 break;
8389 default:
8390 outs() << format(" %7d", cputype);
8391 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8392 break;
8393 }
8394 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
8395 outs() << " LIB64";
8396 } else {
8397 outs() << format(" 0x%02" PRIx32,
8398 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8399 }
8400 switch (filetype) {
8401 case MachO::MH_OBJECT:
8402 outs() << " OBJECT";
8403 break;
8404 case MachO::MH_EXECUTE:
8405 outs() << " EXECUTE";
8406 break;
8407 case MachO::MH_FVMLIB:
8408 outs() << " FVMLIB";
8409 break;
8410 case MachO::MH_CORE:
8411 outs() << " CORE";
8412 break;
8413 case MachO::MH_PRELOAD:
8414 outs() << " PRELOAD";
8415 break;
8416 case MachO::MH_DYLIB:
8417 outs() << " DYLIB";
8418 break;
8419 case MachO::MH_DYLIB_STUB:
8420 outs() << " DYLIB_STUB";
8421 break;
8422 case MachO::MH_DYLINKER:
8423 outs() << " DYLINKER";
8424 break;
8425 case MachO::MH_BUNDLE:
8426 outs() << " BUNDLE";
8427 break;
8428 case MachO::MH_DSYM:
8429 outs() << " DSYM";
8430 break;
8431 case MachO::MH_KEXT_BUNDLE:
8432 outs() << " KEXTBUNDLE";
8433 break;
8434 default:
8435 outs() << format(" %10u", filetype);
8436 break;
8437 }
8438 outs() << format(" %5u", ncmds);
8439 outs() << format(" %10u", sizeofcmds);
8440 uint32_t f = flags;
8441 if (f & MachO::MH_NOUNDEFS) {
8442 outs() << " NOUNDEFS";
8443 f &= ~MachO::MH_NOUNDEFS;
8444 }
8445 if (f & MachO::MH_INCRLINK) {
8446 outs() << " INCRLINK";
8447 f &= ~MachO::MH_INCRLINK;
8448 }
8449 if (f & MachO::MH_DYLDLINK) {
8450 outs() << " DYLDLINK";
8451 f &= ~MachO::MH_DYLDLINK;
8452 }
8453 if (f & MachO::MH_BINDATLOAD) {
8454 outs() << " BINDATLOAD";
8455 f &= ~MachO::MH_BINDATLOAD;
8456 }
8457 if (f & MachO::MH_PREBOUND) {
8458 outs() << " PREBOUND";
8459 f &= ~MachO::MH_PREBOUND;
8460 }
8461 if (f & MachO::MH_SPLIT_SEGS) {
8462 outs() << " SPLIT_SEGS";
8463 f &= ~MachO::MH_SPLIT_SEGS;
8464 }
8465 if (f & MachO::MH_LAZY_INIT) {
8466 outs() << " LAZY_INIT";
8467 f &= ~MachO::MH_LAZY_INIT;
8468 }
8469 if (f & MachO::MH_TWOLEVEL) {
8470 outs() << " TWOLEVEL";
8471 f &= ~MachO::MH_TWOLEVEL;
8472 }
8473 if (f & MachO::MH_FORCE_FLAT) {
8474 outs() << " FORCE_FLAT";
8475 f &= ~MachO::MH_FORCE_FLAT;
8476 }
8477 if (f & MachO::MH_NOMULTIDEFS) {
8478 outs() << " NOMULTIDEFS";
8479 f &= ~MachO::MH_NOMULTIDEFS;
8480 }
8481 if (f & MachO::MH_NOFIXPREBINDING) {
8482 outs() << " NOFIXPREBINDING";
8483 f &= ~MachO::MH_NOFIXPREBINDING;
8484 }
8485 if (f & MachO::MH_PREBINDABLE) {
8486 outs() << " PREBINDABLE";
8487 f &= ~MachO::MH_PREBINDABLE;
8488 }
8489 if (f & MachO::MH_ALLMODSBOUND) {
8490 outs() << " ALLMODSBOUND";
8491 f &= ~MachO::MH_ALLMODSBOUND;
8492 }
8493 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8494 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8495 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8496 }
8497 if (f & MachO::MH_CANONICAL) {
8498 outs() << " CANONICAL";
8499 f &= ~MachO::MH_CANONICAL;
8500 }
8501 if (f & MachO::MH_WEAK_DEFINES) {
8502 outs() << " WEAK_DEFINES";
8503 f &= ~MachO::MH_WEAK_DEFINES;
8504 }
8505 if (f & MachO::MH_BINDS_TO_WEAK) {
8506 outs() << " BINDS_TO_WEAK";
8507 f &= ~MachO::MH_BINDS_TO_WEAK;
8508 }
8509 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8510 outs() << " ALLOW_STACK_EXECUTION";
8511 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8512 }
8513 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8514 outs() << " DEAD_STRIPPABLE_DYLIB";
8515 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8516 }
8517 if (f & MachO::MH_PIE) {
8518 outs() << " PIE";
8519 f &= ~MachO::MH_PIE;
8520 }
8521 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8522 outs() << " NO_REEXPORTED_DYLIBS";
8523 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8524 }
8525 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8526 outs() << " MH_HAS_TLV_DESCRIPTORS";
8527 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8528 }
8529 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8530 outs() << " MH_NO_HEAP_EXECUTION";
8531 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8532 }
8533 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8534 outs() << " APP_EXTENSION_SAFE";
8535 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8536 }
8537 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8538 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8539 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8540 }
8541 if (f != 0 || flags == 0)
8542 outs() << format(" 0x%08" PRIx32, f);
8543 } else {
8544 outs() << format(" 0x%08" PRIx32, magic);
8545 outs() << format(" %7d", cputype);
8546 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8547 outs() << format(" 0x%02" PRIx32,
8548 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8549 outs() << format(" %10u", filetype);
8550 outs() << format(" %5u", ncmds);
8551 outs() << format(" %10u", sizeofcmds);
8552 outs() << format(" 0x%08" PRIx32, flags);
8553 }
8554 outs() << "\n";
8555 }
8556
PrintSegmentCommand(uint32_t cmd,uint32_t cmdsize,StringRef SegName,uint64_t vmaddr,uint64_t vmsize,uint64_t fileoff,uint64_t filesize,uint32_t maxprot,uint32_t initprot,uint32_t nsects,uint32_t flags,uint32_t object_size,bool verbose)8557 static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8558 StringRef SegName, uint64_t vmaddr,
8559 uint64_t vmsize, uint64_t fileoff,
8560 uint64_t filesize, uint32_t maxprot,
8561 uint32_t initprot, uint32_t nsects,
8562 uint32_t flags, uint32_t object_size,
8563 bool verbose) {
8564 uint64_t expected_cmdsize;
8565 if (cmd == MachO::LC_SEGMENT) {
8566 outs() << " cmd LC_SEGMENT\n";
8567 expected_cmdsize = nsects;
8568 expected_cmdsize *= sizeof(struct MachO::section);
8569 expected_cmdsize += sizeof(struct MachO::segment_command);
8570 } else {
8571 outs() << " cmd LC_SEGMENT_64\n";
8572 expected_cmdsize = nsects;
8573 expected_cmdsize *= sizeof(struct MachO::section_64);
8574 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8575 }
8576 outs() << " cmdsize " << cmdsize;
8577 if (cmdsize != expected_cmdsize)
8578 outs() << " Inconsistent size\n";
8579 else
8580 outs() << "\n";
8581 outs() << " segname " << SegName << "\n";
8582 if (cmd == MachO::LC_SEGMENT_64) {
8583 outs() << " vmaddr " << format("0x%016" PRIx64, vmaddr) << "\n";
8584 outs() << " vmsize " << format("0x%016" PRIx64, vmsize) << "\n";
8585 } else {
8586 outs() << " vmaddr " << format("0x%08" PRIx64, vmaddr) << "\n";
8587 outs() << " vmsize " << format("0x%08" PRIx64, vmsize) << "\n";
8588 }
8589 outs() << " fileoff " << fileoff;
8590 if (fileoff > object_size)
8591 outs() << " (past end of file)\n";
8592 else
8593 outs() << "\n";
8594 outs() << " filesize " << filesize;
8595 if (fileoff + filesize > object_size)
8596 outs() << " (past end of file)\n";
8597 else
8598 outs() << "\n";
8599 if (verbose) {
8600 if ((maxprot &
8601 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8602 MachO::VM_PROT_EXECUTE)) != 0)
8603 outs() << " maxprot ?" << format("0x%08" PRIx32, maxprot) << "\n";
8604 else {
8605 outs() << " maxprot ";
8606 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8607 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8608 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8609 }
8610 if ((initprot &
8611 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8612 MachO::VM_PROT_EXECUTE)) != 0)
8613 outs() << " initprot ?" << format("0x%08" PRIx32, initprot) << "\n";
8614 else {
8615 outs() << " initprot ";
8616 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8617 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8618 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8619 }
8620 } else {
8621 outs() << " maxprot " << format("0x%08" PRIx32, maxprot) << "\n";
8622 outs() << " initprot " << format("0x%08" PRIx32, initprot) << "\n";
8623 }
8624 outs() << " nsects " << nsects << "\n";
8625 if (verbose) {
8626 outs() << " flags";
8627 if (flags == 0)
8628 outs() << " (none)\n";
8629 else {
8630 if (flags & MachO::SG_HIGHVM) {
8631 outs() << " HIGHVM";
8632 flags &= ~MachO::SG_HIGHVM;
8633 }
8634 if (flags & MachO::SG_FVMLIB) {
8635 outs() << " FVMLIB";
8636 flags &= ~MachO::SG_FVMLIB;
8637 }
8638 if (flags & MachO::SG_NORELOC) {
8639 outs() << " NORELOC";
8640 flags &= ~MachO::SG_NORELOC;
8641 }
8642 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8643 outs() << " PROTECTED_VERSION_1";
8644 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8645 }
8646 if (flags)
8647 outs() << format(" 0x%08" PRIx32, flags) << " (unknown flags)\n";
8648 else
8649 outs() << "\n";
8650 }
8651 } else {
8652 outs() << " flags " << format("0x%" PRIx32, flags) << "\n";
8653 }
8654 }
8655
PrintSection(const char * sectname,const char * segname,uint64_t addr,uint64_t size,uint32_t offset,uint32_t align,uint32_t reloff,uint32_t nreloc,uint32_t flags,uint32_t reserved1,uint32_t reserved2,uint32_t cmd,const char * sg_segname,uint32_t filetype,uint32_t object_size,bool verbose)8656 static void PrintSection(const char *sectname, const char *segname,
8657 uint64_t addr, uint64_t size, uint32_t offset,
8658 uint32_t align, uint32_t reloff, uint32_t nreloc,
8659 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8660 uint32_t cmd, const char *sg_segname,
8661 uint32_t filetype, uint32_t object_size,
8662 bool verbose) {
8663 outs() << "Section\n";
8664 outs() << " sectname " << format("%.16s\n", sectname);
8665 outs() << " segname " << format("%.16s", segname);
8666 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
8667 outs() << " (does not match segment)\n";
8668 else
8669 outs() << "\n";
8670 if (cmd == MachO::LC_SEGMENT_64) {
8671 outs() << " addr " << format("0x%016" PRIx64, addr) << "\n";
8672 outs() << " size " << format("0x%016" PRIx64, size);
8673 } else {
8674 outs() << " addr " << format("0x%08" PRIx64, addr) << "\n";
8675 outs() << " size " << format("0x%08" PRIx64, size);
8676 }
8677 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8678 outs() << " (past end of file)\n";
8679 else
8680 outs() << "\n";
8681 outs() << " offset " << offset;
8682 if (offset > object_size)
8683 outs() << " (past end of file)\n";
8684 else
8685 outs() << "\n";
8686 uint32_t align_shifted = 1 << align;
8687 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8688 outs() << " reloff " << reloff;
8689 if (reloff > object_size)
8690 outs() << " (past end of file)\n";
8691 else
8692 outs() << "\n";
8693 outs() << " nreloc " << nreloc;
8694 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8695 outs() << " (past end of file)\n";
8696 else
8697 outs() << "\n";
8698 uint32_t section_type = flags & MachO::SECTION_TYPE;
8699 if (verbose) {
8700 outs() << " type";
8701 if (section_type == MachO::S_REGULAR)
8702 outs() << " S_REGULAR\n";
8703 else if (section_type == MachO::S_ZEROFILL)
8704 outs() << " S_ZEROFILL\n";
8705 else if (section_type == MachO::S_CSTRING_LITERALS)
8706 outs() << " S_CSTRING_LITERALS\n";
8707 else if (section_type == MachO::S_4BYTE_LITERALS)
8708 outs() << " S_4BYTE_LITERALS\n";
8709 else if (section_type == MachO::S_8BYTE_LITERALS)
8710 outs() << " S_8BYTE_LITERALS\n";
8711 else if (section_type == MachO::S_16BYTE_LITERALS)
8712 outs() << " S_16BYTE_LITERALS\n";
8713 else if (section_type == MachO::S_LITERAL_POINTERS)
8714 outs() << " S_LITERAL_POINTERS\n";
8715 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8716 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8717 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8718 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8719 else if (section_type == MachO::S_SYMBOL_STUBS)
8720 outs() << " S_SYMBOL_STUBS\n";
8721 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8722 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8723 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8724 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8725 else if (section_type == MachO::S_COALESCED)
8726 outs() << " S_COALESCED\n";
8727 else if (section_type == MachO::S_INTERPOSING)
8728 outs() << " S_INTERPOSING\n";
8729 else if (section_type == MachO::S_DTRACE_DOF)
8730 outs() << " S_DTRACE_DOF\n";
8731 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8732 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8733 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8734 outs() << " S_THREAD_LOCAL_REGULAR\n";
8735 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8736 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8737 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8738 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8739 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8740 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8741 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8742 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8743 else
8744 outs() << format("0x%08" PRIx32, section_type) << "\n";
8745 outs() << "attributes";
8746 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8747 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8748 outs() << " PURE_INSTRUCTIONS";
8749 if (section_attributes & MachO::S_ATTR_NO_TOC)
8750 outs() << " NO_TOC";
8751 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8752 outs() << " STRIP_STATIC_SYMS";
8753 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8754 outs() << " NO_DEAD_STRIP";
8755 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8756 outs() << " LIVE_SUPPORT";
8757 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8758 outs() << " SELF_MODIFYING_CODE";
8759 if (section_attributes & MachO::S_ATTR_DEBUG)
8760 outs() << " DEBUG";
8761 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8762 outs() << " SOME_INSTRUCTIONS";
8763 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8764 outs() << " EXT_RELOC";
8765 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8766 outs() << " LOC_RELOC";
8767 if (section_attributes == 0)
8768 outs() << " (none)";
8769 outs() << "\n";
8770 } else
8771 outs() << " flags " << format("0x%08" PRIx32, flags) << "\n";
8772 outs() << " reserved1 " << reserved1;
8773 if (section_type == MachO::S_SYMBOL_STUBS ||
8774 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8775 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8776 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8777 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8778 outs() << " (index into indirect symbol table)\n";
8779 else
8780 outs() << "\n";
8781 outs() << " reserved2 " << reserved2;
8782 if (section_type == MachO::S_SYMBOL_STUBS)
8783 outs() << " (size of stubs)\n";
8784 else
8785 outs() << "\n";
8786 }
8787
PrintSymtabLoadCommand(MachO::symtab_command st,bool Is64Bit,uint32_t object_size)8788 static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8789 uint32_t object_size) {
8790 outs() << " cmd LC_SYMTAB\n";
8791 outs() << " cmdsize " << st.cmdsize;
8792 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8793 outs() << " Incorrect size\n";
8794 else
8795 outs() << "\n";
8796 outs() << " symoff " << st.symoff;
8797 if (st.symoff > object_size)
8798 outs() << " (past end of file)\n";
8799 else
8800 outs() << "\n";
8801 outs() << " nsyms " << st.nsyms;
8802 uint64_t big_size;
8803 if (Is64Bit) {
8804 big_size = st.nsyms;
8805 big_size *= sizeof(struct MachO::nlist_64);
8806 big_size += st.symoff;
8807 if (big_size > object_size)
8808 outs() << " (past end of file)\n";
8809 else
8810 outs() << "\n";
8811 } else {
8812 big_size = st.nsyms;
8813 big_size *= sizeof(struct MachO::nlist);
8814 big_size += st.symoff;
8815 if (big_size > object_size)
8816 outs() << " (past end of file)\n";
8817 else
8818 outs() << "\n";
8819 }
8820 outs() << " stroff " << st.stroff;
8821 if (st.stroff > object_size)
8822 outs() << " (past end of file)\n";
8823 else
8824 outs() << "\n";
8825 outs() << " strsize " << st.strsize;
8826 big_size = st.stroff;
8827 big_size += st.strsize;
8828 if (big_size > object_size)
8829 outs() << " (past end of file)\n";
8830 else
8831 outs() << "\n";
8832 }
8833
PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,uint32_t nsyms,uint32_t object_size,bool Is64Bit)8834 static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8835 uint32_t nsyms, uint32_t object_size,
8836 bool Is64Bit) {
8837 outs() << " cmd LC_DYSYMTAB\n";
8838 outs() << " cmdsize " << dyst.cmdsize;
8839 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8840 outs() << " Incorrect size\n";
8841 else
8842 outs() << "\n";
8843 outs() << " ilocalsym " << dyst.ilocalsym;
8844 if (dyst.ilocalsym > nsyms)
8845 outs() << " (greater than the number of symbols)\n";
8846 else
8847 outs() << "\n";
8848 outs() << " nlocalsym " << dyst.nlocalsym;
8849 uint64_t big_size;
8850 big_size = dyst.ilocalsym;
8851 big_size += dyst.nlocalsym;
8852 if (big_size > nsyms)
8853 outs() << " (past the end of the symbol table)\n";
8854 else
8855 outs() << "\n";
8856 outs() << " iextdefsym " << dyst.iextdefsym;
8857 if (dyst.iextdefsym > nsyms)
8858 outs() << " (greater than the number of symbols)\n";
8859 else
8860 outs() << "\n";
8861 outs() << " nextdefsym " << dyst.nextdefsym;
8862 big_size = dyst.iextdefsym;
8863 big_size += dyst.nextdefsym;
8864 if (big_size > nsyms)
8865 outs() << " (past the end of the symbol table)\n";
8866 else
8867 outs() << "\n";
8868 outs() << " iundefsym " << dyst.iundefsym;
8869 if (dyst.iundefsym > nsyms)
8870 outs() << " (greater than the number of symbols)\n";
8871 else
8872 outs() << "\n";
8873 outs() << " nundefsym " << dyst.nundefsym;
8874 big_size = dyst.iundefsym;
8875 big_size += dyst.nundefsym;
8876 if (big_size > nsyms)
8877 outs() << " (past the end of the symbol table)\n";
8878 else
8879 outs() << "\n";
8880 outs() << " tocoff " << dyst.tocoff;
8881 if (dyst.tocoff > object_size)
8882 outs() << " (past end of file)\n";
8883 else
8884 outs() << "\n";
8885 outs() << " ntoc " << dyst.ntoc;
8886 big_size = dyst.ntoc;
8887 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8888 big_size += dyst.tocoff;
8889 if (big_size > object_size)
8890 outs() << " (past end of file)\n";
8891 else
8892 outs() << "\n";
8893 outs() << " modtaboff " << dyst.modtaboff;
8894 if (dyst.modtaboff > object_size)
8895 outs() << " (past end of file)\n";
8896 else
8897 outs() << "\n";
8898 outs() << " nmodtab " << dyst.nmodtab;
8899 uint64_t modtabend;
8900 if (Is64Bit) {
8901 modtabend = dyst.nmodtab;
8902 modtabend *= sizeof(struct MachO::dylib_module_64);
8903 modtabend += dyst.modtaboff;
8904 } else {
8905 modtabend = dyst.nmodtab;
8906 modtabend *= sizeof(struct MachO::dylib_module);
8907 modtabend += dyst.modtaboff;
8908 }
8909 if (modtabend > object_size)
8910 outs() << " (past end of file)\n";
8911 else
8912 outs() << "\n";
8913 outs() << " extrefsymoff " << dyst.extrefsymoff;
8914 if (dyst.extrefsymoff > object_size)
8915 outs() << " (past end of file)\n";
8916 else
8917 outs() << "\n";
8918 outs() << " nextrefsyms " << dyst.nextrefsyms;
8919 big_size = dyst.nextrefsyms;
8920 big_size *= sizeof(struct MachO::dylib_reference);
8921 big_size += dyst.extrefsymoff;
8922 if (big_size > object_size)
8923 outs() << " (past end of file)\n";
8924 else
8925 outs() << "\n";
8926 outs() << " indirectsymoff " << dyst.indirectsymoff;
8927 if (dyst.indirectsymoff > object_size)
8928 outs() << " (past end of file)\n";
8929 else
8930 outs() << "\n";
8931 outs() << " nindirectsyms " << dyst.nindirectsyms;
8932 big_size = dyst.nindirectsyms;
8933 big_size *= sizeof(uint32_t);
8934 big_size += dyst.indirectsymoff;
8935 if (big_size > object_size)
8936 outs() << " (past end of file)\n";
8937 else
8938 outs() << "\n";
8939 outs() << " extreloff " << dyst.extreloff;
8940 if (dyst.extreloff > object_size)
8941 outs() << " (past end of file)\n";
8942 else
8943 outs() << "\n";
8944 outs() << " nextrel " << dyst.nextrel;
8945 big_size = dyst.nextrel;
8946 big_size *= sizeof(struct MachO::relocation_info);
8947 big_size += dyst.extreloff;
8948 if (big_size > object_size)
8949 outs() << " (past end of file)\n";
8950 else
8951 outs() << "\n";
8952 outs() << " locreloff " << dyst.locreloff;
8953 if (dyst.locreloff > object_size)
8954 outs() << " (past end of file)\n";
8955 else
8956 outs() << "\n";
8957 outs() << " nlocrel " << dyst.nlocrel;
8958 big_size = dyst.nlocrel;
8959 big_size *= sizeof(struct MachO::relocation_info);
8960 big_size += dyst.locreloff;
8961 if (big_size > object_size)
8962 outs() << " (past end of file)\n";
8963 else
8964 outs() << "\n";
8965 }
8966
PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,uint32_t object_size)8967 static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8968 uint32_t object_size) {
8969 if (dc.cmd == MachO::LC_DYLD_INFO)
8970 outs() << " cmd LC_DYLD_INFO\n";
8971 else
8972 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8973 outs() << " cmdsize " << dc.cmdsize;
8974 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8975 outs() << " Incorrect size\n";
8976 else
8977 outs() << "\n";
8978 outs() << " rebase_off " << dc.rebase_off;
8979 if (dc.rebase_off > object_size)
8980 outs() << " (past end of file)\n";
8981 else
8982 outs() << "\n";
8983 outs() << " rebase_size " << dc.rebase_size;
8984 uint64_t big_size;
8985 big_size = dc.rebase_off;
8986 big_size += dc.rebase_size;
8987 if (big_size > object_size)
8988 outs() << " (past end of file)\n";
8989 else
8990 outs() << "\n";
8991 outs() << " bind_off " << dc.bind_off;
8992 if (dc.bind_off > object_size)
8993 outs() << " (past end of file)\n";
8994 else
8995 outs() << "\n";
8996 outs() << " bind_size " << dc.bind_size;
8997 big_size = dc.bind_off;
8998 big_size += dc.bind_size;
8999 if (big_size > object_size)
9000 outs() << " (past end of file)\n";
9001 else
9002 outs() << "\n";
9003 outs() << " weak_bind_off " << dc.weak_bind_off;
9004 if (dc.weak_bind_off > object_size)
9005 outs() << " (past end of file)\n";
9006 else
9007 outs() << "\n";
9008 outs() << " weak_bind_size " << dc.weak_bind_size;
9009 big_size = dc.weak_bind_off;
9010 big_size += dc.weak_bind_size;
9011 if (big_size > object_size)
9012 outs() << " (past end of file)\n";
9013 else
9014 outs() << "\n";
9015 outs() << " lazy_bind_off " << dc.lazy_bind_off;
9016 if (dc.lazy_bind_off > object_size)
9017 outs() << " (past end of file)\n";
9018 else
9019 outs() << "\n";
9020 outs() << " lazy_bind_size " << dc.lazy_bind_size;
9021 big_size = dc.lazy_bind_off;
9022 big_size += dc.lazy_bind_size;
9023 if (big_size > object_size)
9024 outs() << " (past end of file)\n";
9025 else
9026 outs() << "\n";
9027 outs() << " export_off " << dc.export_off;
9028 if (dc.export_off > object_size)
9029 outs() << " (past end of file)\n";
9030 else
9031 outs() << "\n";
9032 outs() << " export_size " << dc.export_size;
9033 big_size = dc.export_off;
9034 big_size += dc.export_size;
9035 if (big_size > object_size)
9036 outs() << " (past end of file)\n";
9037 else
9038 outs() << "\n";
9039 }
9040
PrintDyldLoadCommand(MachO::dylinker_command dyld,const char * Ptr)9041 static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9042 const char *Ptr) {
9043 if (dyld.cmd == MachO::LC_ID_DYLINKER)
9044 outs() << " cmd LC_ID_DYLINKER\n";
9045 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9046 outs() << " cmd LC_LOAD_DYLINKER\n";
9047 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9048 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
9049 else
9050 outs() << " cmd ?(" << dyld.cmd << ")\n";
9051 outs() << " cmdsize " << dyld.cmdsize;
9052 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9053 outs() << " Incorrect size\n";
9054 else
9055 outs() << "\n";
9056 if (dyld.name >= dyld.cmdsize)
9057 outs() << " name ?(bad offset " << dyld.name << ")\n";
9058 else {
9059 const char *P = (const char *)(Ptr) + dyld.name;
9060 outs() << " name " << P << " (offset " << dyld.name << ")\n";
9061 }
9062 }
9063
PrintUuidLoadCommand(MachO::uuid_command uuid)9064 static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9065 outs() << " cmd LC_UUID\n";
9066 outs() << " cmdsize " << uuid.cmdsize;
9067 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9068 outs() << " Incorrect size\n";
9069 else
9070 outs() << "\n";
9071 outs() << " uuid ";
9072 for (int i = 0; i < 16; ++i) {
9073 outs() << format("%02" PRIX32, uuid.uuid[i]);
9074 if (i == 3 || i == 5 || i == 7 || i == 9)
9075 outs() << "-";
9076 }
9077 outs() << "\n";
9078 }
9079
PrintRpathLoadCommand(MachO::rpath_command rpath,const char * Ptr)9080 static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9081 outs() << " cmd LC_RPATH\n";
9082 outs() << " cmdsize " << rpath.cmdsize;
9083 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9084 outs() << " Incorrect size\n";
9085 else
9086 outs() << "\n";
9087 if (rpath.path >= rpath.cmdsize)
9088 outs() << " path ?(bad offset " << rpath.path << ")\n";
9089 else {
9090 const char *P = (const char *)(Ptr) + rpath.path;
9091 outs() << " path " << P << " (offset " << rpath.path << ")\n";
9092 }
9093 }
9094
PrintVersionMinLoadCommand(MachO::version_min_command vd)9095 static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9096 StringRef LoadCmdName;
9097 switch (vd.cmd) {
9098 case MachO::LC_VERSION_MIN_MACOSX:
9099 LoadCmdName = "LC_VERSION_MIN_MACOSX";
9100 break;
9101 case MachO::LC_VERSION_MIN_IPHONEOS:
9102 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9103 break;
9104 case MachO::LC_VERSION_MIN_TVOS:
9105 LoadCmdName = "LC_VERSION_MIN_TVOS";
9106 break;
9107 case MachO::LC_VERSION_MIN_WATCHOS:
9108 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9109 break;
9110 default:
9111 llvm_unreachable("Unknown version min load command");
9112 }
9113
9114 outs() << " cmd " << LoadCmdName << '\n';
9115 outs() << " cmdsize " << vd.cmdsize;
9116 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9117 outs() << " Incorrect size\n";
9118 else
9119 outs() << "\n";
9120 outs() << " version "
9121 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
9122 << MachOObjectFile::getVersionMinMinor(vd, false);
9123 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
9124 if (Update != 0)
9125 outs() << "." << Update;
9126 outs() << "\n";
9127 if (vd.sdk == 0)
9128 outs() << " sdk n/a";
9129 else {
9130 outs() << " sdk "
9131 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
9132 << MachOObjectFile::getVersionMinMinor(vd, true);
9133 }
9134 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
9135 if (Update != 0)
9136 outs() << "." << Update;
9137 outs() << "\n";
9138 }
9139
PrintNoteLoadCommand(MachO::note_command Nt)9140 static void PrintNoteLoadCommand(MachO::note_command Nt) {
9141 outs() << " cmd LC_NOTE\n";
9142 outs() << " cmdsize " << Nt.cmdsize;
9143 if (Nt.cmdsize != sizeof(struct MachO::note_command))
9144 outs() << " Incorrect size\n";
9145 else
9146 outs() << "\n";
9147 const char *d = Nt.data_owner;
9148 outs() << "data_owner " << format("%.16s\n", d);
9149 outs() << " offset " << Nt.offset << "\n";
9150 outs() << " size " << Nt.size << "\n";
9151 }
9152
PrintBuildToolVersion(MachO::build_tool_version bv)9153 static void PrintBuildToolVersion(MachO::build_tool_version bv) {
9154 outs() << " tool " << MachOObjectFile::getBuildTool(bv.tool) << "\n";
9155 outs() << " version " << MachOObjectFile::getVersionString(bv.version)
9156 << "\n";
9157 }
9158
PrintBuildVersionLoadCommand(const MachOObjectFile * obj,MachO::build_version_command bd)9159 static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9160 MachO::build_version_command bd) {
9161 outs() << " cmd LC_BUILD_VERSION\n";
9162 outs() << " cmdsize " << bd.cmdsize;
9163 if (bd.cmdsize !=
9164 sizeof(struct MachO::build_version_command) +
9165 bd.ntools * sizeof(struct MachO::build_tool_version))
9166 outs() << " Incorrect size\n";
9167 else
9168 outs() << "\n";
9169 outs() << " platform " << MachOObjectFile::getBuildPlatform(bd.platform)
9170 << "\n";
9171 if (bd.sdk)
9172 outs() << " sdk " << MachOObjectFile::getVersionString(bd.sdk)
9173 << "\n";
9174 else
9175 outs() << " sdk n/a\n";
9176 outs() << " minos " << MachOObjectFile::getVersionString(bd.minos)
9177 << "\n";
9178 outs() << " ntools " << bd.ntools << "\n";
9179 for (unsigned i = 0; i < bd.ntools; ++i) {
9180 MachO::build_tool_version bv = obj->getBuildToolVersion(i);
9181 PrintBuildToolVersion(bv);
9182 }
9183 }
9184
PrintSourceVersionCommand(MachO::source_version_command sd)9185 static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9186 outs() << " cmd LC_SOURCE_VERSION\n";
9187 outs() << " cmdsize " << sd.cmdsize;
9188 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9189 outs() << " Incorrect size\n";
9190 else
9191 outs() << "\n";
9192 uint64_t a = (sd.version >> 40) & 0xffffff;
9193 uint64_t b = (sd.version >> 30) & 0x3ff;
9194 uint64_t c = (sd.version >> 20) & 0x3ff;
9195 uint64_t d = (sd.version >> 10) & 0x3ff;
9196 uint64_t e = sd.version & 0x3ff;
9197 outs() << " version " << a << "." << b;
9198 if (e != 0)
9199 outs() << "." << c << "." << d << "." << e;
9200 else if (d != 0)
9201 outs() << "." << c << "." << d;
9202 else if (c != 0)
9203 outs() << "." << c;
9204 outs() << "\n";
9205 }
9206
PrintEntryPointCommand(MachO::entry_point_command ep)9207 static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9208 outs() << " cmd LC_MAIN\n";
9209 outs() << " cmdsize " << ep.cmdsize;
9210 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9211 outs() << " Incorrect size\n";
9212 else
9213 outs() << "\n";
9214 outs() << " entryoff " << ep.entryoff << "\n";
9215 outs() << " stacksize " << ep.stacksize << "\n";
9216 }
9217
PrintEncryptionInfoCommand(MachO::encryption_info_command ec,uint32_t object_size)9218 static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9219 uint32_t object_size) {
9220 outs() << " cmd LC_ENCRYPTION_INFO\n";
9221 outs() << " cmdsize " << ec.cmdsize;
9222 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9223 outs() << " Incorrect size\n";
9224 else
9225 outs() << "\n";
9226 outs() << " cryptoff " << ec.cryptoff;
9227 if (ec.cryptoff > object_size)
9228 outs() << " (past end of file)\n";
9229 else
9230 outs() << "\n";
9231 outs() << " cryptsize " << ec.cryptsize;
9232 if (ec.cryptsize > object_size)
9233 outs() << " (past end of file)\n";
9234 else
9235 outs() << "\n";
9236 outs() << " cryptid " << ec.cryptid << "\n";
9237 }
9238
PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,uint32_t object_size)9239 static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9240 uint32_t object_size) {
9241 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9242 outs() << " cmdsize " << ec.cmdsize;
9243 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9244 outs() << " Incorrect size\n";
9245 else
9246 outs() << "\n";
9247 outs() << " cryptoff " << ec.cryptoff;
9248 if (ec.cryptoff > object_size)
9249 outs() << " (past end of file)\n";
9250 else
9251 outs() << "\n";
9252 outs() << " cryptsize " << ec.cryptsize;
9253 if (ec.cryptsize > object_size)
9254 outs() << " (past end of file)\n";
9255 else
9256 outs() << "\n";
9257 outs() << " cryptid " << ec.cryptid << "\n";
9258 outs() << " pad " << ec.pad << "\n";
9259 }
9260
PrintLinkerOptionCommand(MachO::linker_option_command lo,const char * Ptr)9261 static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9262 const char *Ptr) {
9263 outs() << " cmd LC_LINKER_OPTION\n";
9264 outs() << " cmdsize " << lo.cmdsize;
9265 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9266 outs() << " Incorrect size\n";
9267 else
9268 outs() << "\n";
9269 outs() << " count " << lo.count << "\n";
9270 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9271 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9272 uint32_t i = 0;
9273 while (left > 0) {
9274 while (*string == '\0' && left > 0) {
9275 string++;
9276 left--;
9277 }
9278 if (left > 0) {
9279 i++;
9280 outs() << " string #" << i << " " << format("%.*s\n", left, string);
9281 uint32_t NullPos = StringRef(string, left).find('\0');
9282 uint32_t len = std::min(NullPos, left) + 1;
9283 string += len;
9284 left -= len;
9285 }
9286 }
9287 if (lo.count != i)
9288 outs() << " count " << lo.count << " does not match number of strings "
9289 << i << "\n";
9290 }
9291
PrintSubFrameworkCommand(MachO::sub_framework_command sub,const char * Ptr)9292 static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9293 const char *Ptr) {
9294 outs() << " cmd LC_SUB_FRAMEWORK\n";
9295 outs() << " cmdsize " << sub.cmdsize;
9296 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9297 outs() << " Incorrect size\n";
9298 else
9299 outs() << "\n";
9300 if (sub.umbrella < sub.cmdsize) {
9301 const char *P = Ptr + sub.umbrella;
9302 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9303 } else {
9304 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9305 }
9306 }
9307
PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,const char * Ptr)9308 static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9309 const char *Ptr) {
9310 outs() << " cmd LC_SUB_UMBRELLA\n";
9311 outs() << " cmdsize " << sub.cmdsize;
9312 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9313 outs() << " Incorrect size\n";
9314 else
9315 outs() << "\n";
9316 if (sub.sub_umbrella < sub.cmdsize) {
9317 const char *P = Ptr + sub.sub_umbrella;
9318 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9319 } else {
9320 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9321 }
9322 }
9323
PrintSubLibraryCommand(MachO::sub_library_command sub,const char * Ptr)9324 static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9325 const char *Ptr) {
9326 outs() << " cmd LC_SUB_LIBRARY\n";
9327 outs() << " cmdsize " << sub.cmdsize;
9328 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9329 outs() << " Incorrect size\n";
9330 else
9331 outs() << "\n";
9332 if (sub.sub_library < sub.cmdsize) {
9333 const char *P = Ptr + sub.sub_library;
9334 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9335 } else {
9336 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9337 }
9338 }
9339
PrintSubClientCommand(MachO::sub_client_command sub,const char * Ptr)9340 static void PrintSubClientCommand(MachO::sub_client_command sub,
9341 const char *Ptr) {
9342 outs() << " cmd LC_SUB_CLIENT\n";
9343 outs() << " cmdsize " << sub.cmdsize;
9344 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9345 outs() << " Incorrect size\n";
9346 else
9347 outs() << "\n";
9348 if (sub.client < sub.cmdsize) {
9349 const char *P = Ptr + sub.client;
9350 outs() << " client " << P << " (offset " << sub.client << ")\n";
9351 } else {
9352 outs() << " client ?(bad offset " << sub.client << ")\n";
9353 }
9354 }
9355
PrintRoutinesCommand(MachO::routines_command r)9356 static void PrintRoutinesCommand(MachO::routines_command r) {
9357 outs() << " cmd LC_ROUTINES\n";
9358 outs() << " cmdsize " << r.cmdsize;
9359 if (r.cmdsize != sizeof(struct MachO::routines_command))
9360 outs() << " Incorrect size\n";
9361 else
9362 outs() << "\n";
9363 outs() << " init_address " << format("0x%08" PRIx32, r.init_address) << "\n";
9364 outs() << " init_module " << r.init_module << "\n";
9365 outs() << " reserved1 " << r.reserved1 << "\n";
9366 outs() << " reserved2 " << r.reserved2 << "\n";
9367 outs() << " reserved3 " << r.reserved3 << "\n";
9368 outs() << " reserved4 " << r.reserved4 << "\n";
9369 outs() << " reserved5 " << r.reserved5 << "\n";
9370 outs() << " reserved6 " << r.reserved6 << "\n";
9371 }
9372
PrintRoutinesCommand64(MachO::routines_command_64 r)9373 static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9374 outs() << " cmd LC_ROUTINES_64\n";
9375 outs() << " cmdsize " << r.cmdsize;
9376 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9377 outs() << " Incorrect size\n";
9378 else
9379 outs() << "\n";
9380 outs() << " init_address " << format("0x%016" PRIx64, r.init_address) << "\n";
9381 outs() << " init_module " << r.init_module << "\n";
9382 outs() << " reserved1 " << r.reserved1 << "\n";
9383 outs() << " reserved2 " << r.reserved2 << "\n";
9384 outs() << " reserved3 " << r.reserved3 << "\n";
9385 outs() << " reserved4 " << r.reserved4 << "\n";
9386 outs() << " reserved5 " << r.reserved5 << "\n";
9387 outs() << " reserved6 " << r.reserved6 << "\n";
9388 }
9389
Print_x86_thread_state32_t(MachO::x86_thread_state32_t & cpu32)9390 static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9391 outs() << "\t eax " << format("0x%08" PRIx32, cpu32.eax);
9392 outs() << " ebx " << format("0x%08" PRIx32, cpu32.ebx);
9393 outs() << " ecx " << format("0x%08" PRIx32, cpu32.ecx);
9394 outs() << " edx " << format("0x%08" PRIx32, cpu32.edx) << "\n";
9395 outs() << "\t edi " << format("0x%08" PRIx32, cpu32.edi);
9396 outs() << " esi " << format("0x%08" PRIx32, cpu32.esi);
9397 outs() << " ebp " << format("0x%08" PRIx32, cpu32.ebp);
9398 outs() << " esp " << format("0x%08" PRIx32, cpu32.esp) << "\n";
9399 outs() << "\t ss " << format("0x%08" PRIx32, cpu32.ss);
9400 outs() << " eflags " << format("0x%08" PRIx32, cpu32.eflags);
9401 outs() << " eip " << format("0x%08" PRIx32, cpu32.eip);
9402 outs() << " cs " << format("0x%08" PRIx32, cpu32.cs) << "\n";
9403 outs() << "\t ds " << format("0x%08" PRIx32, cpu32.ds);
9404 outs() << " es " << format("0x%08" PRIx32, cpu32.es);
9405 outs() << " fs " << format("0x%08" PRIx32, cpu32.fs);
9406 outs() << " gs " << format("0x%08" PRIx32, cpu32.gs) << "\n";
9407 }
9408
Print_x86_thread_state64_t(MachO::x86_thread_state64_t & cpu64)9409 static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9410 outs() << " rax " << format("0x%016" PRIx64, cpu64.rax);
9411 outs() << " rbx " << format("0x%016" PRIx64, cpu64.rbx);
9412 outs() << " rcx " << format("0x%016" PRIx64, cpu64.rcx) << "\n";
9413 outs() << " rdx " << format("0x%016" PRIx64, cpu64.rdx);
9414 outs() << " rdi " << format("0x%016" PRIx64, cpu64.rdi);
9415 outs() << " rsi " << format("0x%016" PRIx64, cpu64.rsi) << "\n";
9416 outs() << " rbp " << format("0x%016" PRIx64, cpu64.rbp);
9417 outs() << " rsp " << format("0x%016" PRIx64, cpu64.rsp);
9418 outs() << " r8 " << format("0x%016" PRIx64, cpu64.r8) << "\n";
9419 outs() << " r9 " << format("0x%016" PRIx64, cpu64.r9);
9420 outs() << " r10 " << format("0x%016" PRIx64, cpu64.r10);
9421 outs() << " r11 " << format("0x%016" PRIx64, cpu64.r11) << "\n";
9422 outs() << " r12 " << format("0x%016" PRIx64, cpu64.r12);
9423 outs() << " r13 " << format("0x%016" PRIx64, cpu64.r13);
9424 outs() << " r14 " << format("0x%016" PRIx64, cpu64.r14) << "\n";
9425 outs() << " r15 " << format("0x%016" PRIx64, cpu64.r15);
9426 outs() << " rip " << format("0x%016" PRIx64, cpu64.rip) << "\n";
9427 outs() << "rflags " << format("0x%016" PRIx64, cpu64.rflags);
9428 outs() << " cs " << format("0x%016" PRIx64, cpu64.cs);
9429 outs() << " fs " << format("0x%016" PRIx64, cpu64.fs) << "\n";
9430 outs() << " gs " << format("0x%016" PRIx64, cpu64.gs) << "\n";
9431 }
9432
Print_mmst_reg(MachO::mmst_reg_t & r)9433 static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9434 uint32_t f;
9435 outs() << "\t mmst_reg ";
9436 for (f = 0; f < 10; f++)
9437 outs() << format("%02" PRIx32, (r.mmst_reg[f] & 0xff)) << " ";
9438 outs() << "\n";
9439 outs() << "\t mmst_rsrv ";
9440 for (f = 0; f < 6; f++)
9441 outs() << format("%02" PRIx32, (r.mmst_rsrv[f] & 0xff)) << " ";
9442 outs() << "\n";
9443 }
9444
Print_xmm_reg(MachO::xmm_reg_t & r)9445 static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9446 uint32_t f;
9447 outs() << "\t xmm_reg ";
9448 for (f = 0; f < 16; f++)
9449 outs() << format("%02" PRIx32, (r.xmm_reg[f] & 0xff)) << " ";
9450 outs() << "\n";
9451 }
9452
Print_x86_float_state_t(MachO::x86_float_state64_t & fpu)9453 static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9454 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9455 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9456 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9457 outs() << " denorm " << fpu.fpu_fcw.denorm;
9458 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9459 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9460 outs() << " undfl " << fpu.fpu_fcw.undfl;
9461 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9462 outs() << "\t\t pc ";
9463 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9464 outs() << "FP_PREC_24B ";
9465 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9466 outs() << "FP_PREC_53B ";
9467 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9468 outs() << "FP_PREC_64B ";
9469 else
9470 outs() << fpu.fpu_fcw.pc << " ";
9471 outs() << "rc ";
9472 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9473 outs() << "FP_RND_NEAR ";
9474 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9475 outs() << "FP_RND_DOWN ";
9476 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9477 outs() << "FP_RND_UP ";
9478 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9479 outs() << "FP_CHOP ";
9480 outs() << "\n";
9481 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9482 outs() << " denorm " << fpu.fpu_fsw.denorm;
9483 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9484 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9485 outs() << " undfl " << fpu.fpu_fsw.undfl;
9486 outs() << " precis " << fpu.fpu_fsw.precis;
9487 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9488 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9489 outs() << " c0 " << fpu.fpu_fsw.c0;
9490 outs() << " c1 " << fpu.fpu_fsw.c1;
9491 outs() << " c2 " << fpu.fpu_fsw.c2;
9492 outs() << " tos " << fpu.fpu_fsw.tos;
9493 outs() << " c3 " << fpu.fpu_fsw.c3;
9494 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9495 outs() << "\t fpu_ftw " << format("0x%02" PRIx32, fpu.fpu_ftw);
9496 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32, fpu.fpu_rsrv1);
9497 outs() << " fpu_fop " << format("0x%04" PRIx32, fpu.fpu_fop);
9498 outs() << " fpu_ip " << format("0x%08" PRIx32, fpu.fpu_ip) << "\n";
9499 outs() << "\t fpu_cs " << format("0x%04" PRIx32, fpu.fpu_cs);
9500 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32, fpu.fpu_rsrv2);
9501 outs() << " fpu_dp " << format("0x%08" PRIx32, fpu.fpu_dp);
9502 outs() << " fpu_ds " << format("0x%04" PRIx32, fpu.fpu_ds) << "\n";
9503 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32, fpu.fpu_rsrv3);
9504 outs() << " fpu_mxcsr " << format("0x%08" PRIx32, fpu.fpu_mxcsr);
9505 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32, fpu.fpu_mxcsrmask);
9506 outs() << "\n";
9507 outs() << "\t fpu_stmm0:\n";
9508 Print_mmst_reg(fpu.fpu_stmm0);
9509 outs() << "\t fpu_stmm1:\n";
9510 Print_mmst_reg(fpu.fpu_stmm1);
9511 outs() << "\t fpu_stmm2:\n";
9512 Print_mmst_reg(fpu.fpu_stmm2);
9513 outs() << "\t fpu_stmm3:\n";
9514 Print_mmst_reg(fpu.fpu_stmm3);
9515 outs() << "\t fpu_stmm4:\n";
9516 Print_mmst_reg(fpu.fpu_stmm4);
9517 outs() << "\t fpu_stmm5:\n";
9518 Print_mmst_reg(fpu.fpu_stmm5);
9519 outs() << "\t fpu_stmm6:\n";
9520 Print_mmst_reg(fpu.fpu_stmm6);
9521 outs() << "\t fpu_stmm7:\n";
9522 Print_mmst_reg(fpu.fpu_stmm7);
9523 outs() << "\t fpu_xmm0:\n";
9524 Print_xmm_reg(fpu.fpu_xmm0);
9525 outs() << "\t fpu_xmm1:\n";
9526 Print_xmm_reg(fpu.fpu_xmm1);
9527 outs() << "\t fpu_xmm2:\n";
9528 Print_xmm_reg(fpu.fpu_xmm2);
9529 outs() << "\t fpu_xmm3:\n";
9530 Print_xmm_reg(fpu.fpu_xmm3);
9531 outs() << "\t fpu_xmm4:\n";
9532 Print_xmm_reg(fpu.fpu_xmm4);
9533 outs() << "\t fpu_xmm5:\n";
9534 Print_xmm_reg(fpu.fpu_xmm5);
9535 outs() << "\t fpu_xmm6:\n";
9536 Print_xmm_reg(fpu.fpu_xmm6);
9537 outs() << "\t fpu_xmm7:\n";
9538 Print_xmm_reg(fpu.fpu_xmm7);
9539 outs() << "\t fpu_xmm8:\n";
9540 Print_xmm_reg(fpu.fpu_xmm8);
9541 outs() << "\t fpu_xmm9:\n";
9542 Print_xmm_reg(fpu.fpu_xmm9);
9543 outs() << "\t fpu_xmm10:\n";
9544 Print_xmm_reg(fpu.fpu_xmm10);
9545 outs() << "\t fpu_xmm11:\n";
9546 Print_xmm_reg(fpu.fpu_xmm11);
9547 outs() << "\t fpu_xmm12:\n";
9548 Print_xmm_reg(fpu.fpu_xmm12);
9549 outs() << "\t fpu_xmm13:\n";
9550 Print_xmm_reg(fpu.fpu_xmm13);
9551 outs() << "\t fpu_xmm14:\n";
9552 Print_xmm_reg(fpu.fpu_xmm14);
9553 outs() << "\t fpu_xmm15:\n";
9554 Print_xmm_reg(fpu.fpu_xmm15);
9555 outs() << "\t fpu_rsrv4:\n";
9556 for (uint32_t f = 0; f < 6; f++) {
9557 outs() << "\t ";
9558 for (uint32_t g = 0; g < 16; g++)
9559 outs() << format("%02" PRIx32, fpu.fpu_rsrv4[f * g]) << " ";
9560 outs() << "\n";
9561 }
9562 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32, fpu.fpu_reserved1);
9563 outs() << "\n";
9564 }
9565
Print_x86_exception_state_t(MachO::x86_exception_state64_t & exc64)9566 static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9567 outs() << "\t trapno " << format("0x%08" PRIx32, exc64.trapno);
9568 outs() << " err " << format("0x%08" PRIx32, exc64.err);
9569 outs() << " faultvaddr " << format("0x%016" PRIx64, exc64.faultvaddr) << "\n";
9570 }
9571
Print_arm_thread_state32_t(MachO::arm_thread_state32_t & cpu32)9572 static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9573 outs() << "\t r0 " << format("0x%08" PRIx32, cpu32.r[0]);
9574 outs() << " r1 " << format("0x%08" PRIx32, cpu32.r[1]);
9575 outs() << " r2 " << format("0x%08" PRIx32, cpu32.r[2]);
9576 outs() << " r3 " << format("0x%08" PRIx32, cpu32.r[3]) << "\n";
9577 outs() << "\t r4 " << format("0x%08" PRIx32, cpu32.r[4]);
9578 outs() << " r5 " << format("0x%08" PRIx32, cpu32.r[5]);
9579 outs() << " r6 " << format("0x%08" PRIx32, cpu32.r[6]);
9580 outs() << " r7 " << format("0x%08" PRIx32, cpu32.r[7]) << "\n";
9581 outs() << "\t r8 " << format("0x%08" PRIx32, cpu32.r[8]);
9582 outs() << " r9 " << format("0x%08" PRIx32, cpu32.r[9]);
9583 outs() << " r10 " << format("0x%08" PRIx32, cpu32.r[10]);
9584 outs() << " r11 " << format("0x%08" PRIx32, cpu32.r[11]) << "\n";
9585 outs() << "\t r12 " << format("0x%08" PRIx32, cpu32.r[12]);
9586 outs() << " sp " << format("0x%08" PRIx32, cpu32.sp);
9587 outs() << " lr " << format("0x%08" PRIx32, cpu32.lr);
9588 outs() << " pc " << format("0x%08" PRIx32, cpu32.pc) << "\n";
9589 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu32.cpsr) << "\n";
9590 }
9591
Print_arm_thread_state64_t(MachO::arm_thread_state64_t & cpu64)9592 static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9593 outs() << "\t x0 " << format("0x%016" PRIx64, cpu64.x[0]);
9594 outs() << " x1 " << format("0x%016" PRIx64, cpu64.x[1]);
9595 outs() << " x2 " << format("0x%016" PRIx64, cpu64.x[2]) << "\n";
9596 outs() << "\t x3 " << format("0x%016" PRIx64, cpu64.x[3]);
9597 outs() << " x4 " << format("0x%016" PRIx64, cpu64.x[4]);
9598 outs() << " x5 " << format("0x%016" PRIx64, cpu64.x[5]) << "\n";
9599 outs() << "\t x6 " << format("0x%016" PRIx64, cpu64.x[6]);
9600 outs() << " x7 " << format("0x%016" PRIx64, cpu64.x[7]);
9601 outs() << " x8 " << format("0x%016" PRIx64, cpu64.x[8]) << "\n";
9602 outs() << "\t x9 " << format("0x%016" PRIx64, cpu64.x[9]);
9603 outs() << " x10 " << format("0x%016" PRIx64, cpu64.x[10]);
9604 outs() << " x11 " << format("0x%016" PRIx64, cpu64.x[11]) << "\n";
9605 outs() << "\t x12 " << format("0x%016" PRIx64, cpu64.x[12]);
9606 outs() << " x13 " << format("0x%016" PRIx64, cpu64.x[13]);
9607 outs() << " x14 " << format("0x%016" PRIx64, cpu64.x[14]) << "\n";
9608 outs() << "\t x15 " << format("0x%016" PRIx64, cpu64.x[15]);
9609 outs() << " x16 " << format("0x%016" PRIx64, cpu64.x[16]);
9610 outs() << " x17 " << format("0x%016" PRIx64, cpu64.x[17]) << "\n";
9611 outs() << "\t x18 " << format("0x%016" PRIx64, cpu64.x[18]);
9612 outs() << " x19 " << format("0x%016" PRIx64, cpu64.x[19]);
9613 outs() << " x20 " << format("0x%016" PRIx64, cpu64.x[20]) << "\n";
9614 outs() << "\t x21 " << format("0x%016" PRIx64, cpu64.x[21]);
9615 outs() << " x22 " << format("0x%016" PRIx64, cpu64.x[22]);
9616 outs() << " x23 " << format("0x%016" PRIx64, cpu64.x[23]) << "\n";
9617 outs() << "\t x24 " << format("0x%016" PRIx64, cpu64.x[24]);
9618 outs() << " x25 " << format("0x%016" PRIx64, cpu64.x[25]);
9619 outs() << " x26 " << format("0x%016" PRIx64, cpu64.x[26]) << "\n";
9620 outs() << "\t x27 " << format("0x%016" PRIx64, cpu64.x[27]);
9621 outs() << " x28 " << format("0x%016" PRIx64, cpu64.x[28]);
9622 outs() << " fp " << format("0x%016" PRIx64, cpu64.fp) << "\n";
9623 outs() << "\t lr " << format("0x%016" PRIx64, cpu64.lr);
9624 outs() << " sp " << format("0x%016" PRIx64, cpu64.sp);
9625 outs() << " pc " << format("0x%016" PRIx64, cpu64.pc) << "\n";
9626 outs() << "\t cpsr " << format("0x%08" PRIx32, cpu64.cpsr) << "\n";
9627 }
9628
PrintThreadCommand(MachO::thread_command t,const char * Ptr,bool isLittleEndian,uint32_t cputype)9629 static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9630 bool isLittleEndian, uint32_t cputype) {
9631 if (t.cmd == MachO::LC_THREAD)
9632 outs() << " cmd LC_THREAD\n";
9633 else if (t.cmd == MachO::LC_UNIXTHREAD)
9634 outs() << " cmd LC_UNIXTHREAD\n";
9635 else
9636 outs() << " cmd " << t.cmd << " (unknown)\n";
9637 outs() << " cmdsize " << t.cmdsize;
9638 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9639 outs() << " Incorrect size\n";
9640 else
9641 outs() << "\n";
9642
9643 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9644 const char *end = Ptr + t.cmdsize;
9645 uint32_t flavor, count, left;
9646 if (cputype == MachO::CPU_TYPE_I386) {
9647 while (begin < end) {
9648 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9649 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9650 begin += sizeof(uint32_t);
9651 } else {
9652 flavor = 0;
9653 begin = end;
9654 }
9655 if (isLittleEndian != sys::IsLittleEndianHost)
9656 sys::swapByteOrder(flavor);
9657 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9658 memcpy((char *)&count, begin, sizeof(uint32_t));
9659 begin += sizeof(uint32_t);
9660 } else {
9661 count = 0;
9662 begin = end;
9663 }
9664 if (isLittleEndian != sys::IsLittleEndianHost)
9665 sys::swapByteOrder(count);
9666 if (flavor == MachO::x86_THREAD_STATE32) {
9667 outs() << " flavor i386_THREAD_STATE\n";
9668 if (count == MachO::x86_THREAD_STATE32_COUNT)
9669 outs() << " count i386_THREAD_STATE_COUNT\n";
9670 else
9671 outs() << " count " << count
9672 << " (not x86_THREAD_STATE32_COUNT)\n";
9673 MachO::x86_thread_state32_t cpu32;
9674 left = end - begin;
9675 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9676 memcpy(&cpu32, begin, sizeof(MachO::x86_thread_state32_t));
9677 begin += sizeof(MachO::x86_thread_state32_t);
9678 } else {
9679 memset(&cpu32, '\0', sizeof(MachO::x86_thread_state32_t));
9680 memcpy(&cpu32, begin, left);
9681 begin += left;
9682 }
9683 if (isLittleEndian != sys::IsLittleEndianHost)
9684 swapStruct(cpu32);
9685 Print_x86_thread_state32_t(cpu32);
9686 } else if (flavor == MachO::x86_THREAD_STATE) {
9687 outs() << " flavor x86_THREAD_STATE\n";
9688 if (count == MachO::x86_THREAD_STATE_COUNT)
9689 outs() << " count x86_THREAD_STATE_COUNT\n";
9690 else
9691 outs() << " count " << count
9692 << " (not x86_THREAD_STATE_COUNT)\n";
9693 struct MachO::x86_thread_state_t ts;
9694 left = end - begin;
9695 if (left >= sizeof(MachO::x86_thread_state_t)) {
9696 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9697 begin += sizeof(MachO::x86_thread_state_t);
9698 } else {
9699 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9700 memcpy(&ts, begin, left);
9701 begin += left;
9702 }
9703 if (isLittleEndian != sys::IsLittleEndianHost)
9704 swapStruct(ts);
9705 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9706 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9707 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9708 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9709 else
9710 outs() << "tsh.count " << ts.tsh.count
9711 << " (not x86_THREAD_STATE32_COUNT\n";
9712 Print_x86_thread_state32_t(ts.uts.ts32);
9713 } else {
9714 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9715 << ts.tsh.count << "\n";
9716 }
9717 } else {
9718 outs() << " flavor " << flavor << " (unknown)\n";
9719 outs() << " count " << count << "\n";
9720 outs() << " state (unknown)\n";
9721 begin += count * sizeof(uint32_t);
9722 }
9723 }
9724 } else if (cputype == MachO::CPU_TYPE_X86_64) {
9725 while (begin < end) {
9726 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9727 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9728 begin += sizeof(uint32_t);
9729 } else {
9730 flavor = 0;
9731 begin = end;
9732 }
9733 if (isLittleEndian != sys::IsLittleEndianHost)
9734 sys::swapByteOrder(flavor);
9735 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9736 memcpy((char *)&count, begin, sizeof(uint32_t));
9737 begin += sizeof(uint32_t);
9738 } else {
9739 count = 0;
9740 begin = end;
9741 }
9742 if (isLittleEndian != sys::IsLittleEndianHost)
9743 sys::swapByteOrder(count);
9744 if (flavor == MachO::x86_THREAD_STATE64) {
9745 outs() << " flavor x86_THREAD_STATE64\n";
9746 if (count == MachO::x86_THREAD_STATE64_COUNT)
9747 outs() << " count x86_THREAD_STATE64_COUNT\n";
9748 else
9749 outs() << " count " << count
9750 << " (not x86_THREAD_STATE64_COUNT)\n";
9751 MachO::x86_thread_state64_t cpu64;
9752 left = end - begin;
9753 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9754 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
9755 begin += sizeof(MachO::x86_thread_state64_t);
9756 } else {
9757 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
9758 memcpy(&cpu64, begin, left);
9759 begin += left;
9760 }
9761 if (isLittleEndian != sys::IsLittleEndianHost)
9762 swapStruct(cpu64);
9763 Print_x86_thread_state64_t(cpu64);
9764 } else if (flavor == MachO::x86_THREAD_STATE) {
9765 outs() << " flavor x86_THREAD_STATE\n";
9766 if (count == MachO::x86_THREAD_STATE_COUNT)
9767 outs() << " count x86_THREAD_STATE_COUNT\n";
9768 else
9769 outs() << " count " << count
9770 << " (not x86_THREAD_STATE_COUNT)\n";
9771 struct MachO::x86_thread_state_t ts;
9772 left = end - begin;
9773 if (left >= sizeof(MachO::x86_thread_state_t)) {
9774 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
9775 begin += sizeof(MachO::x86_thread_state_t);
9776 } else {
9777 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
9778 memcpy(&ts, begin, left);
9779 begin += left;
9780 }
9781 if (isLittleEndian != sys::IsLittleEndianHost)
9782 swapStruct(ts);
9783 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9784 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9785 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9786 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9787 else
9788 outs() << "tsh.count " << ts.tsh.count
9789 << " (not x86_THREAD_STATE64_COUNT\n";
9790 Print_x86_thread_state64_t(ts.uts.ts64);
9791 } else {
9792 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9793 << ts.tsh.count << "\n";
9794 }
9795 } else if (flavor == MachO::x86_FLOAT_STATE) {
9796 outs() << " flavor x86_FLOAT_STATE\n";
9797 if (count == MachO::x86_FLOAT_STATE_COUNT)
9798 outs() << " count x86_FLOAT_STATE_COUNT\n";
9799 else
9800 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9801 struct MachO::x86_float_state_t fs;
9802 left = end - begin;
9803 if (left >= sizeof(MachO::x86_float_state_t)) {
9804 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
9805 begin += sizeof(MachO::x86_float_state_t);
9806 } else {
9807 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
9808 memcpy(&fs, begin, left);
9809 begin += left;
9810 }
9811 if (isLittleEndian != sys::IsLittleEndianHost)
9812 swapStruct(fs);
9813 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9814 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
9815 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9816 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9817 else
9818 outs() << "fsh.count " << fs.fsh.count
9819 << " (not x86_FLOAT_STATE64_COUNT\n";
9820 Print_x86_float_state_t(fs.ufs.fs64);
9821 } else {
9822 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9823 << fs.fsh.count << "\n";
9824 }
9825 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9826 outs() << " flavor x86_EXCEPTION_STATE\n";
9827 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9828 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9829 else
9830 outs() << " count " << count
9831 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9832 struct MachO::x86_exception_state_t es;
9833 left = end - begin;
9834 if (left >= sizeof(MachO::x86_exception_state_t)) {
9835 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
9836 begin += sizeof(MachO::x86_exception_state_t);
9837 } else {
9838 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
9839 memcpy(&es, begin, left);
9840 begin += left;
9841 }
9842 if (isLittleEndian != sys::IsLittleEndianHost)
9843 swapStruct(es);
9844 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9845 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
9846 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9847 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9848 else
9849 outs() << "\t esh.count " << es.esh.count
9850 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9851 Print_x86_exception_state_t(es.ues.es64);
9852 } else {
9853 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9854 << es.esh.count << "\n";
9855 }
9856 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9857 outs() << " flavor x86_EXCEPTION_STATE64\n";
9858 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9859 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9860 else
9861 outs() << " count " << count
9862 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9863 struct MachO::x86_exception_state64_t es64;
9864 left = end - begin;
9865 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9866 memcpy(&es64, begin, sizeof(MachO::x86_exception_state64_t));
9867 begin += sizeof(MachO::x86_exception_state64_t);
9868 } else {
9869 memset(&es64, '\0', sizeof(MachO::x86_exception_state64_t));
9870 memcpy(&es64, begin, left);
9871 begin += left;
9872 }
9873 if (isLittleEndian != sys::IsLittleEndianHost)
9874 swapStruct(es64);
9875 Print_x86_exception_state_t(es64);
9876 } else {
9877 outs() << " flavor " << flavor << " (unknown)\n";
9878 outs() << " count " << count << "\n";
9879 outs() << " state (unknown)\n";
9880 begin += count * sizeof(uint32_t);
9881 }
9882 }
9883 } else if (cputype == MachO::CPU_TYPE_ARM) {
9884 while (begin < end) {
9885 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9886 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9887 begin += sizeof(uint32_t);
9888 } else {
9889 flavor = 0;
9890 begin = end;
9891 }
9892 if (isLittleEndian != sys::IsLittleEndianHost)
9893 sys::swapByteOrder(flavor);
9894 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9895 memcpy((char *)&count, begin, sizeof(uint32_t));
9896 begin += sizeof(uint32_t);
9897 } else {
9898 count = 0;
9899 begin = end;
9900 }
9901 if (isLittleEndian != sys::IsLittleEndianHost)
9902 sys::swapByteOrder(count);
9903 if (flavor == MachO::ARM_THREAD_STATE) {
9904 outs() << " flavor ARM_THREAD_STATE\n";
9905 if (count == MachO::ARM_THREAD_STATE_COUNT)
9906 outs() << " count ARM_THREAD_STATE_COUNT\n";
9907 else
9908 outs() << " count " << count
9909 << " (not ARM_THREAD_STATE_COUNT)\n";
9910 MachO::arm_thread_state32_t cpu32;
9911 left = end - begin;
9912 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9913 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
9914 begin += sizeof(MachO::arm_thread_state32_t);
9915 } else {
9916 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
9917 memcpy(&cpu32, begin, left);
9918 begin += left;
9919 }
9920 if (isLittleEndian != sys::IsLittleEndianHost)
9921 swapStruct(cpu32);
9922 Print_arm_thread_state32_t(cpu32);
9923 } else {
9924 outs() << " flavor " << flavor << " (unknown)\n";
9925 outs() << " count " << count << "\n";
9926 outs() << " state (unknown)\n";
9927 begin += count * sizeof(uint32_t);
9928 }
9929 }
9930 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
9931 cputype == MachO::CPU_TYPE_ARM64_32) {
9932 while (begin < end) {
9933 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9934 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9935 begin += sizeof(uint32_t);
9936 } else {
9937 flavor = 0;
9938 begin = end;
9939 }
9940 if (isLittleEndian != sys::IsLittleEndianHost)
9941 sys::swapByteOrder(flavor);
9942 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9943 memcpy((char *)&count, begin, sizeof(uint32_t));
9944 begin += sizeof(uint32_t);
9945 } else {
9946 count = 0;
9947 begin = end;
9948 }
9949 if (isLittleEndian != sys::IsLittleEndianHost)
9950 sys::swapByteOrder(count);
9951 if (flavor == MachO::ARM_THREAD_STATE64) {
9952 outs() << " flavor ARM_THREAD_STATE64\n";
9953 if (count == MachO::ARM_THREAD_STATE64_COUNT)
9954 outs() << " count ARM_THREAD_STATE64_COUNT\n";
9955 else
9956 outs() << " count " << count
9957 << " (not ARM_THREAD_STATE64_COUNT)\n";
9958 MachO::arm_thread_state64_t cpu64;
9959 left = end - begin;
9960 if (left >= sizeof(MachO::arm_thread_state64_t)) {
9961 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
9962 begin += sizeof(MachO::arm_thread_state64_t);
9963 } else {
9964 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
9965 memcpy(&cpu64, begin, left);
9966 begin += left;
9967 }
9968 if (isLittleEndian != sys::IsLittleEndianHost)
9969 swapStruct(cpu64);
9970 Print_arm_thread_state64_t(cpu64);
9971 } else {
9972 outs() << " flavor " << flavor << " (unknown)\n";
9973 outs() << " count " << count << "\n";
9974 outs() << " state (unknown)\n";
9975 begin += count * sizeof(uint32_t);
9976 }
9977 }
9978 } else {
9979 while (begin < end) {
9980 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9981 memcpy((char *)&flavor, begin, sizeof(uint32_t));
9982 begin += sizeof(uint32_t);
9983 } else {
9984 flavor = 0;
9985 begin = end;
9986 }
9987 if (isLittleEndian != sys::IsLittleEndianHost)
9988 sys::swapByteOrder(flavor);
9989 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9990 memcpy((char *)&count, begin, sizeof(uint32_t));
9991 begin += sizeof(uint32_t);
9992 } else {
9993 count = 0;
9994 begin = end;
9995 }
9996 if (isLittleEndian != sys::IsLittleEndianHost)
9997 sys::swapByteOrder(count);
9998 outs() << " flavor " << flavor << "\n";
9999 outs() << " count " << count << "\n";
10000 outs() << " state (Unknown cputype/cpusubtype)\n";
10001 begin += count * sizeof(uint32_t);
10002 }
10003 }
10004 }
10005
PrintDylibCommand(MachO::dylib_command dl,const char * Ptr)10006 static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10007 if (dl.cmd == MachO::LC_ID_DYLIB)
10008 outs() << " cmd LC_ID_DYLIB\n";
10009 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
10010 outs() << " cmd LC_LOAD_DYLIB\n";
10011 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
10012 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
10013 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
10014 outs() << " cmd LC_REEXPORT_DYLIB\n";
10015 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
10016 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
10017 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
10018 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
10019 else
10020 outs() << " cmd " << dl.cmd << " (unknown)\n";
10021 outs() << " cmdsize " << dl.cmdsize;
10022 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
10023 outs() << " Incorrect size\n";
10024 else
10025 outs() << "\n";
10026 if (dl.dylib.name < dl.cmdsize) {
10027 const char *P = (const char *)(Ptr) + dl.dylib.name;
10028 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
10029 } else {
10030 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
10031 }
10032 outs() << " time stamp " << dl.dylib.timestamp << " ";
10033 time_t t = dl.dylib.timestamp;
10034 outs() << ctime(&t);
10035 outs() << " current version ";
10036 if (dl.dylib.current_version == 0xffffffff)
10037 outs() << "n/a\n";
10038 else
10039 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10040 << ((dl.dylib.current_version >> 8) & 0xff) << "."
10041 << (dl.dylib.current_version & 0xff) << "\n";
10042 outs() << "compatibility version ";
10043 if (dl.dylib.compatibility_version == 0xffffffff)
10044 outs() << "n/a\n";
10045 else
10046 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10047 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10048 << (dl.dylib.compatibility_version & 0xff) << "\n";
10049 }
10050
PrintLinkEditDataCommand(MachO::linkedit_data_command ld,uint32_t object_size)10051 static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10052 uint32_t object_size) {
10053 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10054 outs() << " cmd LC_CODE_SIGNATURE\n";
10055 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10056 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
10057 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10058 outs() << " cmd LC_FUNCTION_STARTS\n";
10059 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10060 outs() << " cmd LC_DATA_IN_CODE\n";
10061 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10062 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
10063 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10064 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
10065 else
10066 outs() << " cmd " << ld.cmd << " (?)\n";
10067 outs() << " cmdsize " << ld.cmdsize;
10068 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10069 outs() << " Incorrect size\n";
10070 else
10071 outs() << "\n";
10072 outs() << " dataoff " << ld.dataoff;
10073 if (ld.dataoff > object_size)
10074 outs() << " (past end of file)\n";
10075 else
10076 outs() << "\n";
10077 outs() << " datasize " << ld.datasize;
10078 uint64_t big_size = ld.dataoff;
10079 big_size += ld.datasize;
10080 if (big_size > object_size)
10081 outs() << " (past end of file)\n";
10082 else
10083 outs() << "\n";
10084 }
10085
PrintLoadCommands(const MachOObjectFile * Obj,uint32_t filetype,uint32_t cputype,bool verbose)10086 static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10087 uint32_t cputype, bool verbose) {
10088 StringRef Buf = Obj->getData();
10089 unsigned Index = 0;
10090 for (const auto &Command : Obj->load_commands()) {
10091 outs() << "Load command " << Index++ << "\n";
10092 if (Command.C.cmd == MachO::LC_SEGMENT) {
10093 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
10094 const char *sg_segname = SLC.segname;
10095 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
10096 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
10097 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
10098 verbose);
10099 for (unsigned j = 0; j < SLC.nsects; j++) {
10100 MachO::section S = Obj->getSection(Command, j);
10101 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
10102 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
10103 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
10104 }
10105 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10106 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
10107 const char *sg_segname = SLC_64.segname;
10108 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
10109 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
10110 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
10111 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
10112 for (unsigned j = 0; j < SLC_64.nsects; j++) {
10113 MachO::section_64 S_64 = Obj->getSection64(Command, j);
10114 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
10115 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
10116 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
10117 sg_segname, filetype, Buf.size(), verbose);
10118 }
10119 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10120 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10121 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
10122 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10123 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10124 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10125 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
10126 Obj->is64Bit());
10127 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10128 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10129 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
10130 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
10131 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10132 Command.C.cmd == MachO::LC_ID_DYLINKER ||
10133 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10134 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
10135 PrintDyldLoadCommand(Dyld, Command.Ptr);
10136 } else if (Command.C.cmd == MachO::LC_UUID) {
10137 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
10138 PrintUuidLoadCommand(Uuid);
10139 } else if (Command.C.cmd == MachO::LC_RPATH) {
10140 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
10141 PrintRpathLoadCommand(Rpath, Command.Ptr);
10142 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10143 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10144 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10145 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10146 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
10147 PrintVersionMinLoadCommand(Vd);
10148 } else if (Command.C.cmd == MachO::LC_NOTE) {
10149 MachO::note_command Nt = Obj->getNoteLoadCommand(Command);
10150 PrintNoteLoadCommand(Nt);
10151 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10152 MachO::build_version_command Bv =
10153 Obj->getBuildVersionLoadCommand(Command);
10154 PrintBuildVersionLoadCommand(Obj, Bv);
10155 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10156 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
10157 PrintSourceVersionCommand(Sd);
10158 } else if (Command.C.cmd == MachO::LC_MAIN) {
10159 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
10160 PrintEntryPointCommand(Ep);
10161 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10162 MachO::encryption_info_command Ei =
10163 Obj->getEncryptionInfoCommand(Command);
10164 PrintEncryptionInfoCommand(Ei, Buf.size());
10165 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10166 MachO::encryption_info_command_64 Ei =
10167 Obj->getEncryptionInfoCommand64(Command);
10168 PrintEncryptionInfoCommand64(Ei, Buf.size());
10169 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10170 MachO::linker_option_command Lo =
10171 Obj->getLinkerOptionLoadCommand(Command);
10172 PrintLinkerOptionCommand(Lo, Command.Ptr);
10173 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10174 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
10175 PrintSubFrameworkCommand(Sf, Command.Ptr);
10176 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10177 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
10178 PrintSubUmbrellaCommand(Sf, Command.Ptr);
10179 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10180 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
10181 PrintSubLibraryCommand(Sl, Command.Ptr);
10182 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10183 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
10184 PrintSubClientCommand(Sc, Command.Ptr);
10185 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10186 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
10187 PrintRoutinesCommand(Rc);
10188 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10189 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
10190 PrintRoutinesCommand64(Rc);
10191 } else if (Command.C.cmd == MachO::LC_THREAD ||
10192 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10193 MachO::thread_command Tc = Obj->getThreadCommand(Command);
10194 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
10195 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10196 Command.C.cmd == MachO::LC_ID_DYLIB ||
10197 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10198 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10199 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10200 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10201 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
10202 PrintDylibCommand(Dl, Command.Ptr);
10203 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10204 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10205 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10206 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10207 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10208 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
10209 MachO::linkedit_data_command Ld =
10210 Obj->getLinkeditDataLoadCommand(Command);
10211 PrintLinkEditDataCommand(Ld, Buf.size());
10212 } else {
10213 outs() << " cmd ?(" << format("0x%08" PRIx32, Command.C.cmd)
10214 << ")\n";
10215 outs() << " cmdsize " << Command.C.cmdsize << "\n";
10216 // TODO: get and print the raw bytes of the load command.
10217 }
10218 // TODO: print all the other kinds of load commands.
10219 }
10220 }
10221
PrintMachHeader(const MachOObjectFile * Obj,bool verbose)10222 static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10223 if (Obj->is64Bit()) {
10224 MachO::mach_header_64 H_64;
10225 H_64 = Obj->getHeader64();
10226 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
10227 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
10228 } else {
10229 MachO::mach_header H;
10230 H = Obj->getHeader();
10231 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
10232 H.sizeofcmds, H.flags, verbose);
10233 }
10234 }
10235
printMachOFileHeader(const object::ObjectFile * Obj)10236 void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10237 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10238 PrintMachHeader(file, !NonVerbose);
10239 }
10240
printMachOLoadCommands(const object::ObjectFile * Obj)10241 void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10242 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
10243 uint32_t filetype = 0;
10244 uint32_t cputype = 0;
10245 if (file->is64Bit()) {
10246 MachO::mach_header_64 H_64;
10247 H_64 = file->getHeader64();
10248 filetype = H_64.filetype;
10249 cputype = H_64.cputype;
10250 } else {
10251 MachO::mach_header H;
10252 H = file->getHeader();
10253 filetype = H.filetype;
10254 cputype = H.cputype;
10255 }
10256 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
10257 }
10258
10259 //===----------------------------------------------------------------------===//
10260 // export trie dumping
10261 //===----------------------------------------------------------------------===//
10262
printMachOExportsTrie(const object::MachOObjectFile * Obj)10263 static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10264 uint64_t BaseSegmentAddress = 0;
10265 for (const auto &Command : Obj->load_commands()) {
10266 if (Command.C.cmd == MachO::LC_SEGMENT) {
10267 MachO::segment_command Seg = Obj->getSegmentLoadCommand(Command);
10268 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10269 BaseSegmentAddress = Seg.vmaddr;
10270 break;
10271 }
10272 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10273 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(Command);
10274 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10275 BaseSegmentAddress = Seg.vmaddr;
10276 break;
10277 }
10278 }
10279 }
10280 Error Err = Error::success();
10281 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10282 uint64_t Flags = Entry.flags();
10283 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10284 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10285 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10286 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10287 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10288 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10289 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10290 if (ReExport)
10291 outs() << "[re-export] ";
10292 else
10293 outs() << format("0x%08llX ",
10294 Entry.address() + BaseSegmentAddress);
10295 outs() << Entry.name();
10296 if (WeakDef || ThreadLocal || Resolver || Abs) {
10297 bool NeedsComma = false;
10298 outs() << " [";
10299 if (WeakDef) {
10300 outs() << "weak_def";
10301 NeedsComma = true;
10302 }
10303 if (ThreadLocal) {
10304 if (NeedsComma)
10305 outs() << ", ";
10306 outs() << "per-thread";
10307 NeedsComma = true;
10308 }
10309 if (Abs) {
10310 if (NeedsComma)
10311 outs() << ", ";
10312 outs() << "absolute";
10313 NeedsComma = true;
10314 }
10315 if (Resolver) {
10316 if (NeedsComma)
10317 outs() << ", ";
10318 outs() << format("resolver=0x%08llX", Entry.other());
10319 NeedsComma = true;
10320 }
10321 outs() << "]";
10322 }
10323 if (ReExport) {
10324 StringRef DylibName = "unknown";
10325 int Ordinal = Entry.other() - 1;
10326 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
10327 if (Entry.otherName().empty())
10328 outs() << " (from " << DylibName << ")";
10329 else
10330 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10331 }
10332 outs() << "\n";
10333 }
10334 if (Err)
10335 reportError(std::move(Err), Obj->getFileName());
10336 }
10337
10338 //===----------------------------------------------------------------------===//
10339 // rebase table dumping
10340 //===----------------------------------------------------------------------===//
10341
printMachORebaseTable(object::MachOObjectFile * Obj)10342 static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10343 outs() << "segment section address type\n";
10344 Error Err = Error::success();
10345 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10346 StringRef SegmentName = Entry.segmentName();
10347 StringRef SectionName = Entry.sectionName();
10348 uint64_t Address = Entry.address();
10349
10350 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
10351 outs() << format("%-8s %-18s 0x%08" PRIX64 " %s\n",
10352 SegmentName.str().c_str(), SectionName.str().c_str(),
10353 Address, Entry.typeName().str().c_str());
10354 }
10355 if (Err)
10356 reportError(std::move(Err), Obj->getFileName());
10357 }
10358
ordinalName(const object::MachOObjectFile * Obj,int Ordinal)10359 static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10360 StringRef DylibName;
10361 switch (Ordinal) {
10362 case MachO::BIND_SPECIAL_DYLIB_SELF:
10363 return "this-image";
10364 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10365 return "main-executable";
10366 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10367 return "flat-namespace";
10368 default:
10369 if (Ordinal > 0) {
10370 std::error_code EC =
10371 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
10372 if (EC)
10373 return "<<bad library ordinal>>";
10374 return DylibName;
10375 }
10376 }
10377 return "<<unknown special ordinal>>";
10378 }
10379
10380 //===----------------------------------------------------------------------===//
10381 // bind table dumping
10382 //===----------------------------------------------------------------------===//
10383
printMachOBindTable(object::MachOObjectFile * Obj)10384 static void printMachOBindTable(object::MachOObjectFile *Obj) {
10385 // Build table of sections so names can used in final output.
10386 outs() << "segment section address type "
10387 "addend dylib symbol\n";
10388 Error Err = Error::success();
10389 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10390 StringRef SegmentName = Entry.segmentName();
10391 StringRef SectionName = Entry.sectionName();
10392 uint64_t Address = Entry.address();
10393
10394 // Table lines look like:
10395 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
10396 StringRef Attr;
10397 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10398 Attr = " (weak_import)";
10399 outs() << left_justify(SegmentName, 8) << " "
10400 << left_justify(SectionName, 18) << " "
10401 << format_hex(Address, 10, true) << " "
10402 << left_justify(Entry.typeName(), 8) << " "
10403 << format_decimal(Entry.addend(), 8) << " "
10404 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10405 << Entry.symbolName() << Attr << "\n";
10406 }
10407 if (Err)
10408 reportError(std::move(Err), Obj->getFileName());
10409 }
10410
10411 //===----------------------------------------------------------------------===//
10412 // lazy bind table dumping
10413 //===----------------------------------------------------------------------===//
10414
printMachOLazyBindTable(object::MachOObjectFile * Obj)10415 static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10416 outs() << "segment section address "
10417 "dylib symbol\n";
10418 Error Err = Error::success();
10419 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10420 StringRef SegmentName = Entry.segmentName();
10421 StringRef SectionName = Entry.sectionName();
10422 uint64_t Address = Entry.address();
10423
10424 // Table lines look like:
10425 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
10426 outs() << left_justify(SegmentName, 8) << " "
10427 << left_justify(SectionName, 18) << " "
10428 << format_hex(Address, 10, true) << " "
10429 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
10430 << Entry.symbolName() << "\n";
10431 }
10432 if (Err)
10433 reportError(std::move(Err), Obj->getFileName());
10434 }
10435
10436 //===----------------------------------------------------------------------===//
10437 // weak bind table dumping
10438 //===----------------------------------------------------------------------===//
10439
printMachOWeakBindTable(object::MachOObjectFile * Obj)10440 static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10441 outs() << "segment section address "
10442 "type addend symbol\n";
10443 Error Err = Error::success();
10444 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10445 // Strong symbols don't have a location to update.
10446 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10447 outs() << " strong "
10448 << Entry.symbolName() << "\n";
10449 continue;
10450 }
10451 StringRef SegmentName = Entry.segmentName();
10452 StringRef SectionName = Entry.sectionName();
10453 uint64_t Address = Entry.address();
10454
10455 // Table lines look like:
10456 // __DATA __data 0x00001000 pointer 0 _foo
10457 outs() << left_justify(SegmentName, 8) << " "
10458 << left_justify(SectionName, 18) << " "
10459 << format_hex(Address, 10, true) << " "
10460 << left_justify(Entry.typeName(), 8) << " "
10461 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
10462 << "\n";
10463 }
10464 if (Err)
10465 reportError(std::move(Err), Obj->getFileName());
10466 }
10467
10468 // get_dyld_bind_info_symbolname() is used for disassembly and passed an
10469 // address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10470 // information for that address. If the address is found its binding symbol
10471 // name is returned. If not nullptr is returned.
get_dyld_bind_info_symbolname(uint64_t ReferenceValue,struct DisassembleInfo * info)10472 static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10473 struct DisassembleInfo *info) {
10474 if (info->bindtable == nullptr) {
10475 info->bindtable = std::make_unique<SymbolAddressMap>();
10476 Error Err = Error::success();
10477 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10478 uint64_t Address = Entry.address();
10479 StringRef name = Entry.symbolName();
10480 if (!name.empty())
10481 (*info->bindtable)[Address] = name;
10482 }
10483 if (Err)
10484 reportError(std::move(Err), info->O->getFileName());
10485 }
10486 auto name = info->bindtable->lookup(ReferenceValue);
10487 return !name.empty() ? name.data() : nullptr;
10488 }
10489
printLazyBindTable(ObjectFile * o)10490 void objdump::printLazyBindTable(ObjectFile *o) {
10491 outs() << "Lazy bind table:\n";
10492 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10493 printMachOLazyBindTable(MachO);
10494 else
10495 WithColor::error()
10496 << "This operation is only currently supported "
10497 "for Mach-O executable files.\n";
10498 }
10499
printWeakBindTable(ObjectFile * o)10500 void objdump::printWeakBindTable(ObjectFile *o) {
10501 outs() << "Weak bind table:\n";
10502 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10503 printMachOWeakBindTable(MachO);
10504 else
10505 WithColor::error()
10506 << "This operation is only currently supported "
10507 "for Mach-O executable files.\n";
10508 }
10509
printExportsTrie(const ObjectFile * o)10510 void objdump::printExportsTrie(const ObjectFile *o) {
10511 outs() << "Exports trie:\n";
10512 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10513 printMachOExportsTrie(MachO);
10514 else
10515 WithColor::error()
10516 << "This operation is only currently supported "
10517 "for Mach-O executable files.\n";
10518 }
10519
printRebaseTable(ObjectFile * o)10520 void objdump::printRebaseTable(ObjectFile *o) {
10521 outs() << "Rebase table:\n";
10522 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10523 printMachORebaseTable(MachO);
10524 else
10525 WithColor::error()
10526 << "This operation is only currently supported "
10527 "for Mach-O executable files.\n";
10528 }
10529
printBindTable(ObjectFile * o)10530 void objdump::printBindTable(ObjectFile *o) {
10531 outs() << "Bind table:\n";
10532 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
10533 printMachOBindTable(MachO);
10534 else
10535 WithColor::error()
10536 << "This operation is only currently supported "
10537 "for Mach-O executable files.\n";
10538 }
10539