1//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MachO-specific dumper for llvm-objdump.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MachODump.h"
14
15#include "ObjdumpOptID.h"
16#include "SourcePrinter.h"
17#include "llvm-objdump.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringExtras.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/MC/TargetRegistry.h"
36#include "llvm/Object/MachO.h"
37#include "llvm/Object/MachOUniversal.h"
38#include "llvm/Option/ArgList.h"
39#include "llvm/Support/Casting.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/Endian.h"
42#include "llvm/Support/Format.h"
43#include "llvm/Support/FormattedStream.h"
44#include "llvm/Support/LEB128.h"
45#include "llvm/Support/MemoryBuffer.h"
46#include "llvm/Support/WithColor.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/TargetParser/Triple.h"
49#include <algorithm>
50#include <cstring>
51#include <system_error>
52
53using namespace llvm;
54using namespace llvm::object;
55using namespace llvm::objdump;
56
57bool objdump::FirstPrivateHeader;
58bool objdump::ExportsTrie;
59bool objdump::Rebase;
60bool objdump::Rpaths;
61bool objdump::Bind;
62bool objdump::LazyBind;
63bool objdump::WeakBind;
64static bool UseDbg;
65static std::string DSYMFile;
66bool objdump::FullLeadingAddr;
67bool objdump::LeadingHeaders;
68bool objdump::UniversalHeaders;
69static bool ArchiveMemberOffsets;
70bool objdump::IndirectSymbols;
71bool objdump::DataInCode;
72FunctionStartsMode objdump::FunctionStartsType =
73 objdump::FunctionStartsMode::None;
74bool objdump::LinkOptHints;
75bool objdump::InfoPlist;
76bool objdump::ChainedFixups;
77bool objdump::DyldInfo;
78bool objdump::DylibsUsed;
79bool objdump::DylibId;
80bool objdump::Verbose;
81bool objdump::ObjcMetaData;
82std::string objdump::DisSymName;
83bool objdump::IsOtool;
84bool objdump::UseMemberSyntax;
85bool objdump::SymbolicOperands;
86std::vector<std::string> objdump::ArchFlags;
87
88static bool ArchAll = false;
89static std::string ArchiveMemberFilter;
90static std::string ThumbTripleName;
91
92static StringRef ordinalName(const object::MachOObjectFile *, int);
93
94void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) {
95 FirstPrivateHeader = InputArgs.hasArg(Ids: OBJDUMP_private_header);
96 ExportsTrie = InputArgs.hasArg(Ids: OBJDUMP_exports_trie);
97 Rebase = InputArgs.hasArg(Ids: OBJDUMP_rebase);
98 Rpaths = InputArgs.hasArg(Ids: OBJDUMP_rpaths);
99 Bind = InputArgs.hasArg(Ids: OBJDUMP_bind);
100 LazyBind = InputArgs.hasArg(Ids: OBJDUMP_lazy_bind);
101 WeakBind = InputArgs.hasArg(Ids: OBJDUMP_weak_bind);
102 UseDbg = InputArgs.hasArg(Ids: OBJDUMP_g);
103 DSYMFile = InputArgs.getLastArgValue(Id: OBJDUMP_dsym_EQ).str();
104 FullLeadingAddr = InputArgs.hasArg(Ids: OBJDUMP_full_leading_addr);
105 LeadingHeaders = !InputArgs.hasArg(Ids: OBJDUMP_no_leading_headers);
106 UniversalHeaders = InputArgs.hasArg(Ids: OBJDUMP_universal_headers);
107 ArchiveMemberOffsets = InputArgs.hasArg(Ids: OBJDUMP_archive_member_offsets);
108 IndirectSymbols = InputArgs.hasArg(Ids: OBJDUMP_indirect_symbols);
109 DataInCode = InputArgs.hasArg(Ids: OBJDUMP_data_in_code);
110 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_function_starts_EQ)) {
111 FunctionStartsType = StringSwitch<FunctionStartsMode>(A->getValue())
112 .Case(S: "addrs", Value: FunctionStartsMode::Addrs)
113 .Case(S: "names", Value: FunctionStartsMode::Names)
114 .Case(S: "both", Value: FunctionStartsMode::Both)
115 .Default(Value: FunctionStartsMode::None);
116 if (FunctionStartsType == FunctionStartsMode::None)
117 invalidArgValue(A);
118 }
119 LinkOptHints = InputArgs.hasArg(Ids: OBJDUMP_link_opt_hints);
120 InfoPlist = InputArgs.hasArg(Ids: OBJDUMP_info_plist);
121 ChainedFixups = InputArgs.hasArg(Ids: OBJDUMP_chained_fixups);
122 DyldInfo = InputArgs.hasArg(Ids: OBJDUMP_dyld_info);
123 DylibsUsed = InputArgs.hasArg(Ids: OBJDUMP_dylibs_used);
124 DylibId = InputArgs.hasArg(Ids: OBJDUMP_dylib_id);
125 Verbose = !InputArgs.hasArg(Ids: OBJDUMP_non_verbose);
126 ObjcMetaData = InputArgs.hasArg(Ids: OBJDUMP_objc_meta_data);
127 DisSymName = InputArgs.getLastArgValue(Id: OBJDUMP_dis_symname).str();
128 SymbolicOperands = !InputArgs.hasArg(Ids: OBJDUMP_no_symbolic_operands);
129 ArchFlags = InputArgs.getAllArgValues(Id: OBJDUMP_arch_EQ);
130}
131
132static const Target *GetTarget(const MachOObjectFile *MachOObj,
133 const char **McpuDefault,
134 const Target **ThumbTarget,
135 Triple &ThumbTriple) {
136 // Figure out the target triple.
137 Triple TT(TripleName);
138 if (TripleName.empty()) {
139 TT = MachOObj->getArchTriple(McpuDefault);
140 TripleName = TT.str();
141 }
142
143 if (TT.getArch() == Triple::arm) {
144 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
145 // that support ARM are also capable of Thumb mode.
146 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(Start: 3)).str();
147 ThumbTriple = TT;
148 ThumbTriple.setArchName(ThumbName);
149 ThumbTripleName = ThumbTriple.str();
150 }
151
152 // Get the target specific parser.
153 std::string Error;
154 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple: TT, Error);
155 if (TheTarget && ThumbTripleName.empty())
156 return TheTarget;
157
158 *ThumbTarget = TargetRegistry::lookupTarget(TheTriple: ThumbTriple, Error);
159 if (*ThumbTarget)
160 return TheTarget;
161
162 WithColor::error(OS&: errs(), Prefix: "llvm-objdump") << "unable to get target for '";
163 if (!TheTarget)
164 errs() << TripleName;
165 else
166 errs() << ThumbTripleName;
167 errs() << "', see --version and --triple.\n";
168 return nullptr;
169}
170
171namespace {
172struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
174 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
175 if (!ATypeOrErr)
176 reportError(E: ATypeOrErr.takeError(), FileName: A.getObject()->getFileName());
177 SymbolRef::Type AType = *ATypeOrErr;
178 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
179 if (!BTypeOrErr)
180 reportError(E: BTypeOrErr.takeError(), FileName: B.getObject()->getFileName());
181 SymbolRef::Type BType = *BTypeOrErr;
182 uint64_t AAddr =
183 (AType != SymbolRef::ST_Function) ? 0 : cantFail(ValOrErr: A.getValue());
184 uint64_t BAddr =
185 (BType != SymbolRef::ST_Function) ? 0 : cantFail(ValOrErr: B.getValue());
186 return AAddr < BAddr;
187 }
188};
189
190class MachODumper : public Dumper {
191 const object::MachOObjectFile &Obj;
192
193public:
194 MachODumper(const object::MachOObjectFile &O) : Dumper(O), Obj(O) {}
195 void printPrivateHeaders() override;
196};
197} // namespace
198
199std::unique_ptr<Dumper>
200objdump::createMachODumper(const object::MachOObjectFile &Obj) {
201 return std::make_unique<MachODumper>(args: Obj);
202}
203
204// Types for the storted data in code table that is built before disassembly
205// and the predicate function to sort them.
206typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
207typedef std::vector<DiceTableEntry> DiceTable;
208typedef DiceTable::iterator dice_table_iterator;
209
210// This is used to search for a data in code table entry for the PC being
211// disassembled. The j parameter has the PC in j.first. A single data in code
212// table entry can cover many bytes for each of its Kind's. So if the offset,
213// aka the i.first value, of the data in code table entry plus its Length
214// covers the PC being searched for this will return true. If not it will
215// return false.
216static bool compareDiceTableEntries(const DiceTableEntry &i,
217 const DiceTableEntry &j) {
218 uint16_t Length;
219 i.second.getLength(Result&: Length);
220
221 return j.first >= i.first && j.first < i.first + Length;
222}
223
224static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
225 unsigned short Kind) {
226 uint32_t Value, Size = 1;
227
228 switch (Kind) {
229 default:
230 case MachO::DICE_KIND_DATA:
231 if (Length >= 4) {
232 if (ShowRawInsn)
233 dumpBytes(Bytes: ArrayRef(bytes, 4), OS&: outs());
234 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
235 outs() << "\t.long " << Value;
236 Size = 4;
237 } else if (Length >= 2) {
238 if (ShowRawInsn)
239 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
240 Value = bytes[1] << 8 | bytes[0];
241 outs() << "\t.short " << Value;
242 Size = 2;
243 } else {
244 if (ShowRawInsn)
245 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
246 Value = bytes[0];
247 outs() << "\t.byte " << Value;
248 Size = 1;
249 }
250 if (Kind == MachO::DICE_KIND_DATA)
251 outs() << "\t@ KIND_DATA\n";
252 else
253 outs() << "\t@ data in code kind = " << Kind << "\n";
254 break;
255 case MachO::DICE_KIND_JUMP_TABLE8:
256 if (ShowRawInsn)
257 dumpBytes(Bytes: ArrayRef(bytes, 1), OS&: outs());
258 Value = bytes[0];
259 outs() << "\t.byte " << format(Fmt: "%3u", Vals: Value) << "\t@ KIND_JUMP_TABLE8\n";
260 Size = 1;
261 break;
262 case MachO::DICE_KIND_JUMP_TABLE16:
263 if (ShowRawInsn)
264 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
265 Value = bytes[1] << 8 | bytes[0];
266 outs() << "\t.short " << format(Fmt: "%5u", Vals: Value & 0xffff)
267 << "\t@ KIND_JUMP_TABLE16\n";
268 Size = 2;
269 break;
270 case MachO::DICE_KIND_JUMP_TABLE32:
271 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
272 if (ShowRawInsn)
273 dumpBytes(Bytes: ArrayRef(bytes, 4), OS&: outs());
274 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
275 outs() << "\t.long " << Value;
276 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
277 outs() << "\t@ KIND_JUMP_TABLE32\n";
278 else
279 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
280 Size = 4;
281 break;
282 }
283 return Size;
284}
285
286static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
287 std::vector<SectionRef> &Sections,
288 std::vector<SymbolRef> &Symbols,
289 SmallVectorImpl<uint64_t> &FoundFns,
290 uint64_t &BaseSegmentAddress) {
291 const StringRef FileName = MachOObj->getFileName();
292 for (const SymbolRef &Symbol : MachOObj->symbols()) {
293 StringRef SymName = unwrapOrError(EO: Symbol.getName(), Args: FileName);
294 if (!SymName.starts_with(Prefix: "ltmp"))
295 Symbols.push_back(x: Symbol);
296 }
297
298 append_range(C&: Sections, R: MachOObj->sections());
299
300 bool BaseSegmentAddressSet = false;
301 for (const auto &Command : MachOObj->load_commands()) {
302 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
303 // We found a function starts segment, parse the addresses for later
304 // consumption.
305 MachO::linkedit_data_command LLC =
306 MachOObj->getLinkeditDataLoadCommand(L: Command);
307
308 MachOObj->ReadULEB128s(Index: LLC.dataoff, Out&: FoundFns);
309 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
310 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(L: Command);
311 StringRef SegName = SLC.segname;
312 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
313 BaseSegmentAddressSet = true;
314 BaseSegmentAddress = SLC.vmaddr;
315 }
316 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
317 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(L: Command);
318 StringRef SegName = SLC.segname;
319 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
320 BaseSegmentAddressSet = true;
321 BaseSegmentAddress = SLC.vmaddr;
322 }
323 }
324 }
325}
326
327static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
328 DiceTable &Dices, uint64_t &InstSize) {
329 // Check the data in code table here to see if this is data not an
330 // instruction to be disassembled.
331 DiceTable Dice;
332 Dice.push_back(x: std::make_pair(x&: PC, y: DiceRef()));
333 dice_table_iterator DTI =
334 std::search(first1: Dices.begin(), last1: Dices.end(), first2: Dice.begin(), last2: Dice.end(),
335 predicate: compareDiceTableEntries);
336 if (DTI != Dices.end()) {
337 uint16_t Length;
338 DTI->second.getLength(Result&: Length);
339 uint16_t Kind;
340 DTI->second.getKind(Result&: Kind);
341 InstSize = DumpDataInCode(bytes, Length, Kind);
342 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
343 (PC == (DTI->first + Length - 1)) && (Length & 1))
344 InstSize++;
345 return true;
346 }
347 return false;
348}
349
350static void printRelocationTargetName(const MachOObjectFile *O,
351 const MachO::any_relocation_info &RE,
352 raw_string_ostream &Fmt) {
353 // Target of a scattered relocation is an address. In the interest of
354 // generating pretty output, scan through the symbol table looking for a
355 // symbol that aligns with that address. If we find one, print it.
356 // Otherwise, we just print the hex address of the target.
357 const StringRef FileName = O->getFileName();
358 if (O->isRelocationScattered(RE)) {
359 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
360
361 for (const SymbolRef &Symbol : O->symbols()) {
362 uint64_t Addr = unwrapOrError(EO: Symbol.getAddress(), Args: FileName);
363 if (Addr != Val)
364 continue;
365 Fmt << unwrapOrError(EO: Symbol.getName(), Args: FileName);
366 return;
367 }
368
369 // If we couldn't find a symbol that this relocation refers to, try
370 // to find a section beginning instead.
371 for (const SectionRef &Section : ToolSectionFilter(O: *O)) {
372 uint64_t Addr = Section.getAddress();
373 if (Addr != Val)
374 continue;
375 StringRef NameOrErr = unwrapOrError(EO: Section.getName(), Args: O->getFileName());
376 Fmt << NameOrErr;
377 return;
378 }
379
380 Fmt << format(Fmt: "0x%x", Vals: Val);
381 return;
382 }
383
384 StringRef S;
385 bool isExtern = O->getPlainRelocationExternal(RE);
386 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
387
388 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
389 Triple(O->getArchTriple()).isAArch64()) {
390 Fmt << format(Fmt: "0x%0" PRIx64, Vals: Val);
391 return;
392 }
393
394 if (O->getAnyRelocationType(RE) == MachO::RISCV_RELOC_ADDEND &&
395 O->getArch() == Triple::riscv32) {
396 Fmt << format(Fmt: "0x%0" PRIx64, Vals: Val);
397 return;
398 }
399
400 if (isExtern) {
401 symbol_iterator SI = O->symbol_begin();
402 std::advance(i&: SI, n: Val);
403 S = unwrapOrError(EO: SI->getName(), Args: FileName);
404 } else {
405 section_iterator SI = O->section_begin();
406 // Adjust for the fact that sections are 1-indexed.
407 if (Val == 0) {
408 Fmt << "0 (?,?)";
409 return;
410 }
411 uint32_t I = Val - 1;
412 while (I != 0 && SI != O->section_end()) {
413 --I;
414 std::advance(i&: SI, n: 1);
415 }
416 if (SI == O->section_end()) {
417 Fmt << Val << " (?,?)";
418 } else {
419 if (Expected<StringRef> NameOrErr = SI->getName())
420 S = *NameOrErr;
421 else
422 consumeError(Err: NameOrErr.takeError());
423 }
424 }
425
426 Fmt << S;
427}
428
429Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
430 const RelocationRef &RelRef,
431 SmallVectorImpl<char> &Result) {
432 DataRefImpl Rel = RelRef.getRawDataRefImpl();
433 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
434
435 unsigned Arch = Obj->getArch();
436
437 std::string FmtBuf;
438 raw_string_ostream Fmt(FmtBuf);
439 unsigned Type = Obj->getAnyRelocationType(RE);
440 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
441
442 // Determine any addends that should be displayed with the relocation.
443 // These require decoding the relocation type, which is triple-specific.
444
445 // X86_64 has entirely custom relocation types.
446 if (Arch == Triple::x86_64) {
447 switch (Type) {
448 case MachO::X86_64_RELOC_GOT_LOAD:
449 case MachO::X86_64_RELOC_GOT: {
450 printRelocationTargetName(O: Obj, RE, Fmt);
451 Fmt << "@GOT";
452 if (IsPCRel)
453 Fmt << "PCREL";
454 break;
455 }
456 case MachO::X86_64_RELOC_SUBTRACTOR: {
457 DataRefImpl RelNext = Rel;
458 Obj->moveRelocationNext(Rel&: RelNext);
459 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
460
461 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
462 // X86_64_RELOC_UNSIGNED.
463 // NOTE: Scattered relocations don't exist on x86_64.
464 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
465 if (RType != MachO::X86_64_RELOC_UNSIGNED)
466 reportError(File: Obj->getFileName(), Message: "Expected X86_64_RELOC_UNSIGNED after "
467 "X86_64_RELOC_SUBTRACTOR.");
468
469 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
470 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
471 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
472 Fmt << "-";
473 printRelocationTargetName(O: Obj, RE, Fmt);
474 break;
475 }
476 case MachO::X86_64_RELOC_TLV:
477 printRelocationTargetName(O: Obj, RE, Fmt);
478 Fmt << "@TLV";
479 if (IsPCRel)
480 Fmt << "P";
481 break;
482 case MachO::X86_64_RELOC_SIGNED_1:
483 printRelocationTargetName(O: Obj, RE, Fmt);
484 Fmt << "-1";
485 break;
486 case MachO::X86_64_RELOC_SIGNED_2:
487 printRelocationTargetName(O: Obj, RE, Fmt);
488 Fmt << "-2";
489 break;
490 case MachO::X86_64_RELOC_SIGNED_4:
491 printRelocationTargetName(O: Obj, RE, Fmt);
492 Fmt << "-4";
493 break;
494 default:
495 printRelocationTargetName(O: Obj, RE, Fmt);
496 break;
497 }
498 // X86 and ARM share some relocation types in common.
499 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
500 Arch == Triple::ppc) {
501 // Generic relocation types...
502 switch (Type) {
503 case MachO::GENERIC_RELOC_PAIR: // prints no info
504 return Error::success();
505 case MachO::GENERIC_RELOC_SECTDIFF: {
506 DataRefImpl RelNext = Rel;
507 Obj->moveRelocationNext(Rel&: RelNext);
508 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
509
510 // X86 sect diff's must be followed by a relocation of type
511 // GENERIC_RELOC_PAIR.
512 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
513
514 if (RType != MachO::GENERIC_RELOC_PAIR)
515 reportError(File: Obj->getFileName(), Message: "Expected GENERIC_RELOC_PAIR after "
516 "GENERIC_RELOC_SECTDIFF.");
517
518 printRelocationTargetName(O: Obj, RE, Fmt);
519 Fmt << "-";
520 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
521 break;
522 }
523 }
524
525 if (Arch == Triple::x86 || Arch == Triple::ppc) {
526 switch (Type) {
527 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
528 DataRefImpl RelNext = Rel;
529 Obj->moveRelocationNext(Rel&: RelNext);
530 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
531
532 // X86 sect diff's must be followed by a relocation of type
533 // GENERIC_RELOC_PAIR.
534 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
535 if (RType != MachO::GENERIC_RELOC_PAIR)
536 reportError(File: Obj->getFileName(), Message: "Expected GENERIC_RELOC_PAIR after "
537 "GENERIC_RELOC_LOCAL_SECTDIFF.");
538
539 printRelocationTargetName(O: Obj, RE, Fmt);
540 Fmt << "-";
541 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
542 break;
543 }
544 case MachO::GENERIC_RELOC_TLV: {
545 printRelocationTargetName(O: Obj, RE, Fmt);
546 Fmt << "@TLV";
547 if (IsPCRel)
548 Fmt << "P";
549 break;
550 }
551 default:
552 printRelocationTargetName(O: Obj, RE, Fmt);
553 }
554 } else { // ARM-specific relocations
555 switch (Type) {
556 case MachO::ARM_RELOC_HALF:
557 case MachO::ARM_RELOC_HALF_SECTDIFF: {
558 // Half relocations steal a bit from the length field to encode
559 // whether this is an upper16 or a lower16 relocation.
560 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
561
562 if (isUpper)
563 Fmt << ":upper16:(";
564 else
565 Fmt << ":lower16:(";
566 printRelocationTargetName(O: Obj, RE, Fmt);
567
568 DataRefImpl RelNext = Rel;
569 Obj->moveRelocationNext(Rel&: RelNext);
570 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
571
572 // ARM half relocs must be followed by a relocation of type
573 // ARM_RELOC_PAIR.
574 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
575 if (RType != MachO::ARM_RELOC_PAIR)
576 reportError(File: Obj->getFileName(), Message: "Expected ARM_RELOC_PAIR after "
577 "ARM_RELOC_HALF");
578
579 // NOTE: The half of the target virtual address is stashed in the
580 // address field of the secondary relocation, but we can't reverse
581 // engineer the constant offset from it without decoding the movw/movt
582 // instruction to find the other half in its immediate field.
583
584 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
585 // symbol/section pointer of the follow-on relocation.
586 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
587 Fmt << "-";
588 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
589 }
590
591 Fmt << ")";
592 break;
593 }
594 default: {
595 printRelocationTargetName(O: Obj, RE, Fmt);
596 }
597 }
598 }
599 } else
600 printRelocationTargetName(O: Obj, RE, Fmt);
601
602 Result.append(in_start: FmtBuf.begin(), in_end: FmtBuf.end());
603 return Error::success();
604}
605
606static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
607 uint32_t n, uint32_t count,
608 uint32_t stride, uint64_t addr) {
609 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
610 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
611 if (n > nindirectsyms)
612 outs() << " (entries start past the end of the indirect symbol "
613 "table) (reserved1 field greater than the table size)";
614 else if (n + count > nindirectsyms)
615 outs() << " (entries extends past the end of the indirect symbol "
616 "table)";
617 outs() << "\n";
618 uint32_t cputype = O->getHeader().cputype;
619 if (cputype & MachO::CPU_ARCH_ABI64)
620 outs() << "address index";
621 else
622 outs() << "address index";
623 if (verbose)
624 outs() << " name\n";
625 else
626 outs() << "\n";
627 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
628 if (cputype & MachO::CPU_ARCH_ABI64)
629 outs() << format(Fmt: "0x%016" PRIx64, Vals: addr + j * stride) << " ";
630 else
631 outs() << format(Fmt: "0x%08" PRIx32, Vals: (uint32_t)addr + j * stride) << " ";
632 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
633 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: n + j);
634 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
635 outs() << "LOCAL\n";
636 continue;
637 }
638 if (indirect_symbol ==
639 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
640 outs() << "LOCAL ABSOLUTE\n";
641 continue;
642 }
643 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
644 outs() << "ABSOLUTE\n";
645 continue;
646 }
647 outs() << format(Fmt: "%5u ", Vals: indirect_symbol);
648 if (verbose) {
649 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
650 if (indirect_symbol < Symtab.nsyms) {
651 symbol_iterator Sym = O->getSymbolByIndex(Index: indirect_symbol);
652 SymbolRef Symbol = *Sym;
653 outs() << unwrapOrError(EO: Symbol.getName(), Args: O->getFileName());
654 } else {
655 outs() << "?";
656 }
657 }
658 outs() << "\n";
659 }
660}
661
662static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
663 for (const auto &Load : O->load_commands()) {
664 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
665 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(L: Load);
666 for (unsigned J = 0; J < Seg.nsects; ++J) {
667 MachO::section_64 Sec = O->getSection64(L: Load, Index: J);
668 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
669 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
670 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
671 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
672 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
673 section_type == MachO::S_SYMBOL_STUBS) {
674 uint32_t stride;
675 if (section_type == MachO::S_SYMBOL_STUBS)
676 stride = Sec.reserved2;
677 else
678 stride = 8;
679 if (stride == 0) {
680 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
681 << Sec.sectname << ") "
682 << "(size of stubs in reserved2 field is zero)\n";
683 continue;
684 }
685 uint32_t count = Sec.size / stride;
686 outs() << "Indirect symbols for (" << Sec.segname << ","
687 << Sec.sectname << ") " << count << " entries";
688 uint32_t n = Sec.reserved1;
689 PrintIndirectSymbolTable(O, verbose, n, count, stride, addr: Sec.addr);
690 }
691 }
692 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
693 MachO::segment_command Seg = O->getSegmentLoadCommand(L: Load);
694 for (unsigned J = 0; J < Seg.nsects; ++J) {
695 MachO::section Sec = O->getSection(L: Load, Index: J);
696 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
697 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
698 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
699 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
700 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
701 section_type == MachO::S_SYMBOL_STUBS) {
702 uint32_t stride;
703 if (section_type == MachO::S_SYMBOL_STUBS)
704 stride = Sec.reserved2;
705 else
706 stride = 4;
707 if (stride == 0) {
708 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
709 << Sec.sectname << ") "
710 << "(size of stubs in reserved2 field is zero)\n";
711 continue;
712 }
713 uint32_t count = Sec.size / stride;
714 outs() << "Indirect symbols for (" << Sec.segname << ","
715 << Sec.sectname << ") " << count << " entries";
716 uint32_t n = Sec.reserved1;
717 PrintIndirectSymbolTable(O, verbose, n, count, stride, addr: Sec.addr);
718 }
719 }
720 }
721 }
722}
723
724static void PrintRType(const uint64_t cputype, const unsigned r_type) {
725 static char const *generic_r_types[] = {
726 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
727 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
728 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
729 };
730 static char const *x86_64_r_types[] = {
731 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
732 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
733 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
734 };
735 static char const *arm_r_types[] = {
736 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
737 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
738 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
739 };
740 static char const *arm64_r_types[] = {
741 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
742 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
743 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
744 };
745
746 if (r_type > 0xf){
747 outs() << format(Fmt: "%-7u", Vals: r_type) << " ";
748 return;
749 }
750 switch (cputype) {
751 case MachO::CPU_TYPE_I386:
752 outs() << generic_r_types[r_type];
753 break;
754 case MachO::CPU_TYPE_X86_64:
755 outs() << x86_64_r_types[r_type];
756 break;
757 case MachO::CPU_TYPE_ARM:
758 outs() << arm_r_types[r_type];
759 break;
760 case MachO::CPU_TYPE_ARM64:
761 case MachO::CPU_TYPE_ARM64_32:
762 outs() << arm64_r_types[r_type];
763 break;
764 default:
765 outs() << format(Fmt: "%-7u ", Vals: r_type);
766 }
767}
768
769static void PrintRLength(const uint64_t cputype, const unsigned r_type,
770 const unsigned r_length, const bool previous_arm_half){
771 if (cputype == MachO::CPU_TYPE_ARM &&
772 (r_type == MachO::ARM_RELOC_HALF ||
773 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
774 if ((r_length & 0x1) == 0)
775 outs() << "lo/";
776 else
777 outs() << "hi/";
778 if ((r_length & 0x1) == 0)
779 outs() << "arm ";
780 else
781 outs() << "thm ";
782 } else {
783 switch (r_length) {
784 case 0:
785 outs() << "byte ";
786 break;
787 case 1:
788 outs() << "word ";
789 break;
790 case 2:
791 outs() << "long ";
792 break;
793 case 3:
794 if (cputype == MachO::CPU_TYPE_X86_64)
795 outs() << "quad ";
796 else
797 outs() << format(Fmt: "?(%2d) ", Vals: r_length);
798 break;
799 default:
800 outs() << format(Fmt: "?(%2d) ", Vals: r_length);
801 }
802 }
803}
804
805static void PrintRelocationEntries(const MachOObjectFile *O,
806 const relocation_iterator Begin,
807 const relocation_iterator End,
808 const uint64_t cputype,
809 const bool verbose) {
810 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
811 bool previous_arm_half = false;
812 bool previous_sectdiff = false;
813 uint32_t sectdiff_r_type = 0;
814
815 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
816 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
817 const MachO::any_relocation_info RE = O->getRelocation(Rel);
818 const unsigned r_type = O->getAnyRelocationType(RE);
819 const bool r_scattered = O->isRelocationScattered(RE);
820 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
821 const unsigned r_length = O->getAnyRelocationLength(RE);
822 const unsigned r_address = O->getAnyRelocationAddress(RE);
823 const bool r_extern = (r_scattered ? false :
824 O->getPlainRelocationExternal(RE));
825 const uint32_t r_value = (r_scattered ?
826 O->getScatteredRelocationValue(RE) : 0);
827 const unsigned r_symbolnum = (r_scattered ? 0 :
828 O->getPlainRelocationSymbolNum(RE));
829
830 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
831 if (verbose) {
832 // scattered: address
833 if ((cputype == MachO::CPU_TYPE_I386 &&
834 r_type == MachO::GENERIC_RELOC_PAIR) ||
835 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
836 outs() << " ";
837 else
838 outs() << format(Fmt: "%08x ", Vals: (unsigned int)r_address);
839
840 // scattered: pcrel
841 if (r_pcrel)
842 outs() << "True ";
843 else
844 outs() << "False ";
845
846 // scattered: length
847 PrintRLength(cputype, r_type, r_length, previous_arm_half);
848
849 // scattered: extern & type
850 outs() << "n/a ";
851 PrintRType(cputype, r_type);
852
853 // scattered: scattered & value
854 outs() << format(Fmt: "True 0x%08x", Vals: (unsigned int)r_value);
855 if (previous_sectdiff == false) {
856 if ((cputype == MachO::CPU_TYPE_ARM &&
857 r_type == MachO::ARM_RELOC_PAIR))
858 outs() << format(Fmt: " half = 0x%04x ", Vals: (unsigned int)r_address);
859 } else if (cputype == MachO::CPU_TYPE_ARM &&
860 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
861 outs() << format(Fmt: " other_half = 0x%04x ", Vals: (unsigned int)r_address);
862 if ((cputype == MachO::CPU_TYPE_I386 &&
863 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
864 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
865 (cputype == MachO::CPU_TYPE_ARM &&
866 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
867 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
868 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
869 previous_sectdiff = true;
870 sectdiff_r_type = r_type;
871 } else {
872 previous_sectdiff = false;
873 sectdiff_r_type = 0;
874 }
875 if (cputype == MachO::CPU_TYPE_ARM &&
876 (r_type == MachO::ARM_RELOC_HALF ||
877 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
878 previous_arm_half = true;
879 else
880 previous_arm_half = false;
881 outs() << "\n";
882 }
883 else {
884 // scattered: address pcrel length extern type scattered value
885 outs() << format(Fmt: "%08x %1d %-2d n/a %-7d 1 0x%08x\n",
886 Vals: (unsigned int)r_address, Vals: r_pcrel, Vals: r_length, Vals: r_type,
887 Vals: (unsigned int)r_value);
888 }
889 }
890 else {
891 if (verbose) {
892 // plain: address
893 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
894 outs() << " ";
895 else
896 outs() << format(Fmt: "%08x ", Vals: (unsigned int)r_address);
897
898 // plain: pcrel
899 if (r_pcrel)
900 outs() << "True ";
901 else
902 outs() << "False ";
903
904 // plain: length
905 PrintRLength(cputype, r_type, r_length, previous_arm_half);
906
907 if (r_extern) {
908 // plain: extern & type & scattered
909 outs() << "True ";
910 PrintRType(cputype, r_type);
911 outs() << "False ";
912
913 // plain: symbolnum/value
914 if (r_symbolnum > Symtab.nsyms)
915 outs() << format(Fmt: "?(%d)\n", Vals: r_symbolnum);
916 else {
917 SymbolRef Symbol = *O->getSymbolByIndex(Index: r_symbolnum);
918 Expected<StringRef> SymNameNext = Symbol.getName();
919 const char *name = nullptr;
920 if (SymNameNext)
921 name = SymNameNext->data();
922 if (name == nullptr)
923 outs() << format(Fmt: "?(%d)\n", Vals: r_symbolnum);
924 else
925 outs() << name << "\n";
926 }
927 }
928 else {
929 // plain: extern & type & scattered
930 outs() << "False ";
931 PrintRType(cputype, r_type);
932 outs() << "False ";
933
934 // plain: symbolnum/value
935 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
936 outs() << format(Fmt: "other_half = 0x%04x\n", Vals: (unsigned int)r_address);
937 else if ((cputype == MachO::CPU_TYPE_ARM64 ||
938 cputype == MachO::CPU_TYPE_ARM64_32) &&
939 r_type == MachO::ARM64_RELOC_ADDEND)
940 outs() << format(Fmt: "addend = 0x%06x\n", Vals: (unsigned int)r_symbolnum);
941 else if (cputype == MachO::CPU_TYPE_RISCV &&
942 r_type == MachO::RISCV_RELOC_ADDEND)
943 outs() << format(Fmt: "addend = 0x%06x\n", Vals: (unsigned int)r_symbolnum);
944 else {
945 outs() << format(Fmt: "%d ", Vals: r_symbolnum);
946 if (r_symbolnum == MachO::R_ABS)
947 outs() << "R_ABS\n";
948 else {
949 // in this case, r_symbolnum is actually a 1-based section number
950 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
951 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
952 object::DataRefImpl DRI;
953 DRI.d.a = r_symbolnum-1;
954 StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
955 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
956 outs() << "(" << SegName << "," << *NameOrErr << ")\n";
957 else
958 outs() << "(?,?)\n";
959 }
960 else {
961 outs() << "(?,?)\n";
962 }
963 }
964 }
965 }
966 if (cputype == MachO::CPU_TYPE_ARM &&
967 (r_type == MachO::ARM_RELOC_HALF ||
968 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
969 previous_arm_half = true;
970 else
971 previous_arm_half = false;
972 }
973 else {
974 // plain: address pcrel length extern type scattered symbolnum/section
975 outs() << format(Fmt: "%08x %1d %-2d %1d %-7d 0 %d\n",
976 Vals: (unsigned int)r_address, Vals: r_pcrel, Vals: r_length, Vals: r_extern,
977 Vals: r_type, Vals: r_symbolnum);
978 }
979 }
980 }
981}
982
983static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
984 const uint64_t cputype = O->getHeader().cputype;
985 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
986 if (Dysymtab.nextrel != 0) {
987 outs() << "External relocation information " << Dysymtab.nextrel
988 << " entries";
989 outs() << "\naddress pcrel length extern type scattered "
990 "symbolnum/value\n";
991 PrintRelocationEntries(O, Begin: O->extrel_begin(), End: O->extrel_end(), cputype,
992 verbose);
993 }
994 if (Dysymtab.nlocrel != 0) {
995 outs() << format(Fmt: "Local relocation information %u entries",
996 Vals: Dysymtab.nlocrel);
997 outs() << "\naddress pcrel length extern type scattered "
998 "symbolnum/value\n";
999 PrintRelocationEntries(O, Begin: O->locrel_begin(), End: O->locrel_end(), cputype,
1000 verbose);
1001 }
1002 for (const auto &Load : O->load_commands()) {
1003 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1004 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(L: Load);
1005 for (unsigned J = 0; J < Seg.nsects; ++J) {
1006 const MachO::section_64 Sec = O->getSection64(L: Load, Index: J);
1007 if (Sec.nreloc != 0) {
1008 DataRefImpl DRI;
1009 DRI.d.a = J;
1010 const StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
1011 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
1012 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1013 << format(Fmt: ") %u entries", Vals: Sec.nreloc);
1014 else
1015 outs() << "Relocation information (" << SegName << ",?) "
1016 << format(Fmt: "%u entries", Vals: Sec.nreloc);
1017 outs() << "\naddress pcrel length extern type scattered "
1018 "symbolnum/value\n";
1019 PrintRelocationEntries(O, Begin: O->section_rel_begin(Sec: DRI),
1020 End: O->section_rel_end(Sec: DRI), cputype, verbose);
1021 }
1022 }
1023 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1024 const MachO::segment_command Seg = O->getSegmentLoadCommand(L: Load);
1025 for (unsigned J = 0; J < Seg.nsects; ++J) {
1026 const MachO::section Sec = O->getSection(L: Load, Index: J);
1027 if (Sec.nreloc != 0) {
1028 DataRefImpl DRI;
1029 DRI.d.a = J;
1030 const StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
1031 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
1032 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1033 << format(Fmt: ") %u entries", Vals: Sec.nreloc);
1034 else
1035 outs() << "Relocation information (" << SegName << ",?) "
1036 << format(Fmt: "%u entries", Vals: Sec.nreloc);
1037 outs() << "\naddress pcrel length extern type scattered "
1038 "symbolnum/value\n";
1039 PrintRelocationEntries(O, Begin: O->section_rel_begin(Sec: DRI),
1040 End: O->section_rel_end(Sec: DRI), cputype, verbose);
1041 }
1042 }
1043 }
1044 }
1045}
1046
1047static void PrintFunctionStarts(MachOObjectFile *O) {
1048 uint64_t BaseSegmentAddress = 0;
1049 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1050 if (Command.C.cmd == MachO::LC_SEGMENT) {
1051 MachO::segment_command SLC = O->getSegmentLoadCommand(L: Command);
1052 if (StringRef(SLC.segname) == "__TEXT") {
1053 BaseSegmentAddress = SLC.vmaddr;
1054 break;
1055 }
1056 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1057 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(L: Command);
1058 if (StringRef(SLC.segname) == "__TEXT") {
1059 BaseSegmentAddress = SLC.vmaddr;
1060 break;
1061 }
1062 }
1063 }
1064
1065 SmallVector<uint64_t, 8> FunctionStarts;
1066 for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) {
1067 if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) {
1068 MachO::linkedit_data_command FunctionStartsLC =
1069 O->getLinkeditDataLoadCommand(L: LC);
1070 O->ReadULEB128s(Index: FunctionStartsLC.dataoff, Out&: FunctionStarts);
1071 break;
1072 }
1073 }
1074
1075 DenseMap<uint64_t, StringRef> SymbolNames;
1076 if (FunctionStartsType == FunctionStartsMode::Names ||
1077 FunctionStartsType == FunctionStartsMode::Both) {
1078 for (SymbolRef Sym : O->symbols()) {
1079 if (Expected<uint64_t> Addr = Sym.getAddress()) {
1080 if (Expected<StringRef> Name = Sym.getName()) {
1081 SymbolNames[*Addr] = *Name;
1082 }
1083 }
1084 }
1085 }
1086
1087 for (uint64_t S : FunctionStarts) {
1088 uint64_t Addr = BaseSegmentAddress + S;
1089 if (FunctionStartsType == FunctionStartsMode::Names) {
1090 auto It = SymbolNames.find(Val: Addr);
1091 if (It != SymbolNames.end())
1092 outs() << It->second << "\n";
1093 } else {
1094 if (O->is64Bit())
1095 outs() << format(Fmt: "%016" PRIx64, Vals: Addr);
1096 else
1097 outs() << format(Fmt: "%08" PRIx32, Vals: static_cast<uint32_t>(Addr));
1098
1099 if (FunctionStartsType == FunctionStartsMode::Both) {
1100 auto It = SymbolNames.find(Val: Addr);
1101 if (It != SymbolNames.end())
1102 outs() << " " << It->second;
1103 else
1104 outs() << " ?";
1105 }
1106 outs() << "\n";
1107 }
1108 }
1109}
1110
1111static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1112 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1113 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1114 outs() << "Data in code table (" << nentries << " entries)\n";
1115 outs() << "offset length kind\n";
1116 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1117 ++DI) {
1118 uint32_t Offset;
1119 DI->getOffset(Result&: Offset);
1120 outs() << format(Fmt: "0x%08" PRIx32, Vals: Offset) << " ";
1121 uint16_t Length;
1122 DI->getLength(Result&: Length);
1123 outs() << format(Fmt: "%6u", Vals: Length) << " ";
1124 uint16_t Kind;
1125 DI->getKind(Result&: Kind);
1126 if (verbose) {
1127 switch (Kind) {
1128 case MachO::DICE_KIND_DATA:
1129 outs() << "DATA";
1130 break;
1131 case MachO::DICE_KIND_JUMP_TABLE8:
1132 outs() << "JUMP_TABLE8";
1133 break;
1134 case MachO::DICE_KIND_JUMP_TABLE16:
1135 outs() << "JUMP_TABLE16";
1136 break;
1137 case MachO::DICE_KIND_JUMP_TABLE32:
1138 outs() << "JUMP_TABLE32";
1139 break;
1140 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1141 outs() << "ABS_JUMP_TABLE32";
1142 break;
1143 default:
1144 outs() << format(Fmt: "0x%04" PRIx32, Vals: Kind);
1145 break;
1146 }
1147 } else
1148 outs() << format(Fmt: "0x%04" PRIx32, Vals: Kind);
1149 outs() << "\n";
1150 }
1151}
1152
1153static void PrintLinkOptHints(MachOObjectFile *O) {
1154 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1155 const char *loh = O->getData().substr(Start: LohLC.dataoff, N: 1).data();
1156 uint32_t nloh = LohLC.datasize;
1157 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1158 for (uint32_t i = 0; i < nloh;) {
1159 unsigned n;
1160 uint64_t identifier = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1161 i += n;
1162 outs() << " identifier " << identifier << " ";
1163 if (i >= nloh)
1164 return;
1165 switch (identifier) {
1166 case 1:
1167 outs() << "AdrpAdrp\n";
1168 break;
1169 case 2:
1170 outs() << "AdrpLdr\n";
1171 break;
1172 case 3:
1173 outs() << "AdrpAddLdr\n";
1174 break;
1175 case 4:
1176 outs() << "AdrpLdrGotLdr\n";
1177 break;
1178 case 5:
1179 outs() << "AdrpAddStr\n";
1180 break;
1181 case 6:
1182 outs() << "AdrpLdrGotStr\n";
1183 break;
1184 case 7:
1185 outs() << "AdrpAdd\n";
1186 break;
1187 case 8:
1188 outs() << "AdrpLdrGot\n";
1189 break;
1190 default:
1191 outs() << "Unknown identifier value\n";
1192 break;
1193 }
1194 uint64_t narguments = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1195 i += n;
1196 outs() << " narguments " << narguments << "\n";
1197 if (i >= nloh)
1198 return;
1199
1200 for (uint32_t j = 0; j < narguments; j++) {
1201 uint64_t value = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1202 i += n;
1203 outs() << "\tvalue " << format(Fmt: "0x%" PRIx64, Vals: value) << "\n";
1204 if (i >= nloh)
1205 return;
1206 }
1207 }
1208}
1209
1210static SmallVector<std::string> GetSegmentNames(object::MachOObjectFile *O) {
1211 SmallVector<std::string> Ret;
1212 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1213 if (Command.C.cmd == MachO::LC_SEGMENT) {
1214 MachO::segment_command SLC = O->getSegmentLoadCommand(L: Command);
1215 Ret.push_back(Elt: SLC.segname);
1216 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1217 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(L: Command);
1218 Ret.push_back(Elt: SLC.segname);
1219 }
1220 }
1221 return Ret;
1222}
1223
1224static void
1225PrintChainedFixupsHeader(const MachO::dyld_chained_fixups_header &H) {
1226 outs() << "chained fixups header (LC_DYLD_CHAINED_FIXUPS)\n";
1227 outs() << " fixups_version = " << H.fixups_version << '\n';
1228 outs() << " starts_offset = " << H.starts_offset << '\n';
1229 outs() << " imports_offset = " << H.imports_offset << '\n';
1230 outs() << " symbols_offset = " << H.symbols_offset << '\n';
1231 outs() << " imports_count = " << H.imports_count << '\n';
1232
1233 outs() << " imports_format = " << H.imports_format;
1234 switch (H.imports_format) {
1235 case llvm::MachO::DYLD_CHAINED_IMPORT:
1236 outs() << " (DYLD_CHAINED_IMPORT)";
1237 break;
1238 case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND:
1239 outs() << " (DYLD_CHAINED_IMPORT_ADDEND)";
1240 break;
1241 case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND64:
1242 outs() << " (DYLD_CHAINED_IMPORT_ADDEND64)";
1243 break;
1244 }
1245 outs() << '\n';
1246
1247 outs() << " symbols_format = " << H.symbols_format;
1248 if (H.symbols_format == llvm::MachO::DYLD_CHAINED_SYMBOL_ZLIB)
1249 outs() << " (zlib compressed)";
1250 outs() << '\n';
1251}
1252
1253static constexpr std::array<StringRef, 13> PointerFormats{
1254 "DYLD_CHAINED_PTR_ARM64E",
1255 "DYLD_CHAINED_PTR_64",
1256 "DYLD_CHAINED_PTR_32",
1257 "DYLD_CHAINED_PTR_32_CACHE",
1258 "DYLD_CHAINED_PTR_32_FIRMWARE",
1259 "DYLD_CHAINED_PTR_64_OFFSET",
1260 "DYLD_CHAINED_PTR_ARM64E_KERNEL",
1261 "DYLD_CHAINED_PTR_64_KERNEL_CACHE",
1262 "DYLD_CHAINED_PTR_ARM64E_USERLAND",
1263 "DYLD_CHAINED_PTR_ARM64E_FIRMWARE",
1264 "DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE",
1265 "DYLD_CHAINED_PTR_ARM64E_USERLAND24",
1266};
1267
1268static void PrintChainedFixupsSegment(const ChainedFixupsSegment &Segment,
1269 StringRef SegName) {
1270 outs() << "chained starts in segment " << Segment.SegIdx << " (" << SegName
1271 << ")\n";
1272 outs() << " size = " << Segment.Header.size << '\n';
1273 outs() << " page_size = " << format(Fmt: "0x%0" PRIx16, Vals: Segment.Header.page_size)
1274 << '\n';
1275
1276 outs() << " pointer_format = " << Segment.Header.pointer_format;
1277 if ((Segment.Header.pointer_format - 1) <
1278 MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24)
1279 outs() << " (" << PointerFormats[Segment.Header.pointer_format - 1] << ")";
1280 outs() << '\n';
1281
1282 outs() << " segment_offset = "
1283 << format(Fmt: "0x%0" PRIx64, Vals: Segment.Header.segment_offset) << '\n';
1284 outs() << " max_valid_pointer = " << Segment.Header.max_valid_pointer
1285 << '\n';
1286 outs() << " page_count = " << Segment.Header.page_count << '\n';
1287 for (auto [Index, PageStart] : enumerate(First: Segment.PageStarts)) {
1288 outs() << " page_start[" << Index << "] = " << PageStart;
1289 // FIXME: Support DYLD_CHAINED_PTR_START_MULTI (32-bit only)
1290 if (PageStart == MachO::DYLD_CHAINED_PTR_START_NONE)
1291 outs() << " (DYLD_CHAINED_PTR_START_NONE)";
1292 outs() << '\n';
1293 }
1294}
1295
1296static void PrintChainedFixupTarget(ChainedFixupTarget &Target, size_t Idx,
1297 int Format, MachOObjectFile *O) {
1298 if (Format == MachO::DYLD_CHAINED_IMPORT)
1299 outs() << "dyld chained import";
1300 else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND)
1301 outs() << "dyld chained import addend";
1302 else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND64)
1303 outs() << "dyld chained import addend64";
1304 // FIXME: otool prints the encoded value as well.
1305 outs() << '[' << Idx << "]\n";
1306
1307 outs() << " lib_ordinal = " << Target.libOrdinal() << " ("
1308 << ordinalName(O, Target.libOrdinal()) << ")\n";
1309 outs() << " weak_import = " << Target.weakImport() << '\n';
1310 outs() << " name_offset = " << Target.nameOffset() << " ("
1311 << Target.symbolName() << ")\n";
1312 if (Format != MachO::DYLD_CHAINED_IMPORT)
1313 outs() << " addend = " << (int64_t)Target.addend() << '\n';
1314}
1315
1316static void PrintChainedFixups(MachOObjectFile *O) {
1317 // MachOObjectFile::getChainedFixupsHeader() reads LC_DYLD_CHAINED_FIXUPS.
1318 // FIXME: Support chained fixups in __TEXT,__chain_starts section too.
1319 auto ChainedFixupHeader =
1320 unwrapOrError(EO: O->getChainedFixupsHeader(), Args: O->getFileName());
1321 if (!ChainedFixupHeader)
1322 return;
1323
1324 PrintChainedFixupsHeader(H: *ChainedFixupHeader);
1325
1326 auto [SegCount, Segments] =
1327 unwrapOrError(EO: O->getChainedFixupsSegments(), Args: O->getFileName());
1328
1329 auto SegNames = GetSegmentNames(O);
1330
1331 size_t StartsIdx = 0;
1332 outs() << "chained starts in image\n";
1333 outs() << " seg_count = " << SegCount << '\n';
1334 for (size_t I = 0; I < SegCount; ++I) {
1335 uint64_t SegOffset = 0;
1336 if (StartsIdx < Segments.size() && I == Segments[StartsIdx].SegIdx) {
1337 SegOffset = Segments[StartsIdx].Offset;
1338 ++StartsIdx;
1339 }
1340
1341 outs() << " seg_offset[" << I << "] = " << SegOffset << " ("
1342 << SegNames[I] << ")\n";
1343 }
1344
1345 for (const ChainedFixupsSegment &S : Segments)
1346 PrintChainedFixupsSegment(Segment: S, SegName: SegNames[S.SegIdx]);
1347
1348 auto FixupTargets =
1349 unwrapOrError(EO: O->getDyldChainedFixupTargets(), Args: O->getFileName());
1350
1351 uint32_t ImportsFormat = ChainedFixupHeader->imports_format;
1352 for (auto [Idx, Target] : enumerate(First&: FixupTargets))
1353 PrintChainedFixupTarget(Target, Idx, Format: ImportsFormat, O);
1354}
1355
1356static void PrintDyldInfo(MachOObjectFile *O) {
1357 Error Err = Error::success();
1358
1359 size_t SegmentWidth = strlen(s: "segment");
1360 size_t SectionWidth = strlen(s: "section");
1361 size_t AddressWidth = strlen(s: "address");
1362 size_t AddendWidth = strlen(s: "addend");
1363 size_t DylibWidth = strlen(s: "dylib");
1364 const size_t PointerWidth = 2 + O->getBytesInAddress() * 2;
1365
1366 auto HexLength = [](uint64_t Num) {
1367 return Num ? (size_t)divideCeil(Numerator: Log2_64(Value: Num), Denominator: 4) : 1;
1368 };
1369 for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1370 SegmentWidth = std::max(a: SegmentWidth, b: Entry.segmentName().size());
1371 SectionWidth = std::max(a: SectionWidth, b: Entry.sectionName().size());
1372 AddressWidth = std::max(a: AddressWidth, b: HexLength(Entry.address()) + 2);
1373 if (Entry.isBind()) {
1374 AddendWidth = std::max(a: AddendWidth, b: HexLength(Entry.addend()) + 2);
1375 DylibWidth = std::max(a: DylibWidth, b: Entry.symbolName().size());
1376 }
1377 }
1378 // Errors will be handled when printing the table.
1379 if (Err)
1380 consumeError(Err: std::move(Err));
1381
1382 outs() << "dyld information:\n";
1383 outs() << left_justify(Str: "segment", Width: SegmentWidth) << ' '
1384 << left_justify(Str: "section", Width: SectionWidth) << ' '
1385 << left_justify(Str: "address", Width: AddressWidth) << ' '
1386 << left_justify(Str: "pointer", Width: PointerWidth) << " type "
1387 << left_justify(Str: "addend", Width: AddendWidth) << ' '
1388 << left_justify(Str: "dylib", Width: DylibWidth) << " symbol/vm address\n";
1389 for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1390 outs() << left_justify(Str: Entry.segmentName(), Width: SegmentWidth) << ' '
1391 << left_justify(Str: Entry.sectionName(), Width: SectionWidth) << ' ' << "0x"
1392 << left_justify(Str: utohexstr(X: Entry.address()), Width: AddressWidth - 2) << ' '
1393 << format_hex(N: Entry.rawValue(), Width: PointerWidth, Upper: true) << ' ';
1394 if (Entry.isBind()) {
1395 outs() << "bind "
1396 << "0x" << left_justify(Str: utohexstr(X: Entry.addend()), Width: AddendWidth - 2)
1397 << ' ' << left_justify(Str: ordinalName(O, Entry.ordinal()), Width: DylibWidth)
1398 << ' ' << Entry.symbolName();
1399 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
1400 outs() << " (weak import)";
1401 outs() << '\n';
1402 } else {
1403 assert(Entry.isRebase());
1404 outs() << "rebase";
1405 outs().indent(NumSpaces: AddendWidth + DylibWidth + 2);
1406 outs() << format(Fmt: "0x%" PRIX64, Vals: Entry.pointerValue()) << '\n';
1407 }
1408 }
1409 if (Err)
1410 reportError(E: std::move(Err), FileName: O->getFileName());
1411
1412 // TODO: Print opcode-based fixups if the object uses those.
1413}
1414
1415static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1416 unsigned Index = 0;
1417 for (const auto &Load : O->load_commands()) {
1418 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1419 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1420 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1421 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1422 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1423 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1424 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1425 MachO::dylib_command dl = O->getDylibIDLoadCommand(L: Load);
1426 if (dl.dylib.name < dl.cmdsize) {
1427 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1428 if (JustId)
1429 outs() << p << "\n";
1430 else {
1431 outs() << "\t" << p;
1432 outs() << " (compatibility version "
1433 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1434 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1435 << (dl.dylib.compatibility_version & 0xff) << ",";
1436 outs() << " current version "
1437 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1438 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1439 << (dl.dylib.current_version & 0xff);
1440 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1441 outs() << ", weak";
1442 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1443 outs() << ", reexport";
1444 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1445 outs() << ", upward";
1446 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1447 outs() << ", lazy";
1448 outs() << ")\n";
1449 }
1450 } else {
1451 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1452 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1453 outs() << "LC_ID_DYLIB ";
1454 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1455 outs() << "LC_LOAD_DYLIB ";
1456 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1457 outs() << "LC_LOAD_WEAK_DYLIB ";
1458 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1459 outs() << "LC_LAZY_LOAD_DYLIB ";
1460 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1461 outs() << "LC_REEXPORT_DYLIB ";
1462 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1463 outs() << "LC_LOAD_UPWARD_DYLIB ";
1464 else
1465 outs() << "LC_??? ";
1466 outs() << "command " << Index++ << "\n";
1467 }
1468 }
1469 }
1470}
1471
1472static void printRpaths(MachOObjectFile *O) {
1473 for (const auto &Command : O->load_commands()) {
1474 if (Command.C.cmd == MachO::LC_RPATH) {
1475 auto Rpath = O->getRpathCommand(L: Command);
1476 const char *P = (const char *)(Command.Ptr) + Rpath.path;
1477 outs() << P << "\n";
1478 }
1479 }
1480}
1481
1482typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1483
1484static void CreateSymbolAddressMap(MachOObjectFile *O,
1485 SymbolAddressMap *AddrMap) {
1486 // Create a map of symbol addresses to symbol names.
1487 const StringRef FileName = O->getFileName();
1488 for (const SymbolRef &Symbol : O->symbols()) {
1489 SymbolRef::Type ST = unwrapOrError(EO: Symbol.getType(), Args: FileName);
1490 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1491 ST == SymbolRef::ST_Other) {
1492 uint64_t Address = cantFail(ValOrErr: Symbol.getValue());
1493 StringRef SymName = unwrapOrError(EO: Symbol.getName(), Args: FileName);
1494 if (!SymName.starts_with(Prefix: ".objc"))
1495 (*AddrMap)[Address] = SymName;
1496 }
1497 }
1498}
1499
1500// GuessSymbolName is passed the address of what might be a symbol and a
1501// pointer to the SymbolAddressMap. It returns the name of a symbol
1502// with that address or nullptr if no symbol is found with that address.
1503static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1504 const char *SymbolName = nullptr;
1505 // A DenseMap can't lookup up some values.
1506 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1507 StringRef name = AddrMap->lookup(Val: value);
1508 if (!name.empty())
1509 SymbolName = name.data();
1510 }
1511 return SymbolName;
1512}
1513
1514static void DumpCstringChar(const char c) {
1515 char p[2];
1516 p[0] = c;
1517 p[1] = '\0';
1518 outs().write_escaped(Str: p);
1519}
1520
1521static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1522 uint32_t sect_size, uint64_t sect_addr,
1523 bool print_addresses) {
1524 for (uint32_t i = 0; i < sect_size; i++) {
1525 if (print_addresses) {
1526 if (O->is64Bit())
1527 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1528 else
1529 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1530 }
1531 for (; i < sect_size && sect[i] != '\0'; i++)
1532 DumpCstringChar(c: sect[i]);
1533 if (i < sect_size && sect[i] == '\0')
1534 outs() << "\n";
1535 }
1536}
1537
1538static void DumpLiteral4(uint32_t l, float f) {
1539 outs() << format(Fmt: "0x%08" PRIx32, Vals: l);
1540 if ((l & 0x7f800000) != 0x7f800000)
1541 outs() << format(Fmt: " (%.16e)\n", Vals: f);
1542 else {
1543 if (l == 0x7f800000)
1544 outs() << " (+Infinity)\n";
1545 else if (l == 0xff800000)
1546 outs() << " (-Infinity)\n";
1547 else if ((l & 0x00400000) == 0x00400000)
1548 outs() << " (non-signaling Not-a-Number)\n";
1549 else
1550 outs() << " (signaling Not-a-Number)\n";
1551 }
1552}
1553
1554static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1555 uint32_t sect_size, uint64_t sect_addr,
1556 bool print_addresses) {
1557 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1558 if (print_addresses) {
1559 if (O->is64Bit())
1560 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1561 else
1562 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1563 }
1564 float f;
1565 memcpy(dest: &f, src: sect + i, n: sizeof(float));
1566 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1567 sys::swapByteOrder(Value&: f);
1568 uint32_t l;
1569 memcpy(dest: &l, src: sect + i, n: sizeof(uint32_t));
1570 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1571 sys::swapByteOrder(Value&: l);
1572 DumpLiteral4(l, f);
1573 }
1574}
1575
1576static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1577 double d) {
1578 outs() << format(Fmt: "0x%08" PRIx32, Vals: l0) << " " << format(Fmt: "0x%08" PRIx32, Vals: l1);
1579 uint32_t Hi, Lo;
1580 Hi = (O->isLittleEndian()) ? l1 : l0;
1581 Lo = (O->isLittleEndian()) ? l0 : l1;
1582
1583 // Hi is the high word, so this is equivalent to if(isfinite(d))
1584 if ((Hi & 0x7ff00000) != 0x7ff00000)
1585 outs() << format(Fmt: " (%.16e)\n", Vals: d);
1586 else {
1587 if (Hi == 0x7ff00000 && Lo == 0)
1588 outs() << " (+Infinity)\n";
1589 else if (Hi == 0xfff00000 && Lo == 0)
1590 outs() << " (-Infinity)\n";
1591 else if ((Hi & 0x00080000) == 0x00080000)
1592 outs() << " (non-signaling Not-a-Number)\n";
1593 else
1594 outs() << " (signaling Not-a-Number)\n";
1595 }
1596}
1597
1598static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1599 uint32_t sect_size, uint64_t sect_addr,
1600 bool print_addresses) {
1601 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1602 if (print_addresses) {
1603 if (O->is64Bit())
1604 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1605 else
1606 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1607 }
1608 double d;
1609 memcpy(dest: &d, src: sect + i, n: sizeof(double));
1610 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1611 sys::swapByteOrder(Value&: d);
1612 uint32_t l0, l1;
1613 memcpy(dest: &l0, src: sect + i, n: sizeof(uint32_t));
1614 memcpy(dest: &l1, src: sect + i + sizeof(uint32_t), n: sizeof(uint32_t));
1615 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1616 sys::swapByteOrder(Value&: l0);
1617 sys::swapByteOrder(Value&: l1);
1618 }
1619 DumpLiteral8(O, l0, l1, d);
1620 }
1621}
1622
1623static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1624 outs() << format(Fmt: "0x%08" PRIx32, Vals: l0) << " ";
1625 outs() << format(Fmt: "0x%08" PRIx32, Vals: l1) << " ";
1626 outs() << format(Fmt: "0x%08" PRIx32, Vals: l2) << " ";
1627 outs() << format(Fmt: "0x%08" PRIx32, Vals: l3) << "\n";
1628}
1629
1630static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1631 uint32_t sect_size, uint64_t sect_addr,
1632 bool print_addresses) {
1633 for (uint32_t i = 0; i < sect_size; i += 16) {
1634 if (print_addresses) {
1635 if (O->is64Bit())
1636 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1637 else
1638 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1639 }
1640 uint32_t l0, l1, l2, l3;
1641 memcpy(dest: &l0, src: sect + i, n: sizeof(uint32_t));
1642 memcpy(dest: &l1, src: sect + i + sizeof(uint32_t), n: sizeof(uint32_t));
1643 memcpy(dest: &l2, src: sect + i + 2 * sizeof(uint32_t), n: sizeof(uint32_t));
1644 memcpy(dest: &l3, src: sect + i + 3 * sizeof(uint32_t), n: sizeof(uint32_t));
1645 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1646 sys::swapByteOrder(Value&: l0);
1647 sys::swapByteOrder(Value&: l1);
1648 sys::swapByteOrder(Value&: l2);
1649 sys::swapByteOrder(Value&: l3);
1650 }
1651 DumpLiteral16(l0, l1, l2, l3);
1652 }
1653}
1654
1655static void DumpLiteralPointerSection(MachOObjectFile *O,
1656 const SectionRef &Section,
1657 const char *sect, uint32_t sect_size,
1658 uint64_t sect_addr,
1659 bool print_addresses) {
1660 // Collect the literal sections in this Mach-O file.
1661 std::vector<SectionRef> LiteralSections;
1662 for (const SectionRef &Section : O->sections()) {
1663 DataRefImpl Ref = Section.getRawDataRefImpl();
1664 uint32_t section_type;
1665 if (O->is64Bit()) {
1666 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1667 section_type = Sec.flags & MachO::SECTION_TYPE;
1668 } else {
1669 const MachO::section Sec = O->getSection(DRI: Ref);
1670 section_type = Sec.flags & MachO::SECTION_TYPE;
1671 }
1672 if (section_type == MachO::S_CSTRING_LITERALS ||
1673 section_type == MachO::S_4BYTE_LITERALS ||
1674 section_type == MachO::S_8BYTE_LITERALS ||
1675 section_type == MachO::S_16BYTE_LITERALS)
1676 LiteralSections.push_back(x: Section);
1677 }
1678
1679 // Set the size of the literal pointer.
1680 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1681
1682 // Collect the external relocation symbols for the literal pointers.
1683 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1684 for (const RelocationRef &Reloc : Section.relocations()) {
1685 DataRefImpl Rel;
1686 MachO::any_relocation_info RE;
1687 bool isExtern = false;
1688 Rel = Reloc.getRawDataRefImpl();
1689 RE = O->getRelocation(Rel);
1690 isExtern = O->getPlainRelocationExternal(RE);
1691 if (isExtern) {
1692 uint64_t RelocOffset = Reloc.getOffset();
1693 symbol_iterator RelocSym = Reloc.getSymbol();
1694 Relocs.push_back(x: std::make_pair(x&: RelocOffset, y: *RelocSym));
1695 }
1696 }
1697 array_pod_sort(Start: Relocs.begin(), End: Relocs.end());
1698
1699 // Dump each literal pointer.
1700 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1701 if (print_addresses) {
1702 if (O->is64Bit())
1703 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1704 else
1705 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1706 }
1707 uint64_t lp;
1708 if (O->is64Bit()) {
1709 memcpy(dest: &lp, src: sect + i, n: sizeof(uint64_t));
1710 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1711 sys::swapByteOrder(Value&: lp);
1712 } else {
1713 uint32_t li;
1714 memcpy(dest: &li, src: sect + i, n: sizeof(uint32_t));
1715 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1716 sys::swapByteOrder(Value&: li);
1717 lp = li;
1718 }
1719
1720 // First look for an external relocation entry for this literal pointer.
1721 auto Reloc = find_if(Range&: Relocs, P: [&](const std::pair<uint64_t, SymbolRef> &P) {
1722 return P.first == i;
1723 });
1724 if (Reloc != Relocs.end()) {
1725 symbol_iterator RelocSym = Reloc->second;
1726 StringRef SymName = unwrapOrError(EO: RelocSym->getName(), Args: O->getFileName());
1727 outs() << "external relocation entry for symbol:" << SymName << "\n";
1728 continue;
1729 }
1730
1731 // For local references see what the section the literal pointer points to.
1732 auto Sect = find_if(Range&: LiteralSections, P: [&](const SectionRef &R) {
1733 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1734 });
1735 if (Sect == LiteralSections.end()) {
1736 outs() << format(Fmt: "0x%" PRIx64, Vals: lp) << " (not in a literal section)\n";
1737 continue;
1738 }
1739
1740 uint64_t SectAddress = Sect->getAddress();
1741 uint64_t SectSize = Sect->getSize();
1742
1743 StringRef SectName;
1744 Expected<StringRef> SectNameOrErr = Sect->getName();
1745 if (SectNameOrErr)
1746 SectName = *SectNameOrErr;
1747 else
1748 consumeError(Err: SectNameOrErr.takeError());
1749
1750 DataRefImpl Ref = Sect->getRawDataRefImpl();
1751 StringRef SegmentName = O->getSectionFinalSegmentName(Sec: Ref);
1752 outs() << SegmentName << ":" << SectName << ":";
1753
1754 uint32_t section_type;
1755 if (O->is64Bit()) {
1756 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1757 section_type = Sec.flags & MachO::SECTION_TYPE;
1758 } else {
1759 const MachO::section Sec = O->getSection(DRI: Ref);
1760 section_type = Sec.flags & MachO::SECTION_TYPE;
1761 }
1762
1763 StringRef BytesStr = unwrapOrError(EO: Sect->getContents(), Args: O->getFileName());
1764
1765 const char *Contents = BytesStr.data();
1766
1767 switch (section_type) {
1768 case MachO::S_CSTRING_LITERALS:
1769 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1770 i++) {
1771 DumpCstringChar(c: Contents[i]);
1772 }
1773 outs() << "\n";
1774 break;
1775 case MachO::S_4BYTE_LITERALS:
1776 float f;
1777 memcpy(dest: &f, src: Contents + (lp - SectAddress), n: sizeof(float));
1778 uint32_t l;
1779 memcpy(dest: &l, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1780 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1781 sys::swapByteOrder(Value&: f);
1782 sys::swapByteOrder(Value&: l);
1783 }
1784 DumpLiteral4(l, f);
1785 break;
1786 case MachO::S_8BYTE_LITERALS: {
1787 double d;
1788 memcpy(dest: &d, src: Contents + (lp - SectAddress), n: sizeof(double));
1789 uint32_t l0, l1;
1790 memcpy(dest: &l0, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1791 memcpy(dest: &l1, src: Contents + (lp - SectAddress) + sizeof(uint32_t),
1792 n: sizeof(uint32_t));
1793 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1794 sys::swapByteOrder(Value&: f);
1795 sys::swapByteOrder(Value&: l0);
1796 sys::swapByteOrder(Value&: l1);
1797 }
1798 DumpLiteral8(O, l0, l1, d);
1799 break;
1800 }
1801 case MachO::S_16BYTE_LITERALS: {
1802 uint32_t l0, l1, l2, l3;
1803 memcpy(dest: &l0, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1804 memcpy(dest: &l1, src: Contents + (lp - SectAddress) + sizeof(uint32_t),
1805 n: sizeof(uint32_t));
1806 memcpy(dest: &l2, src: Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1807 n: sizeof(uint32_t));
1808 memcpy(dest: &l3, src: Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1809 n: sizeof(uint32_t));
1810 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1811 sys::swapByteOrder(Value&: l0);
1812 sys::swapByteOrder(Value&: l1);
1813 sys::swapByteOrder(Value&: l2);
1814 sys::swapByteOrder(Value&: l3);
1815 }
1816 DumpLiteral16(l0, l1, l2, l3);
1817 break;
1818 }
1819 }
1820 }
1821}
1822
1823static void DumpInitTermPointerSection(MachOObjectFile *O,
1824 const SectionRef &Section,
1825 const char *sect,
1826 uint32_t sect_size, uint64_t sect_addr,
1827 SymbolAddressMap *AddrMap,
1828 bool verbose) {
1829 uint32_t stride;
1830 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1831
1832 // Collect the external relocation symbols for the pointers.
1833 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1834 for (const RelocationRef &Reloc : Section.relocations()) {
1835 DataRefImpl Rel;
1836 MachO::any_relocation_info RE;
1837 bool isExtern = false;
1838 Rel = Reloc.getRawDataRefImpl();
1839 RE = O->getRelocation(Rel);
1840 isExtern = O->getPlainRelocationExternal(RE);
1841 if (isExtern) {
1842 uint64_t RelocOffset = Reloc.getOffset();
1843 symbol_iterator RelocSym = Reloc.getSymbol();
1844 Relocs.push_back(x: std::make_pair(x&: RelocOffset, y: *RelocSym));
1845 }
1846 }
1847 array_pod_sort(Start: Relocs.begin(), End: Relocs.end());
1848
1849 for (uint32_t i = 0; i < sect_size; i += stride) {
1850 const char *SymbolName = nullptr;
1851 uint64_t p;
1852 if (O->is64Bit()) {
1853 outs() << format(Fmt: "0x%016" PRIx64, Vals: sect_addr + i * stride) << " ";
1854 uint64_t pointer_value;
1855 memcpy(dest: &pointer_value, src: sect + i, n: stride);
1856 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1857 sys::swapByteOrder(Value&: pointer_value);
1858 outs() << format(Fmt: "0x%016" PRIx64, Vals: pointer_value);
1859 p = pointer_value;
1860 } else {
1861 outs() << format(Fmt: "0x%08" PRIx64, Vals: sect_addr + i * stride) << " ";
1862 uint32_t pointer_value;
1863 memcpy(dest: &pointer_value, src: sect + i, n: stride);
1864 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1865 sys::swapByteOrder(Value&: pointer_value);
1866 outs() << format(Fmt: "0x%08" PRIx32, Vals: pointer_value);
1867 p = pointer_value;
1868 }
1869 if (verbose) {
1870 // First look for an external relocation entry for this pointer.
1871 auto Reloc = find_if(Range&: Relocs, P: [&](const std::pair<uint64_t, SymbolRef> &P) {
1872 return P.first == i;
1873 });
1874 if (Reloc != Relocs.end()) {
1875 symbol_iterator RelocSym = Reloc->second;
1876 outs() << " " << unwrapOrError(EO: RelocSym->getName(), Args: O->getFileName());
1877 } else {
1878 SymbolName = GuessSymbolName(value: p, AddrMap);
1879 if (SymbolName)
1880 outs() << " " << SymbolName;
1881 }
1882 }
1883 outs() << "\n";
1884 }
1885}
1886
1887static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1888 uint32_t size, uint64_t addr) {
1889 uint32_t cputype = O->getHeader().cputype;
1890 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1891 uint32_t j;
1892 for (uint32_t i = 0; i < size; i += j, addr += j) {
1893 if (O->is64Bit())
1894 outs() << format(Fmt: "%016" PRIx64, Vals: addr) << "\t";
1895 else
1896 outs() << format(Fmt: "%08" PRIx64, Vals: addr) << "\t";
1897 for (j = 0; j < 16 && i + j < size; j++) {
1898 uint8_t byte_word = *(sect + i + j);
1899 outs() << format(Fmt: "%02" PRIx32, Vals: (uint32_t)byte_word) << " ";
1900 }
1901 outs() << "\n";
1902 }
1903 } else {
1904 uint32_t j;
1905 for (uint32_t i = 0; i < size; i += j, addr += j) {
1906 if (O->is64Bit())
1907 outs() << format(Fmt: "%016" PRIx64, Vals: addr) << "\t";
1908 else
1909 outs() << format(Fmt: "%08" PRIx64, Vals: addr) << "\t";
1910 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1911 j += sizeof(int32_t)) {
1912 if (i + j + sizeof(int32_t) <= size) {
1913 uint32_t long_word;
1914 memcpy(dest: &long_word, src: sect + i + j, n: sizeof(int32_t));
1915 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1916 sys::swapByteOrder(Value&: long_word);
1917 outs() << format(Fmt: "%08" PRIx32, Vals: long_word) << " ";
1918 } else {
1919 for (uint32_t k = 0; i + j + k < size; k++) {
1920 uint8_t byte_word = *(sect + i + j + k);
1921 outs() << format(Fmt: "%02" PRIx32, Vals: (uint32_t)byte_word) << " ";
1922 }
1923 }
1924 }
1925 outs() << "\n";
1926 }
1927 }
1928}
1929
1930static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1931 StringRef DisSegName, StringRef DisSectName);
1932static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1933 uint32_t size, uint32_t addr);
1934static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1935 bool verbose) {
1936 SymbolAddressMap AddrMap;
1937 if (verbose)
1938 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
1939
1940 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1941 StringRef DumpSection = FilterSections[i];
1942 std::pair<StringRef, StringRef> DumpSegSectName;
1943 DumpSegSectName = DumpSection.split(Separator: ',');
1944 StringRef DumpSegName, DumpSectName;
1945 if (!DumpSegSectName.second.empty()) {
1946 DumpSegName = DumpSegSectName.first;
1947 DumpSectName = DumpSegSectName.second;
1948 } else {
1949 DumpSegName = "";
1950 DumpSectName = DumpSegSectName.first;
1951 }
1952 for (const SectionRef &Section : O->sections()) {
1953 StringRef SectName;
1954 Expected<StringRef> SecNameOrErr = Section.getName();
1955 if (SecNameOrErr)
1956 SectName = *SecNameOrErr;
1957 else
1958 consumeError(Err: SecNameOrErr.takeError());
1959
1960 if (!DumpSection.empty())
1961 FoundSectionSet.insert(key: DumpSection);
1962
1963 DataRefImpl Ref = Section.getRawDataRefImpl();
1964 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
1965 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1966 (SectName == DumpSectName)) {
1967
1968 uint32_t section_flags;
1969 if (O->is64Bit()) {
1970 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1971 section_flags = Sec.flags;
1972
1973 } else {
1974 const MachO::section Sec = O->getSection(DRI: Ref);
1975 section_flags = Sec.flags;
1976 }
1977 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1978
1979 StringRef BytesStr =
1980 unwrapOrError(EO: Section.getContents(), Args: O->getFileName());
1981 const char *sect = BytesStr.data();
1982 uint32_t sect_size = BytesStr.size();
1983 uint64_t sect_addr = Section.getAddress();
1984
1985 if (LeadingHeaders)
1986 outs() << "Contents of (" << SegName << "," << SectName
1987 << ") section\n";
1988
1989 if (verbose) {
1990 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1991 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1992 DisassembleMachO(Filename, MachOOF: O, DisSegName: SegName, DisSectName: SectName);
1993 continue;
1994 }
1995 if (SegName == "__TEXT" && SectName == "__info_plist") {
1996 outs() << sect;
1997 continue;
1998 }
1999 if (SegName == "__OBJC" && SectName == "__protocol") {
2000 DumpProtocolSection(O, sect, size: sect_size, addr: sect_addr);
2001 continue;
2002 }
2003 switch (section_type) {
2004 case MachO::S_REGULAR:
2005 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2006 break;
2007 case MachO::S_ZEROFILL:
2008 outs() << "zerofill section and has no contents in the file\n";
2009 break;
2010 case MachO::S_CSTRING_LITERALS:
2011 DumpCstringSection(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2012 break;
2013 case MachO::S_4BYTE_LITERALS:
2014 DumpLiteral4Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2015 break;
2016 case MachO::S_8BYTE_LITERALS:
2017 DumpLiteral8Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2018 break;
2019 case MachO::S_16BYTE_LITERALS:
2020 DumpLiteral16Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2021 break;
2022 case MachO::S_LITERAL_POINTERS:
2023 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
2024 print_addresses: LeadingAddr);
2025 break;
2026 case MachO::S_MOD_INIT_FUNC_POINTERS:
2027 case MachO::S_MOD_TERM_FUNC_POINTERS:
2028 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
2029 AddrMap: &AddrMap, verbose);
2030 break;
2031 default:
2032 outs() << "Unknown section type ("
2033 << format(Fmt: "0x%08" PRIx32, Vals: section_type) << ")\n";
2034 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2035 break;
2036 }
2037 } else {
2038 if (section_type == MachO::S_ZEROFILL)
2039 outs() << "zerofill section and has no contents in the file\n";
2040 else
2041 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2042 }
2043 }
2044 }
2045 }
2046}
2047
2048static void DumpInfoPlistSectionContents(StringRef Filename,
2049 MachOObjectFile *O) {
2050 for (const SectionRef &Section : O->sections()) {
2051 StringRef SectName;
2052 Expected<StringRef> SecNameOrErr = Section.getName();
2053 if (SecNameOrErr)
2054 SectName = *SecNameOrErr;
2055 else
2056 consumeError(Err: SecNameOrErr.takeError());
2057
2058 DataRefImpl Ref = Section.getRawDataRefImpl();
2059 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
2060 if (SegName == "__TEXT" && SectName == "__info_plist") {
2061 if (LeadingHeaders)
2062 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
2063 StringRef BytesStr =
2064 unwrapOrError(EO: Section.getContents(), Args: O->getFileName());
2065 const char *sect = BytesStr.data();
2066 outs() << format(Fmt: "%.*s", Vals: BytesStr.size(), Vals: sect) << "\n";
2067 return;
2068 }
2069 }
2070}
2071
2072// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
2073// and if it is and there is a list of architecture flags is specified then
2074// check to make sure this Mach-O file is one of those architectures or all
2075// architectures were specified. If not then an error is generated and this
2076// routine returns false. Else it returns true.
2077static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
2078 auto *MachO = dyn_cast<MachOObjectFile>(Val: O);
2079
2080 if (!MachO || ArchAll || ArchFlags.empty())
2081 return true;
2082
2083 MachO::mach_header H;
2084 MachO::mach_header_64 H_64;
2085 Triple T;
2086 const char *McpuDefault, *ArchFlag;
2087 if (MachO->is64Bit()) {
2088 H_64 = MachO->MachOObjectFile::getHeader64();
2089 T = MachOObjectFile::getArchTriple(CPUType: H_64.cputype, CPUSubType: H_64.cpusubtype,
2090 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2091 } else {
2092 H = MachO->MachOObjectFile::getHeader();
2093 T = MachOObjectFile::getArchTriple(CPUType: H.cputype, CPUSubType: H.cpusubtype,
2094 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2095 }
2096 const std::string ArchFlagName(ArchFlag);
2097 if (!llvm::is_contained(Range&: ArchFlags, Element: ArchFlagName)) {
2098 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2099 << Filename << ": no architecture specified.\n";
2100 return false;
2101 }
2102 return true;
2103}
2104
2105static void printObjcMetaData(MachOObjectFile *O, bool verbose);
2106
2107// ProcessMachO() is passed a single opened Mach-O file, which may be an
2108// archive member and or in a slice of a universal file. It prints the
2109// the file name and header info and then processes it according to the
2110// command line options.
2111static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
2112 StringRef ArchiveMemberName = StringRef(),
2113 StringRef ArchitectureName = StringRef()) {
2114 std::unique_ptr<Dumper> D = createMachODumper(Obj: *MachOOF);
2115
2116 // If we are doing some processing here on the Mach-O file print the header
2117 // info. And don't print it otherwise like in the case of printing the
2118 // UniversalHeaders or ArchiveHeaders.
2119 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
2120 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
2121 DataInCode || FunctionStartsType != FunctionStartsMode::None ||
2122 LinkOptHints || ChainedFixups || DyldInfo || DylibsUsed || DylibId ||
2123 Rpaths || ObjcMetaData || (!FilterSections.empty())) {
2124 if (LeadingHeaders) {
2125 outs() << Name;
2126 if (!ArchiveMemberName.empty())
2127 outs() << '(' << ArchiveMemberName << ')';
2128 if (!ArchitectureName.empty())
2129 outs() << " (architecture " << ArchitectureName << ")";
2130 outs() << ":\n";
2131 }
2132 }
2133 // To use the report_error() form with an ArchiveName and FileName set
2134 // these up based on what is passed for Name and ArchiveMemberName.
2135 StringRef ArchiveName;
2136 StringRef FileName;
2137 if (!ArchiveMemberName.empty()) {
2138 ArchiveName = Name;
2139 FileName = ArchiveMemberName;
2140 } else {
2141 ArchiveName = StringRef();
2142 FileName = Name;
2143 }
2144
2145 // If we need the symbol table to do the operation then check it here to
2146 // produce a good error message as to where the Mach-O file comes from in
2147 // the error message.
2148 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
2149 if (Error Err = MachOOF->checkSymbolTable())
2150 reportError(E: std::move(Err), FileName, ArchiveName, ArchitectureName);
2151
2152 if (DisassembleAll) {
2153 for (const SectionRef &Section : MachOOF->sections()) {
2154 StringRef SectName;
2155 if (Expected<StringRef> NameOrErr = Section.getName())
2156 SectName = *NameOrErr;
2157 else
2158 consumeError(Err: NameOrErr.takeError());
2159
2160 if (SectName == "__text") {
2161 DataRefImpl Ref = Section.getRawDataRefImpl();
2162 StringRef SegName = MachOOF->getSectionFinalSegmentName(Sec: Ref);
2163 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: SegName, DisSectName: SectName);
2164 }
2165 }
2166 }
2167 else if (Disassemble) {
2168 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
2169 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
2170 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: "__TEXT_EXEC", DisSectName: "__text");
2171 else
2172 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: "__TEXT", DisSectName: "__text");
2173 }
2174 if (IndirectSymbols)
2175 PrintIndirectSymbols(O: MachOOF, verbose: Verbose);
2176 if (DataInCode)
2177 PrintDataInCodeTable(O: MachOOF, verbose: Verbose);
2178 if (FunctionStartsType != FunctionStartsMode::None)
2179 PrintFunctionStarts(O: MachOOF);
2180 if (LinkOptHints)
2181 PrintLinkOptHints(O: MachOOF);
2182 if (Relocations)
2183 PrintRelocations(O: MachOOF, verbose: Verbose);
2184 if (SectionHeaders)
2185 printSectionHeaders(O&: *MachOOF);
2186 if (SectionContents)
2187 printSectionContents(O: MachOOF);
2188 if (!FilterSections.empty())
2189 DumpSectionContents(Filename: FileName, O: MachOOF, verbose: Verbose);
2190 if (InfoPlist)
2191 DumpInfoPlistSectionContents(Filename: FileName, O: MachOOF);
2192 if (DyldInfo)
2193 PrintDyldInfo(O: MachOOF);
2194 if (ChainedFixups)
2195 PrintChainedFixups(O: MachOOF);
2196 if (DylibsUsed)
2197 PrintDylibs(O: MachOOF, JustId: false);
2198 if (DylibId)
2199 PrintDylibs(O: MachOOF, JustId: true);
2200 if (SymbolTable)
2201 D->printSymbolTable(ArchiveName, ArchitectureName);
2202 if (UnwindInfo)
2203 printMachOUnwindInfo(O: MachOOF);
2204 if (PrivateHeaders) {
2205 printMachOFileHeader(O: MachOOF);
2206 printMachOLoadCommands(O: MachOOF);
2207 }
2208 if (FirstPrivateHeader)
2209 printMachOFileHeader(O: MachOOF);
2210 if (ObjcMetaData)
2211 printObjcMetaData(O: MachOOF, verbose: Verbose);
2212 if (ExportsTrie)
2213 printExportsTrie(O: MachOOF);
2214 if (Rebase)
2215 printRebaseTable(O: MachOOF);
2216 if (Rpaths)
2217 printRpaths(O: MachOOF);
2218 if (Bind)
2219 printBindTable(O: MachOOF);
2220 if (LazyBind)
2221 printLazyBindTable(O: MachOOF);
2222 if (WeakBind)
2223 printWeakBindTable(O: MachOOF);
2224
2225 if (DwarfDumpType != DIDT_Null) {
2226 std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj: *MachOOF);
2227 // Dump the complete DWARF structure.
2228 DIDumpOptions DumpOpts;
2229 DumpOpts.DumpType = DwarfDumpType;
2230 DICtx->dump(OS&: outs(), DumpOpts);
2231 }
2232}
2233
2234// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2235static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2236 outs() << " cputype (" << cputype << ")\n";
2237 outs() << " cpusubtype (" << cpusubtype << ")\n";
2238}
2239
2240// printCPUType() helps print_fat_headers by printing the cputype and
2241// pusubtype (symbolically for the one's it knows about).
2242static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2243 switch (cputype) {
2244 case MachO::CPU_TYPE_I386:
2245 switch (cpusubtype) {
2246 case MachO::CPU_SUBTYPE_I386_ALL:
2247 outs() << " cputype CPU_TYPE_I386\n";
2248 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
2249 break;
2250 default:
2251 printUnknownCPUType(cputype, cpusubtype);
2252 break;
2253 }
2254 break;
2255 case MachO::CPU_TYPE_X86_64:
2256 switch (cpusubtype) {
2257 case MachO::CPU_SUBTYPE_X86_64_ALL:
2258 outs() << " cputype CPU_TYPE_X86_64\n";
2259 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2260 break;
2261 case MachO::CPU_SUBTYPE_X86_64_H:
2262 outs() << " cputype CPU_TYPE_X86_64\n";
2263 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2264 break;
2265 default:
2266 printUnknownCPUType(cputype, cpusubtype);
2267 break;
2268 }
2269 break;
2270 case MachO::CPU_TYPE_ARM:
2271 switch (cpusubtype) {
2272 case MachO::CPU_SUBTYPE_ARM_ALL:
2273 outs() << " cputype CPU_TYPE_ARM\n";
2274 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2275 break;
2276 case MachO::CPU_SUBTYPE_ARM_V4T:
2277 outs() << " cputype CPU_TYPE_ARM\n";
2278 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2279 break;
2280 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2281 outs() << " cputype CPU_TYPE_ARM\n";
2282 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2283 break;
2284 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2285 outs() << " cputype CPU_TYPE_ARM\n";
2286 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2287 break;
2288 case MachO::CPU_SUBTYPE_ARM_V6:
2289 outs() << " cputype CPU_TYPE_ARM\n";
2290 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2291 break;
2292 case MachO::CPU_SUBTYPE_ARM_V6M:
2293 outs() << " cputype CPU_TYPE_ARM\n";
2294 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2295 break;
2296 case MachO::CPU_SUBTYPE_ARM_V7:
2297 outs() << " cputype CPU_TYPE_ARM\n";
2298 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2299 break;
2300 case MachO::CPU_SUBTYPE_ARM_V7EM:
2301 outs() << " cputype CPU_TYPE_ARM\n";
2302 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2303 break;
2304 case MachO::CPU_SUBTYPE_ARM_V7K:
2305 outs() << " cputype CPU_TYPE_ARM\n";
2306 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2307 break;
2308 case MachO::CPU_SUBTYPE_ARM_V7M:
2309 outs() << " cputype CPU_TYPE_ARM\n";
2310 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2311 break;
2312 case MachO::CPU_SUBTYPE_ARM_V7S:
2313 outs() << " cputype CPU_TYPE_ARM\n";
2314 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2315 break;
2316 case MachO::CPU_SUBTYPE_ARM_V8M_MAIN:
2317 outs() << " cputype CPU_TYPE_ARM\n";
2318 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8M_MAIN\n";
2319 break;
2320 case MachO::CPU_SUBTYPE_ARM_V8M_BASE:
2321 outs() << " cputype CPU_TYPE_ARM\n";
2322 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8M_BASE\n";
2323 break;
2324 case MachO::CPU_SUBTYPE_ARM_V8_1M_MAIN:
2325 outs() << " cputype CPU_TYPE_ARM\n";
2326 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8_1M_MAIN\n";
2327 break;
2328 default:
2329 printUnknownCPUType(cputype, cpusubtype);
2330 break;
2331 }
2332 break;
2333 case MachO::CPU_TYPE_ARM64:
2334 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2335 case MachO::CPU_SUBTYPE_ARM64_ALL:
2336 outs() << " cputype CPU_TYPE_ARM64\n";
2337 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2338 break;
2339 case MachO::CPU_SUBTYPE_ARM64_V8:
2340 outs() << " cputype CPU_TYPE_ARM64\n";
2341 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2342 break;
2343 case MachO::CPU_SUBTYPE_ARM64E:
2344 outs() << " cputype CPU_TYPE_ARM64\n";
2345 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2346 break;
2347 case MachO::CPU_SUBTYPE_ARM64E_X1:
2348 outs() << " cputype CPU_TYPE_ARM64\n";
2349 outs() << " cpusubtype CPU_SUBTYPE_ARM64E_X1\n";
2350 break;
2351 default:
2352 printUnknownCPUType(cputype, cpusubtype);
2353 break;
2354 }
2355 break;
2356 case MachO::CPU_TYPE_ARM64_32:
2357 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2358 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2359 outs() << " cputype CPU_TYPE_ARM64_32\n";
2360 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2361 break;
2362 default:
2363 printUnknownCPUType(cputype, cpusubtype);
2364 break;
2365 }
2366 break;
2367 default:
2368 printUnknownCPUType(cputype, cpusubtype);
2369 break;
2370 }
2371}
2372
2373static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2374 bool verbose) {
2375 outs() << "Fat headers\n";
2376 if (verbose) {
2377 if (UB->getMagic() == MachO::FAT_MAGIC)
2378 outs() << "fat_magic FAT_MAGIC\n";
2379 else // UB->getMagic() == MachO::FAT_MAGIC_64
2380 outs() << "fat_magic FAT_MAGIC_64\n";
2381 } else
2382 outs() << "fat_magic " << format(Fmt: "0x%" PRIx32, Vals: MachO::FAT_MAGIC) << "\n";
2383
2384 uint32_t nfat_arch = UB->getNumberOfObjects();
2385 StringRef Buf = UB->getData();
2386 uint64_t size = Buf.size();
2387 uint64_t big_size = sizeof(struct MachO::fat_header) +
2388 nfat_arch * sizeof(struct MachO::fat_arch);
2389 outs() << "nfat_arch " << UB->getNumberOfObjects();
2390 if (nfat_arch == 0)
2391 outs() << " (malformed, contains zero architecture types)\n";
2392 else if (big_size > size)
2393 outs() << " (malformed, architectures past end of file)\n";
2394 else
2395 outs() << "\n";
2396
2397 for (uint32_t i = 0; i < nfat_arch; ++i) {
2398 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2399 uint32_t cputype = OFA.getCPUType();
2400 uint32_t cpusubtype = OFA.getCPUSubType();
2401 outs() << "architecture ";
2402 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2403 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2404 uint32_t other_cputype = other_OFA.getCPUType();
2405 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2406 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2407 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2408 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2409 outs() << "(illegal duplicate architecture) ";
2410 break;
2411 }
2412 }
2413 if (verbose) {
2414 outs() << OFA.getArchFlagName() << "\n";
2415 printCPUType(cputype, cpusubtype: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2416 } else {
2417 outs() << i << "\n";
2418 outs() << " cputype " << cputype << "\n";
2419 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2420 << "\n";
2421 }
2422 if (verbose && cputype == MachO::CPU_TYPE_ARM64 &&
2423 MachO::CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(ST: cpusubtype)) {
2424 outs() << " capabilities CPU_SUBTYPE_ARM64E_";
2425 if (MachO::CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(ST: cpusubtype))
2426 outs() << "KERNEL_";
2427 outs() << format(Fmt: "PTRAUTH_VERSION %d",
2428 Vals: MachO::CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(ST: cpusubtype))
2429 << "\n";
2430 } else if (verbose && (cpusubtype & MachO::CPU_SUBTYPE_MASK) ==
2431 MachO::CPU_SUBTYPE_LIB64)
2432 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2433 else
2434 outs() << " capabilities "
2435 << format(Fmt: "0x%" PRIx32,
2436 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2437 outs() << " offset " << OFA.getOffset();
2438 if (OFA.getOffset() > size)
2439 outs() << " (past end of file)";
2440 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2441 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2442 outs() << "\n";
2443 outs() << " size " << OFA.getSize();
2444 big_size = OFA.getOffset() + OFA.getSize();
2445 if (big_size > size)
2446 outs() << " (past end of file)";
2447 outs() << "\n";
2448 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2449 << ")\n";
2450 }
2451}
2452
2453static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2454 size_t ChildIndex, bool verbose,
2455 bool print_offset,
2456 StringRef ArchitectureName = StringRef()) {
2457 if (print_offset)
2458 outs() << C.getChildOffset() << "\t";
2459 sys::fs::perms Mode =
2460 unwrapOrError(EO: C.getAccessMode(), Args: getFileNameForError(C, Index: ChildIndex),
2461 Args&: Filename, Args&: ArchitectureName);
2462 if (verbose) {
2463 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2464 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2465 outs() << "-";
2466 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2467 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2468 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2469 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2470 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2471 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2472 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2473 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2474 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2475 } else {
2476 outs() << format(Fmt: "0%o ", Vals: Mode);
2477 }
2478
2479 outs() << format(Fmt: "%3d/%-3d %5" PRId64 " ",
2480 Vals: unwrapOrError(EO: C.getUID(), Args: getFileNameForError(C, Index: ChildIndex),
2481 Args&: Filename, Args&: ArchitectureName),
2482 Vals: unwrapOrError(EO: C.getGID(), Args: getFileNameForError(C, Index: ChildIndex),
2483 Args&: Filename, Args&: ArchitectureName),
2484 Vals: unwrapOrError(EO: C.getRawSize(),
2485 Args: getFileNameForError(C, Index: ChildIndex), Args&: Filename,
2486 Args&: ArchitectureName));
2487
2488 StringRef RawLastModified = C.getRawLastModified();
2489 if (verbose) {
2490 unsigned Seconds;
2491 if (RawLastModified.getAsInteger(Radix: 10, Result&: Seconds))
2492 outs() << "(date: \"" << RawLastModified
2493 << "\" contains non-decimal chars) ";
2494 else {
2495 // Since cime(3) returns a 26 character string of the form:
2496 // "Sun Sep 16 01:03:52 1973\n\0"
2497 // just print 24 characters.
2498 time_t t = Seconds;
2499 outs() << format(Fmt: "%.24s ", Vals: ctime(timer: &t));
2500 }
2501 } else {
2502 outs() << RawLastModified << " ";
2503 }
2504
2505 if (verbose) {
2506 Expected<StringRef> NameOrErr = C.getName();
2507 if (!NameOrErr) {
2508 consumeError(Err: NameOrErr.takeError());
2509 outs() << unwrapOrError(EO: C.getRawName(),
2510 Args: getFileNameForError(C, Index: ChildIndex), Args&: Filename,
2511 Args&: ArchitectureName)
2512 << "\n";
2513 } else {
2514 StringRef Name = NameOrErr.get();
2515 outs() << Name << "\n";
2516 }
2517 } else {
2518 outs() << unwrapOrError(EO: C.getRawName(), Args: getFileNameForError(C, Index: ChildIndex),
2519 Args&: Filename, Args&: ArchitectureName)
2520 << "\n";
2521 }
2522}
2523
2524static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2525 bool print_offset,
2526 StringRef ArchitectureName = StringRef()) {
2527 Error Err = Error::success();
2528 size_t I = 0;
2529 for (const auto &C : A->children(Err, SkipInternal: false))
2530 printArchiveChild(Filename, C, ChildIndex: I++, verbose, print_offset,
2531 ArchitectureName);
2532
2533 if (Err)
2534 reportError(E: std::move(Err), FileName: Filename, ArchiveName: "", ArchitectureName);
2535}
2536
2537static bool ValidateArchFlags() {
2538 // Check for -arch all and verifiy the -arch flags are valid.
2539 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2540 if (ArchFlags[i] == "all") {
2541 ArchAll = true;
2542 } else {
2543 if (!MachOObjectFile::isValidArch(ArchFlag: ArchFlags[i])) {
2544 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2545 << "unknown architecture named '" + ArchFlags[i] +
2546 "'for the -arch option\n";
2547 return false;
2548 }
2549 }
2550 }
2551 return true;
2552}
2553
2554static bool skipArchiveMember(const object::Archive::Child &C,
2555 StringRef Filename) {
2556 if (ArchiveMemberFilter.empty())
2557 return false;
2558 Expected<StringRef> NameOrErr = C.getName();
2559 if (!NameOrErr) {
2560 reportError(E: NameOrErr.takeError(), FileName: Filename);
2561 return true;
2562 }
2563 return *NameOrErr != ArchiveMemberFilter;
2564}
2565
2566// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2567// -arch flags selecting just those slices as specified by them and also parses
2568// archive files. Then for each individual Mach-O file ProcessMachO() is
2569// called to process the file based on the command line options.
2570void objdump::parseInputMachO(StringRef Filename) {
2571 if (!ValidateArchFlags())
2572 return;
2573
2574 // In otool mode, support archive(member) syntax: if the filename ends
2575 // with ')' and contains '(', split it into the archive path and member
2576 // name. The -m option disables this parsing.
2577 ArchiveMemberFilter.clear();
2578 if (IsOtool && UseMemberSyntax && !Filename.empty() &&
2579 Filename.back() == ')') {
2580 auto Pos = Filename.rfind(C: '(');
2581 if (Pos != StringRef::npos && Pos > 0) {
2582 ArchiveMemberFilter = Filename.substr(Start: Pos + 1).drop_back().str();
2583 Filename = Filename.substr(Start: 0, N: Pos);
2584 }
2585 }
2586
2587 // Attempt to open the binary.
2588 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Path: Filename);
2589 if (!BinaryOrErr) {
2590 if (Error E = isNotObjectErrorInvalidFileType(Err: BinaryOrErr.takeError()))
2591 reportError(E: std::move(E), FileName: Filename);
2592 else
2593 outs() << Filename << ": is not an object file\n";
2594 return;
2595 }
2596 Binary &Bin = *BinaryOrErr.get().getBinary();
2597
2598 if (Archive *A = dyn_cast<Archive>(Val: &Bin)) {
2599 outs() << "Archive : " << Filename << "\n";
2600 if (ArchiveHeaders)
2601 printArchiveHeaders(Filename, A, verbose: Verbose, print_offset: ArchiveMemberOffsets);
2602
2603 Error Err = Error::success();
2604 unsigned I = -1;
2605 bool FoundMember = false;
2606 for (auto &C : A->children(Err)) {
2607 ++I;
2608 if (skipArchiveMember(C, Filename))
2609 continue;
2610 FoundMember = true;
2611 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2612 if (!ChildOrErr) {
2613 if (Error E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2614 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename);
2615 continue;
2616 }
2617 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get())) {
2618 if (!checkMachOAndArchFlags(O, Filename))
2619 return;
2620 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName());
2621 }
2622 }
2623 if (Err)
2624 reportError(E: std::move(Err), FileName: Filename);
2625 if (!FoundMember && !ArchiveMemberFilter.empty())
2626 reportError(File: Filename, Message: "archive does not contain a member named: " +
2627 ArchiveMemberFilter);
2628 return;
2629 }
2630 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Bin)) {
2631 parseInputMachO(UB);
2632 return;
2633 }
2634 if (!ArchiveMemberFilter.empty()) {
2635 reportError(File: Filename, Message: "not an archive (cannot extract member: " +
2636 ArchiveMemberFilter + ")");
2637 return;
2638 }
2639 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Bin)) {
2640 if (!checkMachOAndArchFlags(O, Filename))
2641 return;
2642 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &*O))
2643 ProcessMachO(Name: Filename, MachOOF);
2644 else
2645 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2646 << Filename << "': "
2647 << "object is not a Mach-O file type.\n";
2648 return;
2649 }
2650 llvm_unreachable("Input object can't be invalid at this point");
2651}
2652
2653void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2654 if (!ValidateArchFlags())
2655 return;
2656
2657 auto Filename = UB->getFileName();
2658
2659 if (UniversalHeaders)
2660 printMachOUniversalHeaders(UB, verbose: Verbose);
2661
2662 // If we have a list of architecture flags specified dump only those.
2663 if (!ArchAll && !ArchFlags.empty()) {
2664 // Look for a slice in the universal binary that matches each ArchFlag.
2665 bool ArchFound;
2666 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2667 ArchFound = false;
2668 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2669 E = UB->end_objects();
2670 I != E; ++I) {
2671 if (ArchFlags[i] == I->getArchFlagName()) {
2672 ArchFound = true;
2673 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2674 I->getAsObjectFile();
2675 std::string ArchitectureName;
2676 if (ArchFlags.size() > 1)
2677 ArchitectureName = I->getArchFlagName();
2678 if (ObjOrErr) {
2679 ObjectFile &O = *ObjOrErr.get();
2680 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &O))
2681 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: "", ArchitectureName);
2682 } else if (Error E = isNotObjectErrorInvalidFileType(
2683 Err: ObjOrErr.takeError())) {
2684 reportError(E: std::move(E), FileName: "", ArchiveName: Filename, ArchitectureName);
2685 continue;
2686 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2687 I->getAsArchive()) {
2688 std::unique_ptr<Archive> &A = *AOrErr;
2689 outs() << "Archive : " << Filename;
2690 if (!ArchitectureName.empty())
2691 outs() << " (architecture " << ArchitectureName << ")";
2692 outs() << "\n";
2693 if (ArchiveHeaders)
2694 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose,
2695 print_offset: ArchiveMemberOffsets, ArchitectureName);
2696 Error Err = Error::success();
2697 unsigned I = -1;
2698 bool FoundMember = false;
2699 for (auto &C : A->children(Err)) {
2700 ++I;
2701 if (skipArchiveMember(C, Filename))
2702 continue;
2703 FoundMember = true;
2704 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2705 if (!ChildOrErr) {
2706 if (Error E =
2707 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2708 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename,
2709 ArchitectureName);
2710 continue;
2711 }
2712 if (MachOObjectFile *O =
2713 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get()))
2714 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName(), ArchitectureName);
2715 }
2716 if (Err)
2717 reportError(E: std::move(Err), FileName: Filename);
2718 if (!FoundMember && !ArchiveMemberFilter.empty())
2719 reportError(File: Filename,
2720 Message: "archive does not contain a member named: " +
2721 ArchiveMemberFilter);
2722 } else {
2723 consumeError(Err: AOrErr.takeError());
2724 reportError(File: Filename,
2725 Message: "Mach-O universal file for architecture " +
2726 StringRef(I->getArchFlagName()) +
2727 " is not a Mach-O file or an archive file");
2728 }
2729 }
2730 }
2731 if (!ArchFound) {
2732 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2733 << "file: " + Filename + " does not contain "
2734 << "architecture: " + ArchFlags[i] + "\n";
2735 return;
2736 }
2737 }
2738 return;
2739 }
2740 // No architecture flags were specified so if this contains a slice that
2741 // matches the host architecture dump only that. For otool -a dump all
2742 // architectures to match classic otool behaviour.
2743 if (!ArchAll && !(IsOtool && ArchiveHeaders)) {
2744 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2745 E = UB->end_objects();
2746 I != E; ++I) {
2747 if (MachOObjectFile::getHostArch().getArchName() ==
2748 I->getArchFlagName()) {
2749 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2750 std::string ArchiveName;
2751 ArchiveName.clear();
2752 if (ObjOrErr) {
2753 ObjectFile &O = *ObjOrErr.get();
2754 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &O))
2755 ProcessMachO(Name: Filename, MachOOF);
2756 } else if (Error E =
2757 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2758 reportError(E: std::move(E), FileName: Filename);
2759 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2760 I->getAsArchive()) {
2761 std::unique_ptr<Archive> &A = *AOrErr;
2762 outs() << "Archive : " << Filename << "\n";
2763 if (ArchiveHeaders)
2764 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose,
2765 print_offset: ArchiveMemberOffsets);
2766 Error Err = Error::success();
2767 unsigned I = -1;
2768 bool FoundMember = false;
2769 for (auto &C : A->children(Err)) {
2770 ++I;
2771 if (skipArchiveMember(C, Filename))
2772 continue;
2773 FoundMember = true;
2774 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2775 if (!ChildOrErr) {
2776 if (Error E =
2777 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2778 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename);
2779 continue;
2780 }
2781 if (MachOObjectFile *O =
2782 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get()))
2783 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName());
2784 }
2785 if (Err)
2786 reportError(E: std::move(Err), FileName: Filename);
2787 if (!FoundMember && !ArchiveMemberFilter.empty())
2788 reportError(File: Filename, Message: "archive does not contain a member named: " +
2789 ArchiveMemberFilter);
2790 } else {
2791 consumeError(Err: AOrErr.takeError());
2792 reportError(File: Filename, Message: "Mach-O universal file for architecture " +
2793 StringRef(I->getArchFlagName()) +
2794 " is not a Mach-O file or an archive file");
2795 }
2796 return;
2797 }
2798 }
2799 }
2800 // Either all architectures have been specified or none have been specified
2801 // and this does not contain the host architecture so dump all the slices.
2802 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2803 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2804 E = UB->end_objects();
2805 I != E; ++I) {
2806 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2807 std::string ArchitectureName;
2808 if (moreThanOneArch)
2809 ArchitectureName = I->getArchFlagName();
2810 if (ObjOrErr) {
2811 ObjectFile &Obj = *ObjOrErr.get();
2812 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &Obj))
2813 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: "", ArchitectureName);
2814 } else if (Error E =
2815 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2816 reportError(E: std::move(E), FileName: Filename, ArchiveName: "", ArchitectureName);
2817 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2818 std::unique_ptr<Archive> &A = *AOrErr;
2819 outs() << "Archive : " << Filename;
2820 if (!ArchitectureName.empty())
2821 outs() << " (architecture " << ArchitectureName << ")";
2822 outs() << "\n";
2823 if (ArchiveHeaders)
2824 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose, print_offset: ArchiveMemberOffsets,
2825 ArchitectureName);
2826 Error Err = Error::success();
2827 unsigned I = -1;
2828 bool FoundMember = false;
2829 for (auto &C : A->children(Err)) {
2830 ++I;
2831 if (skipArchiveMember(C, Filename))
2832 continue;
2833 FoundMember = true;
2834 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2835 if (!ChildOrErr) {
2836 if (Error E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2837 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename,
2838 ArchitectureName);
2839 continue;
2840 }
2841 if (MachOObjectFile *O =
2842 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get())) {
2843 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName(), ArchitectureName);
2844 }
2845 }
2846 if (Err)
2847 reportError(E: std::move(Err), FileName: Filename);
2848 if (!FoundMember && !ArchiveMemberFilter.empty())
2849 reportError(File: Filename, Message: "archive does not contain a member named: " +
2850 ArchiveMemberFilter);
2851 } else {
2852 consumeError(Err: AOrErr.takeError());
2853 reportError(File: Filename, Message: "Mach-O universal file for architecture " +
2854 StringRef(I->getArchFlagName()) +
2855 " is not a Mach-O file or an archive file");
2856 }
2857 }
2858}
2859
2860namespace {
2861// The block of info used by the Symbolizer call backs.
2862struct DisassembleInfo {
2863 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2864 std::vector<SectionRef> *Sections, bool verbose)
2865 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2866 bool verbose;
2867 MachOObjectFile *O;
2868 SectionRef S;
2869 SymbolAddressMap *AddrMap;
2870 std::vector<SectionRef> *Sections;
2871 const char *class_name = nullptr;
2872 const char *selector_name = nullptr;
2873 std::unique_ptr<char[]> method = nullptr;
2874 char *demangled_name = nullptr;
2875 uint64_t adrp_addr = 0;
2876 uint32_t adrp_inst = 0;
2877 std::unique_ptr<SymbolAddressMap> bindtable;
2878 uint32_t depth = 0;
2879};
2880} // namespace
2881
2882// SymbolizerGetOpInfo() is the operand information call back function.
2883// This is called to get the symbolic information for operand(s) of an
2884// instruction when it is being done. This routine does this from
2885// the relocation information, symbol table, etc. That block of information
2886// is a pointer to the struct DisassembleInfo that was passed when the
2887// disassembler context was created and passed to back to here when
2888// called back by the disassembler for instruction operands that could have
2889// relocation information. The address of the instruction containing operand is
2890// at the Pc parameter. The immediate value the operand has is passed in
2891// op_info->Value and is at Offset past the start of the instruction and has a
2892// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2893// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2894// names and addends of the symbolic expression to add for the operand. The
2895// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2896// information is returned then this function returns 1 else it returns 0.
2897static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2898 uint64_t OpSize, uint64_t InstSize, int TagType,
2899 void *TagBuf) {
2900 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2901 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2902 uint64_t value = op_info->Value;
2903
2904 // Make sure all fields returned are zero if we don't set them.
2905 memset(s: (void *)op_info, c: '\0', n: sizeof(struct LLVMOpInfo1));
2906 op_info->Value = value;
2907
2908 // If the TagType is not the value 1 which it code knows about or if no
2909 // verbose symbolic information is wanted then just return 0, indicating no
2910 // information is being returned.
2911 if (TagType != 1 || !info->verbose)
2912 return 0;
2913
2914 unsigned int Arch = info->O->getArch();
2915 if (Arch == Triple::x86) {
2916 if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2917 return 0;
2918 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2919 // TODO:
2920 // Search the external relocation entries of a fully linked image
2921 // (if any) for an entry that matches this segment offset.
2922 // uint32_t seg_offset = (Pc + Offset);
2923 return 0;
2924 }
2925 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2926 // for an entry for this section offset.
2927 uint32_t sect_addr = info->S.getAddress();
2928 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2929 bool reloc_found = false;
2930 DataRefImpl Rel;
2931 MachO::any_relocation_info RE;
2932 bool isExtern = false;
2933 SymbolRef Symbol;
2934 bool r_scattered = false;
2935 uint32_t r_value, pair_r_value, r_type;
2936 for (const RelocationRef &Reloc : info->S.relocations()) {
2937 uint64_t RelocOffset = Reloc.getOffset();
2938 if (RelocOffset == sect_offset) {
2939 Rel = Reloc.getRawDataRefImpl();
2940 RE = info->O->getRelocation(Rel);
2941 r_type = info->O->getAnyRelocationType(RE);
2942 r_scattered = info->O->isRelocationScattered(RE);
2943 if (r_scattered) {
2944 r_value = info->O->getScatteredRelocationValue(RE);
2945 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2946 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2947 DataRefImpl RelNext = Rel;
2948 info->O->moveRelocationNext(Rel&: RelNext);
2949 MachO::any_relocation_info RENext;
2950 RENext = info->O->getRelocation(Rel: RelNext);
2951 if (info->O->isRelocationScattered(RE: RENext))
2952 pair_r_value = info->O->getScatteredRelocationValue(RE: RENext);
2953 else
2954 return 0;
2955 }
2956 } else {
2957 isExtern = info->O->getPlainRelocationExternal(RE);
2958 if (isExtern) {
2959 symbol_iterator RelocSym = Reloc.getSymbol();
2960 Symbol = *RelocSym;
2961 }
2962 }
2963 reloc_found = true;
2964 break;
2965 }
2966 }
2967 if (reloc_found && isExtern) {
2968 op_info->AddSymbol.Present = 1;
2969 op_info->AddSymbol.Name =
2970 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
2971 // For i386 extern relocation entries the value in the instruction is
2972 // the offset from the symbol, and value is already set in op_info->Value.
2973 return 1;
2974 }
2975 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2976 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2977 const char *add = GuessSymbolName(value: r_value, AddrMap: info->AddrMap);
2978 const char *sub = GuessSymbolName(value: pair_r_value, AddrMap: info->AddrMap);
2979 uint32_t offset = value - (r_value - pair_r_value);
2980 op_info->AddSymbol.Present = 1;
2981 if (add != nullptr)
2982 op_info->AddSymbol.Name = add;
2983 else
2984 op_info->AddSymbol.Value = r_value;
2985 op_info->SubtractSymbol.Present = 1;
2986 if (sub != nullptr)
2987 op_info->SubtractSymbol.Name = sub;
2988 else
2989 op_info->SubtractSymbol.Value = pair_r_value;
2990 op_info->Value = offset;
2991 return 1;
2992 }
2993 return 0;
2994 }
2995 if (Arch == Triple::x86_64) {
2996 if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2997 return 0;
2998 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2999 // relocation entries of a linked image (if any) for an entry that matches
3000 // this segment offset.
3001 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3002 uint64_t seg_offset = Pc + Offset;
3003 bool reloc_found = false;
3004 DataRefImpl Rel;
3005 MachO::any_relocation_info RE;
3006 bool isExtern = false;
3007 SymbolRef Symbol;
3008 for (const RelocationRef &Reloc : info->O->external_relocations()) {
3009 uint64_t RelocOffset = Reloc.getOffset();
3010 if (RelocOffset == seg_offset) {
3011 Rel = Reloc.getRawDataRefImpl();
3012 RE = info->O->getRelocation(Rel);
3013 // external relocation entries should always be external.
3014 isExtern = info->O->getPlainRelocationExternal(RE);
3015 if (isExtern) {
3016 symbol_iterator RelocSym = Reloc.getSymbol();
3017 Symbol = *RelocSym;
3018 }
3019 reloc_found = true;
3020 break;
3021 }
3022 }
3023 if (reloc_found && isExtern) {
3024 // The Value passed in will be adjusted by the Pc if the instruction
3025 // adds the Pc. But for x86_64 external relocation entries the Value
3026 // is the offset from the external symbol.
3027 if (info->O->getAnyRelocationPCRel(RE))
3028 op_info->Value -= Pc + InstSize;
3029 const char *name =
3030 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3031 op_info->AddSymbol.Present = 1;
3032 op_info->AddSymbol.Name = name;
3033 return 1;
3034 }
3035 return 0;
3036 }
3037 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3038 // for an entry for this section offset.
3039 uint64_t sect_addr = info->S.getAddress();
3040 uint64_t sect_offset = (Pc + Offset) - sect_addr;
3041 bool reloc_found = false;
3042 DataRefImpl Rel;
3043 MachO::any_relocation_info RE;
3044 bool isExtern = false;
3045 SymbolRef Symbol;
3046 for (const RelocationRef &Reloc : info->S.relocations()) {
3047 uint64_t RelocOffset = Reloc.getOffset();
3048 if (RelocOffset == sect_offset) {
3049 Rel = Reloc.getRawDataRefImpl();
3050 RE = info->O->getRelocation(Rel);
3051 // NOTE: Scattered relocations don't exist on x86_64.
3052 isExtern = info->O->getPlainRelocationExternal(RE);
3053 if (isExtern) {
3054 symbol_iterator RelocSym = Reloc.getSymbol();
3055 Symbol = *RelocSym;
3056 }
3057 reloc_found = true;
3058 break;
3059 }
3060 }
3061 if (reloc_found && isExtern) {
3062 // The Value passed in will be adjusted by the Pc if the instruction
3063 // adds the Pc. But for x86_64 external relocation entries the Value
3064 // is the offset from the external symbol.
3065 if (info->O->getAnyRelocationPCRel(RE))
3066 op_info->Value -= Pc + InstSize;
3067 const char *name =
3068 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3069 unsigned Type = info->O->getAnyRelocationType(RE);
3070 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
3071 DataRefImpl RelNext = Rel;
3072 info->O->moveRelocationNext(Rel&: RelNext);
3073 MachO::any_relocation_info RENext = info->O->getRelocation(Rel: RelNext);
3074 unsigned TypeNext = info->O->getAnyRelocationType(RE: RENext);
3075 bool isExternNext = info->O->getPlainRelocationExternal(RE: RENext);
3076 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RE: RENext);
3077 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
3078 op_info->SubtractSymbol.Present = 1;
3079 op_info->SubtractSymbol.Name = name;
3080 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(Index: SymbolNum);
3081 Symbol = *RelocSymNext;
3082 name = unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3083 }
3084 }
3085 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
3086 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
3087 op_info->AddSymbol.Present = 1;
3088 op_info->AddSymbol.Name = name;
3089 return 1;
3090 }
3091 return 0;
3092 }
3093 if (Arch == Triple::arm) {
3094 if (Offset != 0 || (InstSize != 4 && InstSize != 2))
3095 return 0;
3096 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3097 // TODO:
3098 // Search the external relocation entries of a fully linked image
3099 // (if any) for an entry that matches this segment offset.
3100 // uint32_t seg_offset = (Pc + Offset);
3101 return 0;
3102 }
3103 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3104 // for an entry for this section offset.
3105 uint32_t sect_addr = info->S.getAddress();
3106 uint32_t sect_offset = (Pc + Offset) - sect_addr;
3107 DataRefImpl Rel;
3108 MachO::any_relocation_info RE;
3109 bool isExtern = false;
3110 SymbolRef Symbol;
3111 bool r_scattered = false;
3112 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
3113 auto Reloc =
3114 find_if(Range: info->S.relocations(), P: [&](const RelocationRef &Reloc) {
3115 uint64_t RelocOffset = Reloc.getOffset();
3116 return RelocOffset == sect_offset;
3117 });
3118
3119 if (Reloc == info->S.relocations().end())
3120 return 0;
3121
3122 Rel = Reloc->getRawDataRefImpl();
3123 RE = info->O->getRelocation(Rel);
3124 r_length = info->O->getAnyRelocationLength(RE);
3125 r_scattered = info->O->isRelocationScattered(RE);
3126 if (r_scattered) {
3127 r_value = info->O->getScatteredRelocationValue(RE);
3128 r_type = info->O->getScatteredRelocationType(RE);
3129 } else {
3130 r_type = info->O->getAnyRelocationType(RE);
3131 isExtern = info->O->getPlainRelocationExternal(RE);
3132 if (isExtern) {
3133 symbol_iterator RelocSym = Reloc->getSymbol();
3134 Symbol = *RelocSym;
3135 }
3136 }
3137 if (r_type == MachO::ARM_RELOC_HALF ||
3138 r_type == MachO::ARM_RELOC_SECTDIFF ||
3139 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
3140 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3141 DataRefImpl RelNext = Rel;
3142 info->O->moveRelocationNext(Rel&: RelNext);
3143 MachO::any_relocation_info RENext;
3144 RENext = info->O->getRelocation(Rel: RelNext);
3145 other_half = info->O->getAnyRelocationAddress(RE: RENext) & 0xffff;
3146 if (info->O->isRelocationScattered(RE: RENext))
3147 pair_r_value = info->O->getScatteredRelocationValue(RE: RENext);
3148 }
3149
3150 if (isExtern) {
3151 const char *name =
3152 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3153 op_info->AddSymbol.Present = 1;
3154 op_info->AddSymbol.Name = name;
3155 switch (r_type) {
3156 case MachO::ARM_RELOC_HALF:
3157 if ((r_length & 0x1) == 1) {
3158 op_info->Value = value << 16 | other_half;
3159 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3160 } else {
3161 op_info->Value = other_half << 16 | value;
3162 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3163 }
3164 break;
3165 default:
3166 break;
3167 }
3168 return 1;
3169 }
3170 // If we have a branch that is not an external relocation entry then
3171 // return 0 so the code in tryAddingSymbolicOperand() can use the
3172 // SymbolLookUp call back with the branch target address to look up the
3173 // symbol and possibility add an annotation for a symbol stub.
3174 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
3175 r_type == MachO::ARM_THUMB_RELOC_BR22))
3176 return 0;
3177
3178 uint32_t offset = 0;
3179 if (r_type == MachO::ARM_RELOC_HALF ||
3180 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3181 if ((r_length & 0x1) == 1)
3182 value = value << 16 | other_half;
3183 else
3184 value = other_half << 16 | value;
3185 }
3186 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
3187 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
3188 offset = value - r_value;
3189 value = r_value;
3190 }
3191
3192 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3193 if ((r_length & 0x1) == 1)
3194 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3195 else
3196 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3197 const char *add = GuessSymbolName(value: r_value, AddrMap: info->AddrMap);
3198 const char *sub = GuessSymbolName(value: pair_r_value, AddrMap: info->AddrMap);
3199 int32_t offset = value - (r_value - pair_r_value);
3200 op_info->AddSymbol.Present = 1;
3201 if (add != nullptr)
3202 op_info->AddSymbol.Name = add;
3203 else
3204 op_info->AddSymbol.Value = r_value;
3205 op_info->SubtractSymbol.Present = 1;
3206 if (sub != nullptr)
3207 op_info->SubtractSymbol.Name = sub;
3208 else
3209 op_info->SubtractSymbol.Value = pair_r_value;
3210 op_info->Value = offset;
3211 return 1;
3212 }
3213
3214 op_info->AddSymbol.Present = 1;
3215 op_info->Value = offset;
3216 if (r_type == MachO::ARM_RELOC_HALF) {
3217 if ((r_length & 0x1) == 1)
3218 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3219 else
3220 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3221 }
3222 const char *add = GuessSymbolName(value, AddrMap: info->AddrMap);
3223 if (add != nullptr) {
3224 op_info->AddSymbol.Name = add;
3225 return 1;
3226 }
3227 op_info->AddSymbol.Value = value;
3228 return 1;
3229 }
3230 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32) {
3231 if (Offset != 0 || InstSize != 4)
3232 return 0;
3233 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3234 // TODO:
3235 // Search the external relocation entries of a fully linked image
3236 // (if any) for an entry that matches this segment offset.
3237 // uint64_t seg_offset = (Pc + Offset);
3238 return 0;
3239 }
3240 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3241 // for an entry for this section offset.
3242 uint64_t sect_addr = info->S.getAddress();
3243 uint64_t sect_offset = (Pc + Offset) - sect_addr;
3244 auto Reloc =
3245 find_if(Range: info->S.relocations(), P: [&](const RelocationRef &Reloc) {
3246 uint64_t RelocOffset = Reloc.getOffset();
3247 return RelocOffset == sect_offset;
3248 });
3249
3250 if (Reloc == info->S.relocations().end())
3251 return 0;
3252
3253 DataRefImpl Rel = Reloc->getRawDataRefImpl();
3254 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
3255 uint32_t r_type = info->O->getAnyRelocationType(RE);
3256 if (r_type == MachO::ARM64_RELOC_ADDEND) {
3257 DataRefImpl RelNext = Rel;
3258 info->O->moveRelocationNext(Rel&: RelNext);
3259 MachO::any_relocation_info RENext = info->O->getRelocation(Rel: RelNext);
3260 if (value == 0) {
3261 value = info->O->getPlainRelocationSymbolNum(RE: RENext);
3262 op_info->Value = value;
3263 }
3264 }
3265 // NOTE: Scattered relocations don't exist on arm64.
3266 if (!info->O->getPlainRelocationExternal(RE))
3267 return 0;
3268 const char *name =
3269 unwrapOrError(EO: Reloc->getSymbol()->getName(), Args: info->O->getFileName())
3270 .data();
3271 op_info->AddSymbol.Present = 1;
3272 op_info->AddSymbol.Name = name;
3273
3274 switch (r_type) {
3275 case MachO::ARM64_RELOC_PAGE21:
3276 /* @page */
3277 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
3278 break;
3279 case MachO::ARM64_RELOC_PAGEOFF12:
3280 /* @pageoff */
3281 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
3282 break;
3283 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
3284 /* @gotpage */
3285 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
3286 break;
3287 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
3288 /* @gotpageoff */
3289 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
3290 break;
3291 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
3292 /* @tvlppage is not implemented in llvm-mc */
3293 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
3294 break;
3295 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
3296 /* @tvlppageoff is not implemented in llvm-mc */
3297 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3298 break;
3299 default:
3300 case MachO::ARM64_RELOC_BRANCH26:
3301 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3302 break;
3303 }
3304 return 1;
3305 }
3306 return 0;
3307}
3308
3309// GuessCstringPointer is passed the address of what might be a pointer to a
3310// literal string in a cstring section. If that address is in a cstring section
3311// it returns a pointer to that string. Else it returns nullptr.
3312static const char *GuessCstringPointer(uint64_t ReferenceValue,
3313 struct DisassembleInfo *info) {
3314 for (const auto &Load : info->O->load_commands()) {
3315 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3316 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3317 for (unsigned J = 0; J < Seg.nsects; ++J) {
3318 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3319 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3320 if (section_type == MachO::S_CSTRING_LITERALS &&
3321 ReferenceValue >= Sec.addr &&
3322 ReferenceValue < Sec.addr + Sec.size) {
3323 uint64_t sect_offset = ReferenceValue - Sec.addr;
3324 uint64_t object_offset = Sec.offset + sect_offset;
3325 StringRef MachOContents = info->O->getData();
3326 uint64_t object_size = MachOContents.size();
3327 const char *object_addr = MachOContents.data();
3328 if (object_offset < object_size) {
3329 const char *name = object_addr + object_offset;
3330 return name;
3331 } else {
3332 return nullptr;
3333 }
3334 }
3335 }
3336 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3337 MachO::segment_command Seg = info->O->getSegmentLoadCommand(L: Load);
3338 for (unsigned J = 0; J < Seg.nsects; ++J) {
3339 MachO::section Sec = info->O->getSection(L: Load, Index: J);
3340 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3341 if (section_type == MachO::S_CSTRING_LITERALS &&
3342 ReferenceValue >= Sec.addr &&
3343 ReferenceValue < Sec.addr + Sec.size) {
3344 uint64_t sect_offset = ReferenceValue - Sec.addr;
3345 uint64_t object_offset = Sec.offset + sect_offset;
3346 StringRef MachOContents = info->O->getData();
3347 uint64_t object_size = MachOContents.size();
3348 const char *object_addr = MachOContents.data();
3349 if (object_offset < object_size) {
3350 const char *name = object_addr + object_offset;
3351 return name;
3352 } else {
3353 return nullptr;
3354 }
3355 }
3356 }
3357 }
3358 }
3359 return nullptr;
3360}
3361
3362// GuessIndirectSymbol returns the name of the indirect symbol for the
3363// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
3364// an address of a symbol stub or a lazy or non-lazy pointer to associate the
3365// symbol name being referenced by the stub or pointer.
3366static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3367 struct DisassembleInfo *info) {
3368 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3369 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3370 for (const auto &Load : info->O->load_commands()) {
3371 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3372 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3373 for (unsigned J = 0; J < Seg.nsects; ++J) {
3374 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3375 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3376 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3377 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3378 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3379 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3380 section_type == MachO::S_SYMBOL_STUBS) &&
3381 ReferenceValue >= Sec.addr &&
3382 ReferenceValue < Sec.addr + Sec.size) {
3383 uint32_t stride;
3384 if (section_type == MachO::S_SYMBOL_STUBS)
3385 stride = Sec.reserved2;
3386 else
3387 stride = 8;
3388 if (stride == 0)
3389 return nullptr;
3390 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3391 if (index < Dysymtab.nindirectsyms) {
3392 uint32_t indirect_symbol =
3393 info->O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: index);
3394 if (indirect_symbol < Symtab.nsyms) {
3395 symbol_iterator Sym = info->O->getSymbolByIndex(Index: indirect_symbol);
3396 return unwrapOrError(EO: Sym->getName(), Args: info->O->getFileName())
3397 .data();
3398 }
3399 }
3400 }
3401 }
3402 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3403 MachO::segment_command Seg = info->O->getSegmentLoadCommand(L: Load);
3404 for (unsigned J = 0; J < Seg.nsects; ++J) {
3405 MachO::section Sec = info->O->getSection(L: Load, Index: J);
3406 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3407 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3408 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3409 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3410 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3411 section_type == MachO::S_SYMBOL_STUBS) &&
3412 ReferenceValue >= Sec.addr &&
3413 ReferenceValue < Sec.addr + Sec.size) {
3414 uint32_t stride;
3415 if (section_type == MachO::S_SYMBOL_STUBS)
3416 stride = Sec.reserved2;
3417 else
3418 stride = 4;
3419 if (stride == 0)
3420 return nullptr;
3421 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3422 if (index < Dysymtab.nindirectsyms) {
3423 uint32_t indirect_symbol =
3424 info->O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: index);
3425 if (indirect_symbol < Symtab.nsyms) {
3426 symbol_iterator Sym = info->O->getSymbolByIndex(Index: indirect_symbol);
3427 return unwrapOrError(EO: Sym->getName(), Args: info->O->getFileName())
3428 .data();
3429 }
3430 }
3431 }
3432 }
3433 }
3434 }
3435 return nullptr;
3436}
3437
3438// method_reference() is called passing it the ReferenceName that might be
3439// a reference it to an Objective-C method call. If so then it allocates and
3440// assembles a method call string with the values last seen and saved in
3441// the DisassembleInfo's class_name and selector_name fields. This is saved
3442// into the method field of the info and any previous string is free'ed.
3443// Then the class_name field in the info is set to nullptr. The method call
3444// string is set into ReferenceName and ReferenceType is set to
3445// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3446// then both ReferenceType and ReferenceName are left unchanged.
3447static void method_reference(struct DisassembleInfo *info,
3448 uint64_t *ReferenceType,
3449 const char **ReferenceName) {
3450 unsigned int Arch = info->O->getArch();
3451 if (*ReferenceName != nullptr) {
3452 if (strcmp(s1: *ReferenceName, s2: "_objc_msgSend") == 0) {
3453 if (info->selector_name != nullptr) {
3454 if (info->class_name != nullptr) {
3455 info->method = std::make_unique<char[]>(
3456 num: 5 + strlen(s: info->class_name) + strlen(s: info->selector_name));
3457 char *method = info->method.get();
3458 if (method != nullptr) {
3459 strcpy(dest: method, src: "+[");
3460 strcat(dest: method, src: info->class_name);
3461 strcat(dest: method, src: " ");
3462 strcat(dest: method, src: info->selector_name);
3463 strcat(dest: method, src: "]");
3464 *ReferenceName = method;
3465 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3466 }
3467 } else {
3468 info->method =
3469 std::make_unique<char[]>(num: 9 + strlen(s: info->selector_name));
3470 char *method = info->method.get();
3471 if (method != nullptr) {
3472 if (Arch == Triple::x86_64)
3473 strcpy(dest: method, src: "-[%rdi ");
3474 else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32)
3475 strcpy(dest: method, src: "-[x0 ");
3476 else
3477 strcpy(dest: method, src: "-[r? ");
3478 strcat(dest: method, src: info->selector_name);
3479 strcat(dest: method, src: "]");
3480 *ReferenceName = method;
3481 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3482 }
3483 }
3484 info->class_name = nullptr;
3485 }
3486 } else if (strcmp(s1: *ReferenceName, s2: "_objc_msgSendSuper2") == 0) {
3487 if (info->selector_name != nullptr) {
3488 info->method =
3489 std::make_unique<char[]>(num: 17 + strlen(s: info->selector_name));
3490 char *method = info->method.get();
3491 if (method != nullptr) {
3492 if (Arch == Triple::x86_64)
3493 strcpy(dest: method, src: "-[[%rdi super] ");
3494 else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32)
3495 strcpy(dest: method, src: "-[[x0 super] ");
3496 else
3497 strcpy(dest: method, src: "-[[r? super] ");
3498 strcat(dest: method, src: info->selector_name);
3499 strcat(dest: method, src: "]");
3500 *ReferenceName = method;
3501 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3502 }
3503 info->class_name = nullptr;
3504 }
3505 }
3506 }
3507}
3508
3509// GuessPointerPointer() is passed the address of what might be a pointer to
3510// a reference to an Objective-C class, selector, message ref or cfstring.
3511// If so the value of the pointer is returned and one of the booleans are set
3512// to true. If not zero is returned and all the booleans are set to false.
3513static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3514 struct DisassembleInfo *info,
3515 bool &classref, bool &selref, bool &msgref,
3516 bool &cfstring) {
3517 classref = false;
3518 selref = false;
3519 msgref = false;
3520 cfstring = false;
3521 for (const auto &Load : info->O->load_commands()) {
3522 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3523 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3524 for (unsigned J = 0; J < Seg.nsects; ++J) {
3525 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3526 if ((strncmp(s1: Sec.sectname, s2: "__objc_selrefs", n: 16) == 0 ||
3527 strncmp(s1: Sec.sectname, s2: "__objc_classrefs", n: 16) == 0 ||
3528 strncmp(s1: Sec.sectname, s2: "__objc_superrefs", n: 16) == 0 ||
3529 strncmp(s1: Sec.sectname, s2: "__objc_msgrefs", n: 16) == 0 ||
3530 strncmp(s1: Sec.sectname, s2: "__cfstring", n: 16) == 0) &&
3531 ReferenceValue >= Sec.addr &&
3532 ReferenceValue < Sec.addr + Sec.size) {
3533 uint64_t sect_offset = ReferenceValue - Sec.addr;
3534 uint64_t object_offset = Sec.offset + sect_offset;
3535 StringRef MachOContents = info->O->getData();
3536 uint64_t object_size = MachOContents.size();
3537 const char *object_addr = MachOContents.data();
3538 if (object_offset < object_size) {
3539 uint64_t pointer_value;
3540 memcpy(dest: &pointer_value, src: object_addr + object_offset,
3541 n: sizeof(uint64_t));
3542 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3543 sys::swapByteOrder(Value&: pointer_value);
3544 if (strncmp(s1: Sec.sectname, s2: "__objc_selrefs", n: 16) == 0)
3545 selref = true;
3546 else if (strncmp(s1: Sec.sectname, s2: "__objc_classrefs", n: 16) == 0 ||
3547 strncmp(s1: Sec.sectname, s2: "__objc_superrefs", n: 16) == 0)
3548 classref = true;
3549 else if (strncmp(s1: Sec.sectname, s2: "__objc_msgrefs", n: 16) == 0 &&
3550 ReferenceValue + 8 < Sec.addr + Sec.size) {
3551 msgref = true;
3552 memcpy(dest: &pointer_value, src: object_addr + object_offset + 8,
3553 n: sizeof(uint64_t));
3554 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3555 sys::swapByteOrder(Value&: pointer_value);
3556 } else if (strncmp(s1: Sec.sectname, s2: "__cfstring", n: 16) == 0)
3557 cfstring = true;
3558 return pointer_value;
3559 } else {
3560 return 0;
3561 }
3562 }
3563 }
3564 }
3565 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3566 }
3567 return 0;
3568}
3569
3570// get_pointer_64 returns a pointer to the bytes in the object file at the
3571// Address from a section in the Mach-O file. And indirectly returns the
3572// offset into the section, number of bytes left in the section past the offset
3573// and which section is was being referenced. If the Address is not in a
3574// section nullptr is returned.
3575static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3576 uint32_t &left, SectionRef &S,
3577 DisassembleInfo *info,
3578 bool objc_only = false) {
3579 offset = 0;
3580 left = 0;
3581 S = SectionRef();
3582 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3583 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3584 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3585 if (SectSize == 0)
3586 continue;
3587 if (objc_only) {
3588 StringRef SectName;
3589 Expected<StringRef> SecNameOrErr =
3590 ((*(info->Sections))[SectIdx]).getName();
3591 if (SecNameOrErr)
3592 SectName = *SecNameOrErr;
3593 else
3594 consumeError(Err: SecNameOrErr.takeError());
3595
3596 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3597 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
3598 if (SegName != "__OBJC" && SectName != "__cstring")
3599 continue;
3600 }
3601 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3602 S = (*(info->Sections))[SectIdx];
3603 offset = Address - SectAddress;
3604 left = SectSize - offset;
3605 StringRef SectContents = unwrapOrError(
3606 EO: ((*(info->Sections))[SectIdx]).getContents(), Args: info->O->getFileName());
3607 return SectContents.data() + offset;
3608 }
3609 }
3610 return nullptr;
3611}
3612
3613static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3614 uint32_t &left, SectionRef &S,
3615 DisassembleInfo *info,
3616 bool objc_only = false) {
3617 return get_pointer_64(Address, offset, left, S, info, objc_only);
3618}
3619
3620// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3621// the symbol indirectly through n_value. Based on the relocation information
3622// for the specified section offset in the specified section reference.
3623// If no relocation information is found and a non-zero ReferenceValue for the
3624// symbol is passed, look up that address in the info's AddrMap.
3625static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3626 DisassembleInfo *info, uint64_t &n_value,
3627 uint64_t ReferenceValue = 0) {
3628 n_value = 0;
3629 if (!info->verbose)
3630 return nullptr;
3631
3632 // See if there is an external relocation entry at the sect_offset.
3633 bool reloc_found = false;
3634 DataRefImpl Rel;
3635 MachO::any_relocation_info RE;
3636 bool isExtern = false;
3637 SymbolRef Symbol;
3638 for (const RelocationRef &Reloc : S.relocations()) {
3639 uint64_t RelocOffset = Reloc.getOffset();
3640 if (RelocOffset == sect_offset) {
3641 Rel = Reloc.getRawDataRefImpl();
3642 RE = info->O->getRelocation(Rel);
3643 if (info->O->isRelocationScattered(RE))
3644 continue;
3645 isExtern = info->O->getPlainRelocationExternal(RE);
3646 if (isExtern) {
3647 symbol_iterator RelocSym = Reloc.getSymbol();
3648 Symbol = *RelocSym;
3649 }
3650 reloc_found = true;
3651 break;
3652 }
3653 }
3654 // If there is an external relocation entry for a symbol in this section
3655 // at this section_offset then use that symbol's value for the n_value
3656 // and return its name.
3657 const char *SymbolName = nullptr;
3658 if (reloc_found && isExtern) {
3659 n_value = cantFail(ValOrErr: Symbol.getValue());
3660 StringRef Name = unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName());
3661 if (!Name.empty()) {
3662 SymbolName = Name.data();
3663 return SymbolName;
3664 }
3665 }
3666
3667 // TODO: For fully linked images, look through the external relocation
3668 // entries off the dynamic symtab command. For these the r_offset is from the
3669 // start of the first writeable segment in the Mach-O file. So the offset
3670 // to this section from that segment is passed to this routine by the caller,
3671 // as the database_offset. Which is the difference of the section's starting
3672 // address and the first writable segment.
3673 //
3674 // NOTE: need add passing the database_offset to this routine.
3675
3676 // We did not find an external relocation entry so look up the ReferenceValue
3677 // as an address of a symbol and if found return that symbol's name.
3678 SymbolName = GuessSymbolName(value: ReferenceValue, AddrMap: info->AddrMap);
3679
3680 return SymbolName;
3681}
3682
3683static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3684 DisassembleInfo *info,
3685 uint32_t ReferenceValue) {
3686 uint64_t n_value64;
3687 return get_symbol_64(sect_offset, S, info, n_value&: n_value64, ReferenceValue);
3688}
3689
3690namespace {
3691
3692// These are structs in the Objective-C meta data and read to produce the
3693// comments for disassembly. While these are part of the ABI they are no
3694// public definitions. So the are here not in include/llvm/BinaryFormat/MachO.h
3695// .
3696
3697// The cfstring object in a 64-bit Mach-O file.
3698struct cfstring64_t {
3699 uint64_t isa; // class64_t * (64-bit pointer)
3700 uint64_t flags; // flag bits
3701 uint64_t characters; // char * (64-bit pointer)
3702 uint64_t length; // number of non-NULL characters in above
3703};
3704
3705// The class object in a 64-bit Mach-O file.
3706struct class64_t {
3707 uint64_t isa; // class64_t * (64-bit pointer)
3708 uint64_t superclass; // class64_t * (64-bit pointer)
3709 uint64_t cache; // Cache (64-bit pointer)
3710 uint64_t vtable; // IMP * (64-bit pointer)
3711 uint64_t data; // class_ro64_t * (64-bit pointer)
3712};
3713
3714struct class32_t {
3715 uint32_t isa; /* class32_t * (32-bit pointer) */
3716 uint32_t superclass; /* class32_t * (32-bit pointer) */
3717 uint32_t cache; /* Cache (32-bit pointer) */
3718 uint32_t vtable; /* IMP * (32-bit pointer) */
3719 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3720};
3721
3722struct class_ro64_t {
3723 uint32_t flags;
3724 uint32_t instanceStart;
3725 uint32_t instanceSize;
3726 uint32_t reserved;
3727 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3728 uint64_t name; // const char * (64-bit pointer)
3729 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3730 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3731 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3732 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3733 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3734};
3735
3736struct class_ro32_t {
3737 uint32_t flags;
3738 uint32_t instanceStart;
3739 uint32_t instanceSize;
3740 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3741 uint32_t name; /* const char * (32-bit pointer) */
3742 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3743 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3744 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3745 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3746 uint32_t baseProperties; /* const struct objc_property_list *
3747 (32-bit pointer) */
3748};
3749
3750/* Values for class_ro{64,32}_t->flags */
3751#define RO_META (1 << 0)
3752#define RO_ROOT (1 << 1)
3753#define RO_HAS_CXX_STRUCTORS (1 << 2)
3754
3755/* Values for method_list{64,32}_t->entsize */
3756#define ML_HAS_RELATIVE_PTRS (1 << 31)
3757#define ML_ENTSIZE_MASK 0xFFFF
3758
3759struct method_list64_t {
3760 uint32_t entsize;
3761 uint32_t count;
3762 /* struct method64_t first; These structures follow inline */
3763};
3764
3765struct method_list32_t {
3766 uint32_t entsize;
3767 uint32_t count;
3768 /* struct method32_t first; These structures follow inline */
3769};
3770
3771struct method64_t {
3772 uint64_t name; /* SEL (64-bit pointer) */
3773 uint64_t types; /* const char * (64-bit pointer) */
3774 uint64_t imp; /* IMP (64-bit pointer) */
3775};
3776
3777struct method32_t {
3778 uint32_t name; /* SEL (32-bit pointer) */
3779 uint32_t types; /* const char * (32-bit pointer) */
3780 uint32_t imp; /* IMP (32-bit pointer) */
3781};
3782
3783struct method_relative_t {
3784 int32_t name; /* SEL (32-bit relative) */
3785 int32_t types; /* const char * (32-bit relative) */
3786 int32_t imp; /* IMP (32-bit relative) */
3787};
3788
3789struct protocol_list64_t {
3790 uint64_t count; /* uintptr_t (a 64-bit value) */
3791 /* struct protocol64_t * list[0]; These pointers follow inline */
3792};
3793
3794struct protocol_list32_t {
3795 uint32_t count; /* uintptr_t (a 32-bit value) */
3796 /* struct protocol32_t * list[0]; These pointers follow inline */
3797};
3798
3799struct protocol64_t {
3800 uint64_t isa; /* id * (64-bit pointer) */
3801 uint64_t name; /* const char * (64-bit pointer) */
3802 uint64_t protocols; /* struct protocol_list64_t *
3803 (64-bit pointer) */
3804 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3805 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3806 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3807 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3808 uint64_t instanceProperties; /* struct objc_property_list *
3809 (64-bit pointer) */
3810};
3811
3812struct protocol32_t {
3813 uint32_t isa; /* id * (32-bit pointer) */
3814 uint32_t name; /* const char * (32-bit pointer) */
3815 uint32_t protocols; /* struct protocol_list_t *
3816 (32-bit pointer) */
3817 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3818 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3819 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3820 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3821 uint32_t instanceProperties; /* struct objc_property_list *
3822 (32-bit pointer) */
3823};
3824
3825struct ivar_list64_t {
3826 uint32_t entsize;
3827 uint32_t count;
3828 /* struct ivar64_t first; These structures follow inline */
3829};
3830
3831struct ivar_list32_t {
3832 uint32_t entsize;
3833 uint32_t count;
3834 /* struct ivar32_t first; These structures follow inline */
3835};
3836
3837struct ivar64_t {
3838 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3839 uint64_t name; /* const char * (64-bit pointer) */
3840 uint64_t type; /* const char * (64-bit pointer) */
3841 uint32_t alignment;
3842 uint32_t size;
3843};
3844
3845struct ivar32_t {
3846 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3847 uint32_t name; /* const char * (32-bit pointer) */
3848 uint32_t type; /* const char * (32-bit pointer) */
3849 uint32_t alignment;
3850 uint32_t size;
3851};
3852
3853struct objc_property_list64 {
3854 uint32_t entsize;
3855 uint32_t count;
3856 /* struct objc_property64 first; These structures follow inline */
3857};
3858
3859struct objc_property_list32 {
3860 uint32_t entsize;
3861 uint32_t count;
3862 /* struct objc_property32 first; These structures follow inline */
3863};
3864
3865struct objc_property64 {
3866 uint64_t name; /* const char * (64-bit pointer) */
3867 uint64_t attributes; /* const char * (64-bit pointer) */
3868};
3869
3870struct objc_property32 {
3871 uint32_t name; /* const char * (32-bit pointer) */
3872 uint32_t attributes; /* const char * (32-bit pointer) */
3873};
3874
3875struct category64_t {
3876 uint64_t name; /* const char * (64-bit pointer) */
3877 uint64_t cls; /* struct class_t * (64-bit pointer) */
3878 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3879 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3880 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3881 uint64_t instanceProperties; /* struct objc_property_list *
3882 (64-bit pointer) */
3883};
3884
3885struct category32_t {
3886 uint32_t name; /* const char * (32-bit pointer) */
3887 uint32_t cls; /* struct class_t * (32-bit pointer) */
3888 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3889 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3890 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3891 uint32_t instanceProperties; /* struct objc_property_list *
3892 (32-bit pointer) */
3893};
3894
3895struct objc_image_info64 {
3896 uint32_t version;
3897 uint32_t flags;
3898};
3899struct objc_image_info32 {
3900 uint32_t version;
3901 uint32_t flags;
3902};
3903struct imageInfo_t {
3904 uint32_t version;
3905 uint32_t flags;
3906};
3907/* masks for objc_image_info.flags */
3908#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3909#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3910#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3911#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3912
3913struct message_ref64 {
3914 uint64_t imp; /* IMP (64-bit pointer) */
3915 uint64_t sel; /* SEL (64-bit pointer) */
3916};
3917
3918struct message_ref32 {
3919 uint32_t imp; /* IMP (32-bit pointer) */
3920 uint32_t sel; /* SEL (32-bit pointer) */
3921};
3922
3923// Objective-C 1 (32-bit only) meta data structs.
3924
3925struct objc_module_t {
3926 uint32_t version;
3927 uint32_t size;
3928 uint32_t name; /* char * (32-bit pointer) */
3929 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3930};
3931
3932struct objc_symtab_t {
3933 uint32_t sel_ref_cnt;
3934 uint32_t refs; /* SEL * (32-bit pointer) */
3935 uint16_t cls_def_cnt;
3936 uint16_t cat_def_cnt;
3937 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3938};
3939
3940struct objc_class_t {
3941 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3942 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3943 uint32_t name; /* const char * (32-bit pointer) */
3944 int32_t version;
3945 int32_t info;
3946 int32_t instance_size;
3947 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3948 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3949 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3950 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3951};
3952
3953#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3954// class is not a metaclass
3955#define CLS_CLASS 0x1
3956// class is a metaclass
3957#define CLS_META 0x2
3958
3959struct objc_category_t {
3960 uint32_t category_name; /* char * (32-bit pointer) */
3961 uint32_t class_name; /* char * (32-bit pointer) */
3962 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3963 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3964 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3965};
3966
3967struct objc_ivar_t {
3968 uint32_t ivar_name; /* char * (32-bit pointer) */
3969 uint32_t ivar_type; /* char * (32-bit pointer) */
3970 int32_t ivar_offset;
3971};
3972
3973struct objc_ivar_list_t {
3974 int32_t ivar_count;
3975 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3976};
3977
3978struct objc_method_list_t {
3979 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3980 int32_t method_count;
3981 // struct objc_method_t method_list[1]; /* variable length structure */
3982};
3983
3984struct objc_method_t {
3985 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3986 uint32_t method_types; /* char * (32-bit pointer) */
3987 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3988 (32-bit pointer) */
3989};
3990
3991struct objc_protocol_list_t {
3992 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3993 int32_t count;
3994 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3995 // (32-bit pointer) */
3996};
3997
3998struct objc_protocol_t {
3999 uint32_t isa; /* struct objc_class * (32-bit pointer) */
4000 uint32_t protocol_name; /* char * (32-bit pointer) */
4001 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
4002 uint32_t instance_methods; /* struct objc_method_description_list *
4003 (32-bit pointer) */
4004 uint32_t class_methods; /* struct objc_method_description_list *
4005 (32-bit pointer) */
4006};
4007
4008struct objc_method_description_list_t {
4009 int32_t count;
4010 // struct objc_method_description_t list[1];
4011};
4012
4013struct objc_method_description_t {
4014 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
4015 uint32_t types; /* char * (32-bit pointer) */
4016};
4017
4018inline void swapStruct(struct cfstring64_t &cfs) {
4019 sys::swapByteOrder(Value&: cfs.isa);
4020 sys::swapByteOrder(Value&: cfs.flags);
4021 sys::swapByteOrder(Value&: cfs.characters);
4022 sys::swapByteOrder(Value&: cfs.length);
4023}
4024
4025inline void swapStruct(struct class64_t &c) {
4026 sys::swapByteOrder(Value&: c.isa);
4027 sys::swapByteOrder(Value&: c.superclass);
4028 sys::swapByteOrder(Value&: c.cache);
4029 sys::swapByteOrder(Value&: c.vtable);
4030 sys::swapByteOrder(Value&: c.data);
4031}
4032
4033inline void swapStruct(struct class32_t &c) {
4034 sys::swapByteOrder(Value&: c.isa);
4035 sys::swapByteOrder(Value&: c.superclass);
4036 sys::swapByteOrder(Value&: c.cache);
4037 sys::swapByteOrder(Value&: c.vtable);
4038 sys::swapByteOrder(Value&: c.data);
4039}
4040
4041inline void swapStruct(struct class_ro64_t &cro) {
4042 sys::swapByteOrder(Value&: cro.flags);
4043 sys::swapByteOrder(Value&: cro.instanceStart);
4044 sys::swapByteOrder(Value&: cro.instanceSize);
4045 sys::swapByteOrder(Value&: cro.reserved);
4046 sys::swapByteOrder(Value&: cro.ivarLayout);
4047 sys::swapByteOrder(Value&: cro.name);
4048 sys::swapByteOrder(Value&: cro.baseMethods);
4049 sys::swapByteOrder(Value&: cro.baseProtocols);
4050 sys::swapByteOrder(Value&: cro.ivars);
4051 sys::swapByteOrder(Value&: cro.weakIvarLayout);
4052 sys::swapByteOrder(Value&: cro.baseProperties);
4053}
4054
4055inline void swapStruct(struct class_ro32_t &cro) {
4056 sys::swapByteOrder(Value&: cro.flags);
4057 sys::swapByteOrder(Value&: cro.instanceStart);
4058 sys::swapByteOrder(Value&: cro.instanceSize);
4059 sys::swapByteOrder(Value&: cro.ivarLayout);
4060 sys::swapByteOrder(Value&: cro.name);
4061 sys::swapByteOrder(Value&: cro.baseMethods);
4062 sys::swapByteOrder(Value&: cro.baseProtocols);
4063 sys::swapByteOrder(Value&: cro.ivars);
4064 sys::swapByteOrder(Value&: cro.weakIvarLayout);
4065 sys::swapByteOrder(Value&: cro.baseProperties);
4066}
4067
4068inline void swapStruct(struct method_list64_t &ml) {
4069 sys::swapByteOrder(Value&: ml.entsize);
4070 sys::swapByteOrder(Value&: ml.count);
4071}
4072
4073inline void swapStruct(struct method_list32_t &ml) {
4074 sys::swapByteOrder(Value&: ml.entsize);
4075 sys::swapByteOrder(Value&: ml.count);
4076}
4077
4078inline void swapStruct(struct method64_t &m) {
4079 sys::swapByteOrder(Value&: m.name);
4080 sys::swapByteOrder(Value&: m.types);
4081 sys::swapByteOrder(Value&: m.imp);
4082}
4083
4084inline void swapStruct(struct method32_t &m) {
4085 sys::swapByteOrder(Value&: m.name);
4086 sys::swapByteOrder(Value&: m.types);
4087 sys::swapByteOrder(Value&: m.imp);
4088}
4089
4090inline void swapStruct(struct method_relative_t &m) {
4091 sys::swapByteOrder(Value&: m.name);
4092 sys::swapByteOrder(Value&: m.types);
4093 sys::swapByteOrder(Value&: m.imp);
4094}
4095
4096inline void swapStruct(struct protocol_list64_t &pl) {
4097 sys::swapByteOrder(Value&: pl.count);
4098}
4099
4100inline void swapStruct(struct protocol_list32_t &pl) {
4101 sys::swapByteOrder(Value&: pl.count);
4102}
4103
4104inline void swapStruct(struct protocol64_t &p) {
4105 sys::swapByteOrder(Value&: p.isa);
4106 sys::swapByteOrder(Value&: p.name);
4107 sys::swapByteOrder(Value&: p.protocols);
4108 sys::swapByteOrder(Value&: p.instanceMethods);
4109 sys::swapByteOrder(Value&: p.classMethods);
4110 sys::swapByteOrder(Value&: p.optionalInstanceMethods);
4111 sys::swapByteOrder(Value&: p.optionalClassMethods);
4112 sys::swapByteOrder(Value&: p.instanceProperties);
4113}
4114
4115inline void swapStruct(struct protocol32_t &p) {
4116 sys::swapByteOrder(Value&: p.isa);
4117 sys::swapByteOrder(Value&: p.name);
4118 sys::swapByteOrder(Value&: p.protocols);
4119 sys::swapByteOrder(Value&: p.instanceMethods);
4120 sys::swapByteOrder(Value&: p.classMethods);
4121 sys::swapByteOrder(Value&: p.optionalInstanceMethods);
4122 sys::swapByteOrder(Value&: p.optionalClassMethods);
4123 sys::swapByteOrder(Value&: p.instanceProperties);
4124}
4125
4126inline void swapStruct(struct ivar_list64_t &il) {
4127 sys::swapByteOrder(Value&: il.entsize);
4128 sys::swapByteOrder(Value&: il.count);
4129}
4130
4131inline void swapStruct(struct ivar_list32_t &il) {
4132 sys::swapByteOrder(Value&: il.entsize);
4133 sys::swapByteOrder(Value&: il.count);
4134}
4135
4136inline void swapStruct(struct ivar64_t &i) {
4137 sys::swapByteOrder(Value&: i.offset);
4138 sys::swapByteOrder(Value&: i.name);
4139 sys::swapByteOrder(Value&: i.type);
4140 sys::swapByteOrder(Value&: i.alignment);
4141 sys::swapByteOrder(Value&: i.size);
4142}
4143
4144inline void swapStruct(struct ivar32_t &i) {
4145 sys::swapByteOrder(Value&: i.offset);
4146 sys::swapByteOrder(Value&: i.name);
4147 sys::swapByteOrder(Value&: i.type);
4148 sys::swapByteOrder(Value&: i.alignment);
4149 sys::swapByteOrder(Value&: i.size);
4150}
4151
4152inline void swapStruct(struct objc_property_list64 &pl) {
4153 sys::swapByteOrder(Value&: pl.entsize);
4154 sys::swapByteOrder(Value&: pl.count);
4155}
4156
4157inline void swapStruct(struct objc_property_list32 &pl) {
4158 sys::swapByteOrder(Value&: pl.entsize);
4159 sys::swapByteOrder(Value&: pl.count);
4160}
4161
4162inline void swapStruct(struct objc_property64 &op) {
4163 sys::swapByteOrder(Value&: op.name);
4164 sys::swapByteOrder(Value&: op.attributes);
4165}
4166
4167inline void swapStruct(struct objc_property32 &op) {
4168 sys::swapByteOrder(Value&: op.name);
4169 sys::swapByteOrder(Value&: op.attributes);
4170}
4171
4172inline void swapStruct(struct category64_t &c) {
4173 sys::swapByteOrder(Value&: c.name);
4174 sys::swapByteOrder(Value&: c.cls);
4175 sys::swapByteOrder(Value&: c.instanceMethods);
4176 sys::swapByteOrder(Value&: c.classMethods);
4177 sys::swapByteOrder(Value&: c.protocols);
4178 sys::swapByteOrder(Value&: c.instanceProperties);
4179}
4180
4181inline void swapStruct(struct category32_t &c) {
4182 sys::swapByteOrder(Value&: c.name);
4183 sys::swapByteOrder(Value&: c.cls);
4184 sys::swapByteOrder(Value&: c.instanceMethods);
4185 sys::swapByteOrder(Value&: c.classMethods);
4186 sys::swapByteOrder(Value&: c.protocols);
4187 sys::swapByteOrder(Value&: c.instanceProperties);
4188}
4189
4190inline void swapStruct(struct objc_image_info64 &o) {
4191 sys::swapByteOrder(Value&: o.version);
4192 sys::swapByteOrder(Value&: o.flags);
4193}
4194
4195inline void swapStruct(struct objc_image_info32 &o) {
4196 sys::swapByteOrder(Value&: o.version);
4197 sys::swapByteOrder(Value&: o.flags);
4198}
4199
4200inline void swapStruct(struct imageInfo_t &o) {
4201 sys::swapByteOrder(Value&: o.version);
4202 sys::swapByteOrder(Value&: o.flags);
4203}
4204
4205inline void swapStruct(struct message_ref64 &mr) {
4206 sys::swapByteOrder(Value&: mr.imp);
4207 sys::swapByteOrder(Value&: mr.sel);
4208}
4209
4210inline void swapStruct(struct message_ref32 &mr) {
4211 sys::swapByteOrder(Value&: mr.imp);
4212 sys::swapByteOrder(Value&: mr.sel);
4213}
4214
4215inline void swapStruct(struct objc_module_t &module) {
4216 sys::swapByteOrder(Value&: module.version);
4217 sys::swapByteOrder(Value&: module.size);
4218 sys::swapByteOrder(Value&: module.name);
4219 sys::swapByteOrder(Value&: module.symtab);
4220}
4221
4222inline void swapStruct(struct objc_symtab_t &symtab) {
4223 sys::swapByteOrder(Value&: symtab.sel_ref_cnt);
4224 sys::swapByteOrder(Value&: symtab.refs);
4225 sys::swapByteOrder(Value&: symtab.cls_def_cnt);
4226 sys::swapByteOrder(Value&: symtab.cat_def_cnt);
4227}
4228
4229inline void swapStruct(struct objc_class_t &objc_class) {
4230 sys::swapByteOrder(Value&: objc_class.isa);
4231 sys::swapByteOrder(Value&: objc_class.super_class);
4232 sys::swapByteOrder(Value&: objc_class.name);
4233 sys::swapByteOrder(Value&: objc_class.version);
4234 sys::swapByteOrder(Value&: objc_class.info);
4235 sys::swapByteOrder(Value&: objc_class.instance_size);
4236 sys::swapByteOrder(Value&: objc_class.ivars);
4237 sys::swapByteOrder(Value&: objc_class.methodLists);
4238 sys::swapByteOrder(Value&: objc_class.cache);
4239 sys::swapByteOrder(Value&: objc_class.protocols);
4240}
4241
4242inline void swapStruct(struct objc_category_t &objc_category) {
4243 sys::swapByteOrder(Value&: objc_category.category_name);
4244 sys::swapByteOrder(Value&: objc_category.class_name);
4245 sys::swapByteOrder(Value&: objc_category.instance_methods);
4246 sys::swapByteOrder(Value&: objc_category.class_methods);
4247 sys::swapByteOrder(Value&: objc_category.protocols);
4248}
4249
4250inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
4251 sys::swapByteOrder(Value&: objc_ivar_list.ivar_count);
4252}
4253
4254inline void swapStruct(struct objc_ivar_t &objc_ivar) {
4255 sys::swapByteOrder(Value&: objc_ivar.ivar_name);
4256 sys::swapByteOrder(Value&: objc_ivar.ivar_type);
4257 sys::swapByteOrder(Value&: objc_ivar.ivar_offset);
4258}
4259
4260inline void swapStruct(struct objc_method_list_t &method_list) {
4261 sys::swapByteOrder(Value&: method_list.obsolete);
4262 sys::swapByteOrder(Value&: method_list.method_count);
4263}
4264
4265inline void swapStruct(struct objc_method_t &method) {
4266 sys::swapByteOrder(Value&: method.method_name);
4267 sys::swapByteOrder(Value&: method.method_types);
4268 sys::swapByteOrder(Value&: method.method_imp);
4269}
4270
4271inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
4272 sys::swapByteOrder(Value&: protocol_list.next);
4273 sys::swapByteOrder(Value&: protocol_list.count);
4274}
4275
4276inline void swapStruct(struct objc_protocol_t &protocol) {
4277 sys::swapByteOrder(Value&: protocol.isa);
4278 sys::swapByteOrder(Value&: protocol.protocol_name);
4279 sys::swapByteOrder(Value&: protocol.protocol_list);
4280 sys::swapByteOrder(Value&: protocol.instance_methods);
4281 sys::swapByteOrder(Value&: protocol.class_methods);
4282}
4283
4284inline void swapStruct(struct objc_method_description_list_t &mdl) {
4285 sys::swapByteOrder(Value&: mdl.count);
4286}
4287
4288inline void swapStruct(struct objc_method_description_t &md) {
4289 sys::swapByteOrder(Value&: md.name);
4290 sys::swapByteOrder(Value&: md.types);
4291}
4292
4293} // namespace
4294
4295static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4296 struct DisassembleInfo *info);
4297
4298// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
4299// to an Objective-C class and returns the class name. It is also passed the
4300// address of the pointer, so when the pointer is zero as it can be in an .o
4301// file, that is used to look for an external relocation entry with a symbol
4302// name.
4303static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
4304 uint64_t ReferenceValue,
4305 struct DisassembleInfo *info) {
4306 const char *r;
4307 uint32_t offset, left;
4308 SectionRef S;
4309
4310 // The pointer_value can be 0 in an object file and have a relocation
4311 // entry for the class symbol at the ReferenceValue (the address of the
4312 // pointer).
4313 if (pointer_value == 0) {
4314 r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4315 if (r == nullptr || left < sizeof(uint64_t))
4316 return nullptr;
4317 uint64_t n_value;
4318 const char *symbol_name = get_symbol_64(sect_offset: offset, S, info, n_value);
4319 if (symbol_name == nullptr)
4320 return nullptr;
4321 const char *class_name = strrchr(s: symbol_name, c: '$');
4322 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4323 return class_name + 2;
4324 else
4325 return nullptr;
4326 }
4327
4328 // The case were the pointer_value is non-zero and points to a class defined
4329 // in this Mach-O file.
4330 r = get_pointer_64(Address: pointer_value, offset, left, S, info);
4331 if (r == nullptr || left < sizeof(struct class64_t))
4332 return nullptr;
4333 struct class64_t c;
4334 memcpy(dest: &c, src: r, n: sizeof(struct class64_t));
4335 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4336 swapStruct(c);
4337 if (c.data == 0)
4338 return nullptr;
4339 r = get_pointer_64(Address: c.data, offset, left, S, info);
4340 if (r == nullptr || left < sizeof(struct class_ro64_t))
4341 return nullptr;
4342 struct class_ro64_t cro;
4343 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro64_t));
4344 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4345 swapStruct(cro);
4346 if (cro.name == 0)
4347 return nullptr;
4348 const char *name = get_pointer_64(Address: cro.name, offset, left, S, info);
4349 return name;
4350}
4351
4352// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4353// pointer to a cfstring and returns its name or nullptr.
4354static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4355 struct DisassembleInfo *info) {
4356 const char *r, *name;
4357 uint32_t offset, left;
4358 SectionRef S;
4359 struct cfstring64_t cfs;
4360 uint64_t cfs_characters;
4361
4362 r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4363 if (r == nullptr || left < sizeof(struct cfstring64_t))
4364 return nullptr;
4365 memcpy(dest: &cfs, src: r, n: sizeof(struct cfstring64_t));
4366 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4367 swapStruct(cfs);
4368 if (cfs.characters == 0) {
4369 uint64_t n_value;
4370 const char *symbol_name = get_symbol_64(
4371 sect_offset: offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4372 if (symbol_name == nullptr)
4373 return nullptr;
4374 cfs_characters = n_value;
4375 } else
4376 cfs_characters = cfs.characters;
4377 name = get_pointer_64(Address: cfs_characters, offset, left, S, info);
4378
4379 return name;
4380}
4381
4382// get_objc2_64bit_selref() is used for disassembly and is passed a the address
4383// of a pointer to an Objective-C selector reference when the pointer value is
4384// zero as in a .o file and is likely to have a external relocation entry with
4385// who's symbol's n_value is the real pointer to the selector name. If that is
4386// the case the real pointer to the selector name is returned else 0 is
4387// returned
4388static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4389 struct DisassembleInfo *info) {
4390 uint32_t offset, left;
4391 SectionRef S;
4392
4393 const char *r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4394 if (r == nullptr || left < sizeof(uint64_t))
4395 return 0;
4396 uint64_t n_value;
4397 const char *symbol_name = get_symbol_64(sect_offset: offset, S, info, n_value);
4398 if (symbol_name == nullptr)
4399 return 0;
4400 return n_value;
4401}
4402
4403static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4404 const char *sectname) {
4405 for (const SectionRef &Section : O->sections()) {
4406 StringRef SectName;
4407 Expected<StringRef> SecNameOrErr = Section.getName();
4408 if (SecNameOrErr)
4409 SectName = *SecNameOrErr;
4410 else
4411 consumeError(Err: SecNameOrErr.takeError());
4412
4413 DataRefImpl Ref = Section.getRawDataRefImpl();
4414 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4415 if (SegName == segname && SectName == sectname)
4416 return Section;
4417 }
4418 return SectionRef();
4419}
4420
4421static void
4422walk_pointer_list_64(const char *listname, const SectionRef S,
4423 MachOObjectFile *O, struct DisassembleInfo *info,
4424 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4425 if (S == SectionRef())
4426 return;
4427
4428 StringRef SectName;
4429 Expected<StringRef> SecNameOrErr = S.getName();
4430 if (SecNameOrErr)
4431 SectName = *SecNameOrErr;
4432 else
4433 consumeError(Err: SecNameOrErr.takeError());
4434
4435 DataRefImpl Ref = S.getRawDataRefImpl();
4436 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4437 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4438
4439 StringRef BytesStr = unwrapOrError(EO: S.getContents(), Args: O->getFileName());
4440 const char *Contents = BytesStr.data();
4441
4442 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4443 uint32_t left = S.getSize() - i;
4444 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4445 uint64_t p = 0;
4446 memcpy(dest: &p, src: Contents + i, n: size);
4447 if (i + sizeof(uint64_t) > S.getSize())
4448 outs() << listname << " list pointer extends past end of (" << SegName
4449 << "," << SectName << ") section\n";
4450 outs() << format(Fmt: "%016" PRIx64, Vals: S.getAddress() + i) << " ";
4451
4452 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4453 sys::swapByteOrder(Value&: p);
4454
4455 uint64_t n_value = 0;
4456 const char *name = get_symbol_64(sect_offset: i, S, info, n_value, ReferenceValue: p);
4457 if (name == nullptr)
4458 name = get_dyld_bind_info_symbolname(ReferenceValue: S.getAddress() + i, info);
4459
4460 if (n_value != 0) {
4461 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4462 if (p != 0)
4463 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: p);
4464 } else
4465 outs() << format(Fmt: "0x%" PRIx64, Vals: p);
4466 if (name != nullptr)
4467 outs() << " " << name;
4468 outs() << "\n";
4469
4470 p += n_value;
4471 if (func)
4472 func(p, info);
4473 }
4474}
4475
4476static void
4477walk_pointer_list_32(const char *listname, const SectionRef S,
4478 MachOObjectFile *O, struct DisassembleInfo *info,
4479 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4480 if (S == SectionRef())
4481 return;
4482
4483 StringRef SectName = unwrapOrError(EO: S.getName(), Args: O->getFileName());
4484 DataRefImpl Ref = S.getRawDataRefImpl();
4485 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4486 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4487
4488 StringRef BytesStr = unwrapOrError(EO: S.getContents(), Args: O->getFileName());
4489 const char *Contents = BytesStr.data();
4490
4491 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4492 uint32_t left = S.getSize() - i;
4493 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4494 uint32_t p = 0;
4495 memcpy(dest: &p, src: Contents + i, n: size);
4496 if (i + sizeof(uint32_t) > S.getSize())
4497 outs() << listname << " list pointer extends past end of (" << SegName
4498 << "," << SectName << ") section\n";
4499 uint32_t Address = S.getAddress() + i;
4500 outs() << format(Fmt: "%08" PRIx32, Vals: Address) << " ";
4501
4502 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4503 sys::swapByteOrder(Value&: p);
4504 outs() << format(Fmt: "0x%" PRIx32, Vals: p);
4505
4506 const char *name = get_symbol_32(sect_offset: i, S, info, ReferenceValue: p);
4507 if (name != nullptr)
4508 outs() << " " << name;
4509 outs() << "\n";
4510
4511 if (func)
4512 func(p, info);
4513 }
4514}
4515
4516static void print_layout_map(const char *layout_map, uint32_t left) {
4517 if (layout_map == nullptr)
4518 return;
4519 outs() << " layout map: ";
4520 do {
4521 outs() << format(Fmt: "0x%02" PRIx32, Vals: (*layout_map) & 0xff) << " ";
4522 left--;
4523 layout_map++;
4524 } while (*layout_map != '\0' && left != 0);
4525 outs() << "\n";
4526}
4527
4528static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4529 uint32_t offset, left;
4530 SectionRef S;
4531 const char *layout_map;
4532
4533 if (p == 0)
4534 return;
4535 layout_map = get_pointer_64(Address: p, offset, left, S, info);
4536 print_layout_map(layout_map, left);
4537}
4538
4539static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4540 uint32_t offset, left;
4541 SectionRef S;
4542 const char *layout_map;
4543
4544 if (p == 0)
4545 return;
4546 layout_map = get_pointer_32(Address: p, offset, left, S, info);
4547 print_layout_map(layout_map, left);
4548}
4549
4550static void print_relative_method_list(uint32_t structSizeAndFlags,
4551 uint32_t structCount, uint64_t p,
4552 struct DisassembleInfo *info,
4553 const char *indent,
4554 uint32_t pointerBits) {
4555 struct method_relative_t m;
4556 const char *r, *name;
4557 uint32_t offset, xoffset, left, i;
4558 SectionRef S, xS;
4559
4560 assert(((structSizeAndFlags & ML_HAS_RELATIVE_PTRS) != 0) &&
4561 "expected structSizeAndFlags to have ML_HAS_RELATIVE_PTRS flag");
4562
4563 outs() << indent << "\t\t entsize "
4564 << (structSizeAndFlags & ML_ENTSIZE_MASK) << " (relative) \n";
4565 outs() << indent << "\t\t count " << structCount << "\n";
4566
4567 for (i = 0; i < structCount; i++) {
4568 r = get_pointer_64(Address: p, offset, left, S, info);
4569 memset(s: &m, c: '\0', n: sizeof(struct method_relative_t));
4570 if (left < sizeof(struct method_relative_t)) {
4571 memcpy(dest: &m, src: r, n: left);
4572 outs() << indent << " (method_t extends past the end of the section)\n";
4573 } else
4574 memcpy(dest: &m, src: r, n: sizeof(struct method_relative_t));
4575 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4576 swapStruct(m);
4577
4578 outs() << indent << "\t\t name " << format(Fmt: "0x%" PRIx32, Vals: m.name);
4579 uint64_t relNameRefVA = p + offsetof(struct method_relative_t, name);
4580 uint64_t absNameRefVA = relNameRefVA + m.name;
4581 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absNameRefVA) << ")";
4582
4583 // since this is a relative list, absNameRefVA is the address of the
4584 // __objc_selrefs entry, so a pointer, not the actual name
4585 const char *nameRefPtr =
4586 get_pointer_64(Address: absNameRefVA, offset&: xoffset, left, S&: xS, info);
4587 if (nameRefPtr) {
4588 uint32_t pointerSize = pointerBits / CHAR_BIT;
4589 if (left < pointerSize)
4590 outs() << indent << " (nameRefPtr extends past the end of the section)";
4591 else {
4592 if (pointerSize == 64) {
4593 uint64_t nameOff_64 = *reinterpret_cast<const uint64_t *>(nameRefPtr);
4594 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4595 sys::swapByteOrder(Value&: nameOff_64);
4596 name = get_pointer_64(Address: nameOff_64, offset&: xoffset, left, S&: xS, info);
4597 } else {
4598 uint32_t nameOff_32 = *reinterpret_cast<const uint32_t *>(nameRefPtr);
4599 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4600 sys::swapByteOrder(Value&: nameOff_32);
4601 name = get_pointer_32(Address: nameOff_32, offset&: xoffset, left, S&: xS, info);
4602 }
4603 if (name != nullptr)
4604 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4605 }
4606 }
4607 outs() << "\n";
4608
4609 outs() << indent << "\t\t types " << format(Fmt: "0x%" PRIx32, Vals: m.types);
4610 uint64_t relTypesVA = p + offsetof(struct method_relative_t, types);
4611 uint64_t absTypesVA = relTypesVA + m.types;
4612 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absTypesVA) << ")";
4613 name = get_pointer_32(Address: absTypesVA, offset&: xoffset, left, S&: xS, info);
4614 if (name != nullptr)
4615 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4616 outs() << "\n";
4617
4618 outs() << indent << "\t\t imp " << format(Fmt: "0x%" PRIx32, Vals: m.imp);
4619 uint64_t relImpVA = p + offsetof(struct method_relative_t, imp);
4620 uint64_t absImpVA = relImpVA + m.imp;
4621 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absImpVA) << ")";
4622 name = GuessSymbolName(value: absImpVA, AddrMap: info->AddrMap);
4623 if (name != nullptr)
4624 outs() << " " << name;
4625 outs() << "\n";
4626
4627 p += sizeof(struct method_relative_t);
4628 offset += sizeof(struct method_relative_t);
4629 }
4630}
4631
4632static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4633 const char *indent) {
4634 struct method_list64_t ml;
4635 struct method64_t m;
4636 const char *r;
4637 uint32_t offset, xoffset, left, i;
4638 SectionRef S, xS;
4639 const char *name, *sym_name;
4640 uint64_t n_value;
4641
4642 r = get_pointer_64(Address: p, offset, left, S, info);
4643 if (r == nullptr)
4644 return;
4645 memset(s: &ml, c: '\0', n: sizeof(struct method_list64_t));
4646 if (left < sizeof(struct method_list64_t)) {
4647 memcpy(dest: &ml, src: r, n: left);
4648 outs() << " (method_list_t entends past the end of the section)\n";
4649 } else
4650 memcpy(dest: &ml, src: r, n: sizeof(struct method_list64_t));
4651 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4652 swapStruct(ml);
4653 p += sizeof(struct method_list64_t);
4654
4655 if ((ml.entsize & ML_HAS_RELATIVE_PTRS) != 0) {
4656 print_relative_method_list(structSizeAndFlags: ml.entsize, structCount: ml.count, p, info, indent,
4657 /*pointerBits=*/64);
4658 return;
4659 }
4660
4661 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4662 outs() << indent << "\t\t count " << ml.count << "\n";
4663
4664 offset += sizeof(struct method_list64_t);
4665 for (i = 0; i < ml.count; i++) {
4666 r = get_pointer_64(Address: p, offset, left, S, info);
4667 if (r == nullptr)
4668 return;
4669 memset(s: &m, c: '\0', n: sizeof(struct method64_t));
4670 if (left < sizeof(struct method64_t)) {
4671 memcpy(dest: &m, src: r, n: left);
4672 outs() << indent << " (method_t extends past the end of the section)\n";
4673 } else
4674 memcpy(dest: &m, src: r, n: sizeof(struct method64_t));
4675 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4676 swapStruct(m);
4677
4678 outs() << indent << "\t\t name ";
4679 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, name), S,
4680 info, n_value, ReferenceValue: m.name);
4681 if (n_value != 0) {
4682 if (info->verbose && sym_name != nullptr)
4683 outs() << sym_name;
4684 else
4685 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4686 if (m.name != 0)
4687 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: m.name);
4688 } else
4689 outs() << format(Fmt: "0x%" PRIx64, Vals: m.name);
4690 name = get_pointer_64(Address: m.name + n_value, offset&: xoffset, left, S&: xS, info);
4691 if (name != nullptr)
4692 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4693 outs() << "\n";
4694
4695 outs() << indent << "\t\t types ";
4696 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, types), S,
4697 info, n_value, ReferenceValue: m.types);
4698 if (n_value != 0) {
4699 if (info->verbose && sym_name != nullptr)
4700 outs() << sym_name;
4701 else
4702 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4703 if (m.types != 0)
4704 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: m.types);
4705 } else
4706 outs() << format(Fmt: "0x%" PRIx64, Vals: m.types);
4707 name = get_pointer_64(Address: m.types + n_value, offset&: xoffset, left, S&: xS, info);
4708 if (name != nullptr)
4709 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4710 outs() << "\n";
4711
4712 outs() << indent << "\t\t imp ";
4713 name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, imp), S, info,
4714 n_value, ReferenceValue: m.imp);
4715 if (info->verbose && name == nullptr) {
4716 if (n_value != 0) {
4717 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value) << " ";
4718 if (m.imp != 0)
4719 outs() << "+ " << format(Fmt: "0x%" PRIx64, Vals: m.imp) << " ";
4720 } else
4721 outs() << format(Fmt: "0x%" PRIx64, Vals: m.imp) << " ";
4722 }
4723 if (name != nullptr)
4724 outs() << name;
4725 outs() << "\n";
4726
4727 p += sizeof(struct method64_t);
4728 offset += sizeof(struct method64_t);
4729 }
4730}
4731
4732static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4733 const char *indent) {
4734 struct method_list32_t ml;
4735 struct method32_t m;
4736 const char *r, *name;
4737 uint32_t offset, xoffset, left, i;
4738 SectionRef S, xS;
4739
4740 r = get_pointer_32(Address: p, offset, left, S, info);
4741 if (r == nullptr)
4742 return;
4743 memset(s: &ml, c: '\0', n: sizeof(struct method_list32_t));
4744 if (left < sizeof(struct method_list32_t)) {
4745 memcpy(dest: &ml, src: r, n: left);
4746 outs() << " (method_list_t entends past the end of the section)\n";
4747 } else
4748 memcpy(dest: &ml, src: r, n: sizeof(struct method_list32_t));
4749 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4750 swapStruct(ml);
4751 p += sizeof(struct method_list32_t);
4752
4753 if ((ml.entsize & ML_HAS_RELATIVE_PTRS) != 0) {
4754 print_relative_method_list(structSizeAndFlags: ml.entsize, structCount: ml.count, p, info, indent,
4755 /*pointerBits=*/32);
4756 return;
4757 }
4758
4759 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4760 outs() << indent << "\t\t count " << ml.count << "\n";
4761
4762 offset += sizeof(struct method_list32_t);
4763 for (i = 0; i < ml.count; i++) {
4764 r = get_pointer_32(Address: p, offset, left, S, info);
4765 if (r == nullptr)
4766 return;
4767 memset(s: &m, c: '\0', n: sizeof(struct method32_t));
4768 if (left < sizeof(struct method32_t)) {
4769 memcpy(dest: &ml, src: r, n: left);
4770 outs() << indent << " (method_t entends past the end of the section)\n";
4771 } else
4772 memcpy(dest: &m, src: r, n: sizeof(struct method32_t));
4773 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4774 swapStruct(m);
4775
4776 outs() << indent << "\t\t name " << format(Fmt: "0x%" PRIx32, Vals: m.name);
4777 name = get_pointer_32(Address: m.name, offset&: xoffset, left, S&: xS, info);
4778 if (name != nullptr)
4779 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4780 outs() << "\n";
4781
4782 outs() << indent << "\t\t types " << format(Fmt: "0x%" PRIx32, Vals: m.types);
4783 name = get_pointer_32(Address: m.types, offset&: xoffset, left, S&: xS, info);
4784 if (name != nullptr)
4785 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4786 outs() << "\n";
4787
4788 outs() << indent << "\t\t imp " << format(Fmt: "0x%" PRIx32, Vals: m.imp);
4789 name = get_symbol_32(sect_offset: offset + offsetof(struct method32_t, imp), S, info,
4790 ReferenceValue: m.imp);
4791 if (name != nullptr)
4792 outs() << " " << name;
4793 outs() << "\n";
4794
4795 p += sizeof(struct method32_t);
4796 offset += sizeof(struct method32_t);
4797 }
4798}
4799
4800static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4801 uint32_t offset, left, xleft;
4802 SectionRef S;
4803 struct objc_method_list_t method_list;
4804 struct objc_method_t method;
4805 const char *r, *methods, *name, *SymbolName;
4806 int32_t i;
4807
4808 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
4809 if (r == nullptr)
4810 return true;
4811
4812 outs() << "\n";
4813 if (left > sizeof(struct objc_method_list_t)) {
4814 memcpy(dest: &method_list, src: r, n: sizeof(struct objc_method_list_t));
4815 } else {
4816 outs() << "\t\t objc_method_list extends past end of the section\n";
4817 memset(s: &method_list, c: '\0', n: sizeof(struct objc_method_list_t));
4818 memcpy(dest: &method_list, src: r, n: left);
4819 }
4820 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4821 swapStruct(method_list);
4822
4823 outs() << "\t\t obsolete "
4824 << format(Fmt: "0x%08" PRIx32, Vals: method_list.obsolete) << "\n";
4825 outs() << "\t\t method_count " << method_list.method_count << "\n";
4826
4827 methods = r + sizeof(struct objc_method_list_t);
4828 for (i = 0; i < method_list.method_count; i++) {
4829 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4830 outs() << "\t\t remaining method's extend past the of the section\n";
4831 break;
4832 }
4833 memcpy(dest: &method, src: methods + i * sizeof(struct objc_method_t),
4834 n: sizeof(struct objc_method_t));
4835 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4836 swapStruct(method);
4837
4838 outs() << "\t\t method_name "
4839 << format(Fmt: "0x%08" PRIx32, Vals: method.method_name);
4840 if (info->verbose) {
4841 name = get_pointer_32(Address: method.method_name, offset, left&: xleft, S, info, objc_only: true);
4842 if (name != nullptr)
4843 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
4844 else
4845 outs() << " (not in an __OBJC section)";
4846 }
4847 outs() << "\n";
4848
4849 outs() << "\t\t method_types "
4850 << format(Fmt: "0x%08" PRIx32, Vals: method.method_types);
4851 if (info->verbose) {
4852 name = get_pointer_32(Address: method.method_types, offset, left&: xleft, S, info, objc_only: true);
4853 if (name != nullptr)
4854 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
4855 else
4856 outs() << " (not in an __OBJC section)";
4857 }
4858 outs() << "\n";
4859
4860 outs() << "\t\t method_imp "
4861 << format(Fmt: "0x%08" PRIx32, Vals: method.method_imp) << " ";
4862 if (info->verbose) {
4863 SymbolName = GuessSymbolName(value: method.method_imp, AddrMap: info->AddrMap);
4864 if (SymbolName != nullptr)
4865 outs() << SymbolName;
4866 }
4867 outs() << "\n";
4868 }
4869 return false;
4870}
4871
4872static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4873 struct protocol_list64_t pl;
4874 uint64_t q, n_value;
4875 struct protocol64_t pc;
4876 const char *r;
4877 uint32_t offset, xoffset, left, i;
4878 SectionRef S, xS;
4879 const char *name, *sym_name;
4880
4881 r = get_pointer_64(Address: p, offset, left, S, info);
4882 if (r == nullptr)
4883 return;
4884 memset(s: &pl, c: '\0', n: sizeof(struct protocol_list64_t));
4885 if (left < sizeof(struct protocol_list64_t)) {
4886 memcpy(dest: &pl, src: r, n: left);
4887 outs() << " (protocol_list_t entends past the end of the section)\n";
4888 } else
4889 memcpy(dest: &pl, src: r, n: sizeof(struct protocol_list64_t));
4890 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4891 swapStruct(pl);
4892 outs() << " count " << pl.count << "\n";
4893
4894 p += sizeof(struct protocol_list64_t);
4895 offset += sizeof(struct protocol_list64_t);
4896 for (i = 0; i < pl.count; i++) {
4897 r = get_pointer_64(Address: p, offset, left, S, info);
4898 if (r == nullptr)
4899 return;
4900 q = 0;
4901 if (left < sizeof(uint64_t)) {
4902 memcpy(dest: &q, src: r, n: left);
4903 outs() << " (protocol_t * entends past the end of the section)\n";
4904 } else
4905 memcpy(dest: &q, src: r, n: sizeof(uint64_t));
4906 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4907 sys::swapByteOrder(Value&: q);
4908
4909 outs() << "\t\t list[" << i << "] ";
4910 sym_name = get_symbol_64(sect_offset: offset, S, info, n_value, ReferenceValue: q);
4911 if (n_value != 0) {
4912 if (info->verbose && sym_name != nullptr)
4913 outs() << sym_name;
4914 else
4915 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4916 if (q != 0)
4917 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: q);
4918 } else
4919 outs() << format(Fmt: "0x%" PRIx64, Vals: q);
4920 outs() << " (struct protocol_t *)\n";
4921
4922 r = get_pointer_64(Address: q + n_value, offset, left, S, info);
4923 if (r == nullptr)
4924 return;
4925 memset(s: &pc, c: '\0', n: sizeof(struct protocol64_t));
4926 if (left < sizeof(struct protocol64_t)) {
4927 memcpy(dest: &pc, src: r, n: left);
4928 outs() << " (protocol_t entends past the end of the section)\n";
4929 } else
4930 memcpy(dest: &pc, src: r, n: sizeof(struct protocol64_t));
4931 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4932 swapStruct(p&: pc);
4933
4934 outs() << "\t\t\t isa " << format(Fmt: "0x%" PRIx64, Vals: pc.isa) << "\n";
4935
4936 outs() << "\t\t\t name ";
4937 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, name), S,
4938 info, n_value, ReferenceValue: pc.name);
4939 if (n_value != 0) {
4940 if (info->verbose && sym_name != nullptr)
4941 outs() << sym_name;
4942 else
4943 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4944 if (pc.name != 0)
4945 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.name);
4946 } else
4947 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.name);
4948 name = get_pointer_64(Address: pc.name + n_value, offset&: xoffset, left, S&: xS, info);
4949 if (name != nullptr)
4950 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4951 outs() << "\n";
4952
4953 outs() << "\t\t\tprotocols " << format(Fmt: "0x%" PRIx64, Vals: pc.protocols) << "\n";
4954
4955 outs() << "\t\t instanceMethods ";
4956 sym_name =
4957 get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, instanceMethods),
4958 S, info, n_value, ReferenceValue: pc.instanceMethods);
4959 if (n_value != 0) {
4960 if (info->verbose && sym_name != nullptr)
4961 outs() << sym_name;
4962 else
4963 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4964 if (pc.instanceMethods != 0)
4965 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.instanceMethods);
4966 } else
4967 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.instanceMethods);
4968 outs() << " (struct method_list_t *)\n";
4969 if (pc.instanceMethods + n_value != 0)
4970 print_method_list64_t(p: pc.instanceMethods + n_value, info, indent: "\t");
4971
4972 outs() << "\t\t classMethods ";
4973 sym_name =
4974 get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, classMethods), S,
4975 info, n_value, ReferenceValue: pc.classMethods);
4976 if (n_value != 0) {
4977 if (info->verbose && sym_name != nullptr)
4978 outs() << sym_name;
4979 else
4980 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4981 if (pc.classMethods != 0)
4982 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.classMethods);
4983 } else
4984 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.classMethods);
4985 outs() << " (struct method_list_t *)\n";
4986 if (pc.classMethods + n_value != 0)
4987 print_method_list64_t(p: pc.classMethods + n_value, info, indent: "\t");
4988
4989 outs() << "\t optionalInstanceMethods "
4990 << format(Fmt: "0x%" PRIx64, Vals: pc.optionalInstanceMethods) << "\n";
4991 outs() << "\t optionalClassMethods "
4992 << format(Fmt: "0x%" PRIx64, Vals: pc.optionalClassMethods) << "\n";
4993 outs() << "\t instanceProperties "
4994 << format(Fmt: "0x%" PRIx64, Vals: pc.instanceProperties) << "\n";
4995
4996 p += sizeof(uint64_t);
4997 offset += sizeof(uint64_t);
4998 }
4999}
5000
5001static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
5002 struct protocol_list32_t pl;
5003 uint32_t q;
5004 struct protocol32_t pc;
5005 const char *r;
5006 uint32_t offset, xoffset, left, i;
5007 SectionRef S, xS;
5008 const char *name;
5009
5010 r = get_pointer_32(Address: p, offset, left, S, info);
5011 if (r == nullptr)
5012 return;
5013 memset(s: &pl, c: '\0', n: sizeof(struct protocol_list32_t));
5014 if (left < sizeof(struct protocol_list32_t)) {
5015 memcpy(dest: &pl, src: r, n: left);
5016 outs() << " (protocol_list_t entends past the end of the section)\n";
5017 } else
5018 memcpy(dest: &pl, src: r, n: sizeof(struct protocol_list32_t));
5019 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5020 swapStruct(pl);
5021 outs() << " count " << pl.count << "\n";
5022
5023 p += sizeof(struct protocol_list32_t);
5024 offset += sizeof(struct protocol_list32_t);
5025 for (i = 0; i < pl.count; i++) {
5026 r = get_pointer_32(Address: p, offset, left, S, info);
5027 if (r == nullptr)
5028 return;
5029 q = 0;
5030 if (left < sizeof(uint32_t)) {
5031 memcpy(dest: &q, src: r, n: left);
5032 outs() << " (protocol_t * entends past the end of the section)\n";
5033 } else
5034 memcpy(dest: &q, src: r, n: sizeof(uint32_t));
5035 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5036 sys::swapByteOrder(Value&: q);
5037 outs() << "\t\t list[" << i << "] " << format(Fmt: "0x%" PRIx32, Vals: q)
5038 << " (struct protocol_t *)\n";
5039 r = get_pointer_32(Address: q, offset, left, S, info);
5040 if (r == nullptr)
5041 return;
5042 memset(s: &pc, c: '\0', n: sizeof(struct protocol32_t));
5043 if (left < sizeof(struct protocol32_t)) {
5044 memcpy(dest: &pc, src: r, n: left);
5045 outs() << " (protocol_t entends past the end of the section)\n";
5046 } else
5047 memcpy(dest: &pc, src: r, n: sizeof(struct protocol32_t));
5048 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5049 swapStruct(p&: pc);
5050 outs() << "\t\t\t isa " << format(Fmt: "0x%" PRIx32, Vals: pc.isa) << "\n";
5051 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: pc.name);
5052 name = get_pointer_32(Address: pc.name, offset&: xoffset, left, S&: xS, info);
5053 if (name != nullptr)
5054 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5055 outs() << "\n";
5056 outs() << "\t\t\tprotocols " << format(Fmt: "0x%" PRIx32, Vals: pc.protocols) << "\n";
5057 outs() << "\t\t instanceMethods "
5058 << format(Fmt: "0x%" PRIx32, Vals: pc.instanceMethods)
5059 << " (struct method_list_t *)\n";
5060 if (pc.instanceMethods != 0)
5061 print_method_list32_t(p: pc.instanceMethods, info, indent: "\t");
5062 outs() << "\t\t classMethods " << format(Fmt: "0x%" PRIx32, Vals: pc.classMethods)
5063 << " (struct method_list_t *)\n";
5064 if (pc.classMethods != 0)
5065 print_method_list32_t(p: pc.classMethods, info, indent: "\t");
5066 outs() << "\t optionalInstanceMethods "
5067 << format(Fmt: "0x%" PRIx32, Vals: pc.optionalInstanceMethods) << "\n";
5068 outs() << "\t optionalClassMethods "
5069 << format(Fmt: "0x%" PRIx32, Vals: pc.optionalClassMethods) << "\n";
5070 outs() << "\t instanceProperties "
5071 << format(Fmt: "0x%" PRIx32, Vals: pc.instanceProperties) << "\n";
5072 p += sizeof(uint32_t);
5073 offset += sizeof(uint32_t);
5074 }
5075}
5076
5077static void print_indent(uint32_t indent) {
5078 for (uint32_t i = 0; i < indent;) {
5079 if (indent - i >= 8) {
5080 outs() << "\t";
5081 i += 8;
5082 } else {
5083 for (uint32_t j = i; j < indent; j++)
5084 outs() << " ";
5085 return;
5086 }
5087 }
5088}
5089
5090static bool print_method_description_list(uint32_t p, uint32_t indent,
5091 struct DisassembleInfo *info) {
5092 uint32_t offset, left, xleft;
5093 SectionRef S;
5094 struct objc_method_description_list_t mdl;
5095 struct objc_method_description_t md;
5096 const char *r, *list, *name;
5097 int32_t i;
5098
5099 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5100 if (r == nullptr)
5101 return true;
5102
5103 outs() << "\n";
5104 if (left > sizeof(struct objc_method_description_list_t)) {
5105 memcpy(dest: &mdl, src: r, n: sizeof(struct objc_method_description_list_t));
5106 } else {
5107 print_indent(indent);
5108 outs() << " objc_method_description_list extends past end of the section\n";
5109 memset(s: &mdl, c: '\0', n: sizeof(struct objc_method_description_list_t));
5110 memcpy(dest: &mdl, src: r, n: left);
5111 }
5112 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5113 swapStruct(mdl);
5114
5115 print_indent(indent);
5116 outs() << " count " << mdl.count << "\n";
5117
5118 list = r + sizeof(struct objc_method_description_list_t);
5119 for (i = 0; i < mdl.count; i++) {
5120 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
5121 print_indent(indent);
5122 outs() << " remaining list entries extend past the of the section\n";
5123 break;
5124 }
5125 print_indent(indent);
5126 outs() << " list[" << i << "]\n";
5127 memcpy(dest: &md, src: list + i * sizeof(struct objc_method_description_t),
5128 n: sizeof(struct objc_method_description_t));
5129 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5130 swapStruct(md);
5131
5132 print_indent(indent);
5133 outs() << " name " << format(Fmt: "0x%08" PRIx32, Vals: md.name);
5134 if (info->verbose) {
5135 name = get_pointer_32(Address: md.name, offset, left&: xleft, S, info, objc_only: true);
5136 if (name != nullptr)
5137 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5138 else
5139 outs() << " (not in an __OBJC section)";
5140 }
5141 outs() << "\n";
5142
5143 print_indent(indent);
5144 outs() << " types " << format(Fmt: "0x%08" PRIx32, Vals: md.types);
5145 if (info->verbose) {
5146 name = get_pointer_32(Address: md.types, offset, left&: xleft, S, info, objc_only: true);
5147 if (name != nullptr)
5148 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5149 else
5150 outs() << " (not in an __OBJC section)";
5151 }
5152 outs() << "\n";
5153 }
5154 return false;
5155}
5156
5157static bool print_protocol_list(uint32_t p, uint32_t indent,
5158 struct DisassembleInfo *info);
5159
5160static bool print_protocol(uint32_t p, uint32_t indent,
5161 struct DisassembleInfo *info) {
5162 uint32_t offset, left;
5163 SectionRef S;
5164 struct objc_protocol_t protocol;
5165 const char *r, *name;
5166
5167 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5168 if (r == nullptr)
5169 return true;
5170
5171 outs() << "\n";
5172 if (left >= sizeof(struct objc_protocol_t)) {
5173 memcpy(dest: &protocol, src: r, n: sizeof(struct objc_protocol_t));
5174 } else {
5175 print_indent(indent);
5176 outs() << " Protocol extends past end of the section\n";
5177 memset(s: &protocol, c: '\0', n: sizeof(struct objc_protocol_t));
5178 memcpy(dest: &protocol, src: r, n: left);
5179 }
5180 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5181 swapStruct(protocol);
5182
5183 print_indent(indent);
5184 outs() << " isa " << format(Fmt: "0x%08" PRIx32, Vals: protocol.isa)
5185 << "\n";
5186
5187 print_indent(indent);
5188 outs() << " protocol_name "
5189 << format(Fmt: "0x%08" PRIx32, Vals: protocol.protocol_name);
5190 if (info->verbose) {
5191 name = get_pointer_32(Address: protocol.protocol_name, offset, left, S, info, objc_only: true);
5192 if (name != nullptr)
5193 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5194 else
5195 outs() << " (not in an __OBJC section)";
5196 }
5197 outs() << "\n";
5198
5199 print_indent(indent);
5200 outs() << " protocol_list "
5201 << format(Fmt: "0x%08" PRIx32, Vals: protocol.protocol_list);
5202 if (print_protocol_list(p: protocol.protocol_list, indent: indent + 4, info))
5203 outs() << " (not in an __OBJC section)\n";
5204
5205 print_indent(indent);
5206 outs() << " instance_methods "
5207 << format(Fmt: "0x%08" PRIx32, Vals: protocol.instance_methods);
5208 if (print_method_description_list(p: protocol.instance_methods, indent, info))
5209 outs() << " (not in an __OBJC section)\n";
5210
5211 print_indent(indent);
5212 outs() << " class_methods "
5213 << format(Fmt: "0x%08" PRIx32, Vals: protocol.class_methods);
5214 if (print_method_description_list(p: protocol.class_methods, indent, info))
5215 outs() << " (not in an __OBJC section)\n";
5216
5217 return false;
5218}
5219
5220static bool print_protocol_list(uint32_t p, uint32_t indent,
5221 struct DisassembleInfo *info) {
5222 uint32_t offset, left, l;
5223 SectionRef S;
5224 struct objc_protocol_list_t protocol_list;
5225 const char *r, *list;
5226 int32_t i;
5227
5228 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5229 if (r == nullptr)
5230 return true;
5231
5232 outs() << "\n";
5233 if (left > sizeof(struct objc_protocol_list_t)) {
5234 memcpy(dest: &protocol_list, src: r, n: sizeof(struct objc_protocol_list_t));
5235 } else {
5236 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
5237 memset(s: &protocol_list, c: '\0', n: sizeof(struct objc_protocol_list_t));
5238 memcpy(dest: &protocol_list, src: r, n: left);
5239 }
5240 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5241 swapStruct(protocol_list);
5242
5243 print_indent(indent);
5244 outs() << " next " << format(Fmt: "0x%08" PRIx32, Vals: protocol_list.next)
5245 << "\n";
5246 print_indent(indent);
5247 outs() << " count " << protocol_list.count << "\n";
5248
5249 list = r + sizeof(struct objc_protocol_list_t);
5250 for (i = 0; i < protocol_list.count; i++) {
5251 if ((i + 1) * sizeof(uint32_t) > left) {
5252 outs() << "\t\t remaining list entries extend past the of the section\n";
5253 break;
5254 }
5255 memcpy(dest: &l, src: list + i * sizeof(uint32_t), n: sizeof(uint32_t));
5256 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5257 sys::swapByteOrder(Value&: l);
5258
5259 print_indent(indent);
5260 outs() << " list[" << i << "] " << format(Fmt: "0x%08" PRIx32, Vals: l);
5261 if (print_protocol(p: l, indent, info))
5262 outs() << "(not in an __OBJC section)\n";
5263 }
5264 return false;
5265}
5266
5267static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
5268 struct ivar_list64_t il;
5269 struct ivar64_t i;
5270 const char *r;
5271 uint32_t offset, xoffset, left, j;
5272 SectionRef S, xS;
5273 const char *name, *sym_name, *ivar_offset_p;
5274 uint64_t ivar_offset, n_value;
5275
5276 r = get_pointer_64(Address: p, offset, left, S, info);
5277 if (r == nullptr)
5278 return;
5279 memset(s: &il, c: '\0', n: sizeof(struct ivar_list64_t));
5280 if (left < sizeof(struct ivar_list64_t)) {
5281 memcpy(dest: &il, src: r, n: left);
5282 outs() << " (ivar_list_t entends past the end of the section)\n";
5283 } else
5284 memcpy(dest: &il, src: r, n: sizeof(struct ivar_list64_t));
5285 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5286 swapStruct(il);
5287 outs() << " entsize " << il.entsize << "\n";
5288 outs() << " count " << il.count << "\n";
5289
5290 p += sizeof(struct ivar_list64_t);
5291 offset += sizeof(struct ivar_list64_t);
5292 for (j = 0; j < il.count; j++) {
5293 r = get_pointer_64(Address: p, offset, left, S, info);
5294 if (r == nullptr)
5295 return;
5296 memset(s: &i, c: '\0', n: sizeof(struct ivar64_t));
5297 if (left < sizeof(struct ivar64_t)) {
5298 memcpy(dest: &i, src: r, n: left);
5299 outs() << " (ivar_t entends past the end of the section)\n";
5300 } else
5301 memcpy(dest: &i, src: r, n: sizeof(struct ivar64_t));
5302 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5303 swapStruct(i);
5304
5305 outs() << "\t\t\t offset ";
5306 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, offset), S,
5307 info, n_value, ReferenceValue: i.offset);
5308 if (n_value != 0) {
5309 if (info->verbose && sym_name != nullptr)
5310 outs() << sym_name;
5311 else
5312 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5313 if (i.offset != 0)
5314 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.offset);
5315 } else
5316 outs() << format(Fmt: "0x%" PRIx64, Vals: i.offset);
5317 ivar_offset_p = get_pointer_64(Address: i.offset + n_value, offset&: xoffset, left, S&: xS, info);
5318 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5319 memcpy(dest: &ivar_offset, src: ivar_offset_p, n: sizeof(ivar_offset));
5320 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5321 sys::swapByteOrder(Value&: ivar_offset);
5322 outs() << " " << ivar_offset << "\n";
5323 } else
5324 outs() << "\n";
5325
5326 outs() << "\t\t\t name ";
5327 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, name), S, info,
5328 n_value, ReferenceValue: i.name);
5329 if (n_value != 0) {
5330 if (info->verbose && sym_name != nullptr)
5331 outs() << sym_name;
5332 else
5333 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5334 if (i.name != 0)
5335 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.name);
5336 } else
5337 outs() << format(Fmt: "0x%" PRIx64, Vals: i.name);
5338 name = get_pointer_64(Address: i.name + n_value, offset&: xoffset, left, S&: xS, info);
5339 if (name != nullptr)
5340 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5341 outs() << "\n";
5342
5343 outs() << "\t\t\t type ";
5344 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, type), S, info,
5345 n_value, ReferenceValue: i.name);
5346 name = get_pointer_64(Address: i.type + n_value, offset&: xoffset, left, S&: xS, info);
5347 if (n_value != 0) {
5348 if (info->verbose && sym_name != nullptr)
5349 outs() << sym_name;
5350 else
5351 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5352 if (i.type != 0)
5353 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.type);
5354 } else
5355 outs() << format(Fmt: "0x%" PRIx64, Vals: i.type);
5356 if (name != nullptr)
5357 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5358 outs() << "\n";
5359
5360 outs() << "\t\t\talignment " << i.alignment << "\n";
5361 outs() << "\t\t\t size " << i.size << "\n";
5362
5363 p += sizeof(struct ivar64_t);
5364 offset += sizeof(struct ivar64_t);
5365 }
5366}
5367
5368static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
5369 struct ivar_list32_t il;
5370 struct ivar32_t i;
5371 const char *r;
5372 uint32_t offset, xoffset, left, j;
5373 SectionRef S, xS;
5374 const char *name, *ivar_offset_p;
5375 uint32_t ivar_offset;
5376
5377 r = get_pointer_32(Address: p, offset, left, S, info);
5378 if (r == nullptr)
5379 return;
5380 memset(s: &il, c: '\0', n: sizeof(struct ivar_list32_t));
5381 if (left < sizeof(struct ivar_list32_t)) {
5382 memcpy(dest: &il, src: r, n: left);
5383 outs() << " (ivar_list_t entends past the end of the section)\n";
5384 } else
5385 memcpy(dest: &il, src: r, n: sizeof(struct ivar_list32_t));
5386 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5387 swapStruct(il);
5388 outs() << " entsize " << il.entsize << "\n";
5389 outs() << " count " << il.count << "\n";
5390
5391 p += sizeof(struct ivar_list32_t);
5392 offset += sizeof(struct ivar_list32_t);
5393 for (j = 0; j < il.count; j++) {
5394 r = get_pointer_32(Address: p, offset, left, S, info);
5395 if (r == nullptr)
5396 return;
5397 memset(s: &i, c: '\0', n: sizeof(struct ivar32_t));
5398 if (left < sizeof(struct ivar32_t)) {
5399 memcpy(dest: &i, src: r, n: left);
5400 outs() << " (ivar_t entends past the end of the section)\n";
5401 } else
5402 memcpy(dest: &i, src: r, n: sizeof(struct ivar32_t));
5403 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5404 swapStruct(i);
5405
5406 outs() << "\t\t\t offset " << format(Fmt: "0x%" PRIx32, Vals: i.offset);
5407 ivar_offset_p = get_pointer_32(Address: i.offset, offset&: xoffset, left, S&: xS, info);
5408 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5409 memcpy(dest: &ivar_offset, src: ivar_offset_p, n: sizeof(ivar_offset));
5410 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5411 sys::swapByteOrder(Value&: ivar_offset);
5412 outs() << " " << ivar_offset << "\n";
5413 } else
5414 outs() << "\n";
5415
5416 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: i.name);
5417 name = get_pointer_32(Address: i.name, offset&: xoffset, left, S&: xS, info);
5418 if (name != nullptr)
5419 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5420 outs() << "\n";
5421
5422 outs() << "\t\t\t type " << format(Fmt: "0x%" PRIx32, Vals: i.type);
5423 name = get_pointer_32(Address: i.type, offset&: xoffset, left, S&: xS, info);
5424 if (name != nullptr)
5425 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5426 outs() << "\n";
5427
5428 outs() << "\t\t\talignment " << i.alignment << "\n";
5429 outs() << "\t\t\t size " << i.size << "\n";
5430
5431 p += sizeof(struct ivar32_t);
5432 offset += sizeof(struct ivar32_t);
5433 }
5434}
5435
5436static void print_objc_property_list64(uint64_t p,
5437 struct DisassembleInfo *info) {
5438 struct objc_property_list64 opl;
5439 struct objc_property64 op;
5440 const char *r;
5441 uint32_t offset, xoffset, left, j;
5442 SectionRef S, xS;
5443 const char *name, *sym_name;
5444 uint64_t n_value;
5445
5446 r = get_pointer_64(Address: p, offset, left, S, info);
5447 if (r == nullptr)
5448 return;
5449 memset(s: &opl, c: '\0', n: sizeof(struct objc_property_list64));
5450 if (left < sizeof(struct objc_property_list64)) {
5451 memcpy(dest: &opl, src: r, n: left);
5452 outs() << " (objc_property_list entends past the end of the section)\n";
5453 } else
5454 memcpy(dest: &opl, src: r, n: sizeof(struct objc_property_list64));
5455 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5456 swapStruct(pl&: opl);
5457 outs() << " entsize " << opl.entsize << "\n";
5458 outs() << " count " << opl.count << "\n";
5459
5460 p += sizeof(struct objc_property_list64);
5461 offset += sizeof(struct objc_property_list64);
5462 for (j = 0; j < opl.count; j++) {
5463 r = get_pointer_64(Address: p, offset, left, S, info);
5464 if (r == nullptr)
5465 return;
5466 memset(s: &op, c: '\0', n: sizeof(struct objc_property64));
5467 if (left < sizeof(struct objc_property64)) {
5468 memcpy(dest: &op, src: r, n: left);
5469 outs() << " (objc_property entends past the end of the section)\n";
5470 } else
5471 memcpy(dest: &op, src: r, n: sizeof(struct objc_property64));
5472 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5473 swapStruct(op);
5474
5475 outs() << "\t\t\t name ";
5476 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct objc_property64, name), S,
5477 info, n_value, ReferenceValue: op.name);
5478 if (n_value != 0) {
5479 if (info->verbose && sym_name != nullptr)
5480 outs() << sym_name;
5481 else
5482 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5483 if (op.name != 0)
5484 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: op.name);
5485 } else
5486 outs() << format(Fmt: "0x%" PRIx64, Vals: op.name);
5487 name = get_pointer_64(Address: op.name + n_value, offset&: xoffset, left, S&: xS, info);
5488 if (name != nullptr)
5489 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5490 outs() << "\n";
5491
5492 outs() << "\t\t\tattributes ";
5493 sym_name =
5494 get_symbol_64(sect_offset: offset + offsetof(struct objc_property64, attributes), S,
5495 info, n_value, ReferenceValue: op.attributes);
5496 if (n_value != 0) {
5497 if (info->verbose && sym_name != nullptr)
5498 outs() << sym_name;
5499 else
5500 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5501 if (op.attributes != 0)
5502 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: op.attributes);
5503 } else
5504 outs() << format(Fmt: "0x%" PRIx64, Vals: op.attributes);
5505 name = get_pointer_64(Address: op.attributes + n_value, offset&: xoffset, left, S&: xS, info);
5506 if (name != nullptr)
5507 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5508 outs() << "\n";
5509
5510 p += sizeof(struct objc_property64);
5511 offset += sizeof(struct objc_property64);
5512 }
5513}
5514
5515static void print_objc_property_list32(uint32_t p,
5516 struct DisassembleInfo *info) {
5517 struct objc_property_list32 opl;
5518 struct objc_property32 op;
5519 const char *r;
5520 uint32_t offset, xoffset, left, j;
5521 SectionRef S, xS;
5522 const char *name;
5523
5524 r = get_pointer_32(Address: p, offset, left, S, info);
5525 if (r == nullptr)
5526 return;
5527 memset(s: &opl, c: '\0', n: sizeof(struct objc_property_list32));
5528 if (left < sizeof(struct objc_property_list32)) {
5529 memcpy(dest: &opl, src: r, n: left);
5530 outs() << " (objc_property_list entends past the end of the section)\n";
5531 } else
5532 memcpy(dest: &opl, src: r, n: sizeof(struct objc_property_list32));
5533 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5534 swapStruct(pl&: opl);
5535 outs() << " entsize " << opl.entsize << "\n";
5536 outs() << " count " << opl.count << "\n";
5537
5538 p += sizeof(struct objc_property_list32);
5539 offset += sizeof(struct objc_property_list32);
5540 for (j = 0; j < opl.count; j++) {
5541 r = get_pointer_32(Address: p, offset, left, S, info);
5542 if (r == nullptr)
5543 return;
5544 memset(s: &op, c: '\0', n: sizeof(struct objc_property32));
5545 if (left < sizeof(struct objc_property32)) {
5546 memcpy(dest: &op, src: r, n: left);
5547 outs() << " (objc_property entends past the end of the section)\n";
5548 } else
5549 memcpy(dest: &op, src: r, n: sizeof(struct objc_property32));
5550 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5551 swapStruct(op);
5552
5553 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: op.name);
5554 name = get_pointer_32(Address: op.name, offset&: xoffset, left, S&: xS, info);
5555 if (name != nullptr)
5556 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5557 outs() << "\n";
5558
5559 outs() << "\t\t\tattributes " << format(Fmt: "0x%" PRIx32, Vals: op.attributes);
5560 name = get_pointer_32(Address: op.attributes, offset&: xoffset, left, S&: xS, info);
5561 if (name != nullptr)
5562 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5563 outs() << "\n";
5564
5565 p += sizeof(struct objc_property32);
5566 offset += sizeof(struct objc_property32);
5567 }
5568}
5569
5570static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5571 bool &is_meta_class) {
5572 struct class_ro64_t cro;
5573 const char *r;
5574 uint32_t offset, xoffset, left;
5575 SectionRef S, xS;
5576 const char *name, *sym_name;
5577 uint64_t n_value;
5578
5579 r = get_pointer_64(Address: p, offset, left, S, info);
5580 if (r == nullptr || left < sizeof(struct class_ro64_t))
5581 return false;
5582 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro64_t));
5583 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5584 swapStruct(cro);
5585 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: cro.flags);
5586 if (cro.flags & RO_META)
5587 outs() << " RO_META";
5588 if (cro.flags & RO_ROOT)
5589 outs() << " RO_ROOT";
5590 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5591 outs() << " RO_HAS_CXX_STRUCTORS";
5592 outs() << "\n";
5593 outs() << " instanceStart " << cro.instanceStart << "\n";
5594 outs() << " instanceSize " << cro.instanceSize << "\n";
5595 outs() << " reserved " << format(Fmt: "0x%" PRIx32, Vals: cro.reserved)
5596 << "\n";
5597 outs() << " ivarLayout " << format(Fmt: "0x%" PRIx64, Vals: cro.ivarLayout)
5598 << "\n";
5599 print_layout_map64(p: cro.ivarLayout, info);
5600
5601 outs() << " name ";
5602 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, name), S,
5603 info, n_value, ReferenceValue: cro.name);
5604 if (n_value != 0) {
5605 if (info->verbose && sym_name != nullptr)
5606 outs() << sym_name;
5607 else
5608 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5609 if (cro.name != 0)
5610 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.name);
5611 } else
5612 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.name);
5613 name = get_pointer_64(Address: cro.name + n_value, offset&: xoffset, left, S&: xS, info);
5614 if (name != nullptr)
5615 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5616 outs() << "\n";
5617
5618 outs() << " baseMethods ";
5619 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseMethods),
5620 S, info, n_value, ReferenceValue: cro.baseMethods);
5621 if (n_value != 0) {
5622 if (info->verbose && sym_name != nullptr)
5623 outs() << sym_name;
5624 else
5625 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5626 if (cro.baseMethods != 0)
5627 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseMethods);
5628 } else
5629 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseMethods);
5630 outs() << " (struct method_list_t *)\n";
5631 if (cro.baseMethods + n_value != 0)
5632 print_method_list64_t(p: cro.baseMethods + n_value, info, indent: "");
5633
5634 outs() << " baseProtocols ";
5635 sym_name =
5636 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseProtocols), S,
5637 info, n_value, ReferenceValue: cro.baseProtocols);
5638 if (n_value != 0) {
5639 if (info->verbose && sym_name != nullptr)
5640 outs() << sym_name;
5641 else
5642 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5643 if (cro.baseProtocols != 0)
5644 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseProtocols);
5645 } else
5646 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseProtocols);
5647 outs() << "\n";
5648 if (cro.baseProtocols + n_value != 0)
5649 print_protocol_list64_t(p: cro.baseProtocols + n_value, info);
5650
5651 outs() << " ivars ";
5652 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, ivars), S,
5653 info, n_value, ReferenceValue: cro.ivars);
5654 if (n_value != 0) {
5655 if (info->verbose && sym_name != nullptr)
5656 outs() << sym_name;
5657 else
5658 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5659 if (cro.ivars != 0)
5660 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.ivars);
5661 } else
5662 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.ivars);
5663 outs() << "\n";
5664 if (cro.ivars + n_value != 0)
5665 print_ivar_list64_t(p: cro.ivars + n_value, info);
5666
5667 outs() << " weakIvarLayout ";
5668 sym_name =
5669 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5670 info, n_value, ReferenceValue: cro.weakIvarLayout);
5671 if (n_value != 0) {
5672 if (info->verbose && sym_name != nullptr)
5673 outs() << sym_name;
5674 else
5675 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5676 if (cro.weakIvarLayout != 0)
5677 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.weakIvarLayout);
5678 } else
5679 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.weakIvarLayout);
5680 outs() << "\n";
5681 print_layout_map64(p: cro.weakIvarLayout + n_value, info);
5682
5683 outs() << " baseProperties ";
5684 sym_name =
5685 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseProperties), S,
5686 info, n_value, ReferenceValue: cro.baseProperties);
5687 if (n_value != 0) {
5688 if (info->verbose && sym_name != nullptr)
5689 outs() << sym_name;
5690 else
5691 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5692 if (cro.baseProperties != 0)
5693 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseProperties);
5694 } else
5695 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseProperties);
5696 outs() << "\n";
5697 if (cro.baseProperties + n_value != 0)
5698 print_objc_property_list64(p: cro.baseProperties + n_value, info);
5699
5700 is_meta_class = (cro.flags & RO_META) != 0;
5701 return true;
5702}
5703
5704static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5705 bool &is_meta_class) {
5706 struct class_ro32_t cro;
5707 const char *r;
5708 uint32_t offset, xoffset, left;
5709 SectionRef S, xS;
5710 const char *name;
5711
5712 r = get_pointer_32(Address: p, offset, left, S, info);
5713 if (r == nullptr)
5714 return false;
5715 memset(s: &cro, c: '\0', n: sizeof(struct class_ro32_t));
5716 if (left < sizeof(struct class_ro32_t)) {
5717 memcpy(dest: &cro, src: r, n: left);
5718 outs() << " (class_ro_t entends past the end of the section)\n";
5719 } else
5720 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro32_t));
5721 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5722 swapStruct(cro);
5723 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: cro.flags);
5724 if (cro.flags & RO_META)
5725 outs() << " RO_META";
5726 if (cro.flags & RO_ROOT)
5727 outs() << " RO_ROOT";
5728 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5729 outs() << " RO_HAS_CXX_STRUCTORS";
5730 outs() << "\n";
5731 outs() << " instanceStart " << cro.instanceStart << "\n";
5732 outs() << " instanceSize " << cro.instanceSize << "\n";
5733 outs() << " ivarLayout " << format(Fmt: "0x%" PRIx32, Vals: cro.ivarLayout)
5734 << "\n";
5735 print_layout_map32(p: cro.ivarLayout, info);
5736
5737 outs() << " name " << format(Fmt: "0x%" PRIx32, Vals: cro.name);
5738 name = get_pointer_32(Address: cro.name, offset&: xoffset, left, S&: xS, info);
5739 if (name != nullptr)
5740 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5741 outs() << "\n";
5742
5743 outs() << " baseMethods "
5744 << format(Fmt: "0x%" PRIx32, Vals: cro.baseMethods)
5745 << " (struct method_list_t *)\n";
5746 if (cro.baseMethods != 0)
5747 print_method_list32_t(p: cro.baseMethods, info, indent: "");
5748
5749 outs() << " baseProtocols "
5750 << format(Fmt: "0x%" PRIx32, Vals: cro.baseProtocols) << "\n";
5751 if (cro.baseProtocols != 0)
5752 print_protocol_list32_t(p: cro.baseProtocols, info);
5753 outs() << " ivars " << format(Fmt: "0x%" PRIx32, Vals: cro.ivars)
5754 << "\n";
5755 if (cro.ivars != 0)
5756 print_ivar_list32_t(p: cro.ivars, info);
5757 outs() << " weakIvarLayout "
5758 << format(Fmt: "0x%" PRIx32, Vals: cro.weakIvarLayout) << "\n";
5759 print_layout_map32(p: cro.weakIvarLayout, info);
5760 outs() << " baseProperties "
5761 << format(Fmt: "0x%" PRIx32, Vals: cro.baseProperties) << "\n";
5762 if (cro.baseProperties != 0)
5763 print_objc_property_list32(p: cro.baseProperties, info);
5764 is_meta_class = (cro.flags & RO_META) != 0;
5765 return true;
5766}
5767
5768static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5769 struct class64_t c;
5770 const char *r;
5771 uint32_t offset, left;
5772 SectionRef S;
5773 const char *name;
5774 uint64_t isa_n_value, n_value;
5775
5776 r = get_pointer_64(Address: p, offset, left, S, info);
5777 if (r == nullptr || left < sizeof(struct class64_t))
5778 return;
5779 memcpy(dest: &c, src: r, n: sizeof(struct class64_t));
5780 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5781 swapStruct(c);
5782
5783 outs() << " isa " << format(Fmt: "0x%" PRIx64, Vals: c.isa);
5784 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, isa), S, info,
5785 n_value&: isa_n_value, ReferenceValue: c.isa);
5786 if (name != nullptr)
5787 outs() << " " << name;
5788 outs() << "\n";
5789
5790 outs() << " superclass " << format(Fmt: "0x%" PRIx64, Vals: c.superclass);
5791 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, superclass), S, info,
5792 n_value, ReferenceValue: c.superclass);
5793 if (name != nullptr)
5794 outs() << " " << name;
5795 else {
5796 name = get_dyld_bind_info_symbolname(ReferenceValue: S.getAddress() +
5797 offset + offsetof(struct class64_t, superclass), info);
5798 if (name != nullptr)
5799 outs() << " " << name;
5800 }
5801 outs() << "\n";
5802
5803 outs() << " cache " << format(Fmt: "0x%" PRIx64, Vals: c.cache);
5804 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, cache), S, info,
5805 n_value, ReferenceValue: c.cache);
5806 if (name != nullptr)
5807 outs() << " " << name;
5808 outs() << "\n";
5809
5810 outs() << " vtable " << format(Fmt: "0x%" PRIx64, Vals: c.vtable);
5811 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, vtable), S, info,
5812 n_value, ReferenceValue: c.vtable);
5813 if (name != nullptr)
5814 outs() << " " << name;
5815 outs() << "\n";
5816
5817 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, data), S, info,
5818 n_value, ReferenceValue: c.data);
5819 outs() << " data ";
5820 if (n_value != 0) {
5821 if (info->verbose && name != nullptr)
5822 outs() << name;
5823 else
5824 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5825 if (c.data != 0)
5826 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.data);
5827 } else
5828 outs() << format(Fmt: "0x%" PRIx64, Vals: c.data);
5829 outs() << " (struct class_ro_t *)";
5830
5831 // This is a Swift class if some of the low bits of the pointer are set.
5832 if ((c.data + n_value) & 0x7)
5833 outs() << " Swift class";
5834 outs() << "\n";
5835 bool is_meta_class;
5836 if (!print_class_ro64_t(p: (c.data + n_value) & ~0x7, info, is_meta_class))
5837 return;
5838
5839 if (!is_meta_class &&
5840 c.isa + isa_n_value != p &&
5841 c.isa + isa_n_value != 0 &&
5842 info->depth < 100) {
5843 info->depth++;
5844 outs() << "Meta Class\n";
5845 print_class64_t(p: c.isa + isa_n_value, info);
5846 }
5847}
5848
5849static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5850 struct class32_t c;
5851 const char *r;
5852 uint32_t offset, left;
5853 SectionRef S;
5854 const char *name;
5855
5856 r = get_pointer_32(Address: p, offset, left, S, info);
5857 if (r == nullptr)
5858 return;
5859 memset(s: &c, c: '\0', n: sizeof(struct class32_t));
5860 if (left < sizeof(struct class32_t)) {
5861 memcpy(dest: &c, src: r, n: left);
5862 outs() << " (class_t entends past the end of the section)\n";
5863 } else
5864 memcpy(dest: &c, src: r, n: sizeof(struct class32_t));
5865 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5866 swapStruct(c);
5867
5868 outs() << " isa " << format(Fmt: "0x%" PRIx32, Vals: c.isa);
5869 name =
5870 get_symbol_32(sect_offset: offset + offsetof(struct class32_t, isa), S, info, ReferenceValue: c.isa);
5871 if (name != nullptr)
5872 outs() << " " << name;
5873 outs() << "\n";
5874
5875 outs() << " superclass " << format(Fmt: "0x%" PRIx32, Vals: c.superclass);
5876 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, superclass), S, info,
5877 ReferenceValue: c.superclass);
5878 if (name != nullptr)
5879 outs() << " " << name;
5880 outs() << "\n";
5881
5882 outs() << " cache " << format(Fmt: "0x%" PRIx32, Vals: c.cache);
5883 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, cache), S, info,
5884 ReferenceValue: c.cache);
5885 if (name != nullptr)
5886 outs() << " " << name;
5887 outs() << "\n";
5888
5889 outs() << " vtable " << format(Fmt: "0x%" PRIx32, Vals: c.vtable);
5890 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, vtable), S, info,
5891 ReferenceValue: c.vtable);
5892 if (name != nullptr)
5893 outs() << " " << name;
5894 outs() << "\n";
5895
5896 name =
5897 get_symbol_32(sect_offset: offset + offsetof(struct class32_t, data), S, info, ReferenceValue: c.data);
5898 outs() << " data " << format(Fmt: "0x%" PRIx32, Vals: c.data)
5899 << " (struct class_ro_t *)";
5900
5901 // This is a Swift class if some of the low bits of the pointer are set.
5902 if (c.data & 0x3)
5903 outs() << " Swift class";
5904 outs() << "\n";
5905 bool is_meta_class;
5906 if (!print_class_ro32_t(p: c.data & ~0x3, info, is_meta_class))
5907 return;
5908
5909 if (!is_meta_class) {
5910 outs() << "Meta Class\n";
5911 print_class32_t(p: c.isa, info);
5912 }
5913}
5914
5915static void print_objc_class_t(struct objc_class_t *objc_class,
5916 struct DisassembleInfo *info) {
5917 uint32_t offset, left, xleft;
5918 const char *name, *p, *ivar_list;
5919 SectionRef S;
5920 int32_t i;
5921 struct objc_ivar_list_t objc_ivar_list;
5922 struct objc_ivar_t ivar;
5923
5924 outs() << "\t\t isa " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->isa);
5925 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5926 name = get_pointer_32(Address: objc_class->isa, offset, left, S, info, objc_only: true);
5927 if (name != nullptr)
5928 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5929 else
5930 outs() << " (not in an __OBJC section)";
5931 }
5932 outs() << "\n";
5933
5934 outs() << "\t super_class "
5935 << format(Fmt: "0x%08" PRIx32, Vals: objc_class->super_class);
5936 if (info->verbose) {
5937 name = get_pointer_32(Address: objc_class->super_class, offset, left, S, info, objc_only: true);
5938 if (name != nullptr)
5939 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5940 else
5941 outs() << " (not in an __OBJC section)";
5942 }
5943 outs() << "\n";
5944
5945 outs() << "\t\t name " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->name);
5946 if (info->verbose) {
5947 name = get_pointer_32(Address: objc_class->name, offset, left, S, info, objc_only: true);
5948 if (name != nullptr)
5949 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5950 else
5951 outs() << " (not in an __OBJC section)";
5952 }
5953 outs() << "\n";
5954
5955 outs() << "\t\t version " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->version)
5956 << "\n";
5957
5958 outs() << "\t\t info " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->info);
5959 if (info->verbose) {
5960 if (CLS_GETINFO(objc_class, CLS_CLASS))
5961 outs() << " CLS_CLASS";
5962 else if (CLS_GETINFO(objc_class, CLS_META))
5963 outs() << " CLS_META";
5964 }
5965 outs() << "\n";
5966
5967 outs() << "\t instance_size "
5968 << format(Fmt: "0x%08" PRIx32, Vals: objc_class->instance_size) << "\n";
5969
5970 p = get_pointer_32(Address: objc_class->ivars, offset, left, S, info, objc_only: true);
5971 outs() << "\t\t ivars " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->ivars);
5972 if (p != nullptr) {
5973 if (left > sizeof(struct objc_ivar_list_t)) {
5974 outs() << "\n";
5975 memcpy(dest: &objc_ivar_list, src: p, n: sizeof(struct objc_ivar_list_t));
5976 } else {
5977 outs() << " (entends past the end of the section)\n";
5978 memset(s: &objc_ivar_list, c: '\0', n: sizeof(struct objc_ivar_list_t));
5979 memcpy(dest: &objc_ivar_list, src: p, n: left);
5980 }
5981 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5982 swapStruct(objc_ivar_list);
5983 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5984 ivar_list = p + sizeof(struct objc_ivar_list_t);
5985 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5986 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5987 outs() << "\t\t remaining ivar's extend past the of the section\n";
5988 break;
5989 }
5990 memcpy(dest: &ivar, src: ivar_list + i * sizeof(struct objc_ivar_t),
5991 n: sizeof(struct objc_ivar_t));
5992 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5993 swapStruct(objc_ivar&: ivar);
5994
5995 outs() << "\t\t\tivar_name " << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_name);
5996 if (info->verbose) {
5997 name = get_pointer_32(Address: ivar.ivar_name, offset, left&: xleft, S, info, objc_only: true);
5998 if (name != nullptr)
5999 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
6000 else
6001 outs() << " (not in an __OBJC section)";
6002 }
6003 outs() << "\n";
6004
6005 outs() << "\t\t\tivar_type " << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_type);
6006 if (info->verbose) {
6007 name = get_pointer_32(Address: ivar.ivar_type, offset, left&: xleft, S, info, objc_only: true);
6008 if (name != nullptr)
6009 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
6010 else
6011 outs() << " (not in an __OBJC section)";
6012 }
6013 outs() << "\n";
6014
6015 outs() << "\t\t ivar_offset "
6016 << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_offset) << "\n";
6017 }
6018 } else {
6019 outs() << " (not in an __OBJC section)\n";
6020 }
6021
6022 outs() << "\t\t methods " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->methodLists);
6023 if (print_method_list(p: objc_class->methodLists, info))
6024 outs() << " (not in an __OBJC section)\n";
6025
6026 outs() << "\t\t cache " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->cache)
6027 << "\n";
6028
6029 outs() << "\t\tprotocols " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->protocols);
6030 if (print_protocol_list(p: objc_class->protocols, indent: 16, info))
6031 outs() << " (not in an __OBJC section)\n";
6032}
6033
6034static void print_objc_objc_category_t(struct objc_category_t *objc_category,
6035 struct DisassembleInfo *info) {
6036 uint32_t offset, left;
6037 const char *name;
6038 SectionRef S;
6039
6040 outs() << "\t category name "
6041 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->category_name);
6042 if (info->verbose) {
6043 name = get_pointer_32(Address: objc_category->category_name, offset, left, S, info,
6044 objc_only: true);
6045 if (name != nullptr)
6046 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6047 else
6048 outs() << " (not in an __OBJC section)";
6049 }
6050 outs() << "\n";
6051
6052 outs() << "\t\t class name "
6053 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->class_name);
6054 if (info->verbose) {
6055 name =
6056 get_pointer_32(Address: objc_category->class_name, offset, left, S, info, objc_only: true);
6057 if (name != nullptr)
6058 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6059 else
6060 outs() << " (not in an __OBJC section)";
6061 }
6062 outs() << "\n";
6063
6064 outs() << "\t instance methods "
6065 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->instance_methods);
6066 if (print_method_list(p: objc_category->instance_methods, info))
6067 outs() << " (not in an __OBJC section)\n";
6068
6069 outs() << "\t class methods "
6070 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->class_methods);
6071 if (print_method_list(p: objc_category->class_methods, info))
6072 outs() << " (not in an __OBJC section)\n";
6073}
6074
6075static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
6076 struct category64_t c;
6077 const char *r;
6078 uint32_t offset, xoffset, left;
6079 SectionRef S, xS;
6080 const char *name, *sym_name;
6081 uint64_t n_value;
6082
6083 r = get_pointer_64(Address: p, offset, left, S, info);
6084 if (r == nullptr)
6085 return;
6086 memset(s: &c, c: '\0', n: sizeof(struct category64_t));
6087 if (left < sizeof(struct category64_t)) {
6088 memcpy(dest: &c, src: r, n: left);
6089 outs() << " (category_t entends past the end of the section)\n";
6090 } else
6091 memcpy(dest: &c, src: r, n: sizeof(struct category64_t));
6092 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6093 swapStruct(c);
6094
6095 outs() << " name ";
6096 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, name), S,
6097 info, n_value, ReferenceValue: c.name);
6098 if (n_value != 0) {
6099 if (info->verbose && sym_name != nullptr)
6100 outs() << sym_name;
6101 else
6102 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6103 if (c.name != 0)
6104 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.name);
6105 } else
6106 outs() << format(Fmt: "0x%" PRIx64, Vals: c.name);
6107 name = get_pointer_64(Address: c.name + n_value, offset&: xoffset, left, S&: xS, info);
6108 if (name != nullptr)
6109 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6110 outs() << "\n";
6111
6112 outs() << " cls ";
6113 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, cls), S, info,
6114 n_value, ReferenceValue: c.cls);
6115 if (n_value != 0) {
6116 if (info->verbose && sym_name != nullptr)
6117 outs() << sym_name;
6118 else
6119 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6120 if (c.cls != 0)
6121 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.cls);
6122 } else
6123 outs() << format(Fmt: "0x%" PRIx64, Vals: c.cls);
6124 outs() << "\n";
6125 if (c.cls + n_value != 0)
6126 print_class64_t(p: c.cls + n_value, info);
6127
6128 outs() << " instanceMethods ";
6129 sym_name =
6130 get_symbol_64(sect_offset: offset + offsetof(struct category64_t, instanceMethods), S,
6131 info, n_value, ReferenceValue: c.instanceMethods);
6132 if (n_value != 0) {
6133 if (info->verbose && sym_name != nullptr)
6134 outs() << sym_name;
6135 else
6136 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6137 if (c.instanceMethods != 0)
6138 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.instanceMethods);
6139 } else
6140 outs() << format(Fmt: "0x%" PRIx64, Vals: c.instanceMethods);
6141 outs() << "\n";
6142 if (c.instanceMethods + n_value != 0)
6143 print_method_list64_t(p: c.instanceMethods + n_value, info, indent: "");
6144
6145 outs() << " classMethods ";
6146 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, classMethods),
6147 S, info, n_value, ReferenceValue: c.classMethods);
6148 if (n_value != 0) {
6149 if (info->verbose && sym_name != nullptr)
6150 outs() << sym_name;
6151 else
6152 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6153 if (c.classMethods != 0)
6154 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.classMethods);
6155 } else
6156 outs() << format(Fmt: "0x%" PRIx64, Vals: c.classMethods);
6157 outs() << "\n";
6158 if (c.classMethods + n_value != 0)
6159 print_method_list64_t(p: c.classMethods + n_value, info, indent: "");
6160
6161 outs() << " protocols ";
6162 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, protocols), S,
6163 info, n_value, ReferenceValue: c.protocols);
6164 if (n_value != 0) {
6165 if (info->verbose && sym_name != nullptr)
6166 outs() << sym_name;
6167 else
6168 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6169 if (c.protocols != 0)
6170 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.protocols);
6171 } else
6172 outs() << format(Fmt: "0x%" PRIx64, Vals: c.protocols);
6173 outs() << "\n";
6174 if (c.protocols + n_value != 0)
6175 print_protocol_list64_t(p: c.protocols + n_value, info);
6176
6177 outs() << "instanceProperties ";
6178 sym_name =
6179 get_symbol_64(sect_offset: offset + offsetof(struct category64_t, instanceProperties),
6180 S, info, n_value, ReferenceValue: c.instanceProperties);
6181 if (n_value != 0) {
6182 if (info->verbose && sym_name != nullptr)
6183 outs() << sym_name;
6184 else
6185 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6186 if (c.instanceProperties != 0)
6187 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.instanceProperties);
6188 } else
6189 outs() << format(Fmt: "0x%" PRIx64, Vals: c.instanceProperties);
6190 outs() << "\n";
6191 if (c.instanceProperties + n_value != 0)
6192 print_objc_property_list64(p: c.instanceProperties + n_value, info);
6193}
6194
6195static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
6196 struct category32_t c;
6197 const char *r;
6198 uint32_t offset, left;
6199 SectionRef S, xS;
6200 const char *name;
6201
6202 r = get_pointer_32(Address: p, offset, left, S, info);
6203 if (r == nullptr)
6204 return;
6205 memset(s: &c, c: '\0', n: sizeof(struct category32_t));
6206 if (left < sizeof(struct category32_t)) {
6207 memcpy(dest: &c, src: r, n: left);
6208 outs() << " (category_t entends past the end of the section)\n";
6209 } else
6210 memcpy(dest: &c, src: r, n: sizeof(struct category32_t));
6211 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6212 swapStruct(c);
6213
6214 outs() << " name " << format(Fmt: "0x%" PRIx32, Vals: c.name);
6215 name = get_symbol_32(sect_offset: offset + offsetof(struct category32_t, name), S, info,
6216 ReferenceValue: c.name);
6217 if (name)
6218 outs() << " " << name;
6219 outs() << "\n";
6220
6221 outs() << " cls " << format(Fmt: "0x%" PRIx32, Vals: c.cls) << "\n";
6222 if (c.cls != 0)
6223 print_class32_t(p: c.cls, info);
6224 outs() << " instanceMethods " << format(Fmt: "0x%" PRIx32, Vals: c.instanceMethods)
6225 << "\n";
6226 if (c.instanceMethods != 0)
6227 print_method_list32_t(p: c.instanceMethods, info, indent: "");
6228 outs() << " classMethods " << format(Fmt: "0x%" PRIx32, Vals: c.classMethods)
6229 << "\n";
6230 if (c.classMethods != 0)
6231 print_method_list32_t(p: c.classMethods, info, indent: "");
6232 outs() << " protocols " << format(Fmt: "0x%" PRIx32, Vals: c.protocols) << "\n";
6233 if (c.protocols != 0)
6234 print_protocol_list32_t(p: c.protocols, info);
6235 outs() << "instanceProperties " << format(Fmt: "0x%" PRIx32, Vals: c.instanceProperties)
6236 << "\n";
6237 if (c.instanceProperties != 0)
6238 print_objc_property_list32(p: c.instanceProperties, info);
6239}
6240
6241static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
6242 uint32_t i, left, offset, xoffset;
6243 uint64_t p, n_value;
6244 struct message_ref64 mr;
6245 const char *name, *sym_name;
6246 const char *r;
6247 SectionRef xS;
6248
6249 if (S == SectionRef())
6250 return;
6251
6252 StringRef SectName;
6253 Expected<StringRef> SecNameOrErr = S.getName();
6254 if (SecNameOrErr)
6255 SectName = *SecNameOrErr;
6256 else
6257 consumeError(Err: SecNameOrErr.takeError());
6258
6259 DataRefImpl Ref = S.getRawDataRefImpl();
6260 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6261 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6262 offset = 0;
6263 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6264 p = S.getAddress() + i;
6265 r = get_pointer_64(Address: p, offset, left, S, info);
6266 if (r == nullptr)
6267 return;
6268 memset(s: &mr, c: '\0', n: sizeof(struct message_ref64));
6269 if (left < sizeof(struct message_ref64)) {
6270 memcpy(dest: &mr, src: r, n: left);
6271 outs() << " (message_ref entends past the end of the section)\n";
6272 } else
6273 memcpy(dest: &mr, src: r, n: sizeof(struct message_ref64));
6274 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6275 swapStruct(mr);
6276
6277 outs() << " imp ";
6278 name = get_symbol_64(sect_offset: offset + offsetof(struct message_ref64, imp), S, info,
6279 n_value, ReferenceValue: mr.imp);
6280 if (n_value != 0) {
6281 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value) << " ";
6282 if (mr.imp != 0)
6283 outs() << "+ " << format(Fmt: "0x%" PRIx64, Vals: mr.imp) << " ";
6284 } else
6285 outs() << format(Fmt: "0x%" PRIx64, Vals: mr.imp) << " ";
6286 if (name != nullptr)
6287 outs() << " " << name;
6288 outs() << "\n";
6289
6290 outs() << " sel ";
6291 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct message_ref64, sel), S,
6292 info, n_value, ReferenceValue: mr.sel);
6293 if (n_value != 0) {
6294 if (info->verbose && sym_name != nullptr)
6295 outs() << sym_name;
6296 else
6297 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6298 if (mr.sel != 0)
6299 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: mr.sel);
6300 } else
6301 outs() << format(Fmt: "0x%" PRIx64, Vals: mr.sel);
6302 name = get_pointer_64(Address: mr.sel + n_value, offset&: xoffset, left, S&: xS, info);
6303 if (name != nullptr)
6304 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6305 outs() << "\n";
6306
6307 offset += sizeof(struct message_ref64);
6308 }
6309}
6310
6311static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
6312 uint32_t i, left, offset, xoffset, p;
6313 struct message_ref32 mr;
6314 const char *name, *r;
6315 SectionRef xS;
6316
6317 if (S == SectionRef())
6318 return;
6319
6320 StringRef SectName;
6321 Expected<StringRef> SecNameOrErr = S.getName();
6322 if (SecNameOrErr)
6323 SectName = *SecNameOrErr;
6324 else
6325 consumeError(Err: SecNameOrErr.takeError());
6326
6327 DataRefImpl Ref = S.getRawDataRefImpl();
6328 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6329 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6330 offset = 0;
6331 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6332 p = S.getAddress() + i;
6333 r = get_pointer_32(Address: p, offset, left, S, info);
6334 if (r == nullptr)
6335 return;
6336 memset(s: &mr, c: '\0', n: sizeof(struct message_ref32));
6337 if (left < sizeof(struct message_ref32)) {
6338 memcpy(dest: &mr, src: r, n: left);
6339 outs() << " (message_ref entends past the end of the section)\n";
6340 } else
6341 memcpy(dest: &mr, src: r, n: sizeof(struct message_ref32));
6342 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6343 swapStruct(mr);
6344
6345 outs() << " imp " << format(Fmt: "0x%" PRIx32, Vals: mr.imp);
6346 name = get_symbol_32(sect_offset: offset + offsetof(struct message_ref32, imp), S, info,
6347 ReferenceValue: mr.imp);
6348 if (name != nullptr)
6349 outs() << " " << name;
6350 outs() << "\n";
6351
6352 outs() << " sel " << format(Fmt: "0x%" PRIx32, Vals: mr.sel);
6353 name = get_pointer_32(Address: mr.sel, offset&: xoffset, left, S&: xS, info);
6354 if (name != nullptr)
6355 outs() << " " << name;
6356 outs() << "\n";
6357
6358 offset += sizeof(struct message_ref32);
6359 }
6360}
6361
6362static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
6363 uint32_t left, offset, swift_version;
6364 uint64_t p;
6365 struct objc_image_info64 o;
6366 const char *r;
6367
6368 if (S == SectionRef())
6369 return;
6370
6371 StringRef SectName;
6372 Expected<StringRef> SecNameOrErr = S.getName();
6373 if (SecNameOrErr)
6374 SectName = *SecNameOrErr;
6375 else
6376 consumeError(Err: SecNameOrErr.takeError());
6377
6378 DataRefImpl Ref = S.getRawDataRefImpl();
6379 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6380 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6381 p = S.getAddress();
6382 r = get_pointer_64(Address: p, offset, left, S, info);
6383 if (r == nullptr)
6384 return;
6385 memset(s: &o, c: '\0', n: sizeof(struct objc_image_info64));
6386 if (left < sizeof(struct objc_image_info64)) {
6387 memcpy(dest: &o, src: r, n: left);
6388 outs() << " (objc_image_info entends past the end of the section)\n";
6389 } else
6390 memcpy(dest: &o, src: r, n: sizeof(struct objc_image_info64));
6391 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6392 swapStruct(o);
6393 outs() << " version " << o.version << "\n";
6394 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6395 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6396 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6397 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6398 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6399 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
6400 outs() << " OBJC_IMAGE_IS_SIMULATED";
6401 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
6402 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
6403 swift_version = (o.flags >> 8) & 0xff;
6404 if (swift_version != 0) {
6405 if (swift_version == 1)
6406 outs() << " Swift 1.0";
6407 else if (swift_version == 2)
6408 outs() << " Swift 1.1";
6409 else if(swift_version == 3)
6410 outs() << " Swift 2.0";
6411 else if(swift_version == 4)
6412 outs() << " Swift 3.0";
6413 else if(swift_version == 5)
6414 outs() << " Swift 4.0";
6415 else if(swift_version == 6)
6416 outs() << " Swift 4.1/Swift 4.2";
6417 else if(swift_version == 7)
6418 outs() << " Swift 5 or later";
6419 else
6420 outs() << " unknown future Swift version (" << swift_version << ")";
6421 }
6422 outs() << "\n";
6423}
6424
6425static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6426 uint32_t left, offset, swift_version, p;
6427 struct objc_image_info32 o;
6428 const char *r;
6429
6430 if (S == SectionRef())
6431 return;
6432
6433 StringRef SectName;
6434 Expected<StringRef> SecNameOrErr = S.getName();
6435 if (SecNameOrErr)
6436 SectName = *SecNameOrErr;
6437 else
6438 consumeError(Err: SecNameOrErr.takeError());
6439
6440 DataRefImpl Ref = S.getRawDataRefImpl();
6441 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6442 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6443 p = S.getAddress();
6444 r = get_pointer_32(Address: p, offset, left, S, info);
6445 if (r == nullptr)
6446 return;
6447 memset(s: &o, c: '\0', n: sizeof(struct objc_image_info32));
6448 if (left < sizeof(struct objc_image_info32)) {
6449 memcpy(dest: &o, src: r, n: left);
6450 outs() << " (objc_image_info entends past the end of the section)\n";
6451 } else
6452 memcpy(dest: &o, src: r, n: sizeof(struct objc_image_info32));
6453 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6454 swapStruct(o);
6455 outs() << " version " << o.version << "\n";
6456 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6457 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6458 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6459 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6460 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6461 swift_version = (o.flags >> 8) & 0xff;
6462 if (swift_version != 0) {
6463 if (swift_version == 1)
6464 outs() << " Swift 1.0";
6465 else if (swift_version == 2)
6466 outs() << " Swift 1.1";
6467 else if(swift_version == 3)
6468 outs() << " Swift 2.0";
6469 else if(swift_version == 4)
6470 outs() << " Swift 3.0";
6471 else if(swift_version == 5)
6472 outs() << " Swift 4.0";
6473 else if(swift_version == 6)
6474 outs() << " Swift 4.1/Swift 4.2";
6475 else if(swift_version == 7)
6476 outs() << " Swift 5 or later";
6477 else
6478 outs() << " unknown future Swift version (" << swift_version << ")";
6479 }
6480 outs() << "\n";
6481}
6482
6483static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6484 uint32_t left, offset, p;
6485 struct imageInfo_t o;
6486 const char *r;
6487
6488 StringRef SectName;
6489 Expected<StringRef> SecNameOrErr = S.getName();
6490 if (SecNameOrErr)
6491 SectName = *SecNameOrErr;
6492 else
6493 consumeError(Err: SecNameOrErr.takeError());
6494
6495 DataRefImpl Ref = S.getRawDataRefImpl();
6496 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6497 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6498 p = S.getAddress();
6499 r = get_pointer_32(Address: p, offset, left, S, info);
6500 if (r == nullptr)
6501 return;
6502 memset(s: &o, c: '\0', n: sizeof(struct imageInfo_t));
6503 if (left < sizeof(struct imageInfo_t)) {
6504 memcpy(dest: &o, src: r, n: left);
6505 outs() << " (imageInfo entends past the end of the section)\n";
6506 } else
6507 memcpy(dest: &o, src: r, n: sizeof(struct imageInfo_t));
6508 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6509 swapStruct(o);
6510 outs() << " version " << o.version << "\n";
6511 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6512 if (o.flags & 0x1)
6513 outs() << " F&C";
6514 if (o.flags & 0x2)
6515 outs() << " GC";
6516 if (o.flags & 0x4)
6517 outs() << " GC-only";
6518 else
6519 outs() << " RR";
6520 outs() << "\n";
6521}
6522
6523static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6524 SymbolAddressMap AddrMap;
6525 if (verbose)
6526 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6527
6528 std::vector<SectionRef> Sections;
6529 append_range(C&: Sections, R: O->sections());
6530
6531 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6532
6533 SectionRef CL = get_section(O, segname: "__OBJC2", sectname: "__class_list");
6534 if (CL == SectionRef())
6535 CL = get_section(O, segname: "__DATA", sectname: "__objc_classlist");
6536 if (CL == SectionRef())
6537 CL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classlist");
6538 if (CL == SectionRef())
6539 CL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classlist");
6540 info.S = CL;
6541 walk_pointer_list_64(listname: "class", S: CL, O, info: &info, func: print_class64_t);
6542
6543 SectionRef CR = get_section(O, segname: "__OBJC2", sectname: "__class_refs");
6544 if (CR == SectionRef())
6545 CR = get_section(O, segname: "__DATA", sectname: "__objc_classrefs");
6546 if (CR == SectionRef())
6547 CR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classrefs");
6548 if (CR == SectionRef())
6549 CR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classrefs");
6550 info.S = CR;
6551 walk_pointer_list_64(listname: "class refs", S: CR, O, info: &info, func: nullptr);
6552
6553 SectionRef SR = get_section(O, segname: "__OBJC2", sectname: "__super_refs");
6554 if (SR == SectionRef())
6555 SR = get_section(O, segname: "__DATA", sectname: "__objc_superrefs");
6556 if (SR == SectionRef())
6557 SR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_superrefs");
6558 if (SR == SectionRef())
6559 SR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_superrefs");
6560 info.S = SR;
6561 walk_pointer_list_64(listname: "super refs", S: SR, O, info: &info, func: nullptr);
6562
6563 SectionRef CA = get_section(O, segname: "__OBJC2", sectname: "__category_list");
6564 if (CA == SectionRef())
6565 CA = get_section(O, segname: "__DATA", sectname: "__objc_catlist");
6566 if (CA == SectionRef())
6567 CA = get_section(O, segname: "__DATA_CONST", sectname: "__objc_catlist");
6568 if (CA == SectionRef())
6569 CA = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_catlist");
6570 info.S = CA;
6571 walk_pointer_list_64(listname: "category", S: CA, O, info: &info, func: print_category64_t);
6572
6573 SectionRef PL = get_section(O, segname: "__OBJC2", sectname: "__protocol_list");
6574 if (PL == SectionRef())
6575 PL = get_section(O, segname: "__DATA", sectname: "__objc_protolist");
6576 if (PL == SectionRef())
6577 PL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_protolist");
6578 if (PL == SectionRef())
6579 PL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_protolist");
6580 info.S = PL;
6581 walk_pointer_list_64(listname: "protocol", S: PL, O, info: &info, func: nullptr);
6582
6583 SectionRef MR = get_section(O, segname: "__OBJC2", sectname: "__message_refs");
6584 if (MR == SectionRef())
6585 MR = get_section(O, segname: "__DATA", sectname: "__objc_msgrefs");
6586 if (MR == SectionRef())
6587 MR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_msgrefs");
6588 if (MR == SectionRef())
6589 MR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_msgrefs");
6590 info.S = MR;
6591 print_message_refs64(S: MR, info: &info);
6592
6593 SectionRef II = get_section(O, segname: "__OBJC2", sectname: "__image_info");
6594 if (II == SectionRef())
6595 II = get_section(O, segname: "__DATA", sectname: "__objc_imageinfo");
6596 if (II == SectionRef())
6597 II = get_section(O, segname: "__DATA_CONST", sectname: "__objc_imageinfo");
6598 if (II == SectionRef())
6599 II = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_imageinfo");
6600 info.S = II;
6601 print_image_info64(S: II, info: &info);
6602}
6603
6604static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6605 SymbolAddressMap AddrMap;
6606 if (verbose)
6607 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6608
6609 std::vector<SectionRef> Sections;
6610 append_range(C&: Sections, R: O->sections());
6611
6612 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6613
6614 SectionRef CL = get_section(O, segname: "__OBJC2", sectname: "__class_list");
6615 if (CL == SectionRef())
6616 CL = get_section(O, segname: "__DATA", sectname: "__objc_classlist");
6617 if (CL == SectionRef())
6618 CL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classlist");
6619 if (CL == SectionRef())
6620 CL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classlist");
6621 info.S = CL;
6622 walk_pointer_list_32(listname: "class", S: CL, O, info: &info, func: print_class32_t);
6623
6624 SectionRef CR = get_section(O, segname: "__OBJC2", sectname: "__class_refs");
6625 if (CR == SectionRef())
6626 CR = get_section(O, segname: "__DATA", sectname: "__objc_classrefs");
6627 if (CR == SectionRef())
6628 CR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classrefs");
6629 if (CR == SectionRef())
6630 CR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classrefs");
6631 info.S = CR;
6632 walk_pointer_list_32(listname: "class refs", S: CR, O, info: &info, func: nullptr);
6633
6634 SectionRef SR = get_section(O, segname: "__OBJC2", sectname: "__super_refs");
6635 if (SR == SectionRef())
6636 SR = get_section(O, segname: "__DATA", sectname: "__objc_superrefs");
6637 if (SR == SectionRef())
6638 SR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_superrefs");
6639 if (SR == SectionRef())
6640 SR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_superrefs");
6641 info.S = SR;
6642 walk_pointer_list_32(listname: "super refs", S: SR, O, info: &info, func: nullptr);
6643
6644 SectionRef CA = get_section(O, segname: "__OBJC2", sectname: "__category_list");
6645 if (CA == SectionRef())
6646 CA = get_section(O, segname: "__DATA", sectname: "__objc_catlist");
6647 if (CA == SectionRef())
6648 CA = get_section(O, segname: "__DATA_CONST", sectname: "__objc_catlist");
6649 if (CA == SectionRef())
6650 CA = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_catlist");
6651 info.S = CA;
6652 walk_pointer_list_32(listname: "category", S: CA, O, info: &info, func: print_category32_t);
6653
6654 SectionRef PL = get_section(O, segname: "__OBJC2", sectname: "__protocol_list");
6655 if (PL == SectionRef())
6656 PL = get_section(O, segname: "__DATA", sectname: "__objc_protolist");
6657 if (PL == SectionRef())
6658 PL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_protolist");
6659 if (PL == SectionRef())
6660 PL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_protolist");
6661 info.S = PL;
6662 walk_pointer_list_32(listname: "protocol", S: PL, O, info: &info, func: nullptr);
6663
6664 SectionRef MR = get_section(O, segname: "__OBJC2", sectname: "__message_refs");
6665 if (MR == SectionRef())
6666 MR = get_section(O, segname: "__DATA", sectname: "__objc_msgrefs");
6667 if (MR == SectionRef())
6668 MR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_msgrefs");
6669 if (MR == SectionRef())
6670 MR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_msgrefs");
6671 info.S = MR;
6672 print_message_refs32(S: MR, info: &info);
6673
6674 SectionRef II = get_section(O, segname: "__OBJC2", sectname: "__image_info");
6675 if (II == SectionRef())
6676 II = get_section(O, segname: "__DATA", sectname: "__objc_imageinfo");
6677 if (II == SectionRef())
6678 II = get_section(O, segname: "__DATA_CONST", sectname: "__objc_imageinfo");
6679 if (II == SectionRef())
6680 II = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_imageinfo");
6681 info.S = II;
6682 print_image_info32(S: II, info: &info);
6683}
6684
6685static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6686 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6687 const char *r, *name, *defs;
6688 struct objc_module_t module;
6689 SectionRef S, xS;
6690 struct objc_symtab_t symtab;
6691 struct objc_class_t objc_class;
6692 struct objc_category_t objc_category;
6693
6694 outs() << "Objective-C segment\n";
6695 S = get_section(O, segname: "__OBJC", sectname: "__module_info");
6696 if (S == SectionRef())
6697 return false;
6698
6699 SymbolAddressMap AddrMap;
6700 if (verbose)
6701 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6702
6703 std::vector<SectionRef> Sections;
6704 append_range(C&: Sections, R: O->sections());
6705
6706 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6707
6708 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6709 p = S.getAddress() + i;
6710 r = get_pointer_32(Address: p, offset, left, S, info: &info, objc_only: true);
6711 if (r == nullptr)
6712 return true;
6713 memset(s: &module, c: '\0', n: sizeof(struct objc_module_t));
6714 if (left < sizeof(struct objc_module_t)) {
6715 memcpy(dest: &module, src: r, n: left);
6716 outs() << " (module extends past end of __module_info section)\n";
6717 } else
6718 memcpy(dest: &module, src: r, n: sizeof(struct objc_module_t));
6719 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6720 swapStruct(module);
6721
6722 outs() << "Module " << format(Fmt: "0x%" PRIx32, Vals: p) << "\n";
6723 outs() << " version " << module.version << "\n";
6724 outs() << " size " << module.size << "\n";
6725 outs() << " name ";
6726 name = get_pointer_32(Address: module.name, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6727 if (name != nullptr)
6728 outs() << format(Fmt: "%.*s", Vals: left, Vals: name);
6729 else
6730 outs() << format(Fmt: "0x%08" PRIx32, Vals: module.name)
6731 << "(not in an __OBJC section)";
6732 outs() << "\n";
6733
6734 r = get_pointer_32(Address: module.symtab, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6735 if (module.symtab == 0 || r == nullptr) {
6736 outs() << " symtab " << format(Fmt: "0x%08" PRIx32, Vals: module.symtab)
6737 << " (not in an __OBJC section)\n";
6738 continue;
6739 }
6740 outs() << " symtab " << format(Fmt: "0x%08" PRIx32, Vals: module.symtab) << "\n";
6741 memset(s: &symtab, c: '\0', n: sizeof(struct objc_symtab_t));
6742 defs_left = 0;
6743 defs = nullptr;
6744 if (left < sizeof(struct objc_symtab_t)) {
6745 memcpy(dest: &symtab, src: r, n: left);
6746 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6747 } else {
6748 memcpy(dest: &symtab, src: r, n: sizeof(struct objc_symtab_t));
6749 if (left > sizeof(struct objc_symtab_t)) {
6750 defs_left = left - sizeof(struct objc_symtab_t);
6751 defs = r + sizeof(struct objc_symtab_t);
6752 }
6753 }
6754 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6755 swapStruct(symtab);
6756
6757 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6758 r = get_pointer_32(Address: symtab.refs, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6759 outs() << "\trefs " << format(Fmt: "0x%08" PRIx32, Vals: symtab.refs);
6760 if (r == nullptr)
6761 outs() << " (not in an __OBJC section)";
6762 outs() << "\n";
6763 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6764 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6765 if (symtab.cls_def_cnt > 0)
6766 outs() << "\tClass Definitions\n";
6767 for (j = 0; j < symtab.cls_def_cnt; j++) {
6768 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6769 outs() << "\t(remaining class defs entries entends past the end of the "
6770 << "section)\n";
6771 break;
6772 }
6773 memcpy(dest: &def, src: defs + j * sizeof(uint32_t), n: sizeof(uint32_t));
6774 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6775 sys::swapByteOrder(Value&: def);
6776
6777 r = get_pointer_32(Address: def, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6778 outs() << "\tdefs[" << j << "] " << format(Fmt: "0x%08" PRIx32, Vals: def);
6779 if (r != nullptr) {
6780 if (left > sizeof(struct objc_class_t)) {
6781 outs() << "\n";
6782 memcpy(dest: &objc_class, src: r, n: sizeof(struct objc_class_t));
6783 } else {
6784 outs() << " (entends past the end of the section)\n";
6785 memset(s: &objc_class, c: '\0', n: sizeof(struct objc_class_t));
6786 memcpy(dest: &objc_class, src: r, n: left);
6787 }
6788 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6789 swapStruct(objc_class);
6790 print_objc_class_t(objc_class: &objc_class, info: &info);
6791 } else {
6792 outs() << "(not in an __OBJC section)\n";
6793 }
6794
6795 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6796 outs() << "\tMeta Class";
6797 r = get_pointer_32(Address: objc_class.isa, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6798 if (r != nullptr) {
6799 if (left > sizeof(struct objc_class_t)) {
6800 outs() << "\n";
6801 memcpy(dest: &objc_class, src: r, n: sizeof(struct objc_class_t));
6802 } else {
6803 outs() << " (entends past the end of the section)\n";
6804 memset(s: &objc_class, c: '\0', n: sizeof(struct objc_class_t));
6805 memcpy(dest: &objc_class, src: r, n: left);
6806 }
6807 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6808 swapStruct(objc_class);
6809 print_objc_class_t(objc_class: &objc_class, info: &info);
6810 } else {
6811 outs() << "(not in an __OBJC section)\n";
6812 }
6813 }
6814 }
6815 if (symtab.cat_def_cnt > 0)
6816 outs() << "\tCategory Definitions\n";
6817 for (j = 0; j < symtab.cat_def_cnt; j++) {
6818 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6819 outs() << "\t(remaining category defs entries entends past the end of "
6820 << "the section)\n";
6821 break;
6822 }
6823 memcpy(dest: &def, src: defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6824 n: sizeof(uint32_t));
6825 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6826 sys::swapByteOrder(Value&: def);
6827
6828 r = get_pointer_32(Address: def, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6829 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6830 << format(Fmt: "0x%08" PRIx32, Vals: def);
6831 if (r != nullptr) {
6832 if (left > sizeof(struct objc_category_t)) {
6833 outs() << "\n";
6834 memcpy(dest: &objc_category, src: r, n: sizeof(struct objc_category_t));
6835 } else {
6836 outs() << " (entends past the end of the section)\n";
6837 memset(s: &objc_category, c: '\0', n: sizeof(struct objc_category_t));
6838 memcpy(dest: &objc_category, src: r, n: left);
6839 }
6840 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6841 swapStruct(objc_category);
6842 print_objc_objc_category_t(objc_category: &objc_category, info: &info);
6843 } else {
6844 outs() << "(not in an __OBJC section)\n";
6845 }
6846 }
6847 }
6848 const SectionRef II = get_section(O, segname: "__OBJC", sectname: "__image_info");
6849 if (II != SectionRef())
6850 print_image_info(S: II, info: &info);
6851
6852 return true;
6853}
6854
6855static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6856 uint32_t size, uint32_t addr) {
6857 SymbolAddressMap AddrMap;
6858 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6859
6860 std::vector<SectionRef> Sections;
6861 append_range(C&: Sections, R: O->sections());
6862
6863 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6864
6865 const char *p;
6866 struct objc_protocol_t protocol;
6867 uint32_t left, paddr;
6868 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6869 memset(s: &protocol, c: '\0', n: sizeof(struct objc_protocol_t));
6870 left = size - (p - sect);
6871 if (left < sizeof(struct objc_protocol_t)) {
6872 outs() << "Protocol extends past end of __protocol section\n";
6873 memcpy(dest: &protocol, src: p, n: left);
6874 } else
6875 memcpy(dest: &protocol, src: p, n: sizeof(struct objc_protocol_t));
6876 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6877 swapStruct(protocol);
6878 paddr = addr + (p - sect);
6879 outs() << "Protocol " << format(Fmt: "0x%" PRIx32, Vals: paddr);
6880 if (print_protocol(p: paddr, indent: 0, info: &info))
6881 outs() << "(not in an __OBJC section)\n";
6882 }
6883}
6884
6885static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6886 if (O->is64Bit())
6887 printObjc2_64bit_MetaData(O, verbose);
6888 else {
6889 MachO::mach_header H;
6890 H = O->getHeader();
6891 if (H.cputype == MachO::CPU_TYPE_ARM)
6892 printObjc2_32bit_MetaData(O, verbose);
6893 else {
6894 // This is the 32-bit non-arm cputype case. Which is normally
6895 // the first Objective-C ABI. But it may be the case of a
6896 // binary for the iOS simulator which is the second Objective-C
6897 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6898 // and return false.
6899 if (!printObjc1_32bit_MetaData(O, verbose))
6900 printObjc2_32bit_MetaData(O, verbose);
6901 }
6902 }
6903}
6904
6905// GuessLiteralPointer returns a string which for the item in the Mach-O file
6906// for the address passed in as ReferenceValue for printing as a comment with
6907// the instruction and also returns the corresponding type of that item
6908// indirectly through ReferenceType.
6909//
6910// If ReferenceValue is an address of literal cstring then a pointer to the
6911// cstring is returned and ReferenceType is set to
6912// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6913//
6914// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6915// Class ref that name is returned and the ReferenceType is set accordingly.
6916//
6917// Lastly, literals which are Symbol address in a literal pool are looked for
6918// and if found the symbol name is returned and ReferenceType is set to
6919// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6920//
6921// If there is no item in the Mach-O file for the address passed in as
6922// ReferenceValue nullptr is returned and ReferenceType is unchanged.
6923static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6924 uint64_t ReferencePC,
6925 uint64_t *ReferenceType,
6926 struct DisassembleInfo *info) {
6927 // First see if there is an external relocation entry at the ReferencePC.
6928 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6929 uint64_t sect_addr = info->S.getAddress();
6930 uint64_t sect_offset = ReferencePC - sect_addr;
6931 bool reloc_found = false;
6932 DataRefImpl Rel;
6933 MachO::any_relocation_info RE;
6934 bool isExtern = false;
6935 SymbolRef Symbol;
6936 for (const RelocationRef &Reloc : info->S.relocations()) {
6937 uint64_t RelocOffset = Reloc.getOffset();
6938 if (RelocOffset == sect_offset) {
6939 Rel = Reloc.getRawDataRefImpl();
6940 RE = info->O->getRelocation(Rel);
6941 if (info->O->isRelocationScattered(RE))
6942 continue;
6943 isExtern = info->O->getPlainRelocationExternal(RE);
6944 if (isExtern) {
6945 symbol_iterator RelocSym = Reloc.getSymbol();
6946 Symbol = *RelocSym;
6947 }
6948 reloc_found = true;
6949 break;
6950 }
6951 }
6952 // If there is an external relocation entry for a symbol in a section
6953 // then used that symbol's value for the value of the reference.
6954 if (reloc_found && isExtern) {
6955 if (info->O->getAnyRelocationPCRel(RE)) {
6956 unsigned Type = info->O->getAnyRelocationType(RE);
6957 if (Type == MachO::X86_64_RELOC_SIGNED) {
6958 ReferenceValue = cantFail(ValOrErr: Symbol.getValue());
6959 }
6960 }
6961 }
6962 }
6963
6964 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6965 // Message refs and Class refs.
6966 bool classref, selref, msgref, cfstring;
6967 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6968 selref, msgref, cfstring);
6969 if (classref && pointer_value == 0) {
6970 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6971 // And the pointer_value in that section is typically zero as it will be
6972 // set by dyld as part of the "bind information".
6973 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6974 if (name != nullptr) {
6975 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6976 const char *class_name = strrchr(s: name, c: '$');
6977 if (class_name != nullptr && class_name[1] == '_' &&
6978 class_name[2] != '\0') {
6979 info->class_name = class_name + 2;
6980 return name;
6981 }
6982 }
6983 }
6984
6985 if (classref) {
6986 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6987 const char *name =
6988 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6989 if (name != nullptr)
6990 info->class_name = name;
6991 else
6992 name = "bad class ref";
6993 return name;
6994 }
6995
6996 if (cfstring) {
6997 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6998 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6999 return name;
7000 }
7001
7002 if (selref && pointer_value == 0)
7003 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
7004
7005 if (pointer_value != 0)
7006 ReferenceValue = pointer_value;
7007
7008 const char *name = GuessCstringPointer(ReferenceValue, info);
7009 if (name) {
7010 if (pointer_value != 0 && selref) {
7011 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
7012 info->selector_name = name;
7013 } else if (pointer_value != 0 && msgref) {
7014 info->class_name = nullptr;
7015 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
7016 info->selector_name = name;
7017 } else
7018 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
7019 return name;
7020 }
7021
7022 // Lastly look for an indirect symbol with this ReferenceValue which is in
7023 // a literal pool. If found return that symbol name.
7024 name = GuessIndirectSymbol(ReferenceValue, info);
7025 if (name) {
7026 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
7027 return name;
7028 }
7029
7030 return nullptr;
7031}
7032
7033// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
7034// the Symbolizer. It looks up the ReferenceValue using the info passed via the
7035// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
7036// is created and returns the symbol name that matches the ReferenceValue or
7037// nullptr if none. The ReferenceType is passed in for the IN type of
7038// reference the instruction is making from the values in defined in the header
7039// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
7040// Out type and the ReferenceName will also be set which is added as a comment
7041// to the disassembled instruction.
7042//
7043// If the symbol name is a C++ mangled name then the demangled name is
7044// returned through ReferenceName and ReferenceType is set to
7045// LLVMDisassembler_ReferenceType_DeMangled_Name .
7046//
7047// When this is called to get a symbol name for a branch target then the
7048// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7049// SymbolValue will be looked for in the indirect symbol table to determine if
7050// it is an address for a symbol stub. If so then the symbol name for that
7051// stub is returned indirectly through ReferenceName and then ReferenceType is
7052// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7053//
7054// When this is called with an value loaded via a PC relative load then
7055// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7056// SymbolValue is checked to be an address of literal pointer, symbol pointer,
7057// or an Objective-C meta data reference. If so the output ReferenceType is
7058// set to correspond to that as well as setting the ReferenceName.
7059static const char *SymbolizerSymbolLookUp(void *DisInfo,
7060 uint64_t ReferenceValue,
7061 uint64_t *ReferenceType,
7062 uint64_t ReferencePC,
7063 const char **ReferenceName) {
7064 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7065 // If no verbose symbolic information is wanted then just return nullptr.
7066 if (!info->verbose) {
7067 *ReferenceName = nullptr;
7068 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7069 return nullptr;
7070 }
7071
7072 const char *SymbolName = GuessSymbolName(value: ReferenceValue, AddrMap: info->AddrMap);
7073
7074 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7075 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7076 if (*ReferenceName != nullptr) {
7077 method_reference(info, ReferenceType, ReferenceName);
7078 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7079 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7080 } else if (SymbolName != nullptr && strncmp(s1: SymbolName, s2: "__Z", n: 3) == 0) {
7081 if (info->demangled_name != nullptr)
7082 free(ptr: info->demangled_name);
7083 info->demangled_name = itaniumDemangle(mangled_name: SymbolName + 1);
7084 if (info->demangled_name != nullptr) {
7085 *ReferenceName = info->demangled_name;
7086 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7087 } else
7088 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7089 } else
7090 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7091 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7092 *ReferenceName =
7093 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7094 if (*ReferenceName)
7095 method_reference(info, ReferenceType, ReferenceName);
7096 else
7097 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7098 // If this is arm64 and the reference is an adrp instruction save the
7099 // instruction, passed in ReferenceValue and the address of the instruction
7100 // for use later if we see and add immediate instruction.
7101 } else if ((info->O->getArch() == Triple::aarch64 ||
7102 info->O->getArch() == Triple::aarch64_32) &&
7103 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7104 info->adrp_inst = ReferenceValue;
7105 info->adrp_addr = ReferencePC;
7106 SymbolName = nullptr;
7107 *ReferenceName = nullptr;
7108 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7109 // If this is arm64 and reference is an add immediate instruction and we
7110 // have
7111 // seen an adrp instruction just before it and the adrp's Xd register
7112 // matches
7113 // this add's Xn register reconstruct the value being referenced and look to
7114 // see if it is a literal pointer. Note the add immediate instruction is
7115 // passed in ReferenceValue.
7116 } else if ((info->O->getArch() == Triple::aarch64 ||
7117 info->O->getArch() == Triple::aarch64_32) &&
7118 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7119 ReferencePC - 4 == info->adrp_addr &&
7120 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7121 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7122 uint32_t addxri_inst;
7123 uint64_t adrp_imm, addxri_imm;
7124
7125 adrp_imm =
7126 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7127 if (info->adrp_inst & 0x0200000)
7128 adrp_imm |= 0xfffffffffc000000LL;
7129
7130 addxri_inst = ReferenceValue;
7131 addxri_imm = (addxri_inst >> 10) & 0xfff;
7132 if (((addxri_inst >> 22) & 0x3) == 1)
7133 addxri_imm <<= 12;
7134
7135 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7136 (adrp_imm << 12) + addxri_imm;
7137
7138 *ReferenceName =
7139 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7140 if (*ReferenceName == nullptr)
7141 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7142 // If this is arm64 and the reference is a load register instruction and we
7143 // have seen an adrp instruction just before it and the adrp's Xd register
7144 // matches this add's Xn register reconstruct the value being referenced and
7145 // look to see if it is a literal pointer. Note the load register
7146 // instruction is passed in ReferenceValue.
7147 } else if ((info->O->getArch() == Triple::aarch64 ||
7148 info->O->getArch() == Triple::aarch64_32) &&
7149 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7150 ReferencePC - 4 == info->adrp_addr &&
7151 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7152 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7153 uint32_t ldrxui_inst;
7154 uint64_t adrp_imm, ldrxui_imm;
7155
7156 adrp_imm =
7157 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7158 if (info->adrp_inst & 0x0200000)
7159 adrp_imm |= 0xfffffffffc000000LL;
7160
7161 ldrxui_inst = ReferenceValue;
7162 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7163
7164 // The size field (bits [31:30]) determines the scaling.
7165 unsigned Scale = (ldrxui_inst >> 30) & 0x3;
7166 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7167 (adrp_imm << 12) + (ldrxui_imm << Scale);
7168
7169 *ReferenceName =
7170 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7171 if (*ReferenceName == nullptr)
7172 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7173 }
7174 // If this arm64 and is an load register (PC-relative) instruction the
7175 // ReferenceValue is the PC plus the immediate value.
7176 else if ((info->O->getArch() == Triple::aarch64 ||
7177 info->O->getArch() == Triple::aarch64_32) &&
7178 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7179 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7180 *ReferenceName =
7181 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7182 if (*ReferenceName == nullptr)
7183 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7184 } else if (SymbolName != nullptr && strncmp(s1: SymbolName, s2: "__Z", n: 3) == 0) {
7185 if (info->demangled_name != nullptr)
7186 free(ptr: info->demangled_name);
7187 info->demangled_name = itaniumDemangle(mangled_name: SymbolName + 1);
7188 if (info->demangled_name != nullptr) {
7189 *ReferenceName = info->demangled_name;
7190 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7191 }
7192 } else {
7193 *ReferenceName = nullptr;
7194 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7195 }
7196
7197 return SymbolName;
7198}
7199
7200/// Emits the comments that are stored in the CommentStream.
7201/// Each comment in the CommentStream must end with a newline.
7202static void emitComments(raw_svector_ostream &CommentStream,
7203 SmallString<128> &CommentsToEmit,
7204 formatted_raw_ostream &FormattedOS,
7205 const MCAsmInfo &MAI) {
7206 // Flush the stream before taking its content.
7207 StringRef Comments = CommentsToEmit.str();
7208 // Get the default information for printing a comment.
7209 StringRef CommentBegin = MAI.getCommentString();
7210 unsigned CommentColumn = MAI.getCommentColumn();
7211 ListSeparator LS("\n");
7212 while (!Comments.empty()) {
7213 FormattedOS << LS;
7214 // Emit a line of comments.
7215 FormattedOS.PadToColumn(NewCol: CommentColumn);
7216 size_t Position = Comments.find(C: '\n');
7217 FormattedOS << CommentBegin << ' ' << Comments.substr(Start: 0, N: Position);
7218 // Move after the newline character.
7219 Comments = Comments.substr(Start: Position + 1);
7220 }
7221 FormattedOS.flush();
7222
7223 // Tell the comment stream that the vector changed underneath it.
7224 CommentsToEmit.clear();
7225}
7226
7227const MachOObjectFile *
7228objdump::getMachODSymObject(const MachOObjectFile *MachOOF, StringRef Filename,
7229 std::unique_ptr<Binary> &DSYMBinary,
7230 std::unique_ptr<MemoryBuffer> &DSYMBuf) {
7231 const MachOObjectFile *DbgObj = MachOOF;
7232 std::string DSYMPath;
7233
7234 // Auto-detect w/o --dsym.
7235 if (DSYMFile.empty()) {
7236 sys::fs::file_status DSYMStatus;
7237 Twine FilenameDSYM = Filename + ".dSYM";
7238 if (!status(path: FilenameDSYM, result&: DSYMStatus)) {
7239 if (sys::fs::is_directory(status: DSYMStatus)) {
7240 SmallString<1024> Path;
7241 FilenameDSYM.toVector(Out&: Path);
7242 sys::path::append(path&: Path, a: "Contents", b: "Resources", c: "DWARF",
7243 d: sys::path::filename(path: Filename));
7244 DSYMPath = std::string(Path);
7245 } else if (sys::fs::is_regular_file(status: DSYMStatus)) {
7246 DSYMPath = FilenameDSYM.str();
7247 }
7248 }
7249 }
7250
7251 if (DSYMPath.empty() && !DSYMFile.empty()) {
7252 // If DSYMPath is a .dSYM directory, append the Mach-O file.
7253 if (sys::fs::is_directory(Path: DSYMFile) &&
7254 sys::path::extension(path: DSYMFile) == ".dSYM") {
7255 SmallString<128> ShortName(sys::path::filename(path: DSYMFile));
7256 sys::path::replace_extension(path&: ShortName, extension: "");
7257 SmallString<1024> FullPath(DSYMFile);
7258 sys::path::append(path&: FullPath, a: "Contents", b: "Resources", c: "DWARF", d: ShortName);
7259 DSYMPath = FullPath.str();
7260 } else {
7261 DSYMPath = DSYMFile;
7262 }
7263 }
7264
7265 if (!DSYMPath.empty()) {
7266 // Load the file.
7267 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7268 MemoryBuffer::getFileOrSTDIN(Filename: DSYMPath);
7269 if (std::error_code EC = BufOrErr.getError()) {
7270 reportError(E: errorCodeToError(EC), FileName: DSYMPath);
7271 return nullptr;
7272 }
7273
7274 // We need to keep the file alive, because we're replacing DbgObj with it.
7275 DSYMBuf = std::move(BufOrErr.get());
7276
7277 Expected<std::unique_ptr<Binary>> BinaryOrErr =
7278 createBinary(Source: DSYMBuf->getMemBufferRef());
7279 if (!BinaryOrErr) {
7280 reportError(E: BinaryOrErr.takeError(), FileName: DSYMPath);
7281 return nullptr;
7282 }
7283
7284 // We need to keep the Binary alive with the buffer
7285 DSYMBinary = std::move(BinaryOrErr.get());
7286 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: DSYMBinary.get())) {
7287 // this is a Mach-O object file, use it
7288 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(Val: &*O)) {
7289 DbgObj = MachDSYM;
7290 } else {
7291 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
7292 << DSYMPath << " is not a Mach-O file type.\n";
7293 return nullptr;
7294 }
7295 } else if (auto *UB = dyn_cast<MachOUniversalBinary>(Val: DSYMBinary.get())) {
7296 // this is a Universal Binary, find a Mach-O for this architecture
7297 uint32_t CPUType, CPUSubType;
7298 const char *ArchFlag;
7299 if (MachOOF->is64Bit()) {
7300 const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7301 CPUType = H_64.cputype;
7302 CPUSubType = H_64.cpusubtype;
7303 } else {
7304 const MachO::mach_header H = MachOOF->getHeader();
7305 CPUType = H.cputype;
7306 CPUSubType = H.cpusubtype;
7307 }
7308 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, McpuDefault: nullptr,
7309 ArchFlag: &ArchFlag);
7310 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7311 UB->getMachOObjectForArch(ArchName: ArchFlag);
7312 if (!MachDSYM) {
7313 reportError(E: MachDSYM.takeError(), FileName: DSYMPath);
7314 return nullptr;
7315 }
7316
7317 // We need to keep the Binary alive with the buffer
7318 DbgObj = &*MachDSYM.get();
7319 DSYMBinary = std::move(*MachDSYM);
7320 } else {
7321 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
7322 << DSYMPath << " is not a Mach-O or Universal file type.\n";
7323 return nullptr;
7324 }
7325 }
7326 return DbgObj;
7327}
7328
7329static bool shouldInstPrinterUseColor() {
7330 switch (DisassemblyColor) {
7331 case ColorOutput::Enable:
7332 return true;
7333 case ColorOutput::Auto:
7334 return outs().has_colors();
7335 case ColorOutput::Disable:
7336 case ColorOutput::Invalid:
7337 return false;
7338 }
7339 return false;
7340}
7341
7342static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7343 StringRef DisSegName, StringRef DisSectName) {
7344 const char *McpuDefault = nullptr;
7345 const Target *ThumbTarget = nullptr;
7346 Triple ThumbTriple;
7347 const Target *TheTarget =
7348 GetTarget(MachOObj: MachOOF, McpuDefault: &McpuDefault, ThumbTarget: &ThumbTarget, ThumbTriple);
7349 if (!TheTarget) {
7350 // GetTarget prints out stuff.
7351 return;
7352 }
7353 std::string MachOMCPU;
7354 if (MCPU.empty() && McpuDefault)
7355 MachOMCPU = McpuDefault;
7356 else
7357 MachOMCPU = MCPU;
7358
7359#define CHECK_TARGET_INFO_CREATION(NAME) \
7360 do { \
7361 if (!NAME) { \
7362 WithColor::error(errs(), "llvm-objdump") \
7363 << "couldn't initialize disassembler for target " << TripleName \
7364 << '\n'; \
7365 return; \
7366 } \
7367 } while (false)
7368#define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \
7369 do { \
7370 if (!NAME) { \
7371 WithColor::error(errs(), "llvm-objdump") \
7372 << "couldn't initialize disassembler for target " << ThumbTripleName \
7373 << '\n'; \
7374 return; \
7375 } \
7376 } while (false)
7377
7378 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7379 CHECK_TARGET_INFO_CREATION(InstrInfo);
7380 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7381 if (ThumbTarget) {
7382 ThumbInstrInfo.reset(p: ThumbTarget->createMCInstrInfo());
7383 CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7384 }
7385
7386 // Package up features to be passed to target/subtarget
7387 std::string FeaturesStr;
7388 if (!MAttrs.empty()) {
7389 SubtargetFeatures Features;
7390 for (unsigned i = 0; i != MAttrs.size(); ++i)
7391 Features.AddFeature(String: MAttrs[i]);
7392 FeaturesStr = Features.getString();
7393 }
7394
7395 Triple TheTriple(TripleName);
7396
7397 MCTargetOptions MCOptions;
7398 // Set up disassembler.
7399 std::unique_ptr<const MCRegisterInfo> MRI(
7400 TheTarget->createMCRegInfo(TT: TheTriple));
7401 CHECK_TARGET_INFO_CREATION(MRI);
7402 std::unique_ptr<const MCAsmInfo> AsmInfo(
7403 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
7404 CHECK_TARGET_INFO_CREATION(AsmInfo);
7405 std::unique_ptr<const MCSubtargetInfo> STI(
7406 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MachOMCPU, Features: FeaturesStr));
7407 CHECK_TARGET_INFO_CREATION(STI);
7408 MCContext Ctx(TheTriple, *AsmInfo, *MRI, *STI);
7409 std::unique_ptr<MCDisassembler> DisAsm(
7410 TheTarget->createMCDisassembler(STI: *STI, Ctx));
7411 CHECK_TARGET_INFO_CREATION(DisAsm);
7412 std::unique_ptr<MCSymbolizer> Symbolizer;
7413 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7414 std::unique_ptr<MCRelocationInfo> RelInfo(
7415 TheTarget->createMCRelocationInfo(TT: TheTriple, Ctx));
7416 if (RelInfo) {
7417 Symbolizer.reset(p: TheTarget->createMCSymbolizer(
7418 TT: TheTriple, GetOpInfo: SymbolizerGetOpInfo, SymbolLookUp: SymbolizerSymbolLookUp, DisInfo: &SymbolizerInfo,
7419 Ctx: &Ctx, RelInfo: std::move(RelInfo)));
7420 DisAsm->setSymbolizer(std::move(Symbolizer));
7421 }
7422 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7423 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7424 T: TheTriple, SyntaxVariant: AsmPrinterVariant, MAI: *AsmInfo, MII: *InstrInfo, MRI: *MRI));
7425 CHECK_TARGET_INFO_CREATION(IP);
7426 IP->setPrintImmHex(PrintImmHex);
7427 IP->setUseColor(shouldInstPrinterUseColor());
7428
7429 // Comment stream and backing vector.
7430 SmallString<128> CommentsToEmit;
7431 raw_svector_ostream CommentStream(CommentsToEmit);
7432 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7433 // if it is done then arm64 comments for string literals don't get printed
7434 // and some constant get printed instead and not setting it causes intel
7435 // (32-bit and 64-bit) comments printed with different spacing before the
7436 // comment causing different diffs with the 'C' disassembler library API.
7437 // IP->setCommentStream(CommentStream);
7438
7439 for (StringRef Opt : DisassemblerOptions)
7440 if (!IP->applyTargetSpecificCLOption(Opt))
7441 reportError(File: Filename, Message: "unrecognized disassembler option: " + Opt);
7442
7443 // Set up separate thumb disassembler if needed.
7444 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7445 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7446 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7447 std::unique_ptr<MCDisassembler> ThumbDisAsm;
7448 std::unique_ptr<MCInstPrinter> ThumbIP;
7449 std::unique_ptr<MCContext> ThumbCtx;
7450 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7451 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7452 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7453 if (ThumbTarget) {
7454 ThumbMRI.reset(p: ThumbTarget->createMCRegInfo(TT: ThumbTriple));
7455 CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7456 ThumbAsmInfo.reset(
7457 p: ThumbTarget->createMCAsmInfo(MRI: *ThumbMRI, TheTriple: ThumbTriple, Options: MCOptions));
7458 CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7459 ThumbSTI.reset(p: ThumbTarget->createMCSubtargetInfo(TheTriple: ThumbTriple, CPU: MachOMCPU,
7460 Features: FeaturesStr));
7461 CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7462 ThumbCtx.reset(
7463 p: new MCContext(ThumbTriple, *ThumbAsmInfo, *ThumbMRI, *ThumbSTI));
7464 ThumbDisAsm.reset(p: ThumbTarget->createMCDisassembler(STI: *ThumbSTI, Ctx&: *ThumbCtx));
7465 CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7466 MCContext *PtrThumbCtx = ThumbCtx.get();
7467 ThumbRelInfo.reset(
7468 p: ThumbTarget->createMCRelocationInfo(TT: ThumbTriple, Ctx&: *PtrThumbCtx));
7469 if (ThumbRelInfo) {
7470 ThumbSymbolizer.reset(p: ThumbTarget->createMCSymbolizer(
7471 TT: ThumbTriple, GetOpInfo: SymbolizerGetOpInfo, SymbolLookUp: SymbolizerSymbolLookUp,
7472 DisInfo: &ThumbSymbolizerInfo, Ctx: PtrThumbCtx, RelInfo: std::move(ThumbRelInfo)));
7473 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7474 }
7475 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7476 ThumbIP.reset(p: ThumbTarget->createMCInstPrinter(
7477 T: ThumbTriple, SyntaxVariant: ThumbAsmPrinterVariant, MAI: *ThumbAsmInfo, MII: *ThumbInstrInfo,
7478 MRI: *ThumbMRI));
7479 CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7480 ThumbIP->setPrintImmHex(PrintImmHex);
7481 ThumbIP->setUseColor(shouldInstPrinterUseColor());
7482 }
7483
7484#undef CHECK_TARGET_INFO_CREATION
7485#undef CHECK_THUMB_TARGET_INFO_CREATION
7486
7487 MachO::mach_header Header = MachOOF->getHeader();
7488
7489 // FIXME: Using the -cfg command line option, this code used to be able to
7490 // annotate relocations with the referenced symbol's name, and if this was
7491 // inside a __[cf]string section, the data it points to. This is now replaced
7492 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7493 std::vector<SectionRef> Sections;
7494 std::vector<SymbolRef> Symbols;
7495 SmallVector<uint64_t, 8> FoundFns;
7496 uint64_t BaseSegmentAddress = 0;
7497
7498 getSectionsAndSymbols(MachOObj: MachOOF, Sections, Symbols, FoundFns,
7499 BaseSegmentAddress);
7500
7501 // Sort the symbols by address, just in case they didn't come in that way.
7502 llvm::stable_sort(Range&: Symbols, C: SymbolSorter());
7503
7504 // Build a data in code table that is sorted on by the address of each entry.
7505 uint64_t BaseAddress = 0;
7506 if (Header.filetype == MachO::MH_OBJECT)
7507 BaseAddress = Sections[0].getAddress();
7508 else
7509 BaseAddress = BaseSegmentAddress;
7510 DiceTable Dices;
7511 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7512 DI != DE; ++DI) {
7513 uint32_t Offset;
7514 DI->getOffset(Result&: Offset);
7515 Dices.push_back(x: std::make_pair(x: BaseAddress + Offset, y: *DI));
7516 }
7517 array_pod_sort(Start: Dices.begin(), End: Dices.end());
7518
7519 // Try to find debug info and set up the DIContext for it.
7520 std::unique_ptr<DIContext> diContext;
7521 std::unique_ptr<Binary> DSYMBinary;
7522 std::unique_ptr<MemoryBuffer> DSYMBuf;
7523 const ObjectFile *DbgObj = MachOOF;
7524 if (UseDbg || PrintSource || PrintLines) {
7525 // Look for debug info in external dSYM file or embedded in the object.
7526 // getMachODSymObject returns MachOOF by default if no external dSYM found.
7527 const ObjectFile *DSym =
7528 getMachODSymObject(MachOOF, Filename, DSYMBinary, DSYMBuf);
7529 if (!DSym)
7530 return;
7531 DbgObj = DSym;
7532 if (UseDbg || PrintLines) {
7533 // Setup the DIContext
7534 diContext = DWARFContext::create(Obj: *DbgObj);
7535 }
7536 }
7537
7538 std::optional<SourcePrinter> SP;
7539 std::optional<LiveElementPrinter> LEP;
7540 if (PrintSource || PrintLines) {
7541 SP.emplace(args&: DbgObj, args: TheTarget->getName());
7542 LEP.emplace(args: *MRI, args: *STI);
7543 }
7544
7545 if (FilterSections.empty())
7546 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7547
7548 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7549 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7550 if (!SecNameOrErr) {
7551 consumeError(Err: SecNameOrErr.takeError());
7552 continue;
7553 }
7554 if (*SecNameOrErr != DisSectName)
7555 continue;
7556
7557 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7558
7559 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(Sec: DR);
7560 if (SegmentName != DisSegName)
7561 continue;
7562
7563 StringRef BytesStr =
7564 unwrapOrError(EO: Sections[SectIdx].getContents(), Args&: Filename);
7565 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(Input: BytesStr);
7566 uint64_t SectAddress = Sections[SectIdx].getAddress();
7567
7568 bool symbolTableWorked = false;
7569
7570 // Create a map of symbol addresses to symbol names for use by
7571 // the SymbolizerSymbolLookUp() routine.
7572 SymbolAddressMap AddrMap;
7573 bool DisSymNameFound = false;
7574 for (const SymbolRef &Symbol : MachOOF->symbols()) {
7575 SymbolRef::Type ST =
7576 unwrapOrError(EO: Symbol.getType(), Args: MachOOF->getFileName());
7577 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7578 ST == SymbolRef::ST_Other) {
7579 uint64_t Address = cantFail(ValOrErr: Symbol.getValue());
7580 StringRef SymName =
7581 unwrapOrError(EO: Symbol.getName(), Args: MachOOF->getFileName());
7582 AddrMap[Address] = SymName;
7583 if (!DisSymName.empty() && DisSymName == SymName)
7584 DisSymNameFound = true;
7585 }
7586 }
7587 if (!DisSymName.empty() && !DisSymNameFound) {
7588 outs() << "Can't find " << (IsOtool ? "-p symbol" : "--dis-symname")
7589 << ": " << DisSymName << "\n";
7590 return;
7591 }
7592 // Set up the block of info used by the Symbolizer call backs.
7593 SymbolizerInfo.verbose = SymbolicOperands;
7594 SymbolizerInfo.O = MachOOF;
7595 SymbolizerInfo.S = Sections[SectIdx];
7596 SymbolizerInfo.AddrMap = &AddrMap;
7597 SymbolizerInfo.Sections = &Sections;
7598 // Same for the ThumbSymbolizer
7599 ThumbSymbolizerInfo.verbose = SymbolicOperands;
7600 ThumbSymbolizerInfo.O = MachOOF;
7601 ThumbSymbolizerInfo.S = Sections[SectIdx];
7602 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7603 ThumbSymbolizerInfo.Sections = &Sections;
7604
7605 unsigned int Arch = MachOOF->getArch();
7606
7607 // Skip all symbols if this is a stubs file.
7608 if (Bytes.empty())
7609 return;
7610
7611 // If the section has symbols but no symbol at the start of the section
7612 // these are used to make sure the bytes before the first symbol are
7613 // disassembled.
7614 bool FirstSymbol = true;
7615 bool FirstSymbolAtSectionStart = true;
7616
7617 // Disassemble symbol by symbol.
7618 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7619 StringRef SymName =
7620 unwrapOrError(EO: Symbols[SymIdx].getName(), Args: MachOOF->getFileName());
7621 SymbolRef::Type ST =
7622 unwrapOrError(EO: Symbols[SymIdx].getType(), Args: MachOOF->getFileName());
7623 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7624 continue;
7625
7626 // Make sure the symbol is defined in this section.
7627 bool containsSym = Sections[SectIdx].containsSymbol(S: Symbols[SymIdx]);
7628 if (!containsSym) {
7629 if (!DisSymName.empty() && DisSymName == SymName) {
7630 outs() << (IsOtool ? "-p symbol" : "--dis-symname") << ": "
7631 << DisSymName << " not in the section\n";
7632 return;
7633 }
7634 continue;
7635 }
7636 // The __mh_execute_header is special and we need to deal with that fact
7637 // this symbol is before the start of the (__TEXT,__text) section and at the
7638 // address of the start of the __TEXT segment. This is because this symbol
7639 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7640 // start of the section in a standard MH_EXECUTE filetype.
7641 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7642 outs() << (IsOtool ? "-p symbol" : "--dis-symname")
7643 << ": __mh_execute_header not in any section\n";
7644 return;
7645 }
7646 // When this code is trying to disassemble a symbol at a time and in the
7647 // case there is only the __mh_execute_header symbol left as in a stripped
7648 // executable, we need to deal with this by ignoring this symbol so the
7649 // whole section is disassembled and this symbol is then not displayed.
7650 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7651 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7652 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7653 continue;
7654
7655 // If we are only disassembling one symbol see if this is that symbol.
7656 if (!DisSymName.empty() && DisSymName != SymName)
7657 continue;
7658
7659 // Start at the address of the symbol relative to the section's address.
7660 uint64_t SectSize = Sections[SectIdx].getSize();
7661 uint64_t Start = cantFail(ValOrErr: Symbols[SymIdx].getValue());
7662 uint64_t SectionAddress = Sections[SectIdx].getAddress();
7663 Start -= SectionAddress;
7664
7665 if (Start > SectSize) {
7666 outs() << "section data ends, " << SymName
7667 << " lies outside valid range\n";
7668 return;
7669 }
7670
7671 // Stop disassembling either at the beginning of the next symbol or at
7672 // the end of the section.
7673 bool containsNextSym = false;
7674 uint64_t NextSym = 0;
7675 uint64_t NextSymIdx = SymIdx + 1;
7676 while (Symbols.size() > NextSymIdx) {
7677 SymbolRef::Type NextSymType = unwrapOrError(
7678 EO: Symbols[NextSymIdx].getType(), Args: MachOOF->getFileName());
7679 if (NextSymType == SymbolRef::ST_Function) {
7680 containsNextSym =
7681 Sections[SectIdx].containsSymbol(S: Symbols[NextSymIdx]);
7682 NextSym = cantFail(ValOrErr: Symbols[NextSymIdx].getValue());
7683 NextSym -= SectionAddress;
7684 break;
7685 }
7686 ++NextSymIdx;
7687 }
7688
7689 uint64_t End = containsNextSym ? std::min(a: NextSym, b: SectSize) : SectSize;
7690 uint64_t Size;
7691
7692 symbolTableWorked = true;
7693
7694 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7695 uint32_t SymbolFlags = cantFail(ValOrErr: MachOOF->getSymbolFlags(Symb));
7696 bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7697
7698 // We only need the dedicated Thumb target if there's a real choice
7699 // (i.e. we're not targeting M-class) and the function is Thumb.
7700 bool UseThumbTarget = IsThumb && ThumbTarget;
7701
7702 // If we are not specifying a symbol to start disassembly with and this
7703 // is the first symbol in the section but not at the start of the section
7704 // then move the disassembly index to the start of the section and
7705 // don't print the symbol name just yet. This is so the bytes before the
7706 // first symbol are disassembled.
7707 uint64_t SymbolStart = Start;
7708 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7709 FirstSymbolAtSectionStart = false;
7710 Start = 0;
7711 }
7712 else
7713 outs() << SymName << ":\n";
7714
7715 DILineInfo lastLine;
7716 for (uint64_t Index = Start; Index < End; Index += Size) {
7717 MCInst Inst;
7718
7719 // If this is the first symbol in the section and it was not at the
7720 // start of the section, see if we are at its Index now and if so print
7721 // the symbol name.
7722 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7723 outs() << SymName << ":\n";
7724
7725 uint64_t PC = SectAddress + Index;
7726
7727 if (PrintSource || PrintLines) {
7728 formatted_raw_ostream FOS(outs());
7729 SP->printSourceLine(OS&: FOS, Address: {.Address: PC, .SectionIndex: SectIdx}, ObjectFilename: Filename, LEP&: *LEP);
7730 }
7731
7732 if (LeadingAddr) {
7733 if (FullLeadingAddr) {
7734 if (MachOOF->is64Bit())
7735 outs() << format(Fmt: "%016" PRIx64, Vals: PC);
7736 else
7737 outs() << format(Fmt: "%08" PRIx64, Vals: PC);
7738 } else {
7739 outs() << format(Fmt: "%8" PRIx64 ":", Vals: PC);
7740 }
7741 }
7742 if (ShowRawInsn || Arch == Triple::arm)
7743 outs() << "\t";
7744
7745 if (DumpAndSkipDataInCode(PC, bytes: Bytes.data() + Index, Dices, InstSize&: Size))
7746 continue;
7747
7748 SmallVector<char, 64> AnnotationsBytes;
7749 raw_svector_ostream Annotations(AnnotationsBytes);
7750
7751 bool gotInst;
7752 if (UseThumbTarget)
7753 gotInst = ThumbDisAsm->getInstruction(Instr&: Inst, Size, Bytes: Bytes.slice(N: Index),
7754 Address: PC, CStream&: Annotations);
7755 else
7756 gotInst = DisAsm->getInstruction(Instr&: Inst, Size, Bytes: Bytes.slice(N: Index), Address: PC,
7757 CStream&: Annotations);
7758 if (gotInst) {
7759 if (ShowRawInsn || Arch == Triple::arm) {
7760 dumpBytes(Bytes: ArrayRef(Bytes.data() + Index, Size), OS&: outs());
7761 }
7762 formatted_raw_ostream FormattedOS(outs());
7763 StringRef AnnotationsStr = Annotations.str();
7764 if (UseThumbTarget)
7765 ThumbIP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *ThumbSTI,
7766 OS&: FormattedOS);
7767 else
7768 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *STI, OS&: FormattedOS);
7769 emitComments(CommentStream, CommentsToEmit, FormattedOS, MAI: *AsmInfo);
7770
7771 // Print debug info.
7772 if (diContext) {
7773 DILineInfo dli = diContext->getLineInfoForAddress(Address: {.Address: PC, .SectionIndex: SectIdx})
7774 .value_or(u: DILineInfo());
7775 // Print valid line info if it changed.
7776 if (dli != lastLine && dli.Line != 0)
7777 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7778 << dli.Column;
7779 lastLine = dli;
7780 }
7781 outs() << "\n";
7782 } else {
7783 if (MachOOF->getArchTriple().isX86()) {
7784 outs() << format(Fmt: "\t.byte 0x%02x #bad opcode\n",
7785 Vals: *(Bytes.data() + Index) & 0xff);
7786 Size = 1; // skip exactly one illegible byte and move on.
7787 } else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32 ||
7788 (Arch == Triple::arm && !IsThumb)) {
7789 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7790 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7791 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7792 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7793 outs() << format(Fmt: "\t.long\t0x%08x\n", Vals: opcode);
7794 Size = 4;
7795 } else if (Arch == Triple::arm) {
7796 assert(IsThumb && "ARM mode should have been dealt with above");
7797 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7798 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7799 outs() << format(Fmt: "\t.short\t0x%04x\n", Vals: opcode);
7800 Size = 2;
7801 } else {
7802 WithColor::warning(OS&: errs(), Prefix: "llvm-objdump")
7803 << "invalid instruction encoding\n";
7804 if (Size == 0)
7805 Size = 1; // skip illegible bytes
7806 }
7807 }
7808 }
7809 // Now that we are done disassembled the first symbol set the bool that
7810 // were doing this to false.
7811 FirstSymbol = false;
7812 }
7813 if (!symbolTableWorked) {
7814 // Reading the symbol table didn't work, disassemble the whole section.
7815 uint64_t SectAddress = Sections[SectIdx].getAddress();
7816 uint64_t SectSize = Sections[SectIdx].getSize();
7817 uint64_t InstSize;
7818 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7819 MCInst Inst;
7820
7821 uint64_t PC = SectAddress + Index;
7822
7823 if (PrintSource || PrintLines) {
7824 formatted_raw_ostream FOS(outs());
7825 SP->printSourceLine(OS&: FOS, Address: {.Address: PC, .SectionIndex: SectIdx}, ObjectFilename: Filename, LEP&: *LEP);
7826 }
7827
7828 if (DumpAndSkipDataInCode(PC, bytes: Bytes.data() + Index, Dices, InstSize))
7829 continue;
7830
7831 SmallVector<char, 64> AnnotationsBytes;
7832 raw_svector_ostream Annotations(AnnotationsBytes);
7833 if (DisAsm->getInstruction(Instr&: Inst, Size&: InstSize, Bytes: Bytes.slice(N: Index), Address: PC,
7834 CStream&: Annotations)) {
7835 if (LeadingAddr) {
7836 if (FullLeadingAddr) {
7837 if (MachOOF->is64Bit())
7838 outs() << format(Fmt: "%016" PRIx64, Vals: PC);
7839 else
7840 outs() << format(Fmt: "%08" PRIx64, Vals: PC);
7841 } else {
7842 outs() << format(Fmt: "%8" PRIx64 ":", Vals: PC);
7843 }
7844 }
7845 if (ShowRawInsn || Arch == Triple::arm) {
7846 outs() << "\t";
7847 dumpBytes(Bytes: ArrayRef(Bytes.data() + Index, InstSize), OS&: outs());
7848 }
7849 StringRef AnnotationsStr = Annotations.str();
7850 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *STI, OS&: outs());
7851 outs() << "\n";
7852 } else {
7853 if (MachOOF->getArchTriple().isX86()) {
7854 outs() << format(Fmt: "\t.byte 0x%02x #bad opcode\n",
7855 Vals: *(Bytes.data() + Index) & 0xff);
7856 InstSize = 1; // skip exactly one illegible byte and move on.
7857 } else {
7858 WithColor::warning(OS&: errs(), Prefix: "llvm-objdump")
7859 << "invalid instruction encoding\n";
7860 if (InstSize == 0)
7861 InstSize = 1; // skip illegible bytes
7862 }
7863 }
7864 }
7865 }
7866 // The TripleName's need to be reset if we are called again for a different
7867 // architecture.
7868 TripleName = "";
7869 ThumbTripleName = "";
7870
7871 if (SymbolizerInfo.demangled_name != nullptr)
7872 free(ptr: SymbolizerInfo.demangled_name);
7873 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7874 free(ptr: ThumbSymbolizerInfo.demangled_name);
7875 }
7876}
7877
7878//===----------------------------------------------------------------------===//
7879// __compact_unwind section dumping
7880//===----------------------------------------------------------------------===//
7881
7882namespace {
7883
7884template <typename T>
7885static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7886 if (Offset + sizeof(T) > Contents.size()) {
7887 outs() << "warning: attempt to read past end of buffer\n";
7888 return T();
7889 }
7890
7891 uint64_t Val = support::endian::read<T, llvm::endianness::little>(
7892 Contents.data() + Offset);
7893 return Val;
7894}
7895
7896template <typename T>
7897static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7898 T Val = read<T>(Contents, Offset);
7899 Offset += sizeof(T);
7900 return Val;
7901}
7902
7903struct CompactUnwindEntry {
7904 uint32_t OffsetInSection;
7905
7906 uint64_t FunctionAddr;
7907 uint32_t Length;
7908 uint32_t CompactEncoding;
7909 uint64_t PersonalityAddr;
7910 uint64_t LSDAAddr;
7911
7912 RelocationRef FunctionReloc;
7913 RelocationRef PersonalityReloc;
7914 RelocationRef LSDAReloc;
7915
7916 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7917 : OffsetInSection(Offset) {
7918 if (Is64)
7919 read<uint64_t>(Contents, Offset);
7920 else
7921 read<uint32_t>(Contents, Offset);
7922 }
7923
7924private:
7925 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7926 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7927 Length = readNext<uint32_t>(Contents, Offset);
7928 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7929 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7930 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7931 }
7932};
7933}
7934
7935/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7936/// and data being relocated, determine the best base Name and Addend to use for
7937/// display purposes.
7938///
7939/// 1. An Extern relocation will directly reference a symbol (and the data is
7940/// then already an addend), so use that.
7941/// 2. Otherwise the data is an offset in the object file's layout; try to find
7942// a symbol before it in the same section, and use the offset from there.
7943/// 3. Finally, if all that fails, fall back to an offset from the start of the
7944/// referenced section.
7945static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7946 std::map<uint64_t, SymbolRef> &Symbols,
7947 const RelocationRef &Reloc, uint64_t Addr,
7948 StringRef &Name, uint64_t &Addend) {
7949 if (Reloc.getSymbol() != Obj->symbol_end()) {
7950 Name = unwrapOrError(EO: Reloc.getSymbol()->getName(), Args: Obj->getFileName());
7951 Addend = Addr;
7952 return;
7953 }
7954
7955 auto RE = Obj->getRelocation(Rel: Reloc.getRawDataRefImpl());
7956 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7957
7958 uint64_t SectionAddr = RelocSection.getAddress();
7959
7960 auto Sym = Symbols.upper_bound(x: Addr);
7961 if (Sym == Symbols.begin()) {
7962 // The first symbol in the object is after this reference, the best we can
7963 // do is section-relative notation.
7964 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7965 Name = *NameOrErr;
7966 else
7967 consumeError(Err: NameOrErr.takeError());
7968
7969 Addend = Addr - SectionAddr;
7970 return;
7971 }
7972
7973 // Go back one so that SymbolAddress <= Addr.
7974 --Sym;
7975
7976 section_iterator SymSection =
7977 unwrapOrError(EO: Sym->second.getSection(), Args: Obj->getFileName());
7978 if (RelocSection == *SymSection) {
7979 // There's a valid symbol in the same section before this reference.
7980 Name = unwrapOrError(EO: Sym->second.getName(), Args: Obj->getFileName());
7981 Addend = Addr - Sym->first;
7982 return;
7983 }
7984
7985 // There is a symbol before this reference, but it's in a different
7986 // section. Probably not helpful to mention it, so use the section name.
7987 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7988 Name = *NameOrErr;
7989 else
7990 consumeError(Err: NameOrErr.takeError());
7991
7992 Addend = Addr - SectionAddr;
7993}
7994
7995static void printUnwindRelocDest(const MachOObjectFile *Obj,
7996 std::map<uint64_t, SymbolRef> &Symbols,
7997 const RelocationRef &Reloc, uint64_t Addr) {
7998 StringRef Name;
7999 uint64_t Addend;
8000
8001 if (!Reloc.getObject())
8002 return;
8003
8004 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
8005
8006 outs() << Name;
8007 if (Addend)
8008 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: Addend);
8009}
8010
8011static void
8012printMachOCompactUnwindSection(const MachOObjectFile *Obj,
8013 std::map<uint64_t, SymbolRef> &Symbols,
8014 const SectionRef &CompactUnwind) {
8015
8016 if (!Obj->isLittleEndian()) {
8017 outs() << "Skipping big-endian __compact_unwind section\n";
8018 return;
8019 }
8020
8021 bool Is64 = Obj->is64Bit();
8022 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
8023 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
8024
8025 StringRef Contents =
8026 unwrapOrError(EO: CompactUnwind.getContents(), Args: Obj->getFileName());
8027 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
8028
8029 // First populate the initial raw offsets, encodings and so on from the entry.
8030 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
8031 CompactUnwindEntry Entry(Contents, Offset, Is64);
8032 CompactUnwinds.push_back(Elt: Entry);
8033 }
8034
8035 // Next we need to look at the relocations to find out what objects are
8036 // actually being referred to.
8037 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
8038 uint64_t RelocAddress = Reloc.getOffset();
8039
8040 uint32_t EntryIdx = RelocAddress / EntrySize;
8041 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
8042 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
8043
8044 if (OffsetInEntry == 0)
8045 Entry.FunctionReloc = Reloc;
8046 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
8047 Entry.PersonalityReloc = Reloc;
8048 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
8049 Entry.LSDAReloc = Reloc;
8050 else {
8051 outs() << "Invalid relocation in __compact_unwind section\n";
8052 return;
8053 }
8054 }
8055
8056 // Finally, we're ready to print the data we've gathered.
8057 outs() << "Contents of __compact_unwind section:\n";
8058 for (auto &Entry : CompactUnwinds) {
8059 outs() << " Entry at offset "
8060 << format(Fmt: "0x%" PRIx32, Vals: Entry.OffsetInSection) << ":\n";
8061
8062 // 1. Start of the region this entry applies to.
8063 outs() << " start: " << format(Fmt: "0x%" PRIx64,
8064 Vals: Entry.FunctionAddr) << ' ';
8065 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.FunctionReloc, Addr: Entry.FunctionAddr);
8066 outs() << '\n';
8067
8068 // 2. Length of the region this entry applies to.
8069 outs() << " length: " << format(Fmt: "0x%" PRIx32, Vals: Entry.Length)
8070 << '\n';
8071 // 3. The 32-bit compact encoding.
8072 outs() << " compact encoding: "
8073 << format(Fmt: "0x%08" PRIx32, Vals: Entry.CompactEncoding) << '\n';
8074
8075 // 4. The personality function, if present.
8076 if (Entry.PersonalityReloc.getObject()) {
8077 outs() << " personality function: "
8078 << format(Fmt: "0x%" PRIx64, Vals: Entry.PersonalityAddr) << ' ';
8079 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.PersonalityReloc,
8080 Addr: Entry.PersonalityAddr);
8081 outs() << '\n';
8082 }
8083
8084 // 5. This entry's language-specific data area.
8085 if (Entry.LSDAReloc.getObject()) {
8086 outs() << " LSDA: " << format(Fmt: "0x%" PRIx64,
8087 Vals: Entry.LSDAAddr) << ' ';
8088 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.LSDAReloc, Addr: Entry.LSDAAddr);
8089 outs() << '\n';
8090 }
8091 }
8092}
8093
8094//===----------------------------------------------------------------------===//
8095// __unwind_info section dumping
8096//===----------------------------------------------------------------------===//
8097
8098static void printRegularSecondLevelUnwindPage(StringRef PageData) {
8099 ptrdiff_t Pos = 0;
8100 uint32_t Kind = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8101 (void)Kind;
8102 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
8103
8104 uint16_t EntriesStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8105 uint16_t NumEntries = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8106
8107 Pos = EntriesStart;
8108 for (unsigned i = 0; i < NumEntries; ++i) {
8109 uint32_t FunctionOffset = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8110 uint32_t Encoding = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8111
8112 outs() << " [" << i << "]: "
8113 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8114 << ", "
8115 << "encoding=" << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8116 }
8117}
8118
8119static void printCompressedSecondLevelUnwindPage(
8120 StringRef PageData, uint32_t FunctionBase,
8121 const SmallVectorImpl<uint32_t> &CommonEncodings) {
8122 ptrdiff_t Pos = 0;
8123 uint32_t Kind = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8124 (void)Kind;
8125 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8126
8127 uint32_t NumCommonEncodings = CommonEncodings.size();
8128 uint16_t EntriesStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8129 uint16_t NumEntries = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8130
8131 uint16_t PageEncodingsStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8132 uint16_t NumPageEncodings = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8133 SmallVector<uint32_t, 64> PageEncodings;
8134 if (NumPageEncodings) {
8135 outs() << " Page encodings: (count = " << NumPageEncodings << ")\n";
8136 Pos = PageEncodingsStart;
8137 for (unsigned i = 0; i < NumPageEncodings; ++i) {
8138 uint32_t Encoding = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8139 PageEncodings.push_back(Elt: Encoding);
8140 outs() << " encoding[" << (i + NumCommonEncodings)
8141 << "]: " << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8142 }
8143 }
8144
8145 Pos = EntriesStart;
8146 for (unsigned i = 0; i < NumEntries; ++i) {
8147 uint32_t Entry = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8148 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8149 uint32_t EncodingIdx = Entry >> 24;
8150
8151 uint32_t Encoding;
8152 if (EncodingIdx < NumCommonEncodings)
8153 Encoding = CommonEncodings[EncodingIdx];
8154 else
8155 Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
8156
8157 outs() << " [" << i << "]: "
8158 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8159 << ", "
8160 << "encoding[" << EncodingIdx
8161 << "]=" << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8162 }
8163}
8164
8165static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8166 std::map<uint64_t, SymbolRef> &Symbols,
8167 const SectionRef &UnwindInfo) {
8168
8169 if (!Obj->isLittleEndian()) {
8170 outs() << "Skipping big-endian __unwind_info section\n";
8171 return;
8172 }
8173
8174 outs() << "Contents of __unwind_info section:\n";
8175
8176 StringRef Contents =
8177 unwrapOrError(EO: UnwindInfo.getContents(), Args: Obj->getFileName());
8178 ptrdiff_t Pos = 0;
8179
8180 //===----------------------------------
8181 // Section header
8182 //===----------------------------------
8183
8184 uint32_t Version = readNext<uint32_t>(Contents, Offset&: Pos);
8185 outs() << " Version: "
8186 << format(Fmt: "0x%" PRIx32, Vals: Version) << '\n';
8187 if (Version != 1) {
8188 outs() << " Skipping section with unknown version\n";
8189 return;
8190 }
8191
8192 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Offset&: Pos);
8193 outs() << " Common encodings array section offset: "
8194 << format(Fmt: "0x%" PRIx32, Vals: CommonEncodingsStart) << '\n';
8195 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Offset&: Pos);
8196 outs() << " Number of common encodings in array: "
8197 << format(Fmt: "0x%" PRIx32, Vals: NumCommonEncodings) << '\n';
8198
8199 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Offset&: Pos);
8200 outs() << " Personality function array section offset: "
8201 << format(Fmt: "0x%" PRIx32, Vals: PersonalitiesStart) << '\n';
8202 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Offset&: Pos);
8203 outs() << " Number of personality functions in array: "
8204 << format(Fmt: "0x%" PRIx32, Vals: NumPersonalities) << '\n';
8205
8206 uint32_t IndicesStart = readNext<uint32_t>(Contents, Offset&: Pos);
8207 outs() << " Index array section offset: "
8208 << format(Fmt: "0x%" PRIx32, Vals: IndicesStart) << '\n';
8209 uint32_t NumIndices = readNext<uint32_t>(Contents, Offset&: Pos);
8210 outs() << " Number of indices in array: "
8211 << format(Fmt: "0x%" PRIx32, Vals: NumIndices) << '\n';
8212
8213 //===----------------------------------
8214 // A shared list of common encodings
8215 //===----------------------------------
8216
8217 // These occupy indices in the range [0, N] whenever an encoding is referenced
8218 // from a compressed 2nd level index table. In practice the linker only
8219 // creates ~128 of these, so that indices are available to embed encodings in
8220 // the 2nd level index.
8221
8222 SmallVector<uint32_t, 64> CommonEncodings;
8223 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
8224 Pos = CommonEncodingsStart;
8225 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8226 uint32_t Encoding = readNext<uint32_t>(Contents, Offset&: Pos);
8227 CommonEncodings.push_back(Elt: Encoding);
8228
8229 outs() << " encoding[" << i << "]: " << format(Fmt: "0x%08" PRIx32, Vals: Encoding)
8230 << '\n';
8231 }
8232
8233 //===----------------------------------
8234 // Personality functions used in this executable
8235 //===----------------------------------
8236
8237 // There should be only a handful of these (one per source language,
8238 // roughly). Particularly since they only get 2 bits in the compact encoding.
8239
8240 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
8241 Pos = PersonalitiesStart;
8242 for (unsigned i = 0; i < NumPersonalities; ++i) {
8243 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Offset&: Pos);
8244 outs() << " personality[" << i + 1
8245 << "]: " << format(Fmt: "0x%08" PRIx32, Vals: PersonalityFn) << '\n';
8246 }
8247
8248 //===----------------------------------
8249 // The level 1 index entries
8250 //===----------------------------------
8251
8252 // These specify an approximate place to start searching for the more detailed
8253 // information, sorted by PC.
8254
8255 struct IndexEntry {
8256 uint32_t FunctionOffset;
8257 uint32_t SecondLevelPageStart;
8258 uint32_t LSDAStart;
8259 };
8260
8261 SmallVector<IndexEntry, 4> IndexEntries;
8262
8263 outs() << " Top level indices: (count = " << NumIndices << ")\n";
8264 Pos = IndicesStart;
8265 for (unsigned i = 0; i < NumIndices; ++i) {
8266 IndexEntry Entry;
8267
8268 Entry.FunctionOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8269 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Offset&: Pos);
8270 Entry.LSDAStart = readNext<uint32_t>(Contents, Offset&: Pos);
8271 IndexEntries.push_back(Elt: Entry);
8272
8273 outs() << " [" << i << "]: "
8274 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: Entry.FunctionOffset)
8275 << ", "
8276 << "2nd level page offset="
8277 << format(Fmt: "0x%08" PRIx32, Vals: Entry.SecondLevelPageStart) << ", "
8278 << "LSDA offset=" << format(Fmt: "0x%08" PRIx32, Vals: Entry.LSDAStart) << '\n';
8279 }
8280
8281 //===----------------------------------
8282 // Next come the LSDA tables
8283 //===----------------------------------
8284
8285 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8286 // the first top-level index's LSDAOffset to the last (sentinel).
8287
8288 outs() << " LSDA descriptors:\n";
8289 Pos = IndexEntries[0].LSDAStart;
8290 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8291 int NumLSDAs =
8292 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8293
8294 for (int i = 0; i < NumLSDAs; ++i) {
8295 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8296 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8297 outs() << " [" << i << "]: "
8298 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8299 << ", "
8300 << "LSDA offset=" << format(Fmt: "0x%08" PRIx32, Vals: LSDAOffset) << '\n';
8301 }
8302
8303 //===----------------------------------
8304 // Finally, the 2nd level indices
8305 //===----------------------------------
8306
8307 // Generally these are 4K in size, and have 2 possible forms:
8308 // + Regular stores up to 511 entries with disparate encodings
8309 // + Compressed stores up to 1021 entries if few enough compact encoding
8310 // values are used.
8311 outs() << " Second level indices:\n";
8312 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8313 // The final sentinel top-level index has no associated 2nd level page
8314 if (IndexEntries[i].SecondLevelPageStart == 0)
8315 break;
8316
8317 outs() << " Second level index[" << i << "]: "
8318 << "offset in section="
8319 << format(Fmt: "0x%08" PRIx32, Vals: IndexEntries[i].SecondLevelPageStart)
8320 << ", "
8321 << "base function offset="
8322 << format(Fmt: "0x%08" PRIx32, Vals: IndexEntries[i].FunctionOffset) << '\n';
8323
8324 Pos = IndexEntries[i].SecondLevelPageStart;
8325 if (Pos + sizeof(uint32_t) > Contents.size()) {
8326 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8327 continue;
8328 }
8329
8330 uint32_t Kind =
8331 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8332 if (Kind == 2)
8333 printRegularSecondLevelUnwindPage(PageData: Contents.substr(Start: Pos, N: 4096));
8334 else if (Kind == 3)
8335 printCompressedSecondLevelUnwindPage(PageData: Contents.substr(Start: Pos, N: 4096),
8336 FunctionBase: IndexEntries[i].FunctionOffset,
8337 CommonEncodings);
8338 else
8339 outs() << " Skipping 2nd level page with unknown kind " << Kind
8340 << '\n';
8341 }
8342}
8343
8344void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8345 std::map<uint64_t, SymbolRef> Symbols;
8346 for (const SymbolRef &SymRef : Obj->symbols()) {
8347 // Discard any undefined or absolute symbols. They're not going to take part
8348 // in the convenience lookup for unwind info and just take up resources.
8349 auto SectOrErr = SymRef.getSection();
8350 if (!SectOrErr) {
8351 // TODO: Actually report errors helpfully.
8352 consumeError(Err: SectOrErr.takeError());
8353 continue;
8354 }
8355 section_iterator Section = *SectOrErr;
8356 if (Section == Obj->section_end())
8357 continue;
8358
8359 uint64_t Addr = cantFail(ValOrErr: SymRef.getValue());
8360 Symbols.insert(x: std::make_pair(x&: Addr, y: SymRef));
8361 }
8362
8363 for (const SectionRef &Section : Obj->sections()) {
8364 StringRef SectName;
8365 if (Expected<StringRef> NameOrErr = Section.getName())
8366 SectName = *NameOrErr;
8367 else
8368 consumeError(Err: NameOrErr.takeError());
8369
8370 if (SectName == "__compact_unwind")
8371 printMachOCompactUnwindSection(Obj, Symbols, CompactUnwind: Section);
8372 else if (SectName == "__unwind_info")
8373 printMachOUnwindInfoSection(Obj, Symbols, UnwindInfo: Section);
8374 }
8375}
8376
8377static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8378 uint32_t cpusubtype, uint32_t filetype,
8379 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8380 bool verbose) {
8381 outs() << "Mach header\n";
8382 outs() << " magic cputype cpusubtype caps filetype ncmds "
8383 "sizeofcmds flags\n";
8384 if (verbose) {
8385 if (magic == MachO::MH_MAGIC)
8386 outs() << " MH_MAGIC";
8387 else if (magic == MachO::MH_MAGIC_64)
8388 outs() << "MH_MAGIC_64";
8389 else
8390 outs() << format(Fmt: " 0x%08" PRIx32, Vals: magic);
8391 switch (cputype) {
8392 case MachO::CPU_TYPE_I386:
8393 outs() << " I386";
8394 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8395 case MachO::CPU_SUBTYPE_I386_ALL:
8396 outs() << " ALL";
8397 break;
8398 default:
8399 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8400 break;
8401 }
8402 break;
8403 case MachO::CPU_TYPE_X86_64:
8404 outs() << " X86_64";
8405 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8406 case MachO::CPU_SUBTYPE_X86_64_ALL:
8407 outs() << " ALL";
8408 break;
8409 case MachO::CPU_SUBTYPE_X86_64_H:
8410 outs() << " Haswell";
8411 break;
8412 default:
8413 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8414 break;
8415 }
8416 break;
8417 case MachO::CPU_TYPE_ARM:
8418 outs() << " ARM";
8419 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8420 case MachO::CPU_SUBTYPE_ARM_ALL:
8421 outs() << " ALL";
8422 break;
8423 case MachO::CPU_SUBTYPE_ARM_V4T:
8424 outs() << " V4T";
8425 break;
8426 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8427 outs() << " V5TEJ";
8428 break;
8429 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8430 outs() << " XSCALE";
8431 break;
8432 case MachO::CPU_SUBTYPE_ARM_V6:
8433 outs() << " V6";
8434 break;
8435 case MachO::CPU_SUBTYPE_ARM_V6M:
8436 outs() << " V6M";
8437 break;
8438 case MachO::CPU_SUBTYPE_ARM_V7:
8439 outs() << " V7";
8440 break;
8441 case MachO::CPU_SUBTYPE_ARM_V7EM:
8442 outs() << " V7EM";
8443 break;
8444 case MachO::CPU_SUBTYPE_ARM_V7K:
8445 outs() << " V7K";
8446 break;
8447 case MachO::CPU_SUBTYPE_ARM_V7M:
8448 outs() << " V7M";
8449 break;
8450 case MachO::CPU_SUBTYPE_ARM_V7S:
8451 outs() << " V7S";
8452 break;
8453 case MachO::CPU_SUBTYPE_ARM_V8M_MAIN:
8454 outs() << " V8M_MAIN";
8455 break;
8456 case MachO::CPU_SUBTYPE_ARM_V8M_BASE:
8457 outs() << " V8M_BASE";
8458 break;
8459 case MachO::CPU_SUBTYPE_ARM_V8_1M_MAIN:
8460 outs() << " V8_1M_MAIN";
8461 break;
8462 default:
8463 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8464 break;
8465 }
8466 break;
8467 case MachO::CPU_TYPE_ARM64:
8468 outs() << " ARM64";
8469 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8470 case MachO::CPU_SUBTYPE_ARM64_ALL:
8471 outs() << " ALL";
8472 break;
8473 case MachO::CPU_SUBTYPE_ARM64_V8:
8474 outs() << " V8";
8475 break;
8476 case MachO::CPU_SUBTYPE_ARM64E:
8477 outs() << " E";
8478 break;
8479 case MachO::CPU_SUBTYPE_ARM64E_X1:
8480 outs() << " E.X1";
8481 break;
8482 default:
8483 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8484 break;
8485 }
8486 break;
8487 case MachO::CPU_TYPE_ARM64_32:
8488 outs() << " ARM64_32";
8489 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8490 case MachO::CPU_SUBTYPE_ARM64_32_V8:
8491 outs() << " V8";
8492 break;
8493 default:
8494 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8495 break;
8496 }
8497 break;
8498 case MachO::CPU_TYPE_POWERPC:
8499 outs() << " PPC";
8500 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8501 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8502 outs() << " ALL";
8503 break;
8504 default:
8505 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8506 break;
8507 }
8508 break;
8509 case MachO::CPU_TYPE_POWERPC64:
8510 outs() << " PPC64";
8511 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8512 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8513 outs() << " ALL";
8514 break;
8515 default:
8516 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8517 break;
8518 }
8519 break;
8520 default:
8521 outs() << format(Fmt: " %7d", Vals: cputype);
8522 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8523 break;
8524 }
8525
8526 if (cputype == MachO::CPU_TYPE_ARM64 &&
8527 MachO::CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(ST: cpusubtype)) {
8528 const char *Format =
8529 MachO::CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(ST: cpusubtype)
8530 ? " PAK%02d"
8531 : " PAC%02d";
8532 outs() << format(Fmt: Format,
8533 Vals: MachO::CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(ST: cpusubtype));
8534 } else if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) ==
8535 MachO::CPU_SUBTYPE_LIB64) {
8536 outs() << " LIB64";
8537 } else {
8538 outs() << format(Fmt: " 0x%02" PRIx32,
8539 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8540 }
8541 switch (filetype) {
8542 case MachO::MH_OBJECT:
8543 outs() << " OBJECT";
8544 break;
8545 case MachO::MH_EXECUTE:
8546 outs() << " EXECUTE";
8547 break;
8548 case MachO::MH_FVMLIB:
8549 outs() << " FVMLIB";
8550 break;
8551 case MachO::MH_CORE:
8552 outs() << " CORE";
8553 break;
8554 case MachO::MH_PRELOAD:
8555 outs() << " PRELOAD";
8556 break;
8557 case MachO::MH_DYLIB:
8558 outs() << " DYLIB";
8559 break;
8560 case MachO::MH_DYLIB_STUB:
8561 outs() << " DYLIB_STUB";
8562 break;
8563 case MachO::MH_DYLINKER:
8564 outs() << " DYLINKER";
8565 break;
8566 case MachO::MH_BUNDLE:
8567 outs() << " BUNDLE";
8568 break;
8569 case MachO::MH_DSYM:
8570 outs() << " DSYM";
8571 break;
8572 case MachO::MH_KEXT_BUNDLE:
8573 outs() << " KEXTBUNDLE";
8574 break;
8575 case MachO::MH_FILESET:
8576 outs() << " FILESET";
8577 break;
8578 default:
8579 outs() << format(Fmt: " %10u", Vals: filetype);
8580 break;
8581 }
8582 outs() << format(Fmt: " %5u", Vals: ncmds);
8583 outs() << format(Fmt: " %10u", Vals: sizeofcmds);
8584 uint32_t f = flags;
8585 if (f & MachO::MH_NOUNDEFS) {
8586 outs() << " NOUNDEFS";
8587 f &= ~MachO::MH_NOUNDEFS;
8588 }
8589 if (f & MachO::MH_INCRLINK) {
8590 outs() << " INCRLINK";
8591 f &= ~MachO::MH_INCRLINK;
8592 }
8593 if (f & MachO::MH_DYLDLINK) {
8594 outs() << " DYLDLINK";
8595 f &= ~MachO::MH_DYLDLINK;
8596 }
8597 if (f & MachO::MH_BINDATLOAD) {
8598 outs() << " BINDATLOAD";
8599 f &= ~MachO::MH_BINDATLOAD;
8600 }
8601 if (f & MachO::MH_PREBOUND) {
8602 outs() << " PREBOUND";
8603 f &= ~MachO::MH_PREBOUND;
8604 }
8605 if (f & MachO::MH_SPLIT_SEGS) {
8606 outs() << " SPLIT_SEGS";
8607 f &= ~MachO::MH_SPLIT_SEGS;
8608 }
8609 if (f & MachO::MH_LAZY_INIT) {
8610 outs() << " LAZY_INIT";
8611 f &= ~MachO::MH_LAZY_INIT;
8612 }
8613 if (f & MachO::MH_TWOLEVEL) {
8614 outs() << " TWOLEVEL";
8615 f &= ~MachO::MH_TWOLEVEL;
8616 }
8617 if (f & MachO::MH_FORCE_FLAT) {
8618 outs() << " FORCE_FLAT";
8619 f &= ~MachO::MH_FORCE_FLAT;
8620 }
8621 if (f & MachO::MH_NOMULTIDEFS) {
8622 outs() << " NOMULTIDEFS";
8623 f &= ~MachO::MH_NOMULTIDEFS;
8624 }
8625 if (f & MachO::MH_NOFIXPREBINDING) {
8626 outs() << " NOFIXPREBINDING";
8627 f &= ~MachO::MH_NOFIXPREBINDING;
8628 }
8629 if (f & MachO::MH_PREBINDABLE) {
8630 outs() << " PREBINDABLE";
8631 f &= ~MachO::MH_PREBINDABLE;
8632 }
8633 if (f & MachO::MH_ALLMODSBOUND) {
8634 outs() << " ALLMODSBOUND";
8635 f &= ~MachO::MH_ALLMODSBOUND;
8636 }
8637 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8638 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8639 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8640 }
8641 if (f & MachO::MH_CANONICAL) {
8642 outs() << " CANONICAL";
8643 f &= ~MachO::MH_CANONICAL;
8644 }
8645 if (f & MachO::MH_WEAK_DEFINES) {
8646 outs() << " WEAK_DEFINES";
8647 f &= ~MachO::MH_WEAK_DEFINES;
8648 }
8649 if (f & MachO::MH_BINDS_TO_WEAK) {
8650 outs() << " BINDS_TO_WEAK";
8651 f &= ~MachO::MH_BINDS_TO_WEAK;
8652 }
8653 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8654 outs() << " ALLOW_STACK_EXECUTION";
8655 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8656 }
8657 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8658 outs() << " DEAD_STRIPPABLE_DYLIB";
8659 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8660 }
8661 if (f & MachO::MH_PIE) {
8662 outs() << " PIE";
8663 f &= ~MachO::MH_PIE;
8664 }
8665 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8666 outs() << " NO_REEXPORTED_DYLIBS";
8667 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8668 }
8669 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8670 outs() << " MH_HAS_TLV_DESCRIPTORS";
8671 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8672 }
8673 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8674 outs() << " MH_NO_HEAP_EXECUTION";
8675 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8676 }
8677 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8678 outs() << " APP_EXTENSION_SAFE";
8679 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8680 }
8681 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8682 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8683 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8684 }
8685 if (f != 0 || flags == 0)
8686 outs() << format(Fmt: " 0x%08" PRIx32, Vals: f);
8687 } else {
8688 outs() << format(Fmt: " 0x%08" PRIx32, Vals: magic);
8689 outs() << format(Fmt: " %7d", Vals: cputype);
8690 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8691 outs() << format(Fmt: " 0x%02" PRIx32,
8692 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8693 outs() << format(Fmt: " %10u", Vals: filetype);
8694 outs() << format(Fmt: " %5u", Vals: ncmds);
8695 outs() << format(Fmt: " %10u", Vals: sizeofcmds);
8696 outs() << format(Fmt: " 0x%08" PRIx32, Vals: flags);
8697 }
8698 outs() << "\n";
8699}
8700
8701static void PrintLoadCommand(uint32_t Cmd, uint32_t CmdSize, bool IsSizeCorrect,
8702 unsigned LabelWidth) {
8703 outs() << right_justify(Str: "cmd", Width: LabelWidth) << ' ';
8704 switch (Cmd) {
8705#define HANDLE_LOAD_COMMAND(Name, Value, Struct) \
8706 case MachO::Name: \
8707 outs() << #Name; \
8708 break;
8709#include "llvm/BinaryFormat/MachO.def"
8710 default:
8711 outs() << format(Fmt: "?(0x%08" PRIx32 ")", Vals: Cmd);
8712 }
8713 outs() << '\n'
8714 << right_justify(Str: "cmdsize", Width: LabelWidth) << ' ' << CmdSize
8715 << (IsSizeCorrect ? "\n" : " Incorrect size\n");
8716}
8717
8718static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8719 StringRef SegName, uint64_t vmaddr,
8720 uint64_t vmsize, uint64_t fileoff,
8721 uint64_t filesize, uint32_t maxprot,
8722 uint32_t initprot, uint32_t nsects,
8723 uint32_t flags, uint32_t object_size,
8724 bool verbose) {
8725 uint64_t expected_cmdsize;
8726 if (cmd == MachO::LC_SEGMENT) {
8727 expected_cmdsize = nsects;
8728 expected_cmdsize *= sizeof(struct MachO::section);
8729 expected_cmdsize += sizeof(struct MachO::segment_command);
8730 } else {
8731 expected_cmdsize = nsects;
8732 expected_cmdsize *= sizeof(struct MachO::section_64);
8733 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8734 }
8735 PrintLoadCommand(Cmd: cmd, CmdSize: cmdsize, IsSizeCorrect: cmdsize == expected_cmdsize,
8736 /*LabelWidth=*/9);
8737 outs() << " segname " << SegName << "\n";
8738 if (cmd == MachO::LC_SEGMENT_64) {
8739 outs() << " vmaddr " << format(Fmt: "0x%016" PRIx64, Vals: vmaddr) << "\n";
8740 outs() << " vmsize " << format(Fmt: "0x%016" PRIx64, Vals: vmsize) << "\n";
8741 } else {
8742 outs() << " vmaddr " << format(Fmt: "0x%08" PRIx64, Vals: vmaddr) << "\n";
8743 outs() << " vmsize " << format(Fmt: "0x%08" PRIx64, Vals: vmsize) << "\n";
8744 }
8745 outs() << " fileoff " << fileoff;
8746 if (fileoff > object_size)
8747 outs() << " (past end of file)\n";
8748 else
8749 outs() << "\n";
8750 outs() << " filesize " << filesize;
8751 if (fileoff + filesize > object_size)
8752 outs() << " (past end of file)\n";
8753 else
8754 outs() << "\n";
8755 if (verbose) {
8756 if ((maxprot &
8757 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8758 MachO::VM_PROT_EXECUTE)) != 0)
8759 outs() << " maxprot ?" << format(Fmt: "0x%08" PRIx32, Vals: maxprot) << "\n";
8760 else {
8761 outs() << " maxprot ";
8762 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8763 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8764 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8765 }
8766 if ((initprot &
8767 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8768 MachO::VM_PROT_EXECUTE)) != 0)
8769 outs() << " initprot ?" << format(Fmt: "0x%08" PRIx32, Vals: initprot) << "\n";
8770 else {
8771 outs() << " initprot ";
8772 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8773 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8774 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8775 }
8776 } else {
8777 outs() << " maxprot " << format(Fmt: "0x%08" PRIx32, Vals: maxprot) << "\n";
8778 outs() << " initprot " << format(Fmt: "0x%08" PRIx32, Vals: initprot) << "\n";
8779 }
8780 outs() << " nsects " << nsects << "\n";
8781 if (verbose) {
8782 outs() << " flags";
8783 if (flags == 0)
8784 outs() << " (none)\n";
8785 else {
8786 if (flags & MachO::SG_HIGHVM) {
8787 outs() << " HIGHVM";
8788 flags &= ~MachO::SG_HIGHVM;
8789 }
8790 if (flags & MachO::SG_FVMLIB) {
8791 outs() << " FVMLIB";
8792 flags &= ~MachO::SG_FVMLIB;
8793 }
8794 if (flags & MachO::SG_NORELOC) {
8795 outs() << " NORELOC";
8796 flags &= ~MachO::SG_NORELOC;
8797 }
8798 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8799 outs() << " PROTECTED_VERSION_1";
8800 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8801 }
8802 if (flags & MachO::SG_READ_ONLY) {
8803 // Apple's otool prints the SG_ prefix for this flag, but not for the
8804 // others.
8805 outs() << " SG_READ_ONLY";
8806 flags &= ~MachO::SG_READ_ONLY;
8807 }
8808 if (flags)
8809 outs() << format(Fmt: " 0x%08" PRIx32, Vals: flags) << " (unknown flags)\n";
8810 else
8811 outs() << "\n";
8812 }
8813 } else {
8814 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: flags) << "\n";
8815 }
8816}
8817
8818static void PrintSection(const char *sectname, const char *segname,
8819 uint64_t addr, uint64_t size, uint32_t offset,
8820 uint32_t align, uint32_t reloff, uint32_t nreloc,
8821 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8822 uint32_t cmd, const char *sg_segname,
8823 uint32_t filetype, uint32_t object_size,
8824 bool verbose) {
8825 outs() << "Section\n";
8826 outs() << " sectname " << format(Fmt: "%.16s\n", Vals: sectname);
8827 outs() << " segname " << format(Fmt: "%.16s", Vals: segname);
8828 if (filetype != MachO::MH_OBJECT && strncmp(s1: sg_segname, s2: segname, n: 16) != 0)
8829 outs() << " (does not match segment)\n";
8830 else
8831 outs() << "\n";
8832 if (cmd == MachO::LC_SEGMENT_64) {
8833 outs() << " addr " << format(Fmt: "0x%016" PRIx64, Vals: addr) << "\n";
8834 outs() << " size " << format(Fmt: "0x%016" PRIx64, Vals: size);
8835 } else {
8836 outs() << " addr " << format(Fmt: "0x%08" PRIx64, Vals: addr) << "\n";
8837 outs() << " size " << format(Fmt: "0x%08" PRIx64, Vals: size);
8838 }
8839 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8840 outs() << " (past end of file)\n";
8841 else
8842 outs() << "\n";
8843 outs() << " offset " << offset;
8844 if (offset > object_size)
8845 outs() << " (past end of file)\n";
8846 else
8847 outs() << "\n";
8848 uint32_t align_shifted = 1 << align;
8849 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8850 outs() << " reloff " << reloff;
8851 if (reloff > object_size)
8852 outs() << " (past end of file)\n";
8853 else
8854 outs() << "\n";
8855 outs() << " nreloc " << nreloc;
8856 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8857 outs() << " (past end of file)\n";
8858 else
8859 outs() << "\n";
8860 uint32_t section_type = flags & MachO::SECTION_TYPE;
8861 if (verbose) {
8862 outs() << " type";
8863 if (section_type == MachO::S_REGULAR)
8864 outs() << " S_REGULAR\n";
8865 else if (section_type == MachO::S_ZEROFILL)
8866 outs() << " S_ZEROFILL\n";
8867 else if (section_type == MachO::S_CSTRING_LITERALS)
8868 outs() << " S_CSTRING_LITERALS\n";
8869 else if (section_type == MachO::S_4BYTE_LITERALS)
8870 outs() << " S_4BYTE_LITERALS\n";
8871 else if (section_type == MachO::S_8BYTE_LITERALS)
8872 outs() << " S_8BYTE_LITERALS\n";
8873 else if (section_type == MachO::S_16BYTE_LITERALS)
8874 outs() << " S_16BYTE_LITERALS\n";
8875 else if (section_type == MachO::S_LITERAL_POINTERS)
8876 outs() << " S_LITERAL_POINTERS\n";
8877 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8878 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8879 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8880 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8881 else if (section_type == MachO::S_SYMBOL_STUBS)
8882 outs() << " S_SYMBOL_STUBS\n";
8883 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8884 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8885 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8886 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8887 else if (section_type == MachO::S_COALESCED)
8888 outs() << " S_COALESCED\n";
8889 else if (section_type == MachO::S_INTERPOSING)
8890 outs() << " S_INTERPOSING\n";
8891 else if (section_type == MachO::S_DTRACE_DOF)
8892 outs() << " S_DTRACE_DOF\n";
8893 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8894 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8895 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8896 outs() << " S_THREAD_LOCAL_REGULAR\n";
8897 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8898 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8899 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8900 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8901 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8902 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8903 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8904 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8905 else if (section_type == MachO::S_INIT_FUNC_OFFSETS)
8906 outs() << " S_INIT_FUNC_OFFSETS\n";
8907 else
8908 outs() << format(Fmt: "0x%08" PRIx32, Vals: section_type) << "\n";
8909 outs() << "attributes";
8910 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8911 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8912 outs() << " PURE_INSTRUCTIONS";
8913 if (section_attributes & MachO::S_ATTR_NO_TOC)
8914 outs() << " NO_TOC";
8915 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8916 outs() << " STRIP_STATIC_SYMS";
8917 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8918 outs() << " NO_DEAD_STRIP";
8919 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8920 outs() << " LIVE_SUPPORT";
8921 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8922 outs() << " SELF_MODIFYING_CODE";
8923 if (section_attributes & MachO::S_ATTR_DEBUG)
8924 outs() << " DEBUG";
8925 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8926 outs() << " SOME_INSTRUCTIONS";
8927 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8928 outs() << " EXT_RELOC";
8929 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8930 outs() << " LOC_RELOC";
8931 if (section_attributes == 0)
8932 outs() << " (none)";
8933 outs() << "\n";
8934 } else
8935 outs() << " flags " << format(Fmt: "0x%08" PRIx32, Vals: flags) << "\n";
8936 outs() << " reserved1 " << reserved1;
8937 if (section_type == MachO::S_SYMBOL_STUBS ||
8938 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8939 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8940 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8941 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8942 outs() << " (index into indirect symbol table)\n";
8943 else
8944 outs() << "\n";
8945 outs() << " reserved2 " << reserved2;
8946 if (section_type == MachO::S_SYMBOL_STUBS)
8947 outs() << " (size of stubs)\n";
8948 else
8949 outs() << "\n";
8950}
8951
8952static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8953 uint32_t object_size) {
8954 PrintLoadCommand(Cmd: st.cmd, CmdSize: st.cmdsize,
8955 IsSizeCorrect: st.cmdsize == sizeof(struct MachO::symtab_command),
8956 /*LabelWidth=*/8);
8957 outs() << " symoff " << st.symoff;
8958 if (st.symoff > object_size)
8959 outs() << " (past end of file)\n";
8960 else
8961 outs() << "\n";
8962 outs() << " nsyms " << st.nsyms;
8963 uint64_t big_size;
8964 if (Is64Bit) {
8965 big_size = st.nsyms;
8966 big_size *= sizeof(struct MachO::nlist_64);
8967 big_size += st.symoff;
8968 if (big_size > object_size)
8969 outs() << " (past end of file)\n";
8970 else
8971 outs() << "\n";
8972 } else {
8973 big_size = st.nsyms;
8974 big_size *= sizeof(struct MachO::nlist);
8975 big_size += st.symoff;
8976 if (big_size > object_size)
8977 outs() << " (past end of file)\n";
8978 else
8979 outs() << "\n";
8980 }
8981 outs() << " stroff " << st.stroff;
8982 if (st.stroff > object_size)
8983 outs() << " (past end of file)\n";
8984 else
8985 outs() << "\n";
8986 outs() << " strsize " << st.strsize;
8987 big_size = st.stroff;
8988 big_size += st.strsize;
8989 if (big_size > object_size)
8990 outs() << " (past end of file)\n";
8991 else
8992 outs() << "\n";
8993}
8994
8995static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8996 uint32_t nsyms, uint32_t object_size,
8997 bool Is64Bit) {
8998 PrintLoadCommand(Cmd: dyst.cmd, CmdSize: dyst.cmdsize,
8999 IsSizeCorrect: dyst.cmdsize == sizeof(struct MachO::dysymtab_command),
9000 /*LabelWidth=*/15);
9001 outs() << " ilocalsym " << dyst.ilocalsym;
9002 if (dyst.ilocalsym > nsyms)
9003 outs() << " (greater than the number of symbols)\n";
9004 else
9005 outs() << "\n";
9006 outs() << " nlocalsym " << dyst.nlocalsym;
9007 uint64_t big_size;
9008 big_size = dyst.ilocalsym;
9009 big_size += dyst.nlocalsym;
9010 if (big_size > nsyms)
9011 outs() << " (past the end of the symbol table)\n";
9012 else
9013 outs() << "\n";
9014 outs() << " iextdefsym " << dyst.iextdefsym;
9015 if (dyst.iextdefsym > nsyms)
9016 outs() << " (greater than the number of symbols)\n";
9017 else
9018 outs() << "\n";
9019 outs() << " nextdefsym " << dyst.nextdefsym;
9020 big_size = dyst.iextdefsym;
9021 big_size += dyst.nextdefsym;
9022 if (big_size > nsyms)
9023 outs() << " (past the end of the symbol table)\n";
9024 else
9025 outs() << "\n";
9026 outs() << " iundefsym " << dyst.iundefsym;
9027 if (dyst.iundefsym > nsyms)
9028 outs() << " (greater than the number of symbols)\n";
9029 else
9030 outs() << "\n";
9031 outs() << " nundefsym " << dyst.nundefsym;
9032 big_size = dyst.iundefsym;
9033 big_size += dyst.nundefsym;
9034 if (big_size > nsyms)
9035 outs() << " (past the end of the symbol table)\n";
9036 else
9037 outs() << "\n";
9038 outs() << " tocoff " << dyst.tocoff;
9039 if (dyst.tocoff > object_size)
9040 outs() << " (past end of file)\n";
9041 else
9042 outs() << "\n";
9043 outs() << " ntoc " << dyst.ntoc;
9044 big_size = dyst.ntoc;
9045 big_size *= sizeof(struct MachO::dylib_table_of_contents);
9046 big_size += dyst.tocoff;
9047 if (big_size > object_size)
9048 outs() << " (past end of file)\n";
9049 else
9050 outs() << "\n";
9051 outs() << " modtaboff " << dyst.modtaboff;
9052 if (dyst.modtaboff > object_size)
9053 outs() << " (past end of file)\n";
9054 else
9055 outs() << "\n";
9056 outs() << " nmodtab " << dyst.nmodtab;
9057 uint64_t modtabend;
9058 if (Is64Bit) {
9059 modtabend = dyst.nmodtab;
9060 modtabend *= sizeof(struct MachO::dylib_module_64);
9061 modtabend += dyst.modtaboff;
9062 } else {
9063 modtabend = dyst.nmodtab;
9064 modtabend *= sizeof(struct MachO::dylib_module);
9065 modtabend += dyst.modtaboff;
9066 }
9067 if (modtabend > object_size)
9068 outs() << " (past end of file)\n";
9069 else
9070 outs() << "\n";
9071 outs() << " extrefsymoff " << dyst.extrefsymoff;
9072 if (dyst.extrefsymoff > object_size)
9073 outs() << " (past end of file)\n";
9074 else
9075 outs() << "\n";
9076 outs() << " nextrefsyms " << dyst.nextrefsyms;
9077 big_size = dyst.nextrefsyms;
9078 big_size *= sizeof(struct MachO::dylib_reference);
9079 big_size += dyst.extrefsymoff;
9080 if (big_size > object_size)
9081 outs() << " (past end of file)\n";
9082 else
9083 outs() << "\n";
9084 outs() << " indirectsymoff " << dyst.indirectsymoff;
9085 if (dyst.indirectsymoff > object_size)
9086 outs() << " (past end of file)\n";
9087 else
9088 outs() << "\n";
9089 outs() << " nindirectsyms " << dyst.nindirectsyms;
9090 big_size = dyst.nindirectsyms;
9091 big_size *= sizeof(uint32_t);
9092 big_size += dyst.indirectsymoff;
9093 if (big_size > object_size)
9094 outs() << " (past end of file)\n";
9095 else
9096 outs() << "\n";
9097 outs() << " extreloff " << dyst.extreloff;
9098 if (dyst.extreloff > object_size)
9099 outs() << " (past end of file)\n";
9100 else
9101 outs() << "\n";
9102 outs() << " nextrel " << dyst.nextrel;
9103 big_size = dyst.nextrel;
9104 big_size *= sizeof(struct MachO::relocation_info);
9105 big_size += dyst.extreloff;
9106 if (big_size > object_size)
9107 outs() << " (past end of file)\n";
9108 else
9109 outs() << "\n";
9110 outs() << " locreloff " << dyst.locreloff;
9111 if (dyst.locreloff > object_size)
9112 outs() << " (past end of file)\n";
9113 else
9114 outs() << "\n";
9115 outs() << " nlocrel " << dyst.nlocrel;
9116 big_size = dyst.nlocrel;
9117 big_size *= sizeof(struct MachO::relocation_info);
9118 big_size += dyst.locreloff;
9119 if (big_size > object_size)
9120 outs() << " (past end of file)\n";
9121 else
9122 outs() << "\n";
9123}
9124
9125static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
9126 uint32_t object_size) {
9127 PrintLoadCommand(Cmd: dc.cmd, CmdSize: dc.cmdsize,
9128 IsSizeCorrect: dc.cmdsize == sizeof(struct MachO::dyld_info_command),
9129 /*LabelWidth=*/15);
9130 outs() << " rebase_off " << dc.rebase_off;
9131 if (dc.rebase_off > object_size)
9132 outs() << " (past end of file)\n";
9133 else
9134 outs() << "\n";
9135 outs() << " rebase_size " << dc.rebase_size;
9136 uint64_t big_size;
9137 big_size = dc.rebase_off;
9138 big_size += dc.rebase_size;
9139 if (big_size > object_size)
9140 outs() << " (past end of file)\n";
9141 else
9142 outs() << "\n";
9143 outs() << " bind_off " << dc.bind_off;
9144 if (dc.bind_off > object_size)
9145 outs() << " (past end of file)\n";
9146 else
9147 outs() << "\n";
9148 outs() << " bind_size " << dc.bind_size;
9149 big_size = dc.bind_off;
9150 big_size += dc.bind_size;
9151 if (big_size > object_size)
9152 outs() << " (past end of file)\n";
9153 else
9154 outs() << "\n";
9155 outs() << " weak_bind_off " << dc.weak_bind_off;
9156 if (dc.weak_bind_off > object_size)
9157 outs() << " (past end of file)\n";
9158 else
9159 outs() << "\n";
9160 outs() << " weak_bind_size " << dc.weak_bind_size;
9161 big_size = dc.weak_bind_off;
9162 big_size += dc.weak_bind_size;
9163 if (big_size > object_size)
9164 outs() << " (past end of file)\n";
9165 else
9166 outs() << "\n";
9167 outs() << " lazy_bind_off " << dc.lazy_bind_off;
9168 if (dc.lazy_bind_off > object_size)
9169 outs() << " (past end of file)\n";
9170 else
9171 outs() << "\n";
9172 outs() << " lazy_bind_size " << dc.lazy_bind_size;
9173 big_size = dc.lazy_bind_off;
9174 big_size += dc.lazy_bind_size;
9175 if (big_size > object_size)
9176 outs() << " (past end of file)\n";
9177 else
9178 outs() << "\n";
9179 outs() << " export_off " << dc.export_off;
9180 if (dc.export_off > object_size)
9181 outs() << " (past end of file)\n";
9182 else
9183 outs() << "\n";
9184 outs() << " export_size " << dc.export_size;
9185 big_size = dc.export_off;
9186 big_size += dc.export_size;
9187 if (big_size > object_size)
9188 outs() << " (past end of file)\n";
9189 else
9190 outs() << "\n";
9191}
9192
9193static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9194 const char *Ptr) {
9195 PrintLoadCommand(Cmd: dyld.cmd, CmdSize: dyld.cmdsize,
9196 IsSizeCorrect: dyld.cmdsize >= sizeof(struct MachO::dylinker_command),
9197 /*LabelWidth=*/13);
9198 if (dyld.name >= dyld.cmdsize)
9199 outs() << " name ?(bad offset " << dyld.name << ")\n";
9200 else {
9201 const char *P = Ptr + dyld.name;
9202 outs() << " name " << P << " (offset " << dyld.name << ")\n";
9203 }
9204}
9205
9206static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9207 PrintLoadCommand(Cmd: uuid.cmd, CmdSize: uuid.cmdsize,
9208 IsSizeCorrect: uuid.cmdsize == sizeof(struct MachO::uuid_command),
9209 /*LabelWidth=*/8);
9210 outs() << " uuid ";
9211 for (int i = 0; i < 16; ++i) {
9212 outs() << format(Fmt: "%02" PRIX32, Vals: uuid.uuid[i]);
9213 if (i == 3 || i == 5 || i == 7 || i == 9)
9214 outs() << "-";
9215 }
9216 outs() << "\n";
9217}
9218
9219static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9220 PrintLoadCommand(Cmd: rpath.cmd, CmdSize: rpath.cmdsize,
9221 IsSizeCorrect: rpath.cmdsize >= sizeof(struct MachO::rpath_command),
9222 /*LabelWidth=*/13);
9223 if (rpath.path >= rpath.cmdsize)
9224 outs() << " path ?(bad offset " << rpath.path << ")\n";
9225 else {
9226 const char *P = Ptr + rpath.path;
9227 outs() << " path " << P << " (offset " << rpath.path << ")\n";
9228 }
9229}
9230
9231static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9232 PrintLoadCommand(Cmd: vd.cmd, CmdSize: vd.cmdsize,
9233 IsSizeCorrect: vd.cmdsize == sizeof(struct MachO::version_min_command),
9234 /*LabelWidth=*/9);
9235 outs() << " version "
9236 << MachOObjectFile::getVersionMinMajor(C&: vd, SDK: false) << "."
9237 << MachOObjectFile::getVersionMinMinor(C&: vd, SDK: false);
9238 uint32_t Update = MachOObjectFile::getVersionMinUpdate(C&: vd, SDK: false);
9239 if (Update != 0)
9240 outs() << "." << Update;
9241 outs() << "\n";
9242 if (vd.sdk == 0)
9243 outs() << " sdk n/a";
9244 else {
9245 outs() << " sdk "
9246 << MachOObjectFile::getVersionMinMajor(C&: vd, SDK: true) << "."
9247 << MachOObjectFile::getVersionMinMinor(C&: vd, SDK: true);
9248 }
9249 Update = MachOObjectFile::getVersionMinUpdate(C&: vd, SDK: true);
9250 if (Update != 0)
9251 outs() << "." << Update;
9252 outs() << "\n";
9253}
9254
9255static void PrintNoteLoadCommand(MachO::note_command Nt) {
9256 PrintLoadCommand(Cmd: Nt.cmd, CmdSize: Nt.cmdsize,
9257 IsSizeCorrect: Nt.cmdsize == sizeof(struct MachO::note_command),
9258 /*LabelWidth=*/10);
9259 const char *d = Nt.data_owner;
9260 outs() << "data_owner " << format(Fmt: "%.16s\n", Vals: d);
9261 outs() << " offset " << Nt.offset << "\n";
9262 outs() << " size " << Nt.size << "\n";
9263}
9264
9265static void PrintBuildToolVersion(MachO::build_tool_version bv, bool verbose) {
9266 outs() << " tool ";
9267 if (verbose)
9268 outs() << MachOObjectFile::getBuildTool(tools: bv.tool);
9269 else
9270 outs() << bv.tool;
9271 outs() << "\n";
9272 outs() << " version " << MachOObjectFile::getVersionString(version: bv.version)
9273 << "\n";
9274}
9275
9276static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9277 MachO::build_version_command bd,
9278 bool verbose) {
9279 PrintLoadCommand(Cmd: bd.cmd, CmdSize: bd.cmdsize,
9280 IsSizeCorrect: bd.cmdsize ==
9281 sizeof(struct MachO::build_version_command) +
9282 bd.ntools * sizeof(struct MachO::build_tool_version),
9283 /*LabelWidth=*/10);
9284 outs() << " platform ";
9285 if (verbose)
9286 outs() << MachOObjectFile::getBuildPlatform(platform: bd.platform);
9287 else
9288 outs() << bd.platform;
9289 outs() << "\n";
9290 if (bd.sdk)
9291 outs() << " sdk " << MachOObjectFile::getVersionString(version: bd.sdk)
9292 << "\n";
9293 else
9294 outs() << " sdk n/a\n";
9295 outs() << " minos " << MachOObjectFile::getVersionString(version: bd.minos)
9296 << "\n";
9297 outs() << " ntools " << bd.ntools << "\n";
9298 for (unsigned i = 0; i < bd.ntools; ++i) {
9299 MachO::build_tool_version bv = obj->getBuildToolVersion(index: i);
9300 PrintBuildToolVersion(bv, verbose);
9301 }
9302}
9303
9304static void PrintTargetTripleCommand(MachO::target_triple_command tt,
9305 const char *Ptr) {
9306 PrintLoadCommand(Cmd: tt.cmd, CmdSize: tt.cmdsize,
9307 IsSizeCorrect: tt.cmdsize >= sizeof(struct MachO::target_triple_command),
9308 /*LabelWidth=*/8);
9309 if (tt.triple < tt.cmdsize) {
9310 const char *P = Ptr + tt.triple;
9311 outs() << " triple " << P << " (offset " << tt.triple << ")\n";
9312 } else {
9313 outs() << " triple ?(bad offset " << tt.triple << ")\n";
9314 }
9315}
9316
9317static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9318 PrintLoadCommand(Cmd: sd.cmd, CmdSize: sd.cmdsize,
9319 IsSizeCorrect: sd.cmdsize == sizeof(struct MachO::source_version_command),
9320 /*LabelWidth=*/9);
9321 uint64_t a = (sd.version >> 40) & 0xffffff;
9322 uint64_t b = (sd.version >> 30) & 0x3ff;
9323 uint64_t c = (sd.version >> 20) & 0x3ff;
9324 uint64_t d = (sd.version >> 10) & 0x3ff;
9325 uint64_t e = sd.version & 0x3ff;
9326 outs() << " version " << a << "." << b;
9327 if (e != 0)
9328 outs() << "." << c << "." << d << "." << e;
9329 else if (d != 0)
9330 outs() << "." << c << "." << d;
9331 else if (c != 0)
9332 outs() << "." << c;
9333 outs() << "\n";
9334}
9335
9336static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9337 PrintLoadCommand(Cmd: ep.cmd, CmdSize: ep.cmdsize,
9338 IsSizeCorrect: ep.cmdsize == sizeof(struct MachO::entry_point_command),
9339 /*LabelWidth=*/10);
9340 outs() << " entryoff " << ep.entryoff << "\n";
9341 outs() << " stacksize " << ep.stacksize << "\n";
9342}
9343
9344static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9345 uint32_t object_size) {
9346 PrintLoadCommand(Cmd: ec.cmd, CmdSize: ec.cmdsize,
9347 IsSizeCorrect: ec.cmdsize == sizeof(struct MachO::encryption_info_command),
9348 /*LabelWidth=*/13);
9349 outs() << " cryptoff " << ec.cryptoff;
9350 if (ec.cryptoff > object_size)
9351 outs() << " (past end of file)\n";
9352 else
9353 outs() << "\n";
9354 outs() << " cryptsize " << ec.cryptsize;
9355 if (ec.cryptsize > object_size)
9356 outs() << " (past end of file)\n";
9357 else
9358 outs() << "\n";
9359 outs() << " cryptid " << ec.cryptid << "\n";
9360}
9361
9362static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9363 uint32_t object_size) {
9364 PrintLoadCommand(Cmd: ec.cmd, CmdSize: ec.cmdsize,
9365 IsSizeCorrect: ec.cmdsize ==
9366 sizeof(struct MachO::encryption_info_command_64),
9367 /*LabelWidth=*/13);
9368 outs() << " cryptoff " << ec.cryptoff;
9369 if (ec.cryptoff > object_size)
9370 outs() << " (past end of file)\n";
9371 else
9372 outs() << "\n";
9373 outs() << " cryptsize " << ec.cryptsize;
9374 if (ec.cryptsize > object_size)
9375 outs() << " (past end of file)\n";
9376 else
9377 outs() << "\n";
9378 outs() << " cryptid " << ec.cryptid << "\n";
9379 outs() << " pad " << ec.pad << "\n";
9380}
9381
9382static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9383 const char *Ptr) {
9384 PrintLoadCommand(Cmd: lo.cmd, CmdSize: lo.cmdsize,
9385 IsSizeCorrect: lo.cmdsize >= sizeof(struct MachO::linker_option_command),
9386 /*LabelWidth=*/8);
9387 outs() << " count " << lo.count << "\n";
9388 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9389 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9390 uint32_t i = 0;
9391 while (left > 0) {
9392 while (*string == '\0' && left > 0) {
9393 string++;
9394 left--;
9395 }
9396 if (left > 0) {
9397 i++;
9398 outs() << " string #" << i << " " << format(Fmt: "%.*s\n", Vals: left, Vals: string);
9399 uint32_t NullPos = StringRef(string, left).find(C: '\0');
9400 uint32_t len = std::min(a: NullPos, b: left) + 1;
9401 string += len;
9402 left -= len;
9403 }
9404 }
9405 if (lo.count != i)
9406 outs() << " count " << lo.count << " does not match number of strings "
9407 << i << "\n";
9408}
9409
9410static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9411 const char *Ptr) {
9412 PrintLoadCommand(Cmd: sub.cmd, CmdSize: sub.cmdsize,
9413 IsSizeCorrect: sub.cmdsize >= sizeof(struct MachO::sub_framework_command),
9414 /*LabelWidth=*/13);
9415 if (sub.umbrella < sub.cmdsize) {
9416 const char *P = Ptr + sub.umbrella;
9417 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9418 } else {
9419 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9420 }
9421}
9422
9423static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9424 const char *Ptr) {
9425 PrintLoadCommand(Cmd: sub.cmd, CmdSize: sub.cmdsize,
9426 IsSizeCorrect: sub.cmdsize >= sizeof(struct MachO::sub_umbrella_command),
9427 /*LabelWidth=*/13);
9428 if (sub.sub_umbrella < sub.cmdsize) {
9429 const char *P = Ptr + sub.sub_umbrella;
9430 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9431 } else {
9432 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9433 }
9434}
9435
9436static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9437 const char *Ptr) {
9438 PrintLoadCommand(Cmd: sub.cmd, CmdSize: sub.cmdsize,
9439 IsSizeCorrect: sub.cmdsize >= sizeof(struct MachO::sub_library_command),
9440 /*LabelWidth=*/13);
9441 if (sub.sub_library < sub.cmdsize) {
9442 const char *P = Ptr + sub.sub_library;
9443 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9444 } else {
9445 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9446 }
9447}
9448
9449static void PrintSubClientCommand(MachO::sub_client_command sub,
9450 const char *Ptr) {
9451 PrintLoadCommand(Cmd: sub.cmd, CmdSize: sub.cmdsize,
9452 IsSizeCorrect: sub.cmdsize >= sizeof(struct MachO::sub_client_command),
9453 /*LabelWidth=*/13);
9454 if (sub.client < sub.cmdsize) {
9455 const char *P = Ptr + sub.client;
9456 outs() << " client " << P << " (offset " << sub.client << ")\n";
9457 } else {
9458 outs() << " client ?(bad offset " << sub.client << ")\n";
9459 }
9460}
9461
9462static void PrintRoutinesCommand(MachO::routines_command r) {
9463 PrintLoadCommand(Cmd: r.cmd, CmdSize: r.cmdsize,
9464 IsSizeCorrect: r.cmdsize == sizeof(struct MachO::routines_command),
9465 /*LabelWidth=*/13);
9466 outs() << " init_address " << format(Fmt: "0x%08" PRIx32, Vals: r.init_address) << "\n";
9467 outs() << " init_module " << r.init_module << "\n";
9468 outs() << " reserved1 " << r.reserved1 << "\n";
9469 outs() << " reserved2 " << r.reserved2 << "\n";
9470 outs() << " reserved3 " << r.reserved3 << "\n";
9471 outs() << " reserved4 " << r.reserved4 << "\n";
9472 outs() << " reserved5 " << r.reserved5 << "\n";
9473 outs() << " reserved6 " << r.reserved6 << "\n";
9474}
9475
9476static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9477 PrintLoadCommand(Cmd: r.cmd, CmdSize: r.cmdsize,
9478 IsSizeCorrect: r.cmdsize == sizeof(struct MachO::routines_command_64),
9479 /*LabelWidth=*/13);
9480 outs() << " init_address " << format(Fmt: "0x%016" PRIx64, Vals: r.init_address) << "\n";
9481 outs() << " init_module " << r.init_module << "\n";
9482 outs() << " reserved1 " << r.reserved1 << "\n";
9483 outs() << " reserved2 " << r.reserved2 << "\n";
9484 outs() << " reserved3 " << r.reserved3 << "\n";
9485 outs() << " reserved4 " << r.reserved4 << "\n";
9486 outs() << " reserved5 " << r.reserved5 << "\n";
9487 outs() << " reserved6 " << r.reserved6 << "\n";
9488}
9489
9490static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9491 outs() << "\t eax " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eax);
9492 outs() << " ebx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ebx);
9493 outs() << " ecx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ecx);
9494 outs() << " edx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.edx) << "\n";
9495 outs() << "\t edi " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.edi);
9496 outs() << " esi " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.esi);
9497 outs() << " ebp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ebp);
9498 outs() << " esp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.esp) << "\n";
9499 outs() << "\t ss " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ss);
9500 outs() << " eflags " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eflags);
9501 outs() << " eip " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eip);
9502 outs() << " cs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.cs) << "\n";
9503 outs() << "\t ds " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ds);
9504 outs() << " es " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.es);
9505 outs() << " fs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.fs);
9506 outs() << " gs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.gs) << "\n";
9507}
9508
9509static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9510 outs() << " rax " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rax);
9511 outs() << " rbx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rbx);
9512 outs() << " rcx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rcx) << "\n";
9513 outs() << " rdx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rdx);
9514 outs() << " rdi " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rdi);
9515 outs() << " rsi " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rsi) << "\n";
9516 outs() << " rbp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rbp);
9517 outs() << " rsp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rsp);
9518 outs() << " r8 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r8) << "\n";
9519 outs() << " r9 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r9);
9520 outs() << " r10 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r10);
9521 outs() << " r11 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r11) << "\n";
9522 outs() << " r12 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r12);
9523 outs() << " r13 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r13);
9524 outs() << " r14 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r14) << "\n";
9525 outs() << " r15 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r15);
9526 outs() << " rip " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rip) << "\n";
9527 outs() << "rflags " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rflags);
9528 outs() << " cs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.cs);
9529 outs() << " fs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.fs) << "\n";
9530 outs() << " gs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.gs) << "\n";
9531}
9532
9533static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9534 uint32_t f;
9535 outs() << "\t mmst_reg ";
9536 for (f = 0; f < 10; f++)
9537 outs() << format(Fmt: "%02" PRIx32, Vals: (r.mmst_reg[f] & 0xff)) << " ";
9538 outs() << "\n";
9539 outs() << "\t mmst_rsrv ";
9540 for (f = 0; f < 6; f++)
9541 outs() << format(Fmt: "%02" PRIx32, Vals: (r.mmst_rsrv[f] & 0xff)) << " ";
9542 outs() << "\n";
9543}
9544
9545static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9546 uint32_t f;
9547 outs() << "\t xmm_reg ";
9548 for (f = 0; f < 16; f++)
9549 outs() << format(Fmt: "%02" PRIx32, Vals: (r.xmm_reg[f] & 0xff)) << " ";
9550 outs() << "\n";
9551}
9552
9553static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9554 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9555 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9556 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9557 outs() << " denorm " << fpu.fpu_fcw.denorm;
9558 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9559 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9560 outs() << " undfl " << fpu.fpu_fcw.undfl;
9561 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9562 outs() << "\t\t pc ";
9563 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9564 outs() << "FP_PREC_24B ";
9565 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9566 outs() << "FP_PREC_53B ";
9567 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9568 outs() << "FP_PREC_64B ";
9569 else
9570 outs() << fpu.fpu_fcw.pc << " ";
9571 outs() << "rc ";
9572 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9573 outs() << "FP_RND_NEAR ";
9574 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9575 outs() << "FP_RND_DOWN ";
9576 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9577 outs() << "FP_RND_UP ";
9578 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9579 outs() << "FP_CHOP ";
9580 outs() << "\n";
9581 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9582 outs() << " denorm " << fpu.fpu_fsw.denorm;
9583 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9584 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9585 outs() << " undfl " << fpu.fpu_fsw.undfl;
9586 outs() << " precis " << fpu.fpu_fsw.precis;
9587 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9588 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9589 outs() << " c0 " << fpu.fpu_fsw.c0;
9590 outs() << " c1 " << fpu.fpu_fsw.c1;
9591 outs() << " c2 " << fpu.fpu_fsw.c2;
9592 outs() << " tos " << fpu.fpu_fsw.tos;
9593 outs() << " c3 " << fpu.fpu_fsw.c3;
9594 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9595 outs() << "\t fpu_ftw " << format(Fmt: "0x%02" PRIx32, Vals: fpu.fpu_ftw);
9596 outs() << " fpu_rsrv1 " << format(Fmt: "0x%02" PRIx32, Vals: fpu.fpu_rsrv1);
9597 outs() << " fpu_fop " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_fop);
9598 outs() << " fpu_ip " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_ip) << "\n";
9599 outs() << "\t fpu_cs " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_cs);
9600 outs() << " fpu_rsrv2 " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_rsrv2);
9601 outs() << " fpu_dp " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_dp);
9602 outs() << " fpu_ds " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_ds) << "\n";
9603 outs() << "\t fpu_rsrv3 " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_rsrv3);
9604 outs() << " fpu_mxcsr " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_mxcsr);
9605 outs() << " fpu_mxcsrmask " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_mxcsrmask);
9606 outs() << "\n";
9607 outs() << "\t fpu_stmm0:\n";
9608 Print_mmst_reg(r&: fpu.fpu_stmm0);
9609 outs() << "\t fpu_stmm1:\n";
9610 Print_mmst_reg(r&: fpu.fpu_stmm1);
9611 outs() << "\t fpu_stmm2:\n";
9612 Print_mmst_reg(r&: fpu.fpu_stmm2);
9613 outs() << "\t fpu_stmm3:\n";
9614 Print_mmst_reg(r&: fpu.fpu_stmm3);
9615 outs() << "\t fpu_stmm4:\n";
9616 Print_mmst_reg(r&: fpu.fpu_stmm4);
9617 outs() << "\t fpu_stmm5:\n";
9618 Print_mmst_reg(r&: fpu.fpu_stmm5);
9619 outs() << "\t fpu_stmm6:\n";
9620 Print_mmst_reg(r&: fpu.fpu_stmm6);
9621 outs() << "\t fpu_stmm7:\n";
9622 Print_mmst_reg(r&: fpu.fpu_stmm7);
9623 outs() << "\t fpu_xmm0:\n";
9624 Print_xmm_reg(r&: fpu.fpu_xmm0);
9625 outs() << "\t fpu_xmm1:\n";
9626 Print_xmm_reg(r&: fpu.fpu_xmm1);
9627 outs() << "\t fpu_xmm2:\n";
9628 Print_xmm_reg(r&: fpu.fpu_xmm2);
9629 outs() << "\t fpu_xmm3:\n";
9630 Print_xmm_reg(r&: fpu.fpu_xmm3);
9631 outs() << "\t fpu_xmm4:\n";
9632 Print_xmm_reg(r&: fpu.fpu_xmm4);
9633 outs() << "\t fpu_xmm5:\n";
9634 Print_xmm_reg(r&: fpu.fpu_xmm5);
9635 outs() << "\t fpu_xmm6:\n";
9636 Print_xmm_reg(r&: fpu.fpu_xmm6);
9637 outs() << "\t fpu_xmm7:\n";
9638 Print_xmm_reg(r&: fpu.fpu_xmm7);
9639 outs() << "\t fpu_xmm8:\n";
9640 Print_xmm_reg(r&: fpu.fpu_xmm8);
9641 outs() << "\t fpu_xmm9:\n";
9642 Print_xmm_reg(r&: fpu.fpu_xmm9);
9643 outs() << "\t fpu_xmm10:\n";
9644 Print_xmm_reg(r&: fpu.fpu_xmm10);
9645 outs() << "\t fpu_xmm11:\n";
9646 Print_xmm_reg(r&: fpu.fpu_xmm11);
9647 outs() << "\t fpu_xmm12:\n";
9648 Print_xmm_reg(r&: fpu.fpu_xmm12);
9649 outs() << "\t fpu_xmm13:\n";
9650 Print_xmm_reg(r&: fpu.fpu_xmm13);
9651 outs() << "\t fpu_xmm14:\n";
9652 Print_xmm_reg(r&: fpu.fpu_xmm14);
9653 outs() << "\t fpu_xmm15:\n";
9654 Print_xmm_reg(r&: fpu.fpu_xmm15);
9655 outs() << "\t fpu_rsrv4:\n";
9656 for (uint32_t f = 0; f < 6; f++) {
9657 outs() << "\t ";
9658 for (uint32_t g = 0; g < 16; g++)
9659 outs() << format(Fmt: "%02" PRIx32, Vals: fpu.fpu_rsrv4[f * g]) << " ";
9660 outs() << "\n";
9661 }
9662 outs() << "\t fpu_reserved1 " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_reserved1);
9663 outs() << "\n";
9664}
9665
9666static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9667 outs() << "\t trapno " << format(Fmt: "0x%08" PRIx32, Vals: exc64.trapno);
9668 outs() << " err " << format(Fmt: "0x%08" PRIx32, Vals: exc64.err);
9669 outs() << " faultvaddr " << format(Fmt: "0x%016" PRIx64, Vals: exc64.faultvaddr) << "\n";
9670}
9671
9672static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9673 outs() << "\t r0 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[0]);
9674 outs() << " r1 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[1]);
9675 outs() << " r2 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[2]);
9676 outs() << " r3 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[3]) << "\n";
9677 outs() << "\t r4 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[4]);
9678 outs() << " r5 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[5]);
9679 outs() << " r6 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[6]);
9680 outs() << " r7 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[7]) << "\n";
9681 outs() << "\t r8 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[8]);
9682 outs() << " r9 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[9]);
9683 outs() << " r10 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[10]);
9684 outs() << " r11 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[11]) << "\n";
9685 outs() << "\t r12 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[12]);
9686 outs() << " sp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.sp);
9687 outs() << " lr " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.lr);
9688 outs() << " pc " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.pc) << "\n";
9689 outs() << "\t cpsr " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.cpsr) << "\n";
9690}
9691
9692static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9693 outs() << "\t x0 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[0]);
9694 outs() << " x1 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[1]);
9695 outs() << " x2 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[2]) << "\n";
9696 outs() << "\t x3 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[3]);
9697 outs() << " x4 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[4]);
9698 outs() << " x5 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[5]) << "\n";
9699 outs() << "\t x6 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[6]);
9700 outs() << " x7 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[7]);
9701 outs() << " x8 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[8]) << "\n";
9702 outs() << "\t x9 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[9]);
9703 outs() << " x10 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[10]);
9704 outs() << " x11 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[11]) << "\n";
9705 outs() << "\t x12 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[12]);
9706 outs() << " x13 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[13]);
9707 outs() << " x14 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[14]) << "\n";
9708 outs() << "\t x15 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[15]);
9709 outs() << " x16 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[16]);
9710 outs() << " x17 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[17]) << "\n";
9711 outs() << "\t x18 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[18]);
9712 outs() << " x19 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[19]);
9713 outs() << " x20 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[20]) << "\n";
9714 outs() << "\t x21 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[21]);
9715 outs() << " x22 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[22]);
9716 outs() << " x23 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[23]) << "\n";
9717 outs() << "\t x24 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[24]);
9718 outs() << " x25 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[25]);
9719 outs() << " x26 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[26]) << "\n";
9720 outs() << "\t x27 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[27]);
9721 outs() << " x28 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[28]);
9722 outs() << " fp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.fp) << "\n";
9723 outs() << "\t lr " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.lr);
9724 outs() << " sp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.sp);
9725 outs() << " pc " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.pc) << "\n";
9726 outs() << "\t cpsr " << format(Fmt: "0x%08" PRIx32, Vals: cpu64.cpsr) << "\n";
9727}
9728
9729static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9730 bool isLittleEndian, uint32_t cputype) {
9731 PrintLoadCommand(Cmd: t.cmd, CmdSize: t.cmdsize,
9732 IsSizeCorrect: t.cmdsize >= sizeof(struct MachO::thread_command) +
9733 2 * sizeof(uint32_t),
9734 /*LabelWidth=*/11);
9735
9736 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9737 const char *end = Ptr + t.cmdsize;
9738 uint32_t flavor, count, left;
9739 if (cputype == MachO::CPU_TYPE_I386) {
9740 while (begin < end) {
9741 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9742 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9743 begin += sizeof(uint32_t);
9744 } else {
9745 flavor = 0;
9746 begin = end;
9747 }
9748 if (isLittleEndian != sys::IsLittleEndianHost)
9749 sys::swapByteOrder(Value&: flavor);
9750 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9751 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9752 begin += sizeof(uint32_t);
9753 } else {
9754 count = 0;
9755 begin = end;
9756 }
9757 if (isLittleEndian != sys::IsLittleEndianHost)
9758 sys::swapByteOrder(Value&: count);
9759 if (flavor == MachO::x86_THREAD_STATE32) {
9760 outs() << " flavor i386_THREAD_STATE\n";
9761 if (count == MachO::x86_THREAD_STATE32_COUNT)
9762 outs() << " count i386_THREAD_STATE_COUNT\n";
9763 else
9764 outs() << " count " << count
9765 << " (not x86_THREAD_STATE32_COUNT)\n";
9766 MachO::x86_thread_state32_t cpu32;
9767 left = end - begin;
9768 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9769 memcpy(dest: &cpu32, src: begin, n: sizeof(MachO::x86_thread_state32_t));
9770 begin += sizeof(MachO::x86_thread_state32_t);
9771 } else {
9772 memset(s: &cpu32, c: '\0', n: sizeof(MachO::x86_thread_state32_t));
9773 memcpy(dest: &cpu32, src: begin, n: left);
9774 begin += left;
9775 }
9776 if (isLittleEndian != sys::IsLittleEndianHost)
9777 swapStruct(x&: cpu32);
9778 Print_x86_thread_state32_t(cpu32);
9779 } else if (flavor == MachO::x86_THREAD_STATE) {
9780 outs() << " flavor x86_THREAD_STATE\n";
9781 if (count == MachO::x86_THREAD_STATE_COUNT)
9782 outs() << " count x86_THREAD_STATE_COUNT\n";
9783 else
9784 outs() << " count " << count
9785 << " (not x86_THREAD_STATE_COUNT)\n";
9786 struct MachO::x86_thread_state_t ts;
9787 left = end - begin;
9788 if (left >= sizeof(MachO::x86_thread_state_t)) {
9789 memcpy(dest: &ts, src: begin, n: sizeof(MachO::x86_thread_state_t));
9790 begin += sizeof(MachO::x86_thread_state_t);
9791 } else {
9792 memset(s: &ts, c: '\0', n: sizeof(MachO::x86_thread_state_t));
9793 memcpy(dest: &ts, src: begin, n: left);
9794 begin += left;
9795 }
9796 if (isLittleEndian != sys::IsLittleEndianHost)
9797 swapStruct(x&: ts);
9798 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9799 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9800 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9801 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9802 else
9803 outs() << "tsh.count " << ts.tsh.count
9804 << " (not x86_THREAD_STATE32_COUNT\n";
9805 Print_x86_thread_state32_t(cpu32&: ts.uts.ts32);
9806 } else {
9807 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9808 << ts.tsh.count << "\n";
9809 }
9810 } else {
9811 outs() << " flavor " << flavor << " (unknown)\n";
9812 outs() << " count " << count << "\n";
9813 outs() << " state (unknown)\n";
9814 begin += count * sizeof(uint32_t);
9815 }
9816 }
9817 } else if (cputype == MachO::CPU_TYPE_X86_64) {
9818 while (begin < end) {
9819 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9820 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9821 begin += sizeof(uint32_t);
9822 } else {
9823 flavor = 0;
9824 begin = end;
9825 }
9826 if (isLittleEndian != sys::IsLittleEndianHost)
9827 sys::swapByteOrder(Value&: flavor);
9828 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9829 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9830 begin += sizeof(uint32_t);
9831 } else {
9832 count = 0;
9833 begin = end;
9834 }
9835 if (isLittleEndian != sys::IsLittleEndianHost)
9836 sys::swapByteOrder(Value&: count);
9837 if (flavor == MachO::x86_THREAD_STATE64) {
9838 outs() << " flavor x86_THREAD_STATE64\n";
9839 if (count == MachO::x86_THREAD_STATE64_COUNT)
9840 outs() << " count x86_THREAD_STATE64_COUNT\n";
9841 else
9842 outs() << " count " << count
9843 << " (not x86_THREAD_STATE64_COUNT)\n";
9844 MachO::x86_thread_state64_t cpu64;
9845 left = end - begin;
9846 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9847 memcpy(dest: &cpu64, src: begin, n: sizeof(MachO::x86_thread_state64_t));
9848 begin += sizeof(MachO::x86_thread_state64_t);
9849 } else {
9850 memset(s: &cpu64, c: '\0', n: sizeof(MachO::x86_thread_state64_t));
9851 memcpy(dest: &cpu64, src: begin, n: left);
9852 begin += left;
9853 }
9854 if (isLittleEndian != sys::IsLittleEndianHost)
9855 swapStruct(x&: cpu64);
9856 Print_x86_thread_state64_t(cpu64);
9857 } else if (flavor == MachO::x86_THREAD_STATE) {
9858 outs() << " flavor x86_THREAD_STATE\n";
9859 if (count == MachO::x86_THREAD_STATE_COUNT)
9860 outs() << " count x86_THREAD_STATE_COUNT\n";
9861 else
9862 outs() << " count " << count
9863 << " (not x86_THREAD_STATE_COUNT)\n";
9864 struct MachO::x86_thread_state_t ts;
9865 left = end - begin;
9866 if (left >= sizeof(MachO::x86_thread_state_t)) {
9867 memcpy(dest: &ts, src: begin, n: sizeof(MachO::x86_thread_state_t));
9868 begin += sizeof(MachO::x86_thread_state_t);
9869 } else {
9870 memset(s: &ts, c: '\0', n: sizeof(MachO::x86_thread_state_t));
9871 memcpy(dest: &ts, src: begin, n: left);
9872 begin += left;
9873 }
9874 if (isLittleEndian != sys::IsLittleEndianHost)
9875 swapStruct(x&: ts);
9876 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9877 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9878 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9879 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9880 else
9881 outs() << "tsh.count " << ts.tsh.count
9882 << " (not x86_THREAD_STATE64_COUNT\n";
9883 Print_x86_thread_state64_t(cpu64&: ts.uts.ts64);
9884 } else {
9885 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9886 << ts.tsh.count << "\n";
9887 }
9888 } else if (flavor == MachO::x86_FLOAT_STATE) {
9889 outs() << " flavor x86_FLOAT_STATE\n";
9890 if (count == MachO::x86_FLOAT_STATE_COUNT)
9891 outs() << " count x86_FLOAT_STATE_COUNT\n";
9892 else
9893 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9894 struct MachO::x86_float_state_t fs;
9895 left = end - begin;
9896 if (left >= sizeof(MachO::x86_float_state_t)) {
9897 memcpy(dest: &fs, src: begin, n: sizeof(MachO::x86_float_state_t));
9898 begin += sizeof(MachO::x86_float_state_t);
9899 } else {
9900 memset(s: &fs, c: '\0', n: sizeof(MachO::x86_float_state_t));
9901 memcpy(dest: &fs, src: begin, n: left);
9902 begin += left;
9903 }
9904 if (isLittleEndian != sys::IsLittleEndianHost)
9905 swapStruct(x&: fs);
9906 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9907 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
9908 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9909 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9910 else
9911 outs() << "fsh.count " << fs.fsh.count
9912 << " (not x86_FLOAT_STATE64_COUNT\n";
9913 Print_x86_float_state_t(fpu&: fs.ufs.fs64);
9914 } else {
9915 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9916 << fs.fsh.count << "\n";
9917 }
9918 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9919 outs() << " flavor x86_EXCEPTION_STATE\n";
9920 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9921 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9922 else
9923 outs() << " count " << count
9924 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9925 struct MachO::x86_exception_state_t es;
9926 left = end - begin;
9927 if (left >= sizeof(MachO::x86_exception_state_t)) {
9928 memcpy(dest: &es, src: begin, n: sizeof(MachO::x86_exception_state_t));
9929 begin += sizeof(MachO::x86_exception_state_t);
9930 } else {
9931 memset(s: &es, c: '\0', n: sizeof(MachO::x86_exception_state_t));
9932 memcpy(dest: &es, src: begin, n: left);
9933 begin += left;
9934 }
9935 if (isLittleEndian != sys::IsLittleEndianHost)
9936 swapStruct(x&: es);
9937 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9938 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
9939 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9940 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9941 else
9942 outs() << "\t esh.count " << es.esh.count
9943 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9944 Print_x86_exception_state_t(exc64&: es.ues.es64);
9945 } else {
9946 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9947 << es.esh.count << "\n";
9948 }
9949 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9950 outs() << " flavor x86_EXCEPTION_STATE64\n";
9951 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9952 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9953 else
9954 outs() << " count " << count
9955 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9956 struct MachO::x86_exception_state64_t es64;
9957 left = end - begin;
9958 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9959 memcpy(dest: &es64, src: begin, n: sizeof(MachO::x86_exception_state64_t));
9960 begin += sizeof(MachO::x86_exception_state64_t);
9961 } else {
9962 memset(s: &es64, c: '\0', n: sizeof(MachO::x86_exception_state64_t));
9963 memcpy(dest: &es64, src: begin, n: left);
9964 begin += left;
9965 }
9966 if (isLittleEndian != sys::IsLittleEndianHost)
9967 swapStruct(x&: es64);
9968 Print_x86_exception_state_t(exc64&: es64);
9969 } else {
9970 outs() << " flavor " << flavor << " (unknown)\n";
9971 outs() << " count " << count << "\n";
9972 outs() << " state (unknown)\n";
9973 begin += count * sizeof(uint32_t);
9974 }
9975 }
9976 } else if (cputype == MachO::CPU_TYPE_ARM) {
9977 while (begin < end) {
9978 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9979 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9980 begin += sizeof(uint32_t);
9981 } else {
9982 flavor = 0;
9983 begin = end;
9984 }
9985 if (isLittleEndian != sys::IsLittleEndianHost)
9986 sys::swapByteOrder(Value&: flavor);
9987 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9988 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9989 begin += sizeof(uint32_t);
9990 } else {
9991 count = 0;
9992 begin = end;
9993 }
9994 if (isLittleEndian != sys::IsLittleEndianHost)
9995 sys::swapByteOrder(Value&: count);
9996 if (flavor == MachO::ARM_THREAD_STATE) {
9997 outs() << " flavor ARM_THREAD_STATE\n";
9998 if (count == MachO::ARM_THREAD_STATE_COUNT)
9999 outs() << " count ARM_THREAD_STATE_COUNT\n";
10000 else
10001 outs() << " count " << count
10002 << " (not ARM_THREAD_STATE_COUNT)\n";
10003 MachO::arm_thread_state32_t cpu32;
10004 left = end - begin;
10005 if (left >= sizeof(MachO::arm_thread_state32_t)) {
10006 memcpy(dest: &cpu32, src: begin, n: sizeof(MachO::arm_thread_state32_t));
10007 begin += sizeof(MachO::arm_thread_state32_t);
10008 } else {
10009 memset(s: &cpu32, c: '\0', n: sizeof(MachO::arm_thread_state32_t));
10010 memcpy(dest: &cpu32, src: begin, n: left);
10011 begin += left;
10012 }
10013 if (isLittleEndian != sys::IsLittleEndianHost)
10014 swapStruct(x&: cpu32);
10015 Print_arm_thread_state32_t(cpu32);
10016 } else {
10017 outs() << " flavor " << flavor << " (unknown)\n";
10018 outs() << " count " << count << "\n";
10019 outs() << " state (unknown)\n";
10020 begin += count * sizeof(uint32_t);
10021 }
10022 }
10023 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
10024 cputype == MachO::CPU_TYPE_ARM64_32) {
10025 while (begin < end) {
10026 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10027 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
10028 begin += sizeof(uint32_t);
10029 } else {
10030 flavor = 0;
10031 begin = end;
10032 }
10033 if (isLittleEndian != sys::IsLittleEndianHost)
10034 sys::swapByteOrder(Value&: flavor);
10035 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10036 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10037 begin += sizeof(uint32_t);
10038 } else {
10039 count = 0;
10040 begin = end;
10041 }
10042 if (isLittleEndian != sys::IsLittleEndianHost)
10043 sys::swapByteOrder(Value&: count);
10044 if (flavor == MachO::ARM_THREAD_STATE64) {
10045 outs() << " flavor ARM_THREAD_STATE64\n";
10046 if (count == MachO::ARM_THREAD_STATE64_COUNT)
10047 outs() << " count ARM_THREAD_STATE64_COUNT\n";
10048 else
10049 outs() << " count " << count
10050 << " (not ARM_THREAD_STATE64_COUNT)\n";
10051 MachO::arm_thread_state64_t cpu64;
10052 left = end - begin;
10053 if (left >= sizeof(MachO::arm_thread_state64_t)) {
10054 memcpy(dest: &cpu64, src: begin, n: sizeof(MachO::arm_thread_state64_t));
10055 begin += sizeof(MachO::arm_thread_state64_t);
10056 } else {
10057 memset(s: &cpu64, c: '\0', n: sizeof(MachO::arm_thread_state64_t));
10058 memcpy(dest: &cpu64, src: begin, n: left);
10059 begin += left;
10060 }
10061 if (isLittleEndian != sys::IsLittleEndianHost)
10062 swapStruct(x&: cpu64);
10063 Print_arm_thread_state64_t(cpu64);
10064 } else {
10065 outs() << " flavor " << flavor << " (unknown)\n";
10066 outs() << " count " << count << "\n";
10067 outs() << " state (unknown)\n";
10068 begin += count * sizeof(uint32_t);
10069 }
10070 }
10071 } else {
10072 while (begin < end) {
10073 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10074 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
10075 begin += sizeof(uint32_t);
10076 } else {
10077 flavor = 0;
10078 begin = end;
10079 }
10080 if (isLittleEndian != sys::IsLittleEndianHost)
10081 sys::swapByteOrder(Value&: flavor);
10082 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10083 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10084 begin += sizeof(uint32_t);
10085 } else {
10086 count = 0;
10087 begin = end;
10088 }
10089 if (isLittleEndian != sys::IsLittleEndianHost)
10090 sys::swapByteOrder(Value&: count);
10091 outs() << " flavor " << flavor << "\n";
10092 outs() << " count " << count << "\n";
10093 outs() << " state (Unknown cputype/cpusubtype)\n";
10094 begin += count * sizeof(uint32_t);
10095 }
10096 }
10097}
10098
10099static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10100 PrintLoadCommand(Cmd: dl.cmd, CmdSize: dl.cmdsize,
10101 IsSizeCorrect: dl.cmdsize >= sizeof(struct MachO::dylib_command),
10102 /*LabelWidth=*/13);
10103 if (dl.dylib.name < dl.cmdsize) {
10104 const char *P = Ptr + dl.dylib.name;
10105 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
10106 } else {
10107 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
10108 }
10109 outs() << " time stamp " << dl.dylib.timestamp << " ";
10110 time_t t = dl.dylib.timestamp;
10111 outs() << ctime(timer: &t);
10112 outs() << " current version ";
10113 if (dl.dylib.current_version == 0xffffffff)
10114 outs() << "n/a\n";
10115 else
10116 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10117 << ((dl.dylib.current_version >> 8) & 0xff) << "."
10118 << (dl.dylib.current_version & 0xff) << "\n";
10119 outs() << "compatibility version ";
10120 if (dl.dylib.compatibility_version == 0xffffffff)
10121 outs() << "n/a\n";
10122 else
10123 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10124 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10125 << (dl.dylib.compatibility_version & 0xff) << "\n";
10126}
10127
10128static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10129 uint32_t object_size) {
10130 PrintLoadCommand(Cmd: ld.cmd, CmdSize: ld.cmdsize,
10131 IsSizeCorrect: ld.cmdsize == sizeof(struct MachO::linkedit_data_command),
10132 /*LabelWidth=*/8);
10133 outs() << " dataoff " << ld.dataoff;
10134 if (ld.dataoff > object_size)
10135 outs() << " (past end of file)\n";
10136 else
10137 outs() << "\n";
10138 outs() << " datasize " << ld.datasize;
10139 uint64_t big_size = ld.dataoff;
10140 big_size += ld.datasize;
10141 if (big_size > object_size)
10142 outs() << " (past end of file)\n";
10143 else
10144 outs() << "\n";
10145}
10146
10147static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10148 uint32_t cputype, bool verbose) {
10149 StringRef Buf = Obj->getData();
10150 unsigned Index = 0;
10151 for (const auto &Command : Obj->load_commands()) {
10152 outs() << "Load command " << Index++ << "\n";
10153 if (Command.C.cmd == MachO::LC_SEGMENT) {
10154 MachO::segment_command SLC = Obj->getSegmentLoadCommand(L: Command);
10155 const char *sg_segname = SLC.segname;
10156 PrintSegmentCommand(cmd: SLC.cmd, cmdsize: SLC.cmdsize, SegName: SLC.segname, vmaddr: SLC.vmaddr,
10157 vmsize: SLC.vmsize, fileoff: SLC.fileoff, filesize: SLC.filesize, maxprot: SLC.maxprot,
10158 initprot: SLC.initprot, nsects: SLC.nsects, flags: SLC.flags, object_size: Buf.size(),
10159 verbose);
10160 for (unsigned j = 0; j < SLC.nsects; j++) {
10161 MachO::section S = Obj->getSection(L: Command, Index: j);
10162 PrintSection(sectname: S.sectname, segname: S.segname, addr: S.addr, size: S.size, offset: S.offset, align: S.align,
10163 reloff: S.reloff, nreloc: S.nreloc, flags: S.flags, reserved1: S.reserved1, reserved2: S.reserved2,
10164 cmd: SLC.cmd, sg_segname, filetype, object_size: Buf.size(), verbose);
10165 }
10166 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10167 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(L: Command);
10168 const char *sg_segname = SLC_64.segname;
10169 PrintSegmentCommand(cmd: SLC_64.cmd, cmdsize: SLC_64.cmdsize, SegName: SLC_64.segname,
10170 vmaddr: SLC_64.vmaddr, vmsize: SLC_64.vmsize, fileoff: SLC_64.fileoff,
10171 filesize: SLC_64.filesize, maxprot: SLC_64.maxprot, initprot: SLC_64.initprot,
10172 nsects: SLC_64.nsects, flags: SLC_64.flags, object_size: Buf.size(), verbose);
10173 for (unsigned j = 0; j < SLC_64.nsects; j++) {
10174 MachO::section_64 S_64 = Obj->getSection64(L: Command, Index: j);
10175 PrintSection(sectname: S_64.sectname, segname: S_64.segname, addr: S_64.addr, size: S_64.size,
10176 offset: S_64.offset, align: S_64.align, reloff: S_64.reloff, nreloc: S_64.nreloc,
10177 flags: S_64.flags, reserved1: S_64.reserved1, reserved2: S_64.reserved2, cmd: SLC_64.cmd,
10178 sg_segname, filetype, object_size: Buf.size(), verbose);
10179 }
10180 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10181 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10182 PrintSymtabLoadCommand(st: Symtab, Is64Bit: Obj->is64Bit(), object_size: Buf.size());
10183 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10184 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10185 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10186 PrintDysymtabLoadCommand(dyst: Dysymtab, nsyms: Symtab.nsyms, object_size: Buf.size(),
10187 Is64Bit: Obj->is64Bit());
10188 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10189 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10190 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(L: Command);
10191 PrintDyldInfoLoadCommand(dc: DyldInfo, object_size: Buf.size());
10192 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10193 Command.C.cmd == MachO::LC_ID_DYLINKER ||
10194 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10195 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(L: Command);
10196 PrintDyldLoadCommand(dyld: Dyld, Ptr: Command.Ptr);
10197 } else if (Command.C.cmd == MachO::LC_UUID) {
10198 MachO::uuid_command Uuid = Obj->getUuidCommand(L: Command);
10199 PrintUuidLoadCommand(uuid: Uuid);
10200 } else if (Command.C.cmd == MachO::LC_RPATH) {
10201 MachO::rpath_command Rpath = Obj->getRpathCommand(L: Command);
10202 PrintRpathLoadCommand(rpath: Rpath, Ptr: Command.Ptr);
10203 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10204 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10205 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10206 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10207 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(L: Command);
10208 PrintVersionMinLoadCommand(vd: Vd);
10209 } else if (Command.C.cmd == MachO::LC_NOTE) {
10210 MachO::note_command Nt = Obj->getNoteLoadCommand(L: Command);
10211 PrintNoteLoadCommand(Nt);
10212 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10213 MachO::build_version_command Bv =
10214 Obj->getBuildVersionLoadCommand(L: Command);
10215 PrintBuildVersionLoadCommand(obj: Obj, bd: Bv, verbose);
10216 } else if (Command.C.cmd == MachO::LC_TARGET_TRIPLE) {
10217 MachO::target_triple_command Tt =
10218 Obj->getTargetTripleLoadCommand(L: Command);
10219 PrintTargetTripleCommand(tt: Tt, Ptr: Command.Ptr);
10220 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10221 MachO::source_version_command Sd = Obj->getSourceVersionCommand(L: Command);
10222 PrintSourceVersionCommand(sd: Sd);
10223 } else if (Command.C.cmd == MachO::LC_MAIN) {
10224 MachO::entry_point_command Ep = Obj->getEntryPointCommand(L: Command);
10225 PrintEntryPointCommand(ep: Ep);
10226 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10227 MachO::encryption_info_command Ei =
10228 Obj->getEncryptionInfoCommand(L: Command);
10229 PrintEncryptionInfoCommand(ec: Ei, object_size: Buf.size());
10230 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10231 MachO::encryption_info_command_64 Ei =
10232 Obj->getEncryptionInfoCommand64(L: Command);
10233 PrintEncryptionInfoCommand64(ec: Ei, object_size: Buf.size());
10234 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10235 MachO::linker_option_command Lo =
10236 Obj->getLinkerOptionLoadCommand(L: Command);
10237 PrintLinkerOptionCommand(lo: Lo, Ptr: Command.Ptr);
10238 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10239 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(L: Command);
10240 PrintSubFrameworkCommand(sub: Sf, Ptr: Command.Ptr);
10241 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10242 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(L: Command);
10243 PrintSubUmbrellaCommand(sub: Sf, Ptr: Command.Ptr);
10244 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10245 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(L: Command);
10246 PrintSubLibraryCommand(sub: Sl, Ptr: Command.Ptr);
10247 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10248 MachO::sub_client_command Sc = Obj->getSubClientCommand(L: Command);
10249 PrintSubClientCommand(sub: Sc, Ptr: Command.Ptr);
10250 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10251 MachO::routines_command Rc = Obj->getRoutinesCommand(L: Command);
10252 PrintRoutinesCommand(r: Rc);
10253 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10254 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(L: Command);
10255 PrintRoutinesCommand64(r: Rc);
10256 } else if (Command.C.cmd == MachO::LC_THREAD ||
10257 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10258 MachO::thread_command Tc = Obj->getThreadCommand(L: Command);
10259 PrintThreadCommand(t: Tc, Ptr: Command.Ptr, isLittleEndian: Obj->isLittleEndian(), cputype);
10260 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10261 Command.C.cmd == MachO::LC_ID_DYLIB ||
10262 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10263 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10264 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10265 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10266 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(L: Command);
10267 PrintDylibCommand(dl: Dl, Ptr: Command.Ptr);
10268 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10269 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10270 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10271 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10272 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10273 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT ||
10274 Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE ||
10275 Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS ||
10276 Command.C.cmd == MachO::LC_ATOM_INFO) {
10277 MachO::linkedit_data_command Ld =
10278 Obj->getLinkeditDataLoadCommand(L: Command);
10279 PrintLinkEditDataCommand(ld: Ld, object_size: Buf.size());
10280 } else {
10281 PrintLoadCommand(Cmd: Command.C.cmd, CmdSize: Command.C.cmdsize, IsSizeCorrect: true,
10282 /*LabelWidth=*/9);
10283 // TODO: get and print the raw bytes of the load command.
10284 }
10285 // TODO: print all the other kinds of load commands.
10286 }
10287}
10288
10289static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10290 if (Obj->is64Bit()) {
10291 MachO::mach_header_64 H_64;
10292 H_64 = Obj->getHeader64();
10293 PrintMachHeader(magic: H_64.magic, cputype: H_64.cputype, cpusubtype: H_64.cpusubtype, filetype: H_64.filetype,
10294 ncmds: H_64.ncmds, sizeofcmds: H_64.sizeofcmds, flags: H_64.flags, verbose);
10295 } else {
10296 MachO::mach_header H;
10297 H = Obj->getHeader();
10298 PrintMachHeader(magic: H.magic, cputype: H.cputype, cpusubtype: H.cpusubtype, filetype: H.filetype, ncmds: H.ncmds,
10299 sizeofcmds: H.sizeofcmds, flags: H.flags, verbose);
10300 }
10301}
10302
10303void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10304 const MachOObjectFile *file = cast<const MachOObjectFile>(Val: Obj);
10305 PrintMachHeader(Obj: file, verbose: Verbose);
10306}
10307
10308void MachODumper::printPrivateHeaders() {
10309 printMachOFileHeader(Obj: &Obj);
10310 if (!FirstPrivateHeader)
10311 printMachOLoadCommands(O: &Obj);
10312}
10313
10314void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10315 const MachOObjectFile *file = cast<const MachOObjectFile>(Val: Obj);
10316 uint32_t filetype = 0;
10317 uint32_t cputype = 0;
10318 if (file->is64Bit()) {
10319 MachO::mach_header_64 H_64;
10320 H_64 = file->getHeader64();
10321 filetype = H_64.filetype;
10322 cputype = H_64.cputype;
10323 } else {
10324 MachO::mach_header H;
10325 H = file->getHeader();
10326 filetype = H.filetype;
10327 cputype = H.cputype;
10328 }
10329 PrintLoadCommands(Obj: file, filetype, cputype, verbose: Verbose);
10330}
10331
10332//===----------------------------------------------------------------------===//
10333// export trie dumping
10334//===----------------------------------------------------------------------===//
10335
10336static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10337 uint64_t BaseSegmentAddress = 0;
10338 for (const auto &Command : Obj->load_commands()) {
10339 if (Command.C.cmd == MachO::LC_SEGMENT) {
10340 MachO::segment_command Seg = Obj->getSegmentLoadCommand(L: Command);
10341 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10342 BaseSegmentAddress = Seg.vmaddr;
10343 break;
10344 }
10345 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10346 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(L: Command);
10347 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10348 BaseSegmentAddress = Seg.vmaddr;
10349 break;
10350 }
10351 }
10352 }
10353 Error Err = Error::success();
10354 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10355 uint64_t Flags = Entry.flags();
10356 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10357 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10358 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10359 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10360 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10361 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10362 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10363 if (ReExport)
10364 outs() << "[re-export] ";
10365 else
10366 outs() << format(Fmt: "0x%08llX ",
10367 Vals: Entry.address() + BaseSegmentAddress);
10368 outs() << Entry.name();
10369 if (WeakDef || ThreadLocal || Resolver || Abs) {
10370 ListSeparator LS;
10371 outs() << " [";
10372 if (WeakDef)
10373 outs() << LS << "weak_def";
10374 if (ThreadLocal)
10375 outs() << LS << "per-thread";
10376 if (Abs)
10377 outs() << LS << "absolute";
10378 if (Resolver)
10379 outs() << LS << format(Fmt: "resolver=0x%08llX", Vals: Entry.other());
10380 outs() << "]";
10381 }
10382 if (ReExport) {
10383 StringRef DylibName = "unknown";
10384 int Ordinal = Entry.other() - 1;
10385 Obj->getLibraryShortNameByIndex(Index: Ordinal, DylibName);
10386 if (Entry.otherName().empty())
10387 outs() << " (from " << DylibName << ")";
10388 else
10389 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10390 }
10391 outs() << "\n";
10392 }
10393 if (Err)
10394 reportError(E: std::move(Err), FileName: Obj->getFileName());
10395}
10396
10397//===----------------------------------------------------------------------===//
10398// rebase table dumping
10399//===----------------------------------------------------------------------===//
10400
10401static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10402 outs() << "segment section address type\n";
10403 Error Err = Error::success();
10404 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10405 StringRef SegmentName = Entry.segmentName();
10406 StringRef SectionName = Entry.sectionName();
10407 uint64_t Address = Entry.address();
10408
10409 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
10410 outs() << format(Fmt: "%-8s %-18s 0x%08" PRIX64 " %s\n",
10411 Vals: SegmentName.str().c_str(), Vals: SectionName.str().c_str(),
10412 Vals: Address, Vals: Entry.typeName().str().c_str());
10413 }
10414 if (Err)
10415 reportError(E: std::move(Err), FileName: Obj->getFileName());
10416}
10417
10418static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10419 StringRef DylibName;
10420 switch (Ordinal) {
10421 case MachO::BIND_SPECIAL_DYLIB_SELF:
10422 return "this-image";
10423 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10424 return "main-executable";
10425 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10426 return "flat-namespace";
10427 case MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP:
10428 return "weak";
10429 default:
10430 if (Ordinal > 0) {
10431 std::error_code EC =
10432 Obj->getLibraryShortNameByIndex(Index: Ordinal - 1, DylibName);
10433 if (EC)
10434 return "<<bad library ordinal>>";
10435 return DylibName;
10436 }
10437 }
10438 return "<<unknown special ordinal>>";
10439}
10440
10441//===----------------------------------------------------------------------===//
10442// bind table dumping
10443//===----------------------------------------------------------------------===//
10444
10445static void printMachOBindTable(object::MachOObjectFile *Obj) {
10446 // Build table of sections so names can used in final output.
10447 outs() << "segment section address type "
10448 "addend dylib symbol\n";
10449 Error Err = Error::success();
10450 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10451 StringRef SegmentName = Entry.segmentName();
10452 StringRef SectionName = Entry.sectionName();
10453 uint64_t Address = Entry.address();
10454
10455 // Table lines look like:
10456 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
10457 StringRef Attr;
10458 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10459 Attr = " (weak_import)";
10460 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10461 << left_justify(Str: SectionName, Width: 18) << " "
10462 << format_hex(N: Address, Width: 10, Upper: true) << " "
10463 << left_justify(Str: Entry.typeName(), Width: 8) << " "
10464 << format_decimal(N: Entry.addend(), Width: 8) << " "
10465 << left_justify(Str: ordinalName(Obj, Ordinal: Entry.ordinal()), Width: 16) << " "
10466 << Entry.symbolName() << Attr << "\n";
10467 }
10468 if (Err)
10469 reportError(E: std::move(Err), FileName: Obj->getFileName());
10470}
10471
10472//===----------------------------------------------------------------------===//
10473// lazy bind table dumping
10474//===----------------------------------------------------------------------===//
10475
10476static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10477 outs() << "segment section address "
10478 "dylib symbol\n";
10479 Error Err = Error::success();
10480 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10481 StringRef SegmentName = Entry.segmentName();
10482 StringRef SectionName = Entry.sectionName();
10483 uint64_t Address = Entry.address();
10484
10485 // Table lines look like:
10486 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
10487 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10488 << left_justify(Str: SectionName, Width: 18) << " "
10489 << format_hex(N: Address, Width: 10, Upper: true) << " "
10490 << left_justify(Str: ordinalName(Obj, Ordinal: Entry.ordinal()), Width: 16) << " "
10491 << Entry.symbolName() << "\n";
10492 }
10493 if (Err)
10494 reportError(E: std::move(Err), FileName: Obj->getFileName());
10495}
10496
10497//===----------------------------------------------------------------------===//
10498// weak bind table dumping
10499//===----------------------------------------------------------------------===//
10500
10501static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10502 outs() << "segment section address "
10503 "type addend symbol\n";
10504 Error Err = Error::success();
10505 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10506 // Strong symbols don't have a location to update.
10507 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10508 outs() << " strong "
10509 << Entry.symbolName() << "\n";
10510 continue;
10511 }
10512 StringRef SegmentName = Entry.segmentName();
10513 StringRef SectionName = Entry.sectionName();
10514 uint64_t Address = Entry.address();
10515
10516 // Table lines look like:
10517 // __DATA __data 0x00001000 pointer 0 _foo
10518 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10519 << left_justify(Str: SectionName, Width: 18) << " "
10520 << format_hex(N: Address, Width: 10, Upper: true) << " "
10521 << left_justify(Str: Entry.typeName(), Width: 8) << " "
10522 << format_decimal(N: Entry.addend(), Width: 8) << " " << Entry.symbolName()
10523 << "\n";
10524 }
10525 if (Err)
10526 reportError(E: std::move(Err), FileName: Obj->getFileName());
10527}
10528
10529// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10530// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10531// information for that address. If the address is found its binding symbol
10532// name is returned. If not nullptr is returned.
10533static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10534 struct DisassembleInfo *info) {
10535 if (info->bindtable == nullptr) {
10536 info->bindtable = std::make_unique<SymbolAddressMap>();
10537 Error Err = Error::success();
10538 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10539 uint64_t Address = Entry.address();
10540 StringRef name = Entry.symbolName();
10541 if (!name.empty())
10542 (*info->bindtable)[Address] = name;
10543 }
10544 if (Err)
10545 reportError(E: std::move(Err), FileName: info->O->getFileName());
10546 }
10547 auto name = info->bindtable->lookup(Val: ReferenceValue);
10548 return !name.empty() ? name.data() : nullptr;
10549}
10550
10551void objdump::printLazyBindTable(ObjectFile *o) {
10552 outs() << "\nLazy bind table:\n";
10553 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10554 printMachOLazyBindTable(Obj: MachO);
10555 else
10556 WithColor::error()
10557 << "This operation is only currently supported "
10558 "for Mach-O executable files.\n";
10559}
10560
10561void objdump::printWeakBindTable(ObjectFile *o) {
10562 outs() << "\nWeak bind table:\n";
10563 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10564 printMachOWeakBindTable(Obj: MachO);
10565 else
10566 WithColor::error()
10567 << "This operation is only currently supported "
10568 "for Mach-O executable files.\n";
10569}
10570
10571void objdump::printExportsTrie(const ObjectFile *o) {
10572 outs() << "\nExports trie:\n";
10573 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10574 printMachOExportsTrie(Obj: MachO);
10575 else
10576 WithColor::error()
10577 << "This operation is only currently supported "
10578 "for Mach-O executable files.\n";
10579}
10580
10581void objdump::printRebaseTable(ObjectFile *o) {
10582 outs() << "\nRebase table:\n";
10583 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10584 printMachORebaseTable(Obj: MachO);
10585 else
10586 WithColor::error()
10587 << "This operation is only currently supported "
10588 "for Mach-O executable files.\n";
10589}
10590
10591void objdump::printBindTable(ObjectFile *o) {
10592 outs() << "\nBind table:\n";
10593 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10594 printMachOBindTable(Obj: MachO);
10595 else
10596 WithColor::error()
10597 << "This operation is only currently supported "
10598 "for Mach-O executable files.\n";
10599}
10600