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 // arm64e images get columns for the signing schema of authenticated fixups.
1370 bool HasAuthColumns = false;
1371 for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1372 SegmentWidth = std::max(a: SegmentWidth, b: Entry.segmentName().size());
1373 SectionWidth = std::max(a: SectionWidth, b: Entry.sectionName().size());
1374 AddressWidth = std::max(a: AddressWidth, b: HexLength(Entry.address()) + 2);
1375 if (Entry.isBind()) {
1376 AddendWidth = std::max(a: AddendWidth, b: HexLength(Entry.addend()) + 2);
1377 DylibWidth = std::max(a: DylibWidth, b: Entry.symbolName().size());
1378 }
1379 HasAuthColumns |=
1380 Entry.pointerFormat() == MachO::DYLD_CHAINED_PTR_ARM64E ||
1381 Entry.pointerFormat() == MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24;
1382 }
1383 // Errors will be handled when printing the table.
1384 if (Err)
1385 consumeError(Err: std::move(Err));
1386
1387 outs() << "dyld information:\n";
1388 outs() << left_justify(Str: "segment", Width: SegmentWidth) << ' '
1389 << left_justify(Str: "section", Width: SectionWidth) << ' '
1390 << left_justify(Str: "address", Width: AddressWidth) << ' '
1391 << left_justify(Str: "pointer", Width: PointerWidth) << " type ";
1392 if (HasAuthColumns)
1393 outs() << "div addr key ";
1394 outs() << left_justify(Str: "addend", Width: AddendWidth) << ' '
1395 << left_justify(Str: "dylib", Width: DylibWidth) << " symbol/vm address\n";
1396 for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1397 outs() << left_justify(Str: Entry.segmentName(), Width: SegmentWidth) << ' '
1398 << left_justify(Str: Entry.sectionName(), Width: SectionWidth) << ' ' << "0x"
1399 << left_justify(Str: utohexstr(X: Entry.address()), Width: AddressWidth - 2) << ' '
1400 << format_hex(N: Entry.rawValue(), Width: PointerWidth, Upper: true) << ' ';
1401 outs() << (Entry.isBind() ? "bind " : "rebase ");
1402 if (HasAuthColumns && Entry.isAuthenticated()) {
1403 static const char *const KeyNames[] = {"IA", "IB", "DA", "DB"};
1404 outs() << format(Fmt: "0x%04X ", Vals: Entry.diversity())
1405 << left_justify(Str: Entry.hasAddressDiversity() ? "true" : "false", Width: 5)
1406 << ' ' << left_justify(Str: KeyNames[Entry.key()], Width: 3) << ' ';
1407 } else if (HasAuthColumns) {
1408 outs().indent(NumSpaces: 17);
1409 }
1410 if (Entry.isBind()) {
1411 outs() << "0x" << left_justify(Str: utohexstr(X: Entry.addend()), Width: AddendWidth - 2)
1412 << ' ' << left_justify(Str: ordinalName(O, Entry.ordinal()), Width: DylibWidth)
1413 << ' ' << Entry.symbolName();
1414 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
1415 outs() << " (weak import)";
1416 outs() << '\n';
1417 } else {
1418 assert(Entry.isRebase());
1419 outs().indent(NumSpaces: AddendWidth + DylibWidth + 1);
1420 outs() << format(Fmt: "0x%" PRIX64, Vals: Entry.pointerValue()) << '\n';
1421 }
1422 }
1423 if (Err)
1424 reportError(E: std::move(Err), FileName: O->getFileName());
1425
1426 // TODO: Print opcode-based fixups if the object uses those.
1427}
1428
1429static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1430 unsigned Index = 0;
1431 for (const auto &Load : O->load_commands()) {
1432 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1433 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1434 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1435 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1436 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1437 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1438 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1439 MachO::dylib_command dl = O->getDylibIDLoadCommand(L: Load);
1440 if (dl.dylib.name < dl.cmdsize) {
1441 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1442 if (JustId)
1443 outs() << p << "\n";
1444 else {
1445 outs() << "\t" << p;
1446 outs() << " (compatibility version "
1447 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1448 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1449 << (dl.dylib.compatibility_version & 0xff) << ",";
1450 outs() << " current version "
1451 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1452 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1453 << (dl.dylib.current_version & 0xff);
1454 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1455 outs() << ", weak";
1456 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1457 outs() << ", reexport";
1458 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1459 outs() << ", upward";
1460 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1461 outs() << ", lazy";
1462 outs() << ")\n";
1463 }
1464 } else {
1465 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1466 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1467 outs() << "LC_ID_DYLIB ";
1468 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1469 outs() << "LC_LOAD_DYLIB ";
1470 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1471 outs() << "LC_LOAD_WEAK_DYLIB ";
1472 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1473 outs() << "LC_LAZY_LOAD_DYLIB ";
1474 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1475 outs() << "LC_REEXPORT_DYLIB ";
1476 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1477 outs() << "LC_LOAD_UPWARD_DYLIB ";
1478 else
1479 outs() << "LC_??? ";
1480 outs() << "command " << Index++ << "\n";
1481 }
1482 }
1483 }
1484}
1485
1486static void printRpaths(MachOObjectFile *O) {
1487 for (const auto &Command : O->load_commands()) {
1488 if (Command.C.cmd == MachO::LC_RPATH) {
1489 auto Rpath = O->getRpathCommand(L: Command);
1490 const char *P = (const char *)(Command.Ptr) + Rpath.path;
1491 outs() << P << "\n";
1492 }
1493 }
1494}
1495
1496typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1497
1498static void CreateSymbolAddressMap(MachOObjectFile *O,
1499 SymbolAddressMap *AddrMap) {
1500 // Create a map of symbol addresses to symbol names.
1501 const StringRef FileName = O->getFileName();
1502 for (const SymbolRef &Symbol : O->symbols()) {
1503 SymbolRef::Type ST = unwrapOrError(EO: Symbol.getType(), Args: FileName);
1504 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1505 ST == SymbolRef::ST_Other) {
1506 uint64_t Address = cantFail(ValOrErr: Symbol.getValue());
1507 StringRef SymName = unwrapOrError(EO: Symbol.getName(), Args: FileName);
1508 if (!SymName.starts_with(Prefix: ".objc"))
1509 (*AddrMap)[Address] = SymName;
1510 }
1511 }
1512}
1513
1514// GuessSymbolName is passed the address of what might be a symbol and a
1515// pointer to the SymbolAddressMap. It returns the name of a symbol
1516// with that address or nullptr if no symbol is found with that address.
1517static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1518 const char *SymbolName = nullptr;
1519 // A DenseMap can't lookup up some values.
1520 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1521 StringRef name = AddrMap->lookup(Val: value);
1522 if (!name.empty())
1523 SymbolName = name.data();
1524 }
1525 return SymbolName;
1526}
1527
1528static void DumpCstringChar(const char c) {
1529 char p[2];
1530 p[0] = c;
1531 p[1] = '\0';
1532 outs().write_escaped(Str: p);
1533}
1534
1535static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1536 uint32_t sect_size, uint64_t sect_addr,
1537 bool print_addresses) {
1538 for (uint32_t i = 0; i < sect_size; i++) {
1539 if (print_addresses) {
1540 if (O->is64Bit())
1541 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1542 else
1543 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1544 }
1545 for (; i < sect_size && sect[i] != '\0'; i++)
1546 DumpCstringChar(c: sect[i]);
1547 if (i < sect_size && sect[i] == '\0')
1548 outs() << "\n";
1549 }
1550}
1551
1552static void DumpLiteral4(uint32_t l, float f) {
1553 outs() << format(Fmt: "0x%08" PRIx32, Vals: l);
1554 if ((l & 0x7f800000) != 0x7f800000)
1555 outs() << format(Fmt: " (%.16e)\n", Vals: f);
1556 else {
1557 if (l == 0x7f800000)
1558 outs() << " (+Infinity)\n";
1559 else if (l == 0xff800000)
1560 outs() << " (-Infinity)\n";
1561 else if ((l & 0x00400000) == 0x00400000)
1562 outs() << " (non-signaling Not-a-Number)\n";
1563 else
1564 outs() << " (signaling Not-a-Number)\n";
1565 }
1566}
1567
1568static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1569 uint32_t sect_size, uint64_t sect_addr,
1570 bool print_addresses) {
1571 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1572 if (print_addresses) {
1573 if (O->is64Bit())
1574 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1575 else
1576 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1577 }
1578 float f;
1579 memcpy(dest: &f, src: sect + i, n: sizeof(float));
1580 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1581 sys::swapByteOrder(Value&: f);
1582 uint32_t l;
1583 memcpy(dest: &l, src: sect + i, n: sizeof(uint32_t));
1584 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1585 sys::swapByteOrder(Value&: l);
1586 DumpLiteral4(l, f);
1587 }
1588}
1589
1590static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1591 double d) {
1592 outs() << format(Fmt: "0x%08" PRIx32, Vals: l0) << " " << format(Fmt: "0x%08" PRIx32, Vals: l1);
1593 uint32_t Hi, Lo;
1594 Hi = (O->isLittleEndian()) ? l1 : l0;
1595 Lo = (O->isLittleEndian()) ? l0 : l1;
1596
1597 // Hi is the high word, so this is equivalent to if(isfinite(d))
1598 if ((Hi & 0x7ff00000) != 0x7ff00000)
1599 outs() << format(Fmt: " (%.16e)\n", Vals: d);
1600 else {
1601 if (Hi == 0x7ff00000 && Lo == 0)
1602 outs() << " (+Infinity)\n";
1603 else if (Hi == 0xfff00000 && Lo == 0)
1604 outs() << " (-Infinity)\n";
1605 else if ((Hi & 0x00080000) == 0x00080000)
1606 outs() << " (non-signaling Not-a-Number)\n";
1607 else
1608 outs() << " (signaling Not-a-Number)\n";
1609 }
1610}
1611
1612static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1613 uint32_t sect_size, uint64_t sect_addr,
1614 bool print_addresses) {
1615 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1616 if (print_addresses) {
1617 if (O->is64Bit())
1618 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1619 else
1620 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1621 }
1622 double d;
1623 memcpy(dest: &d, src: sect + i, n: sizeof(double));
1624 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1625 sys::swapByteOrder(Value&: d);
1626 uint32_t l0, l1;
1627 memcpy(dest: &l0, src: sect + i, n: sizeof(uint32_t));
1628 memcpy(dest: &l1, src: sect + i + sizeof(uint32_t), n: sizeof(uint32_t));
1629 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1630 sys::swapByteOrder(Value&: l0);
1631 sys::swapByteOrder(Value&: l1);
1632 }
1633 DumpLiteral8(O, l0, l1, d);
1634 }
1635}
1636
1637static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1638 outs() << format(Fmt: "0x%08" PRIx32, Vals: l0) << " ";
1639 outs() << format(Fmt: "0x%08" PRIx32, Vals: l1) << " ";
1640 outs() << format(Fmt: "0x%08" PRIx32, Vals: l2) << " ";
1641 outs() << format(Fmt: "0x%08" PRIx32, Vals: l3) << "\n";
1642}
1643
1644static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1645 uint32_t sect_size, uint64_t sect_addr,
1646 bool print_addresses) {
1647 for (uint32_t i = 0; i < sect_size; i += 16) {
1648 if (print_addresses) {
1649 if (O->is64Bit())
1650 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1651 else
1652 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1653 }
1654 uint32_t l0, l1, l2, l3;
1655 memcpy(dest: &l0, src: sect + i, n: sizeof(uint32_t));
1656 memcpy(dest: &l1, src: sect + i + sizeof(uint32_t), n: sizeof(uint32_t));
1657 memcpy(dest: &l2, src: sect + i + 2 * sizeof(uint32_t), n: sizeof(uint32_t));
1658 memcpy(dest: &l3, src: sect + i + 3 * sizeof(uint32_t), n: sizeof(uint32_t));
1659 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1660 sys::swapByteOrder(Value&: l0);
1661 sys::swapByteOrder(Value&: l1);
1662 sys::swapByteOrder(Value&: l2);
1663 sys::swapByteOrder(Value&: l3);
1664 }
1665 DumpLiteral16(l0, l1, l2, l3);
1666 }
1667}
1668
1669static void DumpLiteralPointerSection(MachOObjectFile *O,
1670 const SectionRef &Section,
1671 const char *sect, uint32_t sect_size,
1672 uint64_t sect_addr,
1673 bool print_addresses) {
1674 // Collect the literal sections in this Mach-O file.
1675 std::vector<SectionRef> LiteralSections;
1676 for (const SectionRef &Section : O->sections()) {
1677 DataRefImpl Ref = Section.getRawDataRefImpl();
1678 uint32_t section_type;
1679 if (O->is64Bit()) {
1680 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1681 section_type = Sec.flags & MachO::SECTION_TYPE;
1682 } else {
1683 const MachO::section Sec = O->getSection(DRI: Ref);
1684 section_type = Sec.flags & MachO::SECTION_TYPE;
1685 }
1686 if (section_type == MachO::S_CSTRING_LITERALS ||
1687 section_type == MachO::S_4BYTE_LITERALS ||
1688 section_type == MachO::S_8BYTE_LITERALS ||
1689 section_type == MachO::S_16BYTE_LITERALS)
1690 LiteralSections.push_back(x: Section);
1691 }
1692
1693 // Set the size of the literal pointer.
1694 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1695
1696 // Collect the external relocation symbols for the literal pointers.
1697 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1698 for (const RelocationRef &Reloc : Section.relocations()) {
1699 DataRefImpl Rel;
1700 MachO::any_relocation_info RE;
1701 bool isExtern = false;
1702 Rel = Reloc.getRawDataRefImpl();
1703 RE = O->getRelocation(Rel);
1704 isExtern = O->getPlainRelocationExternal(RE);
1705 if (isExtern) {
1706 uint64_t RelocOffset = Reloc.getOffset();
1707 symbol_iterator RelocSym = Reloc.getSymbol();
1708 Relocs.push_back(x: std::make_pair(x&: RelocOffset, y: *RelocSym));
1709 }
1710 }
1711 array_pod_sort(Start: Relocs.begin(), End: Relocs.end());
1712
1713 // Dump each literal pointer.
1714 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1715 if (print_addresses) {
1716 if (O->is64Bit())
1717 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1718 else
1719 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1720 }
1721 uint64_t lp;
1722 if (O->is64Bit()) {
1723 memcpy(dest: &lp, src: sect + i, n: sizeof(uint64_t));
1724 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1725 sys::swapByteOrder(Value&: lp);
1726 } else {
1727 uint32_t li;
1728 memcpy(dest: &li, src: sect + i, n: sizeof(uint32_t));
1729 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1730 sys::swapByteOrder(Value&: li);
1731 lp = li;
1732 }
1733
1734 // First look for an external relocation entry for this literal pointer.
1735 auto Reloc = find_if(Range&: Relocs, P: [&](const std::pair<uint64_t, SymbolRef> &P) {
1736 return P.first == i;
1737 });
1738 if (Reloc != Relocs.end()) {
1739 symbol_iterator RelocSym = Reloc->second;
1740 StringRef SymName = unwrapOrError(EO: RelocSym->getName(), Args: O->getFileName());
1741 outs() << "external relocation entry for symbol:" << SymName << "\n";
1742 continue;
1743 }
1744
1745 // For local references see what the section the literal pointer points to.
1746 auto Sect = find_if(Range&: LiteralSections, P: [&](const SectionRef &R) {
1747 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1748 });
1749 if (Sect == LiteralSections.end()) {
1750 outs() << format(Fmt: "0x%" PRIx64, Vals: lp) << " (not in a literal section)\n";
1751 continue;
1752 }
1753
1754 uint64_t SectAddress = Sect->getAddress();
1755 uint64_t SectSize = Sect->getSize();
1756
1757 StringRef SectName;
1758 Expected<StringRef> SectNameOrErr = Sect->getName();
1759 if (SectNameOrErr)
1760 SectName = *SectNameOrErr;
1761 else
1762 consumeError(Err: SectNameOrErr.takeError());
1763
1764 DataRefImpl Ref = Sect->getRawDataRefImpl();
1765 StringRef SegmentName = O->getSectionFinalSegmentName(Sec: Ref);
1766 outs() << SegmentName << ":" << SectName << ":";
1767
1768 uint32_t section_type;
1769 if (O->is64Bit()) {
1770 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1771 section_type = Sec.flags & MachO::SECTION_TYPE;
1772 } else {
1773 const MachO::section Sec = O->getSection(DRI: Ref);
1774 section_type = Sec.flags & MachO::SECTION_TYPE;
1775 }
1776
1777 StringRef BytesStr = unwrapOrError(EO: Sect->getContents(), Args: O->getFileName());
1778
1779 const char *Contents = BytesStr.data();
1780
1781 switch (section_type) {
1782 case MachO::S_CSTRING_LITERALS:
1783 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1784 i++) {
1785 DumpCstringChar(c: Contents[i]);
1786 }
1787 outs() << "\n";
1788 break;
1789 case MachO::S_4BYTE_LITERALS:
1790 float f;
1791 memcpy(dest: &f, src: Contents + (lp - SectAddress), n: sizeof(float));
1792 uint32_t l;
1793 memcpy(dest: &l, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1794 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1795 sys::swapByteOrder(Value&: f);
1796 sys::swapByteOrder(Value&: l);
1797 }
1798 DumpLiteral4(l, f);
1799 break;
1800 case MachO::S_8BYTE_LITERALS: {
1801 double d;
1802 memcpy(dest: &d, src: Contents + (lp - SectAddress), n: sizeof(double));
1803 uint32_t l0, l1;
1804 memcpy(dest: &l0, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1805 memcpy(dest: &l1, src: Contents + (lp - SectAddress) + sizeof(uint32_t),
1806 n: sizeof(uint32_t));
1807 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1808 sys::swapByteOrder(Value&: f);
1809 sys::swapByteOrder(Value&: l0);
1810 sys::swapByteOrder(Value&: l1);
1811 }
1812 DumpLiteral8(O, l0, l1, d);
1813 break;
1814 }
1815 case MachO::S_16BYTE_LITERALS: {
1816 uint32_t l0, l1, l2, l3;
1817 memcpy(dest: &l0, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1818 memcpy(dest: &l1, src: Contents + (lp - SectAddress) + sizeof(uint32_t),
1819 n: sizeof(uint32_t));
1820 memcpy(dest: &l2, src: Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1821 n: sizeof(uint32_t));
1822 memcpy(dest: &l3, src: Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1823 n: sizeof(uint32_t));
1824 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1825 sys::swapByteOrder(Value&: l0);
1826 sys::swapByteOrder(Value&: l1);
1827 sys::swapByteOrder(Value&: l2);
1828 sys::swapByteOrder(Value&: l3);
1829 }
1830 DumpLiteral16(l0, l1, l2, l3);
1831 break;
1832 }
1833 }
1834 }
1835}
1836
1837static void DumpInitTermPointerSection(MachOObjectFile *O,
1838 const SectionRef &Section,
1839 const char *sect,
1840 uint32_t sect_size, uint64_t sect_addr,
1841 SymbolAddressMap *AddrMap,
1842 bool verbose) {
1843 uint32_t stride;
1844 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1845
1846 // Collect the external relocation symbols for the pointers.
1847 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1848 for (const RelocationRef &Reloc : Section.relocations()) {
1849 DataRefImpl Rel;
1850 MachO::any_relocation_info RE;
1851 bool isExtern = false;
1852 Rel = Reloc.getRawDataRefImpl();
1853 RE = O->getRelocation(Rel);
1854 isExtern = O->getPlainRelocationExternal(RE);
1855 if (isExtern) {
1856 uint64_t RelocOffset = Reloc.getOffset();
1857 symbol_iterator RelocSym = Reloc.getSymbol();
1858 Relocs.push_back(x: std::make_pair(x&: RelocOffset, y: *RelocSym));
1859 }
1860 }
1861 array_pod_sort(Start: Relocs.begin(), End: Relocs.end());
1862
1863 for (uint32_t i = 0; i < sect_size; i += stride) {
1864 const char *SymbolName = nullptr;
1865 uint64_t p;
1866 if (O->is64Bit()) {
1867 outs() << format(Fmt: "0x%016" PRIx64, Vals: sect_addr + i * stride) << " ";
1868 uint64_t pointer_value;
1869 memcpy(dest: &pointer_value, src: sect + i, n: stride);
1870 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1871 sys::swapByteOrder(Value&: pointer_value);
1872 outs() << format(Fmt: "0x%016" PRIx64, Vals: pointer_value);
1873 p = pointer_value;
1874 } else {
1875 outs() << format(Fmt: "0x%08" PRIx64, Vals: sect_addr + i * stride) << " ";
1876 uint32_t pointer_value;
1877 memcpy(dest: &pointer_value, src: sect + i, n: stride);
1878 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1879 sys::swapByteOrder(Value&: pointer_value);
1880 outs() << format(Fmt: "0x%08" PRIx32, Vals: pointer_value);
1881 p = pointer_value;
1882 }
1883 if (verbose) {
1884 // First look for an external relocation entry for this pointer.
1885 auto Reloc = find_if(Range&: Relocs, P: [&](const std::pair<uint64_t, SymbolRef> &P) {
1886 return P.first == i;
1887 });
1888 if (Reloc != Relocs.end()) {
1889 symbol_iterator RelocSym = Reloc->second;
1890 outs() << " " << unwrapOrError(EO: RelocSym->getName(), Args: O->getFileName());
1891 } else {
1892 SymbolName = GuessSymbolName(value: p, AddrMap);
1893 if (SymbolName)
1894 outs() << " " << SymbolName;
1895 }
1896 }
1897 outs() << "\n";
1898 }
1899}
1900
1901static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1902 uint32_t size, uint64_t addr) {
1903 uint32_t cputype = O->getHeader().cputype;
1904 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1905 uint32_t j;
1906 for (uint32_t i = 0; i < size; i += j, addr += j) {
1907 if (O->is64Bit())
1908 outs() << format(Fmt: "%016" PRIx64, Vals: addr) << "\t";
1909 else
1910 outs() << format(Fmt: "%08" PRIx64, Vals: addr) << "\t";
1911 for (j = 0; j < 16 && i + j < size; j++) {
1912 uint8_t byte_word = *(sect + i + j);
1913 outs() << format(Fmt: "%02" PRIx32, Vals: (uint32_t)byte_word) << " ";
1914 }
1915 outs() << "\n";
1916 }
1917 } else {
1918 uint32_t j;
1919 for (uint32_t i = 0; i < size; i += j, addr += j) {
1920 if (O->is64Bit())
1921 outs() << format(Fmt: "%016" PRIx64, Vals: addr) << "\t";
1922 else
1923 outs() << format(Fmt: "%08" PRIx64, Vals: addr) << "\t";
1924 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1925 j += sizeof(int32_t)) {
1926 if (i + j + sizeof(int32_t) <= size) {
1927 uint32_t long_word;
1928 memcpy(dest: &long_word, src: sect + i + j, n: sizeof(int32_t));
1929 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1930 sys::swapByteOrder(Value&: long_word);
1931 outs() << format(Fmt: "%08" PRIx32, Vals: long_word) << " ";
1932 } else {
1933 for (uint32_t k = 0; i + j + k < size; k++) {
1934 uint8_t byte_word = *(sect + i + j + k);
1935 outs() << format(Fmt: "%02" PRIx32, Vals: (uint32_t)byte_word) << " ";
1936 }
1937 }
1938 }
1939 outs() << "\n";
1940 }
1941 }
1942}
1943
1944static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1945 StringRef DisSegName, StringRef DisSectName);
1946static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1947 uint32_t size, uint32_t addr);
1948static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1949 bool verbose) {
1950 SymbolAddressMap AddrMap;
1951 if (verbose)
1952 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
1953
1954 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1955 StringRef DumpSection = FilterSections[i];
1956 std::pair<StringRef, StringRef> DumpSegSectName;
1957 DumpSegSectName = DumpSection.split(Separator: ',');
1958 StringRef DumpSegName, DumpSectName;
1959 if (!DumpSegSectName.second.empty()) {
1960 DumpSegName = DumpSegSectName.first;
1961 DumpSectName = DumpSegSectName.second;
1962 } else {
1963 DumpSegName = "";
1964 DumpSectName = DumpSegSectName.first;
1965 }
1966 for (const SectionRef &Section : O->sections()) {
1967 StringRef SectName;
1968 Expected<StringRef> SecNameOrErr = Section.getName();
1969 if (SecNameOrErr)
1970 SectName = *SecNameOrErr;
1971 else
1972 consumeError(Err: SecNameOrErr.takeError());
1973
1974 if (!DumpSection.empty())
1975 FoundSectionSet.insert(key: DumpSection);
1976
1977 DataRefImpl Ref = Section.getRawDataRefImpl();
1978 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
1979 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1980 (SectName == DumpSectName)) {
1981
1982 uint32_t section_flags;
1983 if (O->is64Bit()) {
1984 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1985 section_flags = Sec.flags;
1986
1987 } else {
1988 const MachO::section Sec = O->getSection(DRI: Ref);
1989 section_flags = Sec.flags;
1990 }
1991 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1992
1993 StringRef BytesStr =
1994 unwrapOrError(EO: Section.getContents(), Args: O->getFileName());
1995 const char *sect = BytesStr.data();
1996 uint32_t sect_size = BytesStr.size();
1997 uint64_t sect_addr = Section.getAddress();
1998
1999 if (LeadingHeaders)
2000 outs() << "Contents of (" << SegName << "," << SectName
2001 << ") section\n";
2002
2003 if (verbose) {
2004 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
2005 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
2006 DisassembleMachO(Filename, MachOOF: O, DisSegName: SegName, DisSectName: SectName);
2007 continue;
2008 }
2009 if (SegName == "__TEXT" && SectName == "__info_plist") {
2010 outs() << sect;
2011 continue;
2012 }
2013 if (SegName == "__OBJC" && SectName == "__protocol") {
2014 DumpProtocolSection(O, sect, size: sect_size, addr: sect_addr);
2015 continue;
2016 }
2017 switch (section_type) {
2018 case MachO::S_REGULAR:
2019 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2020 break;
2021 case MachO::S_ZEROFILL:
2022 outs() << "zerofill section and has no contents in the file\n";
2023 break;
2024 case MachO::S_CSTRING_LITERALS:
2025 DumpCstringSection(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2026 break;
2027 case MachO::S_4BYTE_LITERALS:
2028 DumpLiteral4Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2029 break;
2030 case MachO::S_8BYTE_LITERALS:
2031 DumpLiteral8Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2032 break;
2033 case MachO::S_16BYTE_LITERALS:
2034 DumpLiteral16Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2035 break;
2036 case MachO::S_LITERAL_POINTERS:
2037 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
2038 print_addresses: LeadingAddr);
2039 break;
2040 case MachO::S_MOD_INIT_FUNC_POINTERS:
2041 case MachO::S_MOD_TERM_FUNC_POINTERS:
2042 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
2043 AddrMap: &AddrMap, verbose);
2044 break;
2045 default:
2046 outs() << "Unknown section type ("
2047 << format(Fmt: "0x%08" PRIx32, Vals: section_type) << ")\n";
2048 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2049 break;
2050 }
2051 } else {
2052 if (section_type == MachO::S_ZEROFILL)
2053 outs() << "zerofill section and has no contents in the file\n";
2054 else
2055 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2056 }
2057 }
2058 }
2059 }
2060}
2061
2062static void DumpInfoPlistSectionContents(StringRef Filename,
2063 MachOObjectFile *O) {
2064 for (const SectionRef &Section : O->sections()) {
2065 StringRef SectName;
2066 Expected<StringRef> SecNameOrErr = Section.getName();
2067 if (SecNameOrErr)
2068 SectName = *SecNameOrErr;
2069 else
2070 consumeError(Err: SecNameOrErr.takeError());
2071
2072 DataRefImpl Ref = Section.getRawDataRefImpl();
2073 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
2074 if (SegName == "__TEXT" && SectName == "__info_plist") {
2075 if (LeadingHeaders)
2076 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
2077 StringRef BytesStr =
2078 unwrapOrError(EO: Section.getContents(), Args: O->getFileName());
2079 const char *sect = BytesStr.data();
2080 outs() << format(Fmt: "%.*s", Vals: BytesStr.size(), Vals: sect) << "\n";
2081 return;
2082 }
2083 }
2084}
2085
2086// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
2087// and if it is and there is a list of architecture flags is specified then
2088// check to make sure this Mach-O file is one of those architectures or all
2089// architectures were specified. If not then an error is generated and this
2090// routine returns false. Else it returns true.
2091static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
2092 auto *MachO = dyn_cast<MachOObjectFile>(Val: O);
2093
2094 if (!MachO || ArchAll || ArchFlags.empty())
2095 return true;
2096
2097 MachO::mach_header H;
2098 MachO::mach_header_64 H_64;
2099 Triple T;
2100 const char *McpuDefault, *ArchFlag;
2101 if (MachO->is64Bit()) {
2102 H_64 = MachO->MachOObjectFile::getHeader64();
2103 T = MachOObjectFile::getArchTriple(CPUType: H_64.cputype, CPUSubType: H_64.cpusubtype,
2104 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2105 } else {
2106 H = MachO->MachOObjectFile::getHeader();
2107 T = MachOObjectFile::getArchTriple(CPUType: H.cputype, CPUSubType: H.cpusubtype,
2108 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2109 }
2110 const std::string ArchFlagName(ArchFlag);
2111 if (!llvm::is_contained(Range&: ArchFlags, Element: ArchFlagName)) {
2112 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2113 << Filename << ": no architecture specified.\n";
2114 return false;
2115 }
2116 return true;
2117}
2118
2119static void printObjcMetaData(MachOObjectFile *O, bool verbose);
2120
2121// ProcessMachO() is passed a single opened Mach-O file, which may be an
2122// archive member and or in a slice of a universal file. It prints the
2123// the file name and header info and then processes it according to the
2124// command line options.
2125static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
2126 StringRef ArchiveMemberName = StringRef(),
2127 StringRef ArchitectureName = StringRef()) {
2128 std::unique_ptr<Dumper> D = createMachODumper(Obj: *MachOOF);
2129
2130 // If we are doing some processing here on the Mach-O file print the header
2131 // info. And don't print it otherwise like in the case of printing the
2132 // UniversalHeaders or ArchiveHeaders.
2133 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
2134 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
2135 DataInCode || FunctionStartsType != FunctionStartsMode::None ||
2136 LinkOptHints || ChainedFixups || DyldInfo || DylibsUsed || DylibId ||
2137 Rpaths || ObjcMetaData || (!FilterSections.empty())) {
2138 if (LeadingHeaders) {
2139 outs() << Name;
2140 if (!ArchiveMemberName.empty())
2141 outs() << '(' << ArchiveMemberName << ')';
2142 if (!ArchitectureName.empty())
2143 outs() << " (architecture " << ArchitectureName << ")";
2144 outs() << ":\n";
2145 }
2146 }
2147 // To use the report_error() form with an ArchiveName and FileName set
2148 // these up based on what is passed for Name and ArchiveMemberName.
2149 StringRef ArchiveName;
2150 StringRef FileName;
2151 if (!ArchiveMemberName.empty()) {
2152 ArchiveName = Name;
2153 FileName = ArchiveMemberName;
2154 } else {
2155 ArchiveName = StringRef();
2156 FileName = Name;
2157 }
2158
2159 // If we need the symbol table to do the operation then check it here to
2160 // produce a good error message as to where the Mach-O file comes from in
2161 // the error message.
2162 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
2163 if (Error Err = MachOOF->checkSymbolTable())
2164 reportError(E: std::move(Err), FileName, ArchiveName, ArchitectureName);
2165
2166 if (DisassembleAll) {
2167 for (const SectionRef &Section : MachOOF->sections()) {
2168 StringRef SectName;
2169 if (Expected<StringRef> NameOrErr = Section.getName())
2170 SectName = *NameOrErr;
2171 else
2172 consumeError(Err: NameOrErr.takeError());
2173
2174 if (SectName == "__text") {
2175 DataRefImpl Ref = Section.getRawDataRefImpl();
2176 StringRef SegName = MachOOF->getSectionFinalSegmentName(Sec: Ref);
2177 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: SegName, DisSectName: SectName);
2178 }
2179 }
2180 }
2181 else if (Disassemble) {
2182 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
2183 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
2184 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: "__TEXT_EXEC", DisSectName: "__text");
2185 else
2186 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: "__TEXT", DisSectName: "__text");
2187 }
2188 if (IndirectSymbols)
2189 PrintIndirectSymbols(O: MachOOF, verbose: Verbose);
2190 if (DataInCode)
2191 PrintDataInCodeTable(O: MachOOF, verbose: Verbose);
2192 if (FunctionStartsType != FunctionStartsMode::None)
2193 PrintFunctionStarts(O: MachOOF);
2194 if (LinkOptHints)
2195 PrintLinkOptHints(O: MachOOF);
2196 if (Relocations)
2197 PrintRelocations(O: MachOOF, verbose: Verbose);
2198 if (SectionHeaders)
2199 printSectionHeaders(O&: *MachOOF);
2200 if (SectionContents)
2201 printSectionContents(O: MachOOF);
2202 if (!FilterSections.empty())
2203 DumpSectionContents(Filename: FileName, O: MachOOF, verbose: Verbose);
2204 if (InfoPlist)
2205 DumpInfoPlistSectionContents(Filename: FileName, O: MachOOF);
2206 if (DyldInfo)
2207 PrintDyldInfo(O: MachOOF);
2208 if (ChainedFixups)
2209 PrintChainedFixups(O: MachOOF);
2210 if (DylibsUsed)
2211 PrintDylibs(O: MachOOF, JustId: false);
2212 if (DylibId)
2213 PrintDylibs(O: MachOOF, JustId: true);
2214 if (SymbolTable)
2215 D->printSymbolTable(ArchiveName, ArchitectureName);
2216 if (UnwindInfo)
2217 printMachOUnwindInfo(O: MachOOF);
2218 if (PrivateHeaders) {
2219 printMachOFileHeader(O: MachOOF);
2220 printMachOLoadCommands(O: MachOOF);
2221 }
2222 if (FirstPrivateHeader)
2223 printMachOFileHeader(O: MachOOF);
2224 if (ObjcMetaData)
2225 printObjcMetaData(O: MachOOF, verbose: Verbose);
2226 if (ExportsTrie)
2227 printExportsTrie(O: MachOOF);
2228 if (Rebase)
2229 printRebaseTable(O: MachOOF);
2230 if (Rpaths)
2231 printRpaths(O: MachOOF);
2232 if (Bind)
2233 printBindTable(O: MachOOF);
2234 if (LazyBind)
2235 printLazyBindTable(O: MachOOF);
2236 if (WeakBind)
2237 printWeakBindTable(O: MachOOF);
2238
2239 if (DwarfDumpType != DIDT_Null) {
2240 std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj: *MachOOF);
2241 // Dump the complete DWARF structure.
2242 DIDumpOptions DumpOpts;
2243 DumpOpts.DumpType = DwarfDumpType;
2244 DICtx->dump(OS&: outs(), DumpOpts);
2245 }
2246}
2247
2248// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2249static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2250 outs() << " cputype (" << cputype << ")\n";
2251 outs() << " cpusubtype (" << cpusubtype << ")\n";
2252}
2253
2254// printCPUType() helps print_fat_headers by printing the cputype and
2255// pusubtype (symbolically for the one's it knows about).
2256static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2257 switch (cputype) {
2258 case MachO::CPU_TYPE_I386:
2259 switch (cpusubtype) {
2260 case MachO::CPU_SUBTYPE_I386_ALL:
2261 outs() << " cputype CPU_TYPE_I386\n";
2262 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
2263 break;
2264 default:
2265 printUnknownCPUType(cputype, cpusubtype);
2266 break;
2267 }
2268 break;
2269 case MachO::CPU_TYPE_X86_64:
2270 switch (cpusubtype) {
2271 case MachO::CPU_SUBTYPE_X86_64_ALL:
2272 outs() << " cputype CPU_TYPE_X86_64\n";
2273 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2274 break;
2275 case MachO::CPU_SUBTYPE_X86_64_H:
2276 outs() << " cputype CPU_TYPE_X86_64\n";
2277 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2278 break;
2279 default:
2280 printUnknownCPUType(cputype, cpusubtype);
2281 break;
2282 }
2283 break;
2284 case MachO::CPU_TYPE_ARM:
2285 switch (cpusubtype) {
2286 case MachO::CPU_SUBTYPE_ARM_ALL:
2287 outs() << " cputype CPU_TYPE_ARM\n";
2288 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2289 break;
2290 case MachO::CPU_SUBTYPE_ARM_V4T:
2291 outs() << " cputype CPU_TYPE_ARM\n";
2292 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2293 break;
2294 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2295 outs() << " cputype CPU_TYPE_ARM\n";
2296 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2297 break;
2298 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2299 outs() << " cputype CPU_TYPE_ARM\n";
2300 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2301 break;
2302 case MachO::CPU_SUBTYPE_ARM_V6:
2303 outs() << " cputype CPU_TYPE_ARM\n";
2304 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2305 break;
2306 case MachO::CPU_SUBTYPE_ARM_V6M:
2307 outs() << " cputype CPU_TYPE_ARM\n";
2308 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2309 break;
2310 case MachO::CPU_SUBTYPE_ARM_V7:
2311 outs() << " cputype CPU_TYPE_ARM\n";
2312 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2313 break;
2314 case MachO::CPU_SUBTYPE_ARM_V7EM:
2315 outs() << " cputype CPU_TYPE_ARM\n";
2316 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2317 break;
2318 case MachO::CPU_SUBTYPE_ARM_V7K:
2319 outs() << " cputype CPU_TYPE_ARM\n";
2320 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2321 break;
2322 case MachO::CPU_SUBTYPE_ARM_V7M:
2323 outs() << " cputype CPU_TYPE_ARM\n";
2324 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2325 break;
2326 case MachO::CPU_SUBTYPE_ARM_V7S:
2327 outs() << " cputype CPU_TYPE_ARM\n";
2328 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2329 break;
2330 case MachO::CPU_SUBTYPE_ARM_V8M_MAIN:
2331 outs() << " cputype CPU_TYPE_ARM\n";
2332 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8M_MAIN\n";
2333 break;
2334 case MachO::CPU_SUBTYPE_ARM_V8M_BASE:
2335 outs() << " cputype CPU_TYPE_ARM\n";
2336 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8M_BASE\n";
2337 break;
2338 case MachO::CPU_SUBTYPE_ARM_V8_1M_MAIN:
2339 outs() << " cputype CPU_TYPE_ARM\n";
2340 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8_1M_MAIN\n";
2341 break;
2342 default:
2343 printUnknownCPUType(cputype, cpusubtype);
2344 break;
2345 }
2346 break;
2347 case MachO::CPU_TYPE_ARM64:
2348 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2349 case MachO::CPU_SUBTYPE_ARM64_ALL:
2350 outs() << " cputype CPU_TYPE_ARM64\n";
2351 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2352 break;
2353 case MachO::CPU_SUBTYPE_ARM64_V8:
2354 outs() << " cputype CPU_TYPE_ARM64\n";
2355 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2356 break;
2357 case MachO::CPU_SUBTYPE_ARM64E:
2358 outs() << " cputype CPU_TYPE_ARM64\n";
2359 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2360 break;
2361 case MachO::CPU_SUBTYPE_ARM64E_X1:
2362 outs() << " cputype CPU_TYPE_ARM64\n";
2363 outs() << " cpusubtype CPU_SUBTYPE_ARM64E_X1\n";
2364 break;
2365 default:
2366 printUnknownCPUType(cputype, cpusubtype);
2367 break;
2368 }
2369 break;
2370 case MachO::CPU_TYPE_ARM64_32:
2371 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2372 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2373 outs() << " cputype CPU_TYPE_ARM64_32\n";
2374 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2375 break;
2376 default:
2377 printUnknownCPUType(cputype, cpusubtype);
2378 break;
2379 }
2380 break;
2381 default:
2382 printUnknownCPUType(cputype, cpusubtype);
2383 break;
2384 }
2385}
2386
2387static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2388 bool verbose) {
2389 outs() << "Fat headers\n";
2390 if (verbose) {
2391 if (UB->getMagic() == MachO::FAT_MAGIC)
2392 outs() << "fat_magic FAT_MAGIC\n";
2393 else // UB->getMagic() == MachO::FAT_MAGIC_64
2394 outs() << "fat_magic FAT_MAGIC_64\n";
2395 } else
2396 outs() << "fat_magic " << format(Fmt: "0x%" PRIx32, Vals: MachO::FAT_MAGIC) << "\n";
2397
2398 uint32_t nfat_arch = UB->getNumberOfObjects();
2399 StringRef Buf = UB->getData();
2400 uint64_t size = Buf.size();
2401 uint64_t big_size = sizeof(struct MachO::fat_header) +
2402 nfat_arch * sizeof(struct MachO::fat_arch);
2403 outs() << "nfat_arch " << UB->getNumberOfObjects();
2404 if (nfat_arch == 0)
2405 outs() << " (malformed, contains zero architecture types)\n";
2406 else if (big_size > size)
2407 outs() << " (malformed, architectures past end of file)\n";
2408 else
2409 outs() << "\n";
2410
2411 for (uint32_t i = 0; i < nfat_arch; ++i) {
2412 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2413 uint32_t cputype = OFA.getCPUType();
2414 uint32_t cpusubtype = OFA.getCPUSubType();
2415 outs() << "architecture ";
2416 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2417 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2418 uint32_t other_cputype = other_OFA.getCPUType();
2419 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2420 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2421 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2422 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2423 outs() << "(illegal duplicate architecture) ";
2424 break;
2425 }
2426 }
2427 if (verbose) {
2428 outs() << OFA.getArchFlagName() << "\n";
2429 printCPUType(cputype, cpusubtype: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2430 } else {
2431 outs() << i << "\n";
2432 outs() << " cputype " << cputype << "\n";
2433 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2434 << "\n";
2435 }
2436 if (verbose && cputype == MachO::CPU_TYPE_ARM64 &&
2437 MachO::CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(ST: cpusubtype)) {
2438 outs() << " capabilities CPU_SUBTYPE_ARM64E_";
2439 if (MachO::CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(ST: cpusubtype))
2440 outs() << "KERNEL_";
2441 outs() << format(Fmt: "PTRAUTH_VERSION %d",
2442 Vals: MachO::CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(ST: cpusubtype))
2443 << "\n";
2444 } else if (verbose && (cpusubtype & MachO::CPU_SUBTYPE_MASK) ==
2445 MachO::CPU_SUBTYPE_LIB64)
2446 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2447 else
2448 outs() << " capabilities "
2449 << format(Fmt: "0x%" PRIx32,
2450 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2451 outs() << " offset " << OFA.getOffset();
2452 if (OFA.getOffset() > size)
2453 outs() << " (past end of file)";
2454 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2455 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2456 outs() << "\n";
2457 outs() << " size " << OFA.getSize();
2458 big_size = OFA.getOffset() + OFA.getSize();
2459 if (big_size > size)
2460 outs() << " (past end of file)";
2461 outs() << "\n";
2462 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2463 << ")\n";
2464 }
2465}
2466
2467static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2468 size_t ChildIndex, bool verbose,
2469 bool print_offset,
2470 StringRef ArchitectureName = StringRef()) {
2471 if (print_offset)
2472 outs() << C.getChildOffset() << "\t";
2473 sys::fs::perms Mode =
2474 unwrapOrError(EO: C.getAccessMode(), Args: getFileNameForError(C, Index: ChildIndex),
2475 Args&: Filename, Args&: ArchitectureName);
2476 if (verbose) {
2477 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2478 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2479 outs() << "-";
2480 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2481 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2482 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2483 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2484 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2485 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2486 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2487 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2488 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2489 } else {
2490 outs() << format(Fmt: "0%o ", Vals: Mode);
2491 }
2492
2493 outs() << format(Fmt: "%3d/%-3d %5" PRId64 " ",
2494 Vals: unwrapOrError(EO: C.getUID(), Args: getFileNameForError(C, Index: ChildIndex),
2495 Args&: Filename, Args&: ArchitectureName),
2496 Vals: unwrapOrError(EO: C.getGID(), Args: getFileNameForError(C, Index: ChildIndex),
2497 Args&: Filename, Args&: ArchitectureName),
2498 Vals: unwrapOrError(EO: C.getRawSize(),
2499 Args: getFileNameForError(C, Index: ChildIndex), Args&: Filename,
2500 Args&: ArchitectureName));
2501
2502 StringRef RawLastModified = C.getRawLastModified();
2503 if (verbose) {
2504 unsigned Seconds;
2505 if (RawLastModified.getAsInteger(Radix: 10, Result&: Seconds))
2506 outs() << "(date: \"" << RawLastModified
2507 << "\" contains non-decimal chars) ";
2508 else {
2509 // Since cime(3) returns a 26 character string of the form:
2510 // "Sun Sep 16 01:03:52 1973\n\0"
2511 // just print 24 characters.
2512 time_t t = Seconds;
2513 outs() << format(Fmt: "%.24s ", Vals: ctime(timer: &t));
2514 }
2515 } else {
2516 outs() << RawLastModified << " ";
2517 }
2518
2519 if (verbose) {
2520 Expected<StringRef> NameOrErr = C.getName();
2521 if (!NameOrErr) {
2522 consumeError(Err: NameOrErr.takeError());
2523 outs() << unwrapOrError(EO: C.getRawName(),
2524 Args: getFileNameForError(C, Index: ChildIndex), Args&: Filename,
2525 Args&: ArchitectureName)
2526 << "\n";
2527 } else {
2528 StringRef Name = NameOrErr.get();
2529 outs() << Name << "\n";
2530 }
2531 } else {
2532 outs() << unwrapOrError(EO: C.getRawName(), Args: getFileNameForError(C, Index: ChildIndex),
2533 Args&: Filename, Args&: ArchitectureName)
2534 << "\n";
2535 }
2536}
2537
2538static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2539 bool print_offset,
2540 StringRef ArchitectureName = StringRef()) {
2541 Error Err = Error::success();
2542 size_t I = 0;
2543 for (const auto &C : A->children(Err, SkipInternal: false))
2544 printArchiveChild(Filename, C, ChildIndex: I++, verbose, print_offset,
2545 ArchitectureName);
2546
2547 if (Err)
2548 reportError(E: std::move(Err), FileName: Filename, ArchiveName: "", ArchitectureName);
2549}
2550
2551static bool ValidateArchFlags() {
2552 // Check for -arch all and verifiy the -arch flags are valid.
2553 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2554 if (ArchFlags[i] == "all") {
2555 ArchAll = true;
2556 } else {
2557 if (!MachOObjectFile::isValidArch(ArchFlag: ArchFlags[i])) {
2558 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2559 << "unknown architecture named '" + ArchFlags[i] +
2560 "'for the -arch option\n";
2561 return false;
2562 }
2563 }
2564 }
2565 return true;
2566}
2567
2568static bool skipArchiveMember(const object::Archive::Child &C,
2569 StringRef Filename) {
2570 if (ArchiveMemberFilter.empty())
2571 return false;
2572 Expected<StringRef> NameOrErr = C.getName();
2573 if (!NameOrErr) {
2574 reportError(E: NameOrErr.takeError(), FileName: Filename);
2575 return true;
2576 }
2577 return *NameOrErr != ArchiveMemberFilter;
2578}
2579
2580// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2581// -arch flags selecting just those slices as specified by them and also parses
2582// archive files. Then for each individual Mach-O file ProcessMachO() is
2583// called to process the file based on the command line options.
2584void objdump::parseInputMachO(StringRef Filename) {
2585 if (!ValidateArchFlags())
2586 return;
2587
2588 // In otool mode, support archive(member) syntax: if the filename ends
2589 // with ')' and contains '(', split it into the archive path and member
2590 // name. The -m option disables this parsing.
2591 ArchiveMemberFilter.clear();
2592 if (IsOtool && UseMemberSyntax && !Filename.empty() &&
2593 Filename.back() == ')') {
2594 auto Pos = Filename.rfind(C: '(');
2595 if (Pos != StringRef::npos && Pos > 0) {
2596 ArchiveMemberFilter = Filename.substr(Start: Pos + 1).drop_back().str();
2597 Filename = Filename.substr(Start: 0, N: Pos);
2598 }
2599 }
2600
2601 // Attempt to open the binary.
2602 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Path: Filename);
2603 if (!BinaryOrErr) {
2604 if (Error E = isNotObjectErrorInvalidFileType(Err: BinaryOrErr.takeError()))
2605 reportError(E: std::move(E), FileName: Filename);
2606 else
2607 outs() << Filename << ": is not an object file\n";
2608 return;
2609 }
2610 Binary &Bin = *BinaryOrErr.get().getBinary();
2611
2612 if (Archive *A = dyn_cast<Archive>(Val: &Bin)) {
2613 outs() << "Archive : " << Filename << "\n";
2614 if (ArchiveHeaders)
2615 printArchiveHeaders(Filename, A, verbose: Verbose, print_offset: ArchiveMemberOffsets);
2616
2617 Error Err = Error::success();
2618 unsigned I = -1;
2619 bool FoundMember = false;
2620 for (auto &C : A->children(Err)) {
2621 ++I;
2622 if (skipArchiveMember(C, Filename))
2623 continue;
2624 FoundMember = true;
2625 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2626 if (!ChildOrErr) {
2627 if (Error E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2628 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename);
2629 continue;
2630 }
2631 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get())) {
2632 if (!checkMachOAndArchFlags(O, Filename))
2633 return;
2634 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName());
2635 }
2636 }
2637 if (Err)
2638 reportError(E: std::move(Err), FileName: Filename);
2639 if (!FoundMember && !ArchiveMemberFilter.empty())
2640 reportError(File: Filename, Message: "archive does not contain a member named: " +
2641 ArchiveMemberFilter);
2642 return;
2643 }
2644 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Bin)) {
2645 parseInputMachO(UB);
2646 return;
2647 }
2648 if (!ArchiveMemberFilter.empty()) {
2649 reportError(File: Filename, Message: "not an archive (cannot extract member: " +
2650 ArchiveMemberFilter + ")");
2651 return;
2652 }
2653 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Bin)) {
2654 if (!checkMachOAndArchFlags(O, Filename))
2655 return;
2656 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &*O))
2657 ProcessMachO(Name: Filename, MachOOF);
2658 else
2659 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2660 << Filename << "': "
2661 << "object is not a Mach-O file type.\n";
2662 return;
2663 }
2664 llvm_unreachable("Input object can't be invalid at this point");
2665}
2666
2667void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2668 if (!ValidateArchFlags())
2669 return;
2670
2671 auto Filename = UB->getFileName();
2672
2673 if (UniversalHeaders)
2674 printMachOUniversalHeaders(UB, verbose: Verbose);
2675
2676 // If we have a list of architecture flags specified dump only those.
2677 if (!ArchAll && !ArchFlags.empty()) {
2678 // Look for a slice in the universal binary that matches each ArchFlag.
2679 bool ArchFound;
2680 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2681 ArchFound = false;
2682 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2683 E = UB->end_objects();
2684 I != E; ++I) {
2685 if (ArchFlags[i] == I->getArchFlagName()) {
2686 ArchFound = true;
2687 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2688 I->getAsObjectFile();
2689 std::string ArchitectureName;
2690 if (ArchFlags.size() > 1)
2691 ArchitectureName = I->getArchFlagName();
2692 if (ObjOrErr) {
2693 ObjectFile &O = *ObjOrErr.get();
2694 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &O))
2695 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: "", ArchitectureName);
2696 } else if (Error E = isNotObjectErrorInvalidFileType(
2697 Err: ObjOrErr.takeError())) {
2698 reportError(E: std::move(E), FileName: "", ArchiveName: Filename, ArchitectureName);
2699 continue;
2700 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2701 I->getAsArchive()) {
2702 std::unique_ptr<Archive> &A = *AOrErr;
2703 outs() << "Archive : " << Filename;
2704 if (!ArchitectureName.empty())
2705 outs() << " (architecture " << ArchitectureName << ")";
2706 outs() << "\n";
2707 if (ArchiveHeaders)
2708 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose,
2709 print_offset: ArchiveMemberOffsets, ArchitectureName);
2710 Error Err = Error::success();
2711 unsigned I = -1;
2712 bool FoundMember = false;
2713 for (auto &C : A->children(Err)) {
2714 ++I;
2715 if (skipArchiveMember(C, Filename))
2716 continue;
2717 FoundMember = true;
2718 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2719 if (!ChildOrErr) {
2720 if (Error E =
2721 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2722 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename,
2723 ArchitectureName);
2724 continue;
2725 }
2726 if (MachOObjectFile *O =
2727 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get()))
2728 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName(), ArchitectureName);
2729 }
2730 if (Err)
2731 reportError(E: std::move(Err), FileName: Filename);
2732 if (!FoundMember && !ArchiveMemberFilter.empty())
2733 reportError(File: Filename,
2734 Message: "archive does not contain a member named: " +
2735 ArchiveMemberFilter);
2736 } else {
2737 consumeError(Err: AOrErr.takeError());
2738 reportError(File: Filename,
2739 Message: "Mach-O universal file for architecture " +
2740 StringRef(I->getArchFlagName()) +
2741 " is not a Mach-O file or an archive file");
2742 }
2743 }
2744 }
2745 if (!ArchFound) {
2746 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2747 << "file: " + Filename + " does not contain "
2748 << "architecture: " + ArchFlags[i] + "\n";
2749 return;
2750 }
2751 }
2752 return;
2753 }
2754 // No architecture flags were specified so if this contains a slice that
2755 // matches the host architecture dump only that. For otool -a dump all
2756 // architectures to match classic otool behaviour.
2757 if (!ArchAll && !(IsOtool && ArchiveHeaders)) {
2758 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2759 E = UB->end_objects();
2760 I != E; ++I) {
2761 if (MachOObjectFile::getHostArch().getArchName() ==
2762 I->getArchFlagName()) {
2763 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2764 std::string ArchiveName;
2765 ArchiveName.clear();
2766 if (ObjOrErr) {
2767 ObjectFile &O = *ObjOrErr.get();
2768 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &O))
2769 ProcessMachO(Name: Filename, MachOOF);
2770 } else if (Error E =
2771 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2772 reportError(E: std::move(E), FileName: Filename);
2773 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2774 I->getAsArchive()) {
2775 std::unique_ptr<Archive> &A = *AOrErr;
2776 outs() << "Archive : " << Filename << "\n";
2777 if (ArchiveHeaders)
2778 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose,
2779 print_offset: ArchiveMemberOffsets);
2780 Error Err = Error::success();
2781 unsigned I = -1;
2782 bool FoundMember = false;
2783 for (auto &C : A->children(Err)) {
2784 ++I;
2785 if (skipArchiveMember(C, Filename))
2786 continue;
2787 FoundMember = true;
2788 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2789 if (!ChildOrErr) {
2790 if (Error E =
2791 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2792 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename);
2793 continue;
2794 }
2795 if (MachOObjectFile *O =
2796 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get()))
2797 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName());
2798 }
2799 if (Err)
2800 reportError(E: std::move(Err), FileName: Filename);
2801 if (!FoundMember && !ArchiveMemberFilter.empty())
2802 reportError(File: Filename, Message: "archive does not contain a member named: " +
2803 ArchiveMemberFilter);
2804 } else {
2805 consumeError(Err: AOrErr.takeError());
2806 reportError(File: Filename, Message: "Mach-O universal file for architecture " +
2807 StringRef(I->getArchFlagName()) +
2808 " is not a Mach-O file or an archive file");
2809 }
2810 return;
2811 }
2812 }
2813 }
2814 // Either all architectures have been specified or none have been specified
2815 // and this does not contain the host architecture so dump all the slices.
2816 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2817 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2818 E = UB->end_objects();
2819 I != E; ++I) {
2820 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2821 std::string ArchitectureName;
2822 if (moreThanOneArch)
2823 ArchitectureName = I->getArchFlagName();
2824 if (ObjOrErr) {
2825 ObjectFile &Obj = *ObjOrErr.get();
2826 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &Obj))
2827 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: "", ArchitectureName);
2828 } else if (Error E =
2829 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2830 reportError(E: std::move(E), FileName: Filename, ArchiveName: "", ArchitectureName);
2831 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2832 std::unique_ptr<Archive> &A = *AOrErr;
2833 outs() << "Archive : " << Filename;
2834 if (!ArchitectureName.empty())
2835 outs() << " (architecture " << ArchitectureName << ")";
2836 outs() << "\n";
2837 if (ArchiveHeaders)
2838 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose, print_offset: ArchiveMemberOffsets,
2839 ArchitectureName);
2840 Error Err = Error::success();
2841 unsigned I = -1;
2842 bool FoundMember = false;
2843 for (auto &C : A->children(Err)) {
2844 ++I;
2845 if (skipArchiveMember(C, Filename))
2846 continue;
2847 FoundMember = true;
2848 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2849 if (!ChildOrErr) {
2850 if (Error E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2851 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename,
2852 ArchitectureName);
2853 continue;
2854 }
2855 if (MachOObjectFile *O =
2856 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get())) {
2857 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName(), ArchitectureName);
2858 }
2859 }
2860 if (Err)
2861 reportError(E: std::move(Err), FileName: Filename);
2862 if (!FoundMember && !ArchiveMemberFilter.empty())
2863 reportError(File: Filename, Message: "archive does not contain a member named: " +
2864 ArchiveMemberFilter);
2865 } else {
2866 consumeError(Err: AOrErr.takeError());
2867 reportError(File: Filename, Message: "Mach-O universal file for architecture " +
2868 StringRef(I->getArchFlagName()) +
2869 " is not a Mach-O file or an archive file");
2870 }
2871 }
2872}
2873
2874namespace {
2875// The block of info used by the Symbolizer call backs.
2876struct DisassembleInfo {
2877 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2878 std::vector<SectionRef> *Sections, bool verbose)
2879 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2880 bool verbose;
2881 MachOObjectFile *O;
2882 SectionRef S;
2883 SymbolAddressMap *AddrMap;
2884 std::vector<SectionRef> *Sections;
2885 const char *class_name = nullptr;
2886 const char *selector_name = nullptr;
2887 std::unique_ptr<char[]> method = nullptr;
2888 char *demangled_name = nullptr;
2889 uint64_t adrp_addr = 0;
2890 uint32_t adrp_inst = 0;
2891 std::unique_ptr<SymbolAddressMap> bindtable;
2892 uint32_t depth = 0;
2893};
2894} // namespace
2895
2896// SymbolizerGetOpInfo() is the operand information call back function.
2897// This is called to get the symbolic information for operand(s) of an
2898// instruction when it is being done. This routine does this from
2899// the relocation information, symbol table, etc. That block of information
2900// is a pointer to the struct DisassembleInfo that was passed when the
2901// disassembler context was created and passed to back to here when
2902// called back by the disassembler for instruction operands that could have
2903// relocation information. The address of the instruction containing operand is
2904// at the Pc parameter. The immediate value the operand has is passed in
2905// op_info->Value and is at Offset past the start of the instruction and has a
2906// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2907// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2908// names and addends of the symbolic expression to add for the operand. The
2909// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2910// information is returned then this function returns 1 else it returns 0.
2911static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2912 uint64_t OpSize, uint64_t InstSize, int TagType,
2913 void *TagBuf) {
2914 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2915 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2916 uint64_t value = op_info->Value;
2917
2918 // Make sure all fields returned are zero if we don't set them.
2919 memset(s: (void *)op_info, c: '\0', n: sizeof(struct LLVMOpInfo1));
2920 op_info->Value = value;
2921
2922 // If the TagType is not the value 1 which it code knows about or if no
2923 // verbose symbolic information is wanted then just return 0, indicating no
2924 // information is being returned.
2925 if (TagType != 1 || !info->verbose)
2926 return 0;
2927
2928 unsigned int Arch = info->O->getArch();
2929 if (Arch == Triple::x86) {
2930 if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2931 return 0;
2932 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2933 // TODO:
2934 // Search the external relocation entries of a fully linked image
2935 // (if any) for an entry that matches this segment offset.
2936 // uint32_t seg_offset = (Pc + Offset);
2937 return 0;
2938 }
2939 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2940 // for an entry for this section offset.
2941 uint32_t sect_addr = info->S.getAddress();
2942 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2943 bool reloc_found = false;
2944 DataRefImpl Rel;
2945 MachO::any_relocation_info RE;
2946 bool isExtern = false;
2947 SymbolRef Symbol;
2948 bool r_scattered = false;
2949 uint32_t r_value, pair_r_value, r_type;
2950 for (const RelocationRef &Reloc : info->S.relocations()) {
2951 uint64_t RelocOffset = Reloc.getOffset();
2952 if (RelocOffset == sect_offset) {
2953 Rel = Reloc.getRawDataRefImpl();
2954 RE = info->O->getRelocation(Rel);
2955 r_type = info->O->getAnyRelocationType(RE);
2956 r_scattered = info->O->isRelocationScattered(RE);
2957 if (r_scattered) {
2958 r_value = info->O->getScatteredRelocationValue(RE);
2959 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2960 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2961 DataRefImpl RelNext = Rel;
2962 info->O->moveRelocationNext(Rel&: RelNext);
2963 MachO::any_relocation_info RENext;
2964 RENext = info->O->getRelocation(Rel: RelNext);
2965 if (info->O->isRelocationScattered(RE: RENext))
2966 pair_r_value = info->O->getScatteredRelocationValue(RE: RENext);
2967 else
2968 return 0;
2969 }
2970 } else {
2971 isExtern = info->O->getPlainRelocationExternal(RE);
2972 if (isExtern) {
2973 symbol_iterator RelocSym = Reloc.getSymbol();
2974 Symbol = *RelocSym;
2975 }
2976 }
2977 reloc_found = true;
2978 break;
2979 }
2980 }
2981 if (reloc_found && isExtern) {
2982 op_info->AddSymbol.Present = 1;
2983 op_info->AddSymbol.Name =
2984 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
2985 // For i386 extern relocation entries the value in the instruction is
2986 // the offset from the symbol, and value is already set in op_info->Value.
2987 return 1;
2988 }
2989 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2990 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2991 const char *add = GuessSymbolName(value: r_value, AddrMap: info->AddrMap);
2992 const char *sub = GuessSymbolName(value: pair_r_value, AddrMap: info->AddrMap);
2993 uint32_t offset = value - (r_value - pair_r_value);
2994 op_info->AddSymbol.Present = 1;
2995 if (add != nullptr)
2996 op_info->AddSymbol.Name = add;
2997 else
2998 op_info->AddSymbol.Value = r_value;
2999 op_info->SubtractSymbol.Present = 1;
3000 if (sub != nullptr)
3001 op_info->SubtractSymbol.Name = sub;
3002 else
3003 op_info->SubtractSymbol.Value = pair_r_value;
3004 op_info->Value = offset;
3005 return 1;
3006 }
3007 return 0;
3008 }
3009 if (Arch == Triple::x86_64) {
3010 if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
3011 return 0;
3012 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
3013 // relocation entries of a linked image (if any) for an entry that matches
3014 // this segment offset.
3015 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3016 uint64_t seg_offset = Pc + Offset;
3017 bool reloc_found = false;
3018 DataRefImpl Rel;
3019 MachO::any_relocation_info RE;
3020 bool isExtern = false;
3021 SymbolRef Symbol;
3022 for (const RelocationRef &Reloc : info->O->external_relocations()) {
3023 uint64_t RelocOffset = Reloc.getOffset();
3024 if (RelocOffset == seg_offset) {
3025 Rel = Reloc.getRawDataRefImpl();
3026 RE = info->O->getRelocation(Rel);
3027 // external relocation entries should always be external.
3028 isExtern = info->O->getPlainRelocationExternal(RE);
3029 if (isExtern) {
3030 symbol_iterator RelocSym = Reloc.getSymbol();
3031 Symbol = *RelocSym;
3032 }
3033 reloc_found = true;
3034 break;
3035 }
3036 }
3037 if (reloc_found && isExtern) {
3038 // The Value passed in will be adjusted by the Pc if the instruction
3039 // adds the Pc. But for x86_64 external relocation entries the Value
3040 // is the offset from the external symbol.
3041 if (info->O->getAnyRelocationPCRel(RE))
3042 op_info->Value -= Pc + InstSize;
3043 const char *name =
3044 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3045 op_info->AddSymbol.Present = 1;
3046 op_info->AddSymbol.Name = name;
3047 return 1;
3048 }
3049 return 0;
3050 }
3051 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3052 // for an entry for this section offset.
3053 uint64_t sect_addr = info->S.getAddress();
3054 uint64_t sect_offset = (Pc + Offset) - sect_addr;
3055 bool reloc_found = false;
3056 DataRefImpl Rel;
3057 MachO::any_relocation_info RE;
3058 bool isExtern = false;
3059 SymbolRef Symbol;
3060 for (const RelocationRef &Reloc : info->S.relocations()) {
3061 uint64_t RelocOffset = Reloc.getOffset();
3062 if (RelocOffset == sect_offset) {
3063 Rel = Reloc.getRawDataRefImpl();
3064 RE = info->O->getRelocation(Rel);
3065 // NOTE: Scattered relocations don't exist on x86_64.
3066 isExtern = info->O->getPlainRelocationExternal(RE);
3067 if (isExtern) {
3068 symbol_iterator RelocSym = Reloc.getSymbol();
3069 Symbol = *RelocSym;
3070 }
3071 reloc_found = true;
3072 break;
3073 }
3074 }
3075 if (reloc_found && isExtern) {
3076 // The Value passed in will be adjusted by the Pc if the instruction
3077 // adds the Pc. But for x86_64 external relocation entries the Value
3078 // is the offset from the external symbol.
3079 if (info->O->getAnyRelocationPCRel(RE))
3080 op_info->Value -= Pc + InstSize;
3081 const char *name =
3082 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3083 unsigned Type = info->O->getAnyRelocationType(RE);
3084 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
3085 DataRefImpl RelNext = Rel;
3086 info->O->moveRelocationNext(Rel&: RelNext);
3087 MachO::any_relocation_info RENext = info->O->getRelocation(Rel: RelNext);
3088 unsigned TypeNext = info->O->getAnyRelocationType(RE: RENext);
3089 bool isExternNext = info->O->getPlainRelocationExternal(RE: RENext);
3090 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RE: RENext);
3091 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
3092 op_info->SubtractSymbol.Present = 1;
3093 op_info->SubtractSymbol.Name = name;
3094 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(Index: SymbolNum);
3095 Symbol = *RelocSymNext;
3096 name = unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3097 }
3098 }
3099 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
3100 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
3101 op_info->AddSymbol.Present = 1;
3102 op_info->AddSymbol.Name = name;
3103 return 1;
3104 }
3105 return 0;
3106 }
3107 if (Arch == Triple::arm) {
3108 if (Offset != 0 || (InstSize != 4 && InstSize != 2))
3109 return 0;
3110 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3111 // TODO:
3112 // Search the external relocation entries of a fully linked image
3113 // (if any) for an entry that matches this segment offset.
3114 // uint32_t seg_offset = (Pc + Offset);
3115 return 0;
3116 }
3117 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3118 // for an entry for this section offset.
3119 uint32_t sect_addr = info->S.getAddress();
3120 uint32_t sect_offset = (Pc + Offset) - sect_addr;
3121 DataRefImpl Rel;
3122 MachO::any_relocation_info RE;
3123 bool isExtern = false;
3124 SymbolRef Symbol;
3125 bool r_scattered = false;
3126 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
3127 auto Reloc =
3128 find_if(Range: info->S.relocations(), P: [&](const RelocationRef &Reloc) {
3129 uint64_t RelocOffset = Reloc.getOffset();
3130 return RelocOffset == sect_offset;
3131 });
3132
3133 if (Reloc == info->S.relocations().end())
3134 return 0;
3135
3136 Rel = Reloc->getRawDataRefImpl();
3137 RE = info->O->getRelocation(Rel);
3138 r_length = info->O->getAnyRelocationLength(RE);
3139 r_scattered = info->O->isRelocationScattered(RE);
3140 if (r_scattered) {
3141 r_value = info->O->getScatteredRelocationValue(RE);
3142 r_type = info->O->getScatteredRelocationType(RE);
3143 } else {
3144 r_type = info->O->getAnyRelocationType(RE);
3145 isExtern = info->O->getPlainRelocationExternal(RE);
3146 if (isExtern) {
3147 symbol_iterator RelocSym = Reloc->getSymbol();
3148 Symbol = *RelocSym;
3149 }
3150 }
3151 if (r_type == MachO::ARM_RELOC_HALF ||
3152 r_type == MachO::ARM_RELOC_SECTDIFF ||
3153 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
3154 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3155 DataRefImpl RelNext = Rel;
3156 info->O->moveRelocationNext(Rel&: RelNext);
3157 MachO::any_relocation_info RENext;
3158 RENext = info->O->getRelocation(Rel: RelNext);
3159 other_half = info->O->getAnyRelocationAddress(RE: RENext) & 0xffff;
3160 if (info->O->isRelocationScattered(RE: RENext))
3161 pair_r_value = info->O->getScatteredRelocationValue(RE: RENext);
3162 }
3163
3164 if (isExtern) {
3165 const char *name =
3166 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3167 op_info->AddSymbol.Present = 1;
3168 op_info->AddSymbol.Name = name;
3169 switch (r_type) {
3170 case MachO::ARM_RELOC_HALF:
3171 if ((r_length & 0x1) == 1) {
3172 op_info->Value = value << 16 | other_half;
3173 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3174 } else {
3175 op_info->Value = other_half << 16 | value;
3176 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3177 }
3178 break;
3179 default:
3180 break;
3181 }
3182 return 1;
3183 }
3184 // If we have a branch that is not an external relocation entry then
3185 // return 0 so the code in tryAddingSymbolicOperand() can use the
3186 // SymbolLookUp call back with the branch target address to look up the
3187 // symbol and possibility add an annotation for a symbol stub.
3188 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
3189 r_type == MachO::ARM_THUMB_RELOC_BR22))
3190 return 0;
3191
3192 uint32_t offset = 0;
3193 if (r_type == MachO::ARM_RELOC_HALF ||
3194 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3195 if ((r_length & 0x1) == 1)
3196 value = value << 16 | other_half;
3197 else
3198 value = other_half << 16 | value;
3199 }
3200 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
3201 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
3202 offset = value - r_value;
3203 value = r_value;
3204 }
3205
3206 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3207 if ((r_length & 0x1) == 1)
3208 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3209 else
3210 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3211 const char *add = GuessSymbolName(value: r_value, AddrMap: info->AddrMap);
3212 const char *sub = GuessSymbolName(value: pair_r_value, AddrMap: info->AddrMap);
3213 int32_t offset = value - (r_value - pair_r_value);
3214 op_info->AddSymbol.Present = 1;
3215 if (add != nullptr)
3216 op_info->AddSymbol.Name = add;
3217 else
3218 op_info->AddSymbol.Value = r_value;
3219 op_info->SubtractSymbol.Present = 1;
3220 if (sub != nullptr)
3221 op_info->SubtractSymbol.Name = sub;
3222 else
3223 op_info->SubtractSymbol.Value = pair_r_value;
3224 op_info->Value = offset;
3225 return 1;
3226 }
3227
3228 op_info->AddSymbol.Present = 1;
3229 op_info->Value = offset;
3230 if (r_type == MachO::ARM_RELOC_HALF) {
3231 if ((r_length & 0x1) == 1)
3232 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3233 else
3234 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3235 }
3236 const char *add = GuessSymbolName(value, AddrMap: info->AddrMap);
3237 if (add != nullptr) {
3238 op_info->AddSymbol.Name = add;
3239 return 1;
3240 }
3241 op_info->AddSymbol.Value = value;
3242 return 1;
3243 }
3244 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32) {
3245 if (Offset != 0 || InstSize != 4)
3246 return 0;
3247 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3248 // TODO:
3249 // Search the external relocation entries of a fully linked image
3250 // (if any) for an entry that matches this segment offset.
3251 // uint64_t seg_offset = (Pc + Offset);
3252 return 0;
3253 }
3254 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3255 // for an entry for this section offset.
3256 uint64_t sect_addr = info->S.getAddress();
3257 uint64_t sect_offset = (Pc + Offset) - sect_addr;
3258 auto Reloc =
3259 find_if(Range: info->S.relocations(), P: [&](const RelocationRef &Reloc) {
3260 uint64_t RelocOffset = Reloc.getOffset();
3261 return RelocOffset == sect_offset;
3262 });
3263
3264 if (Reloc == info->S.relocations().end())
3265 return 0;
3266
3267 DataRefImpl Rel = Reloc->getRawDataRefImpl();
3268 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
3269 uint32_t r_type = info->O->getAnyRelocationType(RE);
3270 if (r_type == MachO::ARM64_RELOC_ADDEND) {
3271 DataRefImpl RelNext = Rel;
3272 info->O->moveRelocationNext(Rel&: RelNext);
3273 MachO::any_relocation_info RENext = info->O->getRelocation(Rel: RelNext);
3274 if (value == 0) {
3275 value = info->O->getPlainRelocationSymbolNum(RE: RENext);
3276 op_info->Value = value;
3277 }
3278 }
3279 // NOTE: Scattered relocations don't exist on arm64.
3280 if (!info->O->getPlainRelocationExternal(RE))
3281 return 0;
3282 const char *name =
3283 unwrapOrError(EO: Reloc->getSymbol()->getName(), Args: info->O->getFileName())
3284 .data();
3285 op_info->AddSymbol.Present = 1;
3286 op_info->AddSymbol.Name = name;
3287
3288 switch (r_type) {
3289 case MachO::ARM64_RELOC_PAGE21:
3290 /* @page */
3291 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
3292 break;
3293 case MachO::ARM64_RELOC_PAGEOFF12:
3294 /* @pageoff */
3295 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
3296 break;
3297 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
3298 /* @gotpage */
3299 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
3300 break;
3301 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
3302 /* @gotpageoff */
3303 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
3304 break;
3305 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
3306 /* @tvlppage is not implemented in llvm-mc */
3307 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
3308 break;
3309 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
3310 /* @tvlppageoff is not implemented in llvm-mc */
3311 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3312 break;
3313 default:
3314 case MachO::ARM64_RELOC_BRANCH26:
3315 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3316 break;
3317 }
3318 return 1;
3319 }
3320 return 0;
3321}
3322
3323// GuessCstringPointer is passed the address of what might be a pointer to a
3324// literal string in a cstring section. If that address is in a cstring section
3325// it returns a pointer to that string. Else it returns nullptr.
3326static const char *GuessCstringPointer(uint64_t ReferenceValue,
3327 struct DisassembleInfo *info) {
3328 for (const auto &Load : info->O->load_commands()) {
3329 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3330 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3331 for (unsigned J = 0; J < Seg.nsects; ++J) {
3332 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3333 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3334 if (section_type == MachO::S_CSTRING_LITERALS &&
3335 ReferenceValue >= Sec.addr &&
3336 ReferenceValue < Sec.addr + Sec.size) {
3337 uint64_t sect_offset = ReferenceValue - Sec.addr;
3338 uint64_t object_offset = Sec.offset + sect_offset;
3339 StringRef MachOContents = info->O->getData();
3340 uint64_t object_size = MachOContents.size();
3341 const char *object_addr = MachOContents.data();
3342 if (object_offset < object_size) {
3343 const char *name = object_addr + object_offset;
3344 return name;
3345 } else {
3346 return nullptr;
3347 }
3348 }
3349 }
3350 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3351 MachO::segment_command Seg = info->O->getSegmentLoadCommand(L: Load);
3352 for (unsigned J = 0; J < Seg.nsects; ++J) {
3353 MachO::section Sec = info->O->getSection(L: Load, Index: J);
3354 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3355 if (section_type == MachO::S_CSTRING_LITERALS &&
3356 ReferenceValue >= Sec.addr &&
3357 ReferenceValue < Sec.addr + Sec.size) {
3358 uint64_t sect_offset = ReferenceValue - Sec.addr;
3359 uint64_t object_offset = Sec.offset + sect_offset;
3360 StringRef MachOContents = info->O->getData();
3361 uint64_t object_size = MachOContents.size();
3362 const char *object_addr = MachOContents.data();
3363 if (object_offset < object_size) {
3364 const char *name = object_addr + object_offset;
3365 return name;
3366 } else {
3367 return nullptr;
3368 }
3369 }
3370 }
3371 }
3372 }
3373 return nullptr;
3374}
3375
3376// GuessIndirectSymbol returns the name of the indirect symbol for the
3377// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
3378// an address of a symbol stub or a lazy or non-lazy pointer to associate the
3379// symbol name being referenced by the stub or pointer.
3380static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3381 struct DisassembleInfo *info) {
3382 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3383 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3384 for (const auto &Load : info->O->load_commands()) {
3385 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3386 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3387 for (unsigned J = 0; J < Seg.nsects; ++J) {
3388 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3389 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3390 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3391 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3392 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3393 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3394 section_type == MachO::S_SYMBOL_STUBS) &&
3395 ReferenceValue >= Sec.addr &&
3396 ReferenceValue < Sec.addr + Sec.size) {
3397 uint32_t stride;
3398 if (section_type == MachO::S_SYMBOL_STUBS)
3399 stride = Sec.reserved2;
3400 else
3401 stride = 8;
3402 if (stride == 0)
3403 return nullptr;
3404 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3405 if (index < Dysymtab.nindirectsyms) {
3406 uint32_t indirect_symbol =
3407 info->O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: index);
3408 if (indirect_symbol < Symtab.nsyms) {
3409 symbol_iterator Sym = info->O->getSymbolByIndex(Index: indirect_symbol);
3410 return unwrapOrError(EO: Sym->getName(), Args: info->O->getFileName())
3411 .data();
3412 }
3413 }
3414 }
3415 }
3416 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3417 MachO::segment_command Seg = info->O->getSegmentLoadCommand(L: Load);
3418 for (unsigned J = 0; J < Seg.nsects; ++J) {
3419 MachO::section Sec = info->O->getSection(L: Load, Index: J);
3420 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3421 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3422 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3423 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3424 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3425 section_type == MachO::S_SYMBOL_STUBS) &&
3426 ReferenceValue >= Sec.addr &&
3427 ReferenceValue < Sec.addr + Sec.size) {
3428 uint32_t stride;
3429 if (section_type == MachO::S_SYMBOL_STUBS)
3430 stride = Sec.reserved2;
3431 else
3432 stride = 4;
3433 if (stride == 0)
3434 return nullptr;
3435 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3436 if (index < Dysymtab.nindirectsyms) {
3437 uint32_t indirect_symbol =
3438 info->O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: index);
3439 if (indirect_symbol < Symtab.nsyms) {
3440 symbol_iterator Sym = info->O->getSymbolByIndex(Index: indirect_symbol);
3441 return unwrapOrError(EO: Sym->getName(), Args: info->O->getFileName())
3442 .data();
3443 }
3444 }
3445 }
3446 }
3447 }
3448 }
3449 return nullptr;
3450}
3451
3452// method_reference() is called passing it the ReferenceName that might be
3453// a reference it to an Objective-C method call. If so then it allocates and
3454// assembles a method call string with the values last seen and saved in
3455// the DisassembleInfo's class_name and selector_name fields. This is saved
3456// into the method field of the info and any previous string is free'ed.
3457// Then the class_name field in the info is set to nullptr. The method call
3458// string is set into ReferenceName and ReferenceType is set to
3459// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3460// then both ReferenceType and ReferenceName are left unchanged.
3461static void method_reference(struct DisassembleInfo *info,
3462 uint64_t *ReferenceType,
3463 const char **ReferenceName) {
3464 unsigned int Arch = info->O->getArch();
3465 if (*ReferenceName != nullptr) {
3466 if (strcmp(s1: *ReferenceName, s2: "_objc_msgSend") == 0) {
3467 if (info->selector_name != nullptr) {
3468 if (info->class_name != nullptr) {
3469 info->method = std::make_unique<char[]>(
3470 num: 5 + strlen(s: info->class_name) + strlen(s: info->selector_name));
3471 char *method = info->method.get();
3472 if (method != nullptr) {
3473 strcpy(dest: method, src: "+[");
3474 strcat(dest: method, src: info->class_name);
3475 strcat(dest: method, src: " ");
3476 strcat(dest: method, src: info->selector_name);
3477 strcat(dest: method, src: "]");
3478 *ReferenceName = method;
3479 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3480 }
3481 } else {
3482 info->method =
3483 std::make_unique<char[]>(num: 9 + strlen(s: info->selector_name));
3484 char *method = info->method.get();
3485 if (method != nullptr) {
3486 if (Arch == Triple::x86_64)
3487 strcpy(dest: method, src: "-[%rdi ");
3488 else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32)
3489 strcpy(dest: method, src: "-[x0 ");
3490 else
3491 strcpy(dest: method, src: "-[r? ");
3492 strcat(dest: method, src: info->selector_name);
3493 strcat(dest: method, src: "]");
3494 *ReferenceName = method;
3495 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3496 }
3497 }
3498 info->class_name = nullptr;
3499 }
3500 } else if (strcmp(s1: *ReferenceName, s2: "_objc_msgSendSuper2") == 0) {
3501 if (info->selector_name != nullptr) {
3502 info->method =
3503 std::make_unique<char[]>(num: 17 + strlen(s: info->selector_name));
3504 char *method = info->method.get();
3505 if (method != nullptr) {
3506 if (Arch == Triple::x86_64)
3507 strcpy(dest: method, src: "-[[%rdi super] ");
3508 else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32)
3509 strcpy(dest: method, src: "-[[x0 super] ");
3510 else
3511 strcpy(dest: method, src: "-[[r? super] ");
3512 strcat(dest: method, src: info->selector_name);
3513 strcat(dest: method, src: "]");
3514 *ReferenceName = method;
3515 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3516 }
3517 info->class_name = nullptr;
3518 }
3519 }
3520 }
3521}
3522
3523// GuessPointerPointer() is passed the address of what might be a pointer to
3524// a reference to an Objective-C class, selector, message ref or cfstring.
3525// If so the value of the pointer is returned and one of the booleans are set
3526// to true. If not zero is returned and all the booleans are set to false.
3527static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3528 struct DisassembleInfo *info,
3529 bool &classref, bool &selref, bool &msgref,
3530 bool &cfstring) {
3531 classref = false;
3532 selref = false;
3533 msgref = false;
3534 cfstring = false;
3535 for (const auto &Load : info->O->load_commands()) {
3536 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3537 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3538 for (unsigned J = 0; J < Seg.nsects; ++J) {
3539 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3540 if ((strncmp(s1: Sec.sectname, s2: "__objc_selrefs", n: 16) == 0 ||
3541 strncmp(s1: Sec.sectname, s2: "__objc_classrefs", n: 16) == 0 ||
3542 strncmp(s1: Sec.sectname, s2: "__objc_superrefs", n: 16) == 0 ||
3543 strncmp(s1: Sec.sectname, s2: "__objc_msgrefs", n: 16) == 0 ||
3544 strncmp(s1: Sec.sectname, s2: "__cfstring", n: 16) == 0) &&
3545 ReferenceValue >= Sec.addr &&
3546 ReferenceValue < Sec.addr + Sec.size) {
3547 uint64_t sect_offset = ReferenceValue - Sec.addr;
3548 uint64_t object_offset = Sec.offset + sect_offset;
3549 StringRef MachOContents = info->O->getData();
3550 uint64_t object_size = MachOContents.size();
3551 const char *object_addr = MachOContents.data();
3552 if (object_offset < object_size) {
3553 uint64_t pointer_value;
3554 memcpy(dest: &pointer_value, src: object_addr + object_offset,
3555 n: sizeof(uint64_t));
3556 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3557 sys::swapByteOrder(Value&: pointer_value);
3558 if (strncmp(s1: Sec.sectname, s2: "__objc_selrefs", n: 16) == 0)
3559 selref = true;
3560 else if (strncmp(s1: Sec.sectname, s2: "__objc_classrefs", n: 16) == 0 ||
3561 strncmp(s1: Sec.sectname, s2: "__objc_superrefs", n: 16) == 0)
3562 classref = true;
3563 else if (strncmp(s1: Sec.sectname, s2: "__objc_msgrefs", n: 16) == 0 &&
3564 ReferenceValue + 8 < Sec.addr + Sec.size) {
3565 msgref = true;
3566 memcpy(dest: &pointer_value, src: object_addr + object_offset + 8,
3567 n: sizeof(uint64_t));
3568 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3569 sys::swapByteOrder(Value&: pointer_value);
3570 } else if (strncmp(s1: Sec.sectname, s2: "__cfstring", n: 16) == 0)
3571 cfstring = true;
3572 return pointer_value;
3573 } else {
3574 return 0;
3575 }
3576 }
3577 }
3578 }
3579 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3580 }
3581 return 0;
3582}
3583
3584// get_pointer_64 returns a pointer to the bytes in the object file at the
3585// Address from a section in the Mach-O file. And indirectly returns the
3586// offset into the section, number of bytes left in the section past the offset
3587// and which section is was being referenced. If the Address is not in a
3588// section nullptr is returned.
3589static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3590 uint32_t &left, SectionRef &S,
3591 DisassembleInfo *info,
3592 bool objc_only = false) {
3593 offset = 0;
3594 left = 0;
3595 S = SectionRef();
3596 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3597 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3598 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3599 if (SectSize == 0)
3600 continue;
3601 if (objc_only) {
3602 StringRef SectName;
3603 Expected<StringRef> SecNameOrErr =
3604 ((*(info->Sections))[SectIdx]).getName();
3605 if (SecNameOrErr)
3606 SectName = *SecNameOrErr;
3607 else
3608 consumeError(Err: SecNameOrErr.takeError());
3609
3610 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3611 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
3612 if (SegName != "__OBJC" && SectName != "__cstring")
3613 continue;
3614 }
3615 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3616 S = (*(info->Sections))[SectIdx];
3617 offset = Address - SectAddress;
3618 left = SectSize - offset;
3619 StringRef SectContents = unwrapOrError(
3620 EO: ((*(info->Sections))[SectIdx]).getContents(), Args: info->O->getFileName());
3621 return SectContents.data() + offset;
3622 }
3623 }
3624 return nullptr;
3625}
3626
3627static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3628 uint32_t &left, SectionRef &S,
3629 DisassembleInfo *info,
3630 bool objc_only = false) {
3631 return get_pointer_64(Address, offset, left, S, info, objc_only);
3632}
3633
3634// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3635// the symbol indirectly through n_value. Based on the relocation information
3636// for the specified section offset in the specified section reference.
3637// If no relocation information is found and a non-zero ReferenceValue for the
3638// symbol is passed, look up that address in the info's AddrMap.
3639static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3640 DisassembleInfo *info, uint64_t &n_value,
3641 uint64_t ReferenceValue = 0) {
3642 n_value = 0;
3643 if (!info->verbose)
3644 return nullptr;
3645
3646 // See if there is an external relocation entry at the sect_offset.
3647 bool reloc_found = false;
3648 DataRefImpl Rel;
3649 MachO::any_relocation_info RE;
3650 bool isExtern = false;
3651 SymbolRef Symbol;
3652 for (const RelocationRef &Reloc : S.relocations()) {
3653 uint64_t RelocOffset = Reloc.getOffset();
3654 if (RelocOffset == sect_offset) {
3655 Rel = Reloc.getRawDataRefImpl();
3656 RE = info->O->getRelocation(Rel);
3657 if (info->O->isRelocationScattered(RE))
3658 continue;
3659 isExtern = info->O->getPlainRelocationExternal(RE);
3660 if (isExtern) {
3661 symbol_iterator RelocSym = Reloc.getSymbol();
3662 Symbol = *RelocSym;
3663 }
3664 reloc_found = true;
3665 break;
3666 }
3667 }
3668 // If there is an external relocation entry for a symbol in this section
3669 // at this section_offset then use that symbol's value for the n_value
3670 // and return its name.
3671 const char *SymbolName = nullptr;
3672 if (reloc_found && isExtern) {
3673 n_value = cantFail(ValOrErr: Symbol.getValue());
3674 StringRef Name = unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName());
3675 if (!Name.empty()) {
3676 SymbolName = Name.data();
3677 return SymbolName;
3678 }
3679 }
3680
3681 // TODO: For fully linked images, look through the external relocation
3682 // entries off the dynamic symtab command. For these the r_offset is from the
3683 // start of the first writeable segment in the Mach-O file. So the offset
3684 // to this section from that segment is passed to this routine by the caller,
3685 // as the database_offset. Which is the difference of the section's starting
3686 // address and the first writable segment.
3687 //
3688 // NOTE: need add passing the database_offset to this routine.
3689
3690 // We did not find an external relocation entry so look up the ReferenceValue
3691 // as an address of a symbol and if found return that symbol's name.
3692 SymbolName = GuessSymbolName(value: ReferenceValue, AddrMap: info->AddrMap);
3693
3694 return SymbolName;
3695}
3696
3697static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3698 DisassembleInfo *info,
3699 uint32_t ReferenceValue) {
3700 uint64_t n_value64;
3701 return get_symbol_64(sect_offset, S, info, n_value&: n_value64, ReferenceValue);
3702}
3703
3704namespace {
3705
3706// These are structs in the Objective-C meta data and read to produce the
3707// comments for disassembly. While these are part of the ABI they are no
3708// public definitions. So the are here not in include/llvm/BinaryFormat/MachO.h
3709// .
3710
3711// The cfstring object in a 64-bit Mach-O file.
3712struct cfstring64_t {
3713 uint64_t isa; // class64_t * (64-bit pointer)
3714 uint64_t flags; // flag bits
3715 uint64_t characters; // char * (64-bit pointer)
3716 uint64_t length; // number of non-NULL characters in above
3717};
3718
3719// The class object in a 64-bit Mach-O file.
3720struct class64_t {
3721 uint64_t isa; // class64_t * (64-bit pointer)
3722 uint64_t superclass; // class64_t * (64-bit pointer)
3723 uint64_t cache; // Cache (64-bit pointer)
3724 uint64_t vtable; // IMP * (64-bit pointer)
3725 uint64_t data; // class_ro64_t * (64-bit pointer)
3726};
3727
3728struct class32_t {
3729 uint32_t isa; /* class32_t * (32-bit pointer) */
3730 uint32_t superclass; /* class32_t * (32-bit pointer) */
3731 uint32_t cache; /* Cache (32-bit pointer) */
3732 uint32_t vtable; /* IMP * (32-bit pointer) */
3733 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3734};
3735
3736struct class_ro64_t {
3737 uint32_t flags;
3738 uint32_t instanceStart;
3739 uint32_t instanceSize;
3740 uint32_t reserved;
3741 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3742 uint64_t name; // const char * (64-bit pointer)
3743 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3744 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3745 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3746 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3747 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3748};
3749
3750struct class_ro32_t {
3751 uint32_t flags;
3752 uint32_t instanceStart;
3753 uint32_t instanceSize;
3754 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3755 uint32_t name; /* const char * (32-bit pointer) */
3756 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3757 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3758 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3759 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3760 uint32_t baseProperties; /* const struct objc_property_list *
3761 (32-bit pointer) */
3762};
3763
3764/* Values for class_ro{64,32}_t->flags */
3765#define RO_META (1 << 0)
3766#define RO_ROOT (1 << 1)
3767#define RO_HAS_CXX_STRUCTORS (1 << 2)
3768
3769/* Values for method_list{64,32}_t->entsize */
3770#define ML_HAS_RELATIVE_PTRS (1 << 31)
3771#define ML_ENTSIZE_MASK 0xFFFF
3772
3773struct method_list64_t {
3774 uint32_t entsize;
3775 uint32_t count;
3776 /* struct method64_t first; These structures follow inline */
3777};
3778
3779struct method_list32_t {
3780 uint32_t entsize;
3781 uint32_t count;
3782 /* struct method32_t first; These structures follow inline */
3783};
3784
3785struct method64_t {
3786 uint64_t name; /* SEL (64-bit pointer) */
3787 uint64_t types; /* const char * (64-bit pointer) */
3788 uint64_t imp; /* IMP (64-bit pointer) */
3789};
3790
3791struct method32_t {
3792 uint32_t name; /* SEL (32-bit pointer) */
3793 uint32_t types; /* const char * (32-bit pointer) */
3794 uint32_t imp; /* IMP (32-bit pointer) */
3795};
3796
3797struct method_relative_t {
3798 int32_t name; /* SEL (32-bit relative) */
3799 int32_t types; /* const char * (32-bit relative) */
3800 int32_t imp; /* IMP (32-bit relative) */
3801};
3802
3803struct protocol_list64_t {
3804 uint64_t count; /* uintptr_t (a 64-bit value) */
3805 /* struct protocol64_t * list[0]; These pointers follow inline */
3806};
3807
3808struct protocol_list32_t {
3809 uint32_t count; /* uintptr_t (a 32-bit value) */
3810 /* struct protocol32_t * list[0]; These pointers follow inline */
3811};
3812
3813struct protocol64_t {
3814 uint64_t isa; /* id * (64-bit pointer) */
3815 uint64_t name; /* const char * (64-bit pointer) */
3816 uint64_t protocols; /* struct protocol_list64_t *
3817 (64-bit pointer) */
3818 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3819 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3820 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3821 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3822 uint64_t instanceProperties; /* struct objc_property_list *
3823 (64-bit pointer) */
3824};
3825
3826struct protocol32_t {
3827 uint32_t isa; /* id * (32-bit pointer) */
3828 uint32_t name; /* const char * (32-bit pointer) */
3829 uint32_t protocols; /* struct protocol_list_t *
3830 (32-bit pointer) */
3831 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3832 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3833 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3834 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3835 uint32_t instanceProperties; /* struct objc_property_list *
3836 (32-bit pointer) */
3837};
3838
3839struct ivar_list64_t {
3840 uint32_t entsize;
3841 uint32_t count;
3842 /* struct ivar64_t first; These structures follow inline */
3843};
3844
3845struct ivar_list32_t {
3846 uint32_t entsize;
3847 uint32_t count;
3848 /* struct ivar32_t first; These structures follow inline */
3849};
3850
3851struct ivar64_t {
3852 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3853 uint64_t name; /* const char * (64-bit pointer) */
3854 uint64_t type; /* const char * (64-bit pointer) */
3855 uint32_t alignment;
3856 uint32_t size;
3857};
3858
3859struct ivar32_t {
3860 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3861 uint32_t name; /* const char * (32-bit pointer) */
3862 uint32_t type; /* const char * (32-bit pointer) */
3863 uint32_t alignment;
3864 uint32_t size;
3865};
3866
3867struct objc_property_list64 {
3868 uint32_t entsize;
3869 uint32_t count;
3870 /* struct objc_property64 first; These structures follow inline */
3871};
3872
3873struct objc_property_list32 {
3874 uint32_t entsize;
3875 uint32_t count;
3876 /* struct objc_property32 first; These structures follow inline */
3877};
3878
3879struct objc_property64 {
3880 uint64_t name; /* const char * (64-bit pointer) */
3881 uint64_t attributes; /* const char * (64-bit pointer) */
3882};
3883
3884struct objc_property32 {
3885 uint32_t name; /* const char * (32-bit pointer) */
3886 uint32_t attributes; /* const char * (32-bit pointer) */
3887};
3888
3889struct category64_t {
3890 uint64_t name; /* const char * (64-bit pointer) */
3891 uint64_t cls; /* struct class_t * (64-bit pointer) */
3892 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3893 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3894 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3895 uint64_t instanceProperties; /* struct objc_property_list *
3896 (64-bit pointer) */
3897};
3898
3899struct category32_t {
3900 uint32_t name; /* const char * (32-bit pointer) */
3901 uint32_t cls; /* struct class_t * (32-bit pointer) */
3902 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3903 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3904 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3905 uint32_t instanceProperties; /* struct objc_property_list *
3906 (32-bit pointer) */
3907};
3908
3909struct objc_image_info64 {
3910 uint32_t version;
3911 uint32_t flags;
3912};
3913struct objc_image_info32 {
3914 uint32_t version;
3915 uint32_t flags;
3916};
3917struct imageInfo_t {
3918 uint32_t version;
3919 uint32_t flags;
3920};
3921/* masks for objc_image_info.flags */
3922#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3923#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3924#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3925#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3926
3927struct message_ref64 {
3928 uint64_t imp; /* IMP (64-bit pointer) */
3929 uint64_t sel; /* SEL (64-bit pointer) */
3930};
3931
3932struct message_ref32 {
3933 uint32_t imp; /* IMP (32-bit pointer) */
3934 uint32_t sel; /* SEL (32-bit pointer) */
3935};
3936
3937// Objective-C 1 (32-bit only) meta data structs.
3938
3939struct objc_module_t {
3940 uint32_t version;
3941 uint32_t size;
3942 uint32_t name; /* char * (32-bit pointer) */
3943 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3944};
3945
3946struct objc_symtab_t {
3947 uint32_t sel_ref_cnt;
3948 uint32_t refs; /* SEL * (32-bit pointer) */
3949 uint16_t cls_def_cnt;
3950 uint16_t cat_def_cnt;
3951 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3952};
3953
3954struct objc_class_t {
3955 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3956 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3957 uint32_t name; /* const char * (32-bit pointer) */
3958 int32_t version;
3959 int32_t info;
3960 int32_t instance_size;
3961 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3962 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3963 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3964 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3965};
3966
3967#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3968// class is not a metaclass
3969#define CLS_CLASS 0x1
3970// class is a metaclass
3971#define CLS_META 0x2
3972
3973struct objc_category_t {
3974 uint32_t category_name; /* char * (32-bit pointer) */
3975 uint32_t class_name; /* char * (32-bit pointer) */
3976 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3977 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3978 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3979};
3980
3981struct objc_ivar_t {
3982 uint32_t ivar_name; /* char * (32-bit pointer) */
3983 uint32_t ivar_type; /* char * (32-bit pointer) */
3984 int32_t ivar_offset;
3985};
3986
3987struct objc_ivar_list_t {
3988 int32_t ivar_count;
3989 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3990};
3991
3992struct objc_method_list_t {
3993 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3994 int32_t method_count;
3995 // struct objc_method_t method_list[1]; /* variable length structure */
3996};
3997
3998struct objc_method_t {
3999 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
4000 uint32_t method_types; /* char * (32-bit pointer) */
4001 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
4002 (32-bit pointer) */
4003};
4004
4005struct objc_protocol_list_t {
4006 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
4007 int32_t count;
4008 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
4009 // (32-bit pointer) */
4010};
4011
4012struct objc_protocol_t {
4013 uint32_t isa; /* struct objc_class * (32-bit pointer) */
4014 uint32_t protocol_name; /* char * (32-bit pointer) */
4015 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
4016 uint32_t instance_methods; /* struct objc_method_description_list *
4017 (32-bit pointer) */
4018 uint32_t class_methods; /* struct objc_method_description_list *
4019 (32-bit pointer) */
4020};
4021
4022struct objc_method_description_list_t {
4023 int32_t count;
4024 // struct objc_method_description_t list[1];
4025};
4026
4027struct objc_method_description_t {
4028 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
4029 uint32_t types; /* char * (32-bit pointer) */
4030};
4031
4032inline void swapStruct(struct cfstring64_t &cfs) {
4033 sys::swapByteOrder(Value&: cfs.isa);
4034 sys::swapByteOrder(Value&: cfs.flags);
4035 sys::swapByteOrder(Value&: cfs.characters);
4036 sys::swapByteOrder(Value&: cfs.length);
4037}
4038
4039inline void swapStruct(struct class64_t &c) {
4040 sys::swapByteOrder(Value&: c.isa);
4041 sys::swapByteOrder(Value&: c.superclass);
4042 sys::swapByteOrder(Value&: c.cache);
4043 sys::swapByteOrder(Value&: c.vtable);
4044 sys::swapByteOrder(Value&: c.data);
4045}
4046
4047inline void swapStruct(struct class32_t &c) {
4048 sys::swapByteOrder(Value&: c.isa);
4049 sys::swapByteOrder(Value&: c.superclass);
4050 sys::swapByteOrder(Value&: c.cache);
4051 sys::swapByteOrder(Value&: c.vtable);
4052 sys::swapByteOrder(Value&: c.data);
4053}
4054
4055inline void swapStruct(struct class_ro64_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.reserved);
4060 sys::swapByteOrder(Value&: cro.ivarLayout);
4061 sys::swapByteOrder(Value&: cro.name);
4062 sys::swapByteOrder(Value&: cro.baseMethods);
4063 sys::swapByteOrder(Value&: cro.baseProtocols);
4064 sys::swapByteOrder(Value&: cro.ivars);
4065 sys::swapByteOrder(Value&: cro.weakIvarLayout);
4066 sys::swapByteOrder(Value&: cro.baseProperties);
4067}
4068
4069inline void swapStruct(struct class_ro32_t &cro) {
4070 sys::swapByteOrder(Value&: cro.flags);
4071 sys::swapByteOrder(Value&: cro.instanceStart);
4072 sys::swapByteOrder(Value&: cro.instanceSize);
4073 sys::swapByteOrder(Value&: cro.ivarLayout);
4074 sys::swapByteOrder(Value&: cro.name);
4075 sys::swapByteOrder(Value&: cro.baseMethods);
4076 sys::swapByteOrder(Value&: cro.baseProtocols);
4077 sys::swapByteOrder(Value&: cro.ivars);
4078 sys::swapByteOrder(Value&: cro.weakIvarLayout);
4079 sys::swapByteOrder(Value&: cro.baseProperties);
4080}
4081
4082inline void swapStruct(struct method_list64_t &ml) {
4083 sys::swapByteOrder(Value&: ml.entsize);
4084 sys::swapByteOrder(Value&: ml.count);
4085}
4086
4087inline void swapStruct(struct method_list32_t &ml) {
4088 sys::swapByteOrder(Value&: ml.entsize);
4089 sys::swapByteOrder(Value&: ml.count);
4090}
4091
4092inline void swapStruct(struct method64_t &m) {
4093 sys::swapByteOrder(Value&: m.name);
4094 sys::swapByteOrder(Value&: m.types);
4095 sys::swapByteOrder(Value&: m.imp);
4096}
4097
4098inline void swapStruct(struct method32_t &m) {
4099 sys::swapByteOrder(Value&: m.name);
4100 sys::swapByteOrder(Value&: m.types);
4101 sys::swapByteOrder(Value&: m.imp);
4102}
4103
4104inline void swapStruct(struct method_relative_t &m) {
4105 sys::swapByteOrder(Value&: m.name);
4106 sys::swapByteOrder(Value&: m.types);
4107 sys::swapByteOrder(Value&: m.imp);
4108}
4109
4110inline void swapStruct(struct protocol_list64_t &pl) {
4111 sys::swapByteOrder(Value&: pl.count);
4112}
4113
4114inline void swapStruct(struct protocol_list32_t &pl) {
4115 sys::swapByteOrder(Value&: pl.count);
4116}
4117
4118inline void swapStruct(struct protocol64_t &p) {
4119 sys::swapByteOrder(Value&: p.isa);
4120 sys::swapByteOrder(Value&: p.name);
4121 sys::swapByteOrder(Value&: p.protocols);
4122 sys::swapByteOrder(Value&: p.instanceMethods);
4123 sys::swapByteOrder(Value&: p.classMethods);
4124 sys::swapByteOrder(Value&: p.optionalInstanceMethods);
4125 sys::swapByteOrder(Value&: p.optionalClassMethods);
4126 sys::swapByteOrder(Value&: p.instanceProperties);
4127}
4128
4129inline void swapStruct(struct protocol32_t &p) {
4130 sys::swapByteOrder(Value&: p.isa);
4131 sys::swapByteOrder(Value&: p.name);
4132 sys::swapByteOrder(Value&: p.protocols);
4133 sys::swapByteOrder(Value&: p.instanceMethods);
4134 sys::swapByteOrder(Value&: p.classMethods);
4135 sys::swapByteOrder(Value&: p.optionalInstanceMethods);
4136 sys::swapByteOrder(Value&: p.optionalClassMethods);
4137 sys::swapByteOrder(Value&: p.instanceProperties);
4138}
4139
4140inline void swapStruct(struct ivar_list64_t &il) {
4141 sys::swapByteOrder(Value&: il.entsize);
4142 sys::swapByteOrder(Value&: il.count);
4143}
4144
4145inline void swapStruct(struct ivar_list32_t &il) {
4146 sys::swapByteOrder(Value&: il.entsize);
4147 sys::swapByteOrder(Value&: il.count);
4148}
4149
4150inline void swapStruct(struct ivar64_t &i) {
4151 sys::swapByteOrder(Value&: i.offset);
4152 sys::swapByteOrder(Value&: i.name);
4153 sys::swapByteOrder(Value&: i.type);
4154 sys::swapByteOrder(Value&: i.alignment);
4155 sys::swapByteOrder(Value&: i.size);
4156}
4157
4158inline void swapStruct(struct ivar32_t &i) {
4159 sys::swapByteOrder(Value&: i.offset);
4160 sys::swapByteOrder(Value&: i.name);
4161 sys::swapByteOrder(Value&: i.type);
4162 sys::swapByteOrder(Value&: i.alignment);
4163 sys::swapByteOrder(Value&: i.size);
4164}
4165
4166inline void swapStruct(struct objc_property_list64 &pl) {
4167 sys::swapByteOrder(Value&: pl.entsize);
4168 sys::swapByteOrder(Value&: pl.count);
4169}
4170
4171inline void swapStruct(struct objc_property_list32 &pl) {
4172 sys::swapByteOrder(Value&: pl.entsize);
4173 sys::swapByteOrder(Value&: pl.count);
4174}
4175
4176inline void swapStruct(struct objc_property64 &op) {
4177 sys::swapByteOrder(Value&: op.name);
4178 sys::swapByteOrder(Value&: op.attributes);
4179}
4180
4181inline void swapStruct(struct objc_property32 &op) {
4182 sys::swapByteOrder(Value&: op.name);
4183 sys::swapByteOrder(Value&: op.attributes);
4184}
4185
4186inline void swapStruct(struct category64_t &c) {
4187 sys::swapByteOrder(Value&: c.name);
4188 sys::swapByteOrder(Value&: c.cls);
4189 sys::swapByteOrder(Value&: c.instanceMethods);
4190 sys::swapByteOrder(Value&: c.classMethods);
4191 sys::swapByteOrder(Value&: c.protocols);
4192 sys::swapByteOrder(Value&: c.instanceProperties);
4193}
4194
4195inline void swapStruct(struct category32_t &c) {
4196 sys::swapByteOrder(Value&: c.name);
4197 sys::swapByteOrder(Value&: c.cls);
4198 sys::swapByteOrder(Value&: c.instanceMethods);
4199 sys::swapByteOrder(Value&: c.classMethods);
4200 sys::swapByteOrder(Value&: c.protocols);
4201 sys::swapByteOrder(Value&: c.instanceProperties);
4202}
4203
4204inline void swapStruct(struct objc_image_info64 &o) {
4205 sys::swapByteOrder(Value&: o.version);
4206 sys::swapByteOrder(Value&: o.flags);
4207}
4208
4209inline void swapStruct(struct objc_image_info32 &o) {
4210 sys::swapByteOrder(Value&: o.version);
4211 sys::swapByteOrder(Value&: o.flags);
4212}
4213
4214inline void swapStruct(struct imageInfo_t &o) {
4215 sys::swapByteOrder(Value&: o.version);
4216 sys::swapByteOrder(Value&: o.flags);
4217}
4218
4219inline void swapStruct(struct message_ref64 &mr) {
4220 sys::swapByteOrder(Value&: mr.imp);
4221 sys::swapByteOrder(Value&: mr.sel);
4222}
4223
4224inline void swapStruct(struct message_ref32 &mr) {
4225 sys::swapByteOrder(Value&: mr.imp);
4226 sys::swapByteOrder(Value&: mr.sel);
4227}
4228
4229inline void swapStruct(struct objc_module_t &module) {
4230 sys::swapByteOrder(Value&: module.version);
4231 sys::swapByteOrder(Value&: module.size);
4232 sys::swapByteOrder(Value&: module.name);
4233 sys::swapByteOrder(Value&: module.symtab);
4234}
4235
4236inline void swapStruct(struct objc_symtab_t &symtab) {
4237 sys::swapByteOrder(Value&: symtab.sel_ref_cnt);
4238 sys::swapByteOrder(Value&: symtab.refs);
4239 sys::swapByteOrder(Value&: symtab.cls_def_cnt);
4240 sys::swapByteOrder(Value&: symtab.cat_def_cnt);
4241}
4242
4243inline void swapStruct(struct objc_class_t &objc_class) {
4244 sys::swapByteOrder(Value&: objc_class.isa);
4245 sys::swapByteOrder(Value&: objc_class.super_class);
4246 sys::swapByteOrder(Value&: objc_class.name);
4247 sys::swapByteOrder(Value&: objc_class.version);
4248 sys::swapByteOrder(Value&: objc_class.info);
4249 sys::swapByteOrder(Value&: objc_class.instance_size);
4250 sys::swapByteOrder(Value&: objc_class.ivars);
4251 sys::swapByteOrder(Value&: objc_class.methodLists);
4252 sys::swapByteOrder(Value&: objc_class.cache);
4253 sys::swapByteOrder(Value&: objc_class.protocols);
4254}
4255
4256inline void swapStruct(struct objc_category_t &objc_category) {
4257 sys::swapByteOrder(Value&: objc_category.category_name);
4258 sys::swapByteOrder(Value&: objc_category.class_name);
4259 sys::swapByteOrder(Value&: objc_category.instance_methods);
4260 sys::swapByteOrder(Value&: objc_category.class_methods);
4261 sys::swapByteOrder(Value&: objc_category.protocols);
4262}
4263
4264inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
4265 sys::swapByteOrder(Value&: objc_ivar_list.ivar_count);
4266}
4267
4268inline void swapStruct(struct objc_ivar_t &objc_ivar) {
4269 sys::swapByteOrder(Value&: objc_ivar.ivar_name);
4270 sys::swapByteOrder(Value&: objc_ivar.ivar_type);
4271 sys::swapByteOrder(Value&: objc_ivar.ivar_offset);
4272}
4273
4274inline void swapStruct(struct objc_method_list_t &method_list) {
4275 sys::swapByteOrder(Value&: method_list.obsolete);
4276 sys::swapByteOrder(Value&: method_list.method_count);
4277}
4278
4279inline void swapStruct(struct objc_method_t &method) {
4280 sys::swapByteOrder(Value&: method.method_name);
4281 sys::swapByteOrder(Value&: method.method_types);
4282 sys::swapByteOrder(Value&: method.method_imp);
4283}
4284
4285inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
4286 sys::swapByteOrder(Value&: protocol_list.next);
4287 sys::swapByteOrder(Value&: protocol_list.count);
4288}
4289
4290inline void swapStruct(struct objc_protocol_t &protocol) {
4291 sys::swapByteOrder(Value&: protocol.isa);
4292 sys::swapByteOrder(Value&: protocol.protocol_name);
4293 sys::swapByteOrder(Value&: protocol.protocol_list);
4294 sys::swapByteOrder(Value&: protocol.instance_methods);
4295 sys::swapByteOrder(Value&: protocol.class_methods);
4296}
4297
4298inline void swapStruct(struct objc_method_description_list_t &mdl) {
4299 sys::swapByteOrder(Value&: mdl.count);
4300}
4301
4302inline void swapStruct(struct objc_method_description_t &md) {
4303 sys::swapByteOrder(Value&: md.name);
4304 sys::swapByteOrder(Value&: md.types);
4305}
4306
4307} // namespace
4308
4309static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4310 struct DisassembleInfo *info);
4311
4312// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
4313// to an Objective-C class and returns the class name. It is also passed the
4314// address of the pointer, so when the pointer is zero as it can be in an .o
4315// file, that is used to look for an external relocation entry with a symbol
4316// name.
4317static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
4318 uint64_t ReferenceValue,
4319 struct DisassembleInfo *info) {
4320 const char *r;
4321 uint32_t offset, left;
4322 SectionRef S;
4323
4324 // The pointer_value can be 0 in an object file and have a relocation
4325 // entry for the class symbol at the ReferenceValue (the address of the
4326 // pointer).
4327 if (pointer_value == 0) {
4328 r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4329 if (r == nullptr || left < sizeof(uint64_t))
4330 return nullptr;
4331 uint64_t n_value;
4332 const char *symbol_name = get_symbol_64(sect_offset: offset, S, info, n_value);
4333 if (symbol_name == nullptr)
4334 return nullptr;
4335 const char *class_name = strrchr(s: symbol_name, c: '$');
4336 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4337 return class_name + 2;
4338 else
4339 return nullptr;
4340 }
4341
4342 // The case were the pointer_value is non-zero and points to a class defined
4343 // in this Mach-O file.
4344 r = get_pointer_64(Address: pointer_value, offset, left, S, info);
4345 if (r == nullptr || left < sizeof(struct class64_t))
4346 return nullptr;
4347 struct class64_t c;
4348 memcpy(dest: &c, src: r, n: sizeof(struct class64_t));
4349 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4350 swapStruct(c);
4351 if (c.data == 0)
4352 return nullptr;
4353 r = get_pointer_64(Address: c.data, offset, left, S, info);
4354 if (r == nullptr || left < sizeof(struct class_ro64_t))
4355 return nullptr;
4356 struct class_ro64_t cro;
4357 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro64_t));
4358 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4359 swapStruct(cro);
4360 if (cro.name == 0)
4361 return nullptr;
4362 const char *name = get_pointer_64(Address: cro.name, offset, left, S, info);
4363 return name;
4364}
4365
4366// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4367// pointer to a cfstring and returns its name or nullptr.
4368static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4369 struct DisassembleInfo *info) {
4370 const char *r, *name;
4371 uint32_t offset, left;
4372 SectionRef S;
4373 struct cfstring64_t cfs;
4374 uint64_t cfs_characters;
4375
4376 r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4377 if (r == nullptr || left < sizeof(struct cfstring64_t))
4378 return nullptr;
4379 memcpy(dest: &cfs, src: r, n: sizeof(struct cfstring64_t));
4380 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4381 swapStruct(cfs);
4382 if (cfs.characters == 0) {
4383 uint64_t n_value;
4384 const char *symbol_name = get_symbol_64(
4385 sect_offset: offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4386 if (symbol_name == nullptr)
4387 return nullptr;
4388 cfs_characters = n_value;
4389 } else
4390 cfs_characters = cfs.characters;
4391 name = get_pointer_64(Address: cfs_characters, offset, left, S, info);
4392
4393 return name;
4394}
4395
4396// get_objc2_64bit_selref() is used for disassembly and is passed a the address
4397// of a pointer to an Objective-C selector reference when the pointer value is
4398// zero as in a .o file and is likely to have a external relocation entry with
4399// who's symbol's n_value is the real pointer to the selector name. If that is
4400// the case the real pointer to the selector name is returned else 0 is
4401// returned
4402static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4403 struct DisassembleInfo *info) {
4404 uint32_t offset, left;
4405 SectionRef S;
4406
4407 const char *r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4408 if (r == nullptr || left < sizeof(uint64_t))
4409 return 0;
4410 uint64_t n_value;
4411 const char *symbol_name = get_symbol_64(sect_offset: offset, S, info, n_value);
4412 if (symbol_name == nullptr)
4413 return 0;
4414 return n_value;
4415}
4416
4417static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4418 const char *sectname) {
4419 for (const SectionRef &Section : O->sections()) {
4420 StringRef SectName;
4421 Expected<StringRef> SecNameOrErr = Section.getName();
4422 if (SecNameOrErr)
4423 SectName = *SecNameOrErr;
4424 else
4425 consumeError(Err: SecNameOrErr.takeError());
4426
4427 DataRefImpl Ref = Section.getRawDataRefImpl();
4428 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4429 if (SegName == segname && SectName == sectname)
4430 return Section;
4431 }
4432 return SectionRef();
4433}
4434
4435static void
4436walk_pointer_list_64(const char *listname, const SectionRef S,
4437 MachOObjectFile *O, struct DisassembleInfo *info,
4438 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4439 if (S == SectionRef())
4440 return;
4441
4442 StringRef SectName;
4443 Expected<StringRef> SecNameOrErr = S.getName();
4444 if (SecNameOrErr)
4445 SectName = *SecNameOrErr;
4446 else
4447 consumeError(Err: SecNameOrErr.takeError());
4448
4449 DataRefImpl Ref = S.getRawDataRefImpl();
4450 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4451 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4452
4453 StringRef BytesStr = unwrapOrError(EO: S.getContents(), Args: O->getFileName());
4454 const char *Contents = BytesStr.data();
4455
4456 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4457 uint32_t left = S.getSize() - i;
4458 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4459 uint64_t p = 0;
4460 memcpy(dest: &p, src: Contents + i, n: size);
4461 if (i + sizeof(uint64_t) > S.getSize())
4462 outs() << listname << " list pointer extends past end of (" << SegName
4463 << "," << SectName << ") section\n";
4464 outs() << format(Fmt: "%016" PRIx64, Vals: S.getAddress() + i) << " ";
4465
4466 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4467 sys::swapByteOrder(Value&: p);
4468
4469 uint64_t n_value = 0;
4470 const char *name = get_symbol_64(sect_offset: i, S, info, n_value, ReferenceValue: p);
4471 if (name == nullptr)
4472 name = get_dyld_bind_info_symbolname(ReferenceValue: S.getAddress() + i, info);
4473
4474 if (n_value != 0) {
4475 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4476 if (p != 0)
4477 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: p);
4478 } else
4479 outs() << format(Fmt: "0x%" PRIx64, Vals: p);
4480 if (name != nullptr)
4481 outs() << " " << name;
4482 outs() << "\n";
4483
4484 p += n_value;
4485 if (func)
4486 func(p, info);
4487 }
4488}
4489
4490static void
4491walk_pointer_list_32(const char *listname, const SectionRef S,
4492 MachOObjectFile *O, struct DisassembleInfo *info,
4493 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4494 if (S == SectionRef())
4495 return;
4496
4497 StringRef SectName = unwrapOrError(EO: S.getName(), Args: O->getFileName());
4498 DataRefImpl Ref = S.getRawDataRefImpl();
4499 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4500 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4501
4502 StringRef BytesStr = unwrapOrError(EO: S.getContents(), Args: O->getFileName());
4503 const char *Contents = BytesStr.data();
4504
4505 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4506 uint32_t left = S.getSize() - i;
4507 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4508 uint32_t p = 0;
4509 memcpy(dest: &p, src: Contents + i, n: size);
4510 if (i + sizeof(uint32_t) > S.getSize())
4511 outs() << listname << " list pointer extends past end of (" << SegName
4512 << "," << SectName << ") section\n";
4513 uint32_t Address = S.getAddress() + i;
4514 outs() << format(Fmt: "%08" PRIx32, Vals: Address) << " ";
4515
4516 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4517 sys::swapByteOrder(Value&: p);
4518 outs() << format(Fmt: "0x%" PRIx32, Vals: p);
4519
4520 const char *name = get_symbol_32(sect_offset: i, S, info, ReferenceValue: p);
4521 if (name != nullptr)
4522 outs() << " " << name;
4523 outs() << "\n";
4524
4525 if (func)
4526 func(p, info);
4527 }
4528}
4529
4530static void print_layout_map(const char *layout_map, uint32_t left) {
4531 if (layout_map == nullptr)
4532 return;
4533 outs() << " layout map: ";
4534 do {
4535 outs() << format(Fmt: "0x%02" PRIx32, Vals: (*layout_map) & 0xff) << " ";
4536 left--;
4537 layout_map++;
4538 } while (*layout_map != '\0' && left != 0);
4539 outs() << "\n";
4540}
4541
4542static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4543 uint32_t offset, left;
4544 SectionRef S;
4545 const char *layout_map;
4546
4547 if (p == 0)
4548 return;
4549 layout_map = get_pointer_64(Address: p, offset, left, S, info);
4550 print_layout_map(layout_map, left);
4551}
4552
4553static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4554 uint32_t offset, left;
4555 SectionRef S;
4556 const char *layout_map;
4557
4558 if (p == 0)
4559 return;
4560 layout_map = get_pointer_32(Address: p, offset, left, S, info);
4561 print_layout_map(layout_map, left);
4562}
4563
4564static void print_relative_method_list(uint32_t structSizeAndFlags,
4565 uint32_t structCount, uint64_t p,
4566 struct DisassembleInfo *info,
4567 const char *indent,
4568 uint32_t pointerBits) {
4569 struct method_relative_t m;
4570 const char *r, *name;
4571 uint32_t offset, xoffset, left, i;
4572 SectionRef S, xS;
4573
4574 assert(((structSizeAndFlags & ML_HAS_RELATIVE_PTRS) != 0) &&
4575 "expected structSizeAndFlags to have ML_HAS_RELATIVE_PTRS flag");
4576
4577 outs() << indent << "\t\t entsize "
4578 << (structSizeAndFlags & ML_ENTSIZE_MASK) << " (relative) \n";
4579 outs() << indent << "\t\t count " << structCount << "\n";
4580
4581 for (i = 0; i < structCount; i++) {
4582 r = get_pointer_64(Address: p, offset, left, S, info);
4583 memset(s: &m, c: '\0', n: sizeof(struct method_relative_t));
4584 if (left < sizeof(struct method_relative_t)) {
4585 memcpy(dest: &m, src: r, n: left);
4586 outs() << indent << " (method_t extends past the end of the section)\n";
4587 } else
4588 memcpy(dest: &m, src: r, n: sizeof(struct method_relative_t));
4589 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4590 swapStruct(m);
4591
4592 outs() << indent << "\t\t name " << format(Fmt: "0x%" PRIx32, Vals: m.name);
4593 uint64_t relNameRefVA = p + offsetof(struct method_relative_t, name);
4594 uint64_t absNameRefVA = relNameRefVA + m.name;
4595 outs() << " (" << format(Fmt: "0x%" PRIx64, Vals: absNameRefVA) << ")";
4596
4597 // since this is a relative list, absNameRefVA is the address of the
4598 // __objc_selrefs entry, so a pointer, not the actual name
4599 const char *nameRefPtr =
4600 get_pointer_64(Address: absNameRefVA, offset&: xoffset, left, S&: xS, info);
4601 if (nameRefPtr) {
4602 uint32_t pointerSize = pointerBits / CHAR_BIT;
4603 if (left < pointerSize)
4604 outs() << indent << " (nameRefPtr extends past the end of the section)";
4605 else {
4606 if (pointerBits == 64) {
4607 uint64_t nameOff_64 = *reinterpret_cast<const uint64_t *>(nameRefPtr);
4608 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4609 sys::swapByteOrder(Value&: nameOff_64);
4610 name = get_pointer_64(Address: nameOff_64, offset&: xoffset, left, S&: xS, info);
4611 } else {
4612 uint32_t nameOff_32 = *reinterpret_cast<const uint32_t *>(nameRefPtr);
4613 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4614 sys::swapByteOrder(Value&: nameOff_32);
4615 name = get_pointer_32(Address: nameOff_32, offset&: xoffset, left, S&: xS, info);
4616 }
4617 if (name != nullptr)
4618 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4619 }
4620 }
4621 outs() << "\n";
4622
4623 outs() << indent << "\t\t types " << format(Fmt: "0x%" PRIx32, Vals: m.types);
4624 uint64_t relTypesVA = p + offsetof(struct method_relative_t, types);
4625 uint64_t absTypesVA = relTypesVA + m.types;
4626 outs() << " (" << format(Fmt: "0x%" PRIx64, Vals: absTypesVA) << ")";
4627 name = get_pointer_64(Address: absTypesVA, offset&: xoffset, left, S&: xS, info);
4628 if (name != nullptr)
4629 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4630 outs() << "\n";
4631
4632 outs() << indent << "\t\t imp " << format(Fmt: "0x%" PRIx32, Vals: m.imp);
4633 uint64_t relImpVA = p + offsetof(struct method_relative_t, imp);
4634 uint64_t absImpVA = relImpVA + m.imp;
4635 outs() << " (" << format(Fmt: "0x%" PRIx64, Vals: absImpVA) << ")";
4636 name = GuessSymbolName(value: absImpVA, AddrMap: info->AddrMap);
4637 if (name != nullptr)
4638 outs() << " " << name;
4639 outs() << "\n";
4640
4641 p += sizeof(struct method_relative_t);
4642 offset += sizeof(struct method_relative_t);
4643 }
4644}
4645
4646static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4647 const char *indent) {
4648 struct method_list64_t ml;
4649 struct method64_t m;
4650 const char *r;
4651 uint32_t offset, xoffset, left, i;
4652 SectionRef S, xS;
4653 const char *name, *sym_name;
4654 uint64_t n_value;
4655
4656 r = get_pointer_64(Address: p, offset, left, S, info);
4657 if (r == nullptr)
4658 return;
4659 memset(s: &ml, c: '\0', n: sizeof(struct method_list64_t));
4660 if (left < sizeof(struct method_list64_t)) {
4661 memcpy(dest: &ml, src: r, n: left);
4662 outs() << " (method_list_t entends past the end of the section)\n";
4663 } else
4664 memcpy(dest: &ml, src: r, n: sizeof(struct method_list64_t));
4665 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4666 swapStruct(ml);
4667 p += sizeof(struct method_list64_t);
4668
4669 if ((ml.entsize & ML_HAS_RELATIVE_PTRS) != 0) {
4670 print_relative_method_list(structSizeAndFlags: ml.entsize, structCount: ml.count, p, info, indent,
4671 /*pointerBits=*/64);
4672 return;
4673 }
4674
4675 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4676 outs() << indent << "\t\t count " << ml.count << "\n";
4677
4678 offset += sizeof(struct method_list64_t);
4679 for (i = 0; i < ml.count; i++) {
4680 r = get_pointer_64(Address: p, offset, left, S, info);
4681 if (r == nullptr)
4682 return;
4683 memset(s: &m, c: '\0', n: sizeof(struct method64_t));
4684 if (left < sizeof(struct method64_t)) {
4685 memcpy(dest: &m, src: r, n: left);
4686 outs() << indent << " (method_t extends past the end of the section)\n";
4687 } else
4688 memcpy(dest: &m, src: r, n: sizeof(struct method64_t));
4689 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4690 swapStruct(m);
4691
4692 outs() << indent << "\t\t name ";
4693 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, name), S,
4694 info, n_value, ReferenceValue: m.name);
4695 if (n_value != 0) {
4696 if (info->verbose && sym_name != nullptr)
4697 outs() << sym_name;
4698 else
4699 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4700 if (m.name != 0)
4701 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: m.name);
4702 } else
4703 outs() << format(Fmt: "0x%" PRIx64, Vals: m.name);
4704 name = get_pointer_64(Address: m.name + n_value, offset&: xoffset, left, S&: xS, info);
4705 if (name != nullptr)
4706 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4707 outs() << "\n";
4708
4709 outs() << indent << "\t\t types ";
4710 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, types), S,
4711 info, n_value, ReferenceValue: m.types);
4712 if (n_value != 0) {
4713 if (info->verbose && sym_name != nullptr)
4714 outs() << sym_name;
4715 else
4716 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4717 if (m.types != 0)
4718 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: m.types);
4719 } else
4720 outs() << format(Fmt: "0x%" PRIx64, Vals: m.types);
4721 name = get_pointer_64(Address: m.types + n_value, offset&: xoffset, left, S&: xS, info);
4722 if (name != nullptr)
4723 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4724 outs() << "\n";
4725
4726 outs() << indent << "\t\t imp ";
4727 name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, imp), S, info,
4728 n_value, ReferenceValue: m.imp);
4729 if (info->verbose && name == nullptr) {
4730 if (n_value != 0) {
4731 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value) << " ";
4732 if (m.imp != 0)
4733 outs() << "+ " << format(Fmt: "0x%" PRIx64, Vals: m.imp) << " ";
4734 } else
4735 outs() << format(Fmt: "0x%" PRIx64, Vals: m.imp) << " ";
4736 }
4737 if (name != nullptr)
4738 outs() << name;
4739 outs() << "\n";
4740
4741 p += sizeof(struct method64_t);
4742 offset += sizeof(struct method64_t);
4743 }
4744}
4745
4746static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4747 const char *indent) {
4748 struct method_list32_t ml;
4749 struct method32_t m;
4750 const char *r, *name;
4751 uint32_t offset, xoffset, left, i;
4752 SectionRef S, xS;
4753
4754 r = get_pointer_32(Address: p, offset, left, S, info);
4755 if (r == nullptr)
4756 return;
4757 memset(s: &ml, c: '\0', n: sizeof(struct method_list32_t));
4758 if (left < sizeof(struct method_list32_t)) {
4759 memcpy(dest: &ml, src: r, n: left);
4760 outs() << " (method_list_t entends past the end of the section)\n";
4761 } else
4762 memcpy(dest: &ml, src: r, n: sizeof(struct method_list32_t));
4763 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4764 swapStruct(ml);
4765 p += sizeof(struct method_list32_t);
4766
4767 if ((ml.entsize & ML_HAS_RELATIVE_PTRS) != 0) {
4768 print_relative_method_list(structSizeAndFlags: ml.entsize, structCount: ml.count, p, info, indent,
4769 /*pointerBits=*/32);
4770 return;
4771 }
4772
4773 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4774 outs() << indent << "\t\t count " << ml.count << "\n";
4775
4776 offset += sizeof(struct method_list32_t);
4777 for (i = 0; i < ml.count; i++) {
4778 r = get_pointer_32(Address: p, offset, left, S, info);
4779 if (r == nullptr)
4780 return;
4781 memset(s: &m, c: '\0', n: sizeof(struct method32_t));
4782 if (left < sizeof(struct method32_t)) {
4783 memcpy(dest: &ml, src: r, n: left);
4784 outs() << indent << " (method_t entends past the end of the section)\n";
4785 } else
4786 memcpy(dest: &m, src: r, n: sizeof(struct method32_t));
4787 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4788 swapStruct(m);
4789
4790 outs() << indent << "\t\t name " << format(Fmt: "0x%" PRIx32, Vals: m.name);
4791 name = get_pointer_32(Address: m.name, offset&: xoffset, left, S&: xS, info);
4792 if (name != nullptr)
4793 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4794 outs() << "\n";
4795
4796 outs() << indent << "\t\t types " << format(Fmt: "0x%" PRIx32, Vals: m.types);
4797 name = get_pointer_32(Address: m.types, offset&: xoffset, left, S&: xS, info);
4798 if (name != nullptr)
4799 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4800 outs() << "\n";
4801
4802 outs() << indent << "\t\t imp " << format(Fmt: "0x%" PRIx32, Vals: m.imp);
4803 name = get_symbol_32(sect_offset: offset + offsetof(struct method32_t, imp), S, info,
4804 ReferenceValue: m.imp);
4805 if (name != nullptr)
4806 outs() << " " << name;
4807 outs() << "\n";
4808
4809 p += sizeof(struct method32_t);
4810 offset += sizeof(struct method32_t);
4811 }
4812}
4813
4814static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4815 uint32_t offset, left, xleft;
4816 SectionRef S;
4817 struct objc_method_list_t method_list;
4818 struct objc_method_t method;
4819 const char *r, *methods, *name, *SymbolName;
4820 int32_t i;
4821
4822 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
4823 if (r == nullptr)
4824 return true;
4825
4826 outs() << "\n";
4827 if (left > sizeof(struct objc_method_list_t)) {
4828 memcpy(dest: &method_list, src: r, n: sizeof(struct objc_method_list_t));
4829 } else {
4830 outs() << "\t\t objc_method_list extends past end of the section\n";
4831 memset(s: &method_list, c: '\0', n: sizeof(struct objc_method_list_t));
4832 memcpy(dest: &method_list, src: r, n: left);
4833 }
4834 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4835 swapStruct(method_list);
4836
4837 outs() << "\t\t obsolete "
4838 << format(Fmt: "0x%08" PRIx32, Vals: method_list.obsolete) << "\n";
4839 outs() << "\t\t method_count " << method_list.method_count << "\n";
4840
4841 methods = r + sizeof(struct objc_method_list_t);
4842 for (i = 0; i < method_list.method_count; i++) {
4843 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4844 outs() << "\t\t remaining method's extend past the of the section\n";
4845 break;
4846 }
4847 memcpy(dest: &method, src: methods + i * sizeof(struct objc_method_t),
4848 n: sizeof(struct objc_method_t));
4849 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4850 swapStruct(method);
4851
4852 outs() << "\t\t method_name "
4853 << format(Fmt: "0x%08" PRIx32, Vals: method.method_name);
4854 if (info->verbose) {
4855 name = get_pointer_32(Address: method.method_name, offset, left&: xleft, S, info, objc_only: true);
4856 if (name != nullptr)
4857 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
4858 else
4859 outs() << " (not in an __OBJC section)";
4860 }
4861 outs() << "\n";
4862
4863 outs() << "\t\t method_types "
4864 << format(Fmt: "0x%08" PRIx32, Vals: method.method_types);
4865 if (info->verbose) {
4866 name = get_pointer_32(Address: method.method_types, offset, left&: xleft, S, info, objc_only: true);
4867 if (name != nullptr)
4868 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
4869 else
4870 outs() << " (not in an __OBJC section)";
4871 }
4872 outs() << "\n";
4873
4874 outs() << "\t\t method_imp "
4875 << format(Fmt: "0x%08" PRIx32, Vals: method.method_imp) << " ";
4876 if (info->verbose) {
4877 SymbolName = GuessSymbolName(value: method.method_imp, AddrMap: info->AddrMap);
4878 if (SymbolName != nullptr)
4879 outs() << SymbolName;
4880 }
4881 outs() << "\n";
4882 }
4883 return false;
4884}
4885
4886static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4887 struct protocol_list64_t pl;
4888 uint64_t q, n_value;
4889 struct protocol64_t pc;
4890 const char *r;
4891 uint32_t offset, xoffset, left, i;
4892 SectionRef S, xS;
4893 const char *name, *sym_name;
4894
4895 r = get_pointer_64(Address: p, offset, left, S, info);
4896 if (r == nullptr)
4897 return;
4898 memset(s: &pl, c: '\0', n: sizeof(struct protocol_list64_t));
4899 if (left < sizeof(struct protocol_list64_t)) {
4900 memcpy(dest: &pl, src: r, n: left);
4901 outs() << " (protocol_list_t entends past the end of the section)\n";
4902 } else
4903 memcpy(dest: &pl, src: r, n: sizeof(struct protocol_list64_t));
4904 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4905 swapStruct(pl);
4906 outs() << " count " << pl.count << "\n";
4907
4908 p += sizeof(struct protocol_list64_t);
4909 offset += sizeof(struct protocol_list64_t);
4910 for (i = 0; i < pl.count; i++) {
4911 r = get_pointer_64(Address: p, offset, left, S, info);
4912 if (r == nullptr)
4913 return;
4914 q = 0;
4915 if (left < sizeof(uint64_t)) {
4916 memcpy(dest: &q, src: r, n: left);
4917 outs() << " (protocol_t * entends past the end of the section)\n";
4918 } else
4919 memcpy(dest: &q, src: r, n: sizeof(uint64_t));
4920 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4921 sys::swapByteOrder(Value&: q);
4922
4923 outs() << "\t\t list[" << i << "] ";
4924 sym_name = get_symbol_64(sect_offset: offset, S, info, n_value, ReferenceValue: q);
4925 if (n_value != 0) {
4926 if (info->verbose && sym_name != nullptr)
4927 outs() << sym_name;
4928 else
4929 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4930 if (q != 0)
4931 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: q);
4932 } else
4933 outs() << format(Fmt: "0x%" PRIx64, Vals: q);
4934 outs() << " (struct protocol_t *)\n";
4935
4936 r = get_pointer_64(Address: q + n_value, offset, left, S, info);
4937 if (r == nullptr)
4938 return;
4939 memset(s: &pc, c: '\0', n: sizeof(struct protocol64_t));
4940 if (left < sizeof(struct protocol64_t)) {
4941 memcpy(dest: &pc, src: r, n: left);
4942 outs() << " (protocol_t entends past the end of the section)\n";
4943 } else
4944 memcpy(dest: &pc, src: r, n: sizeof(struct protocol64_t));
4945 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4946 swapStruct(p&: pc);
4947
4948 outs() << "\t\t\t isa " << format(Fmt: "0x%" PRIx64, Vals: pc.isa) << "\n";
4949
4950 outs() << "\t\t\t name ";
4951 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, name), S,
4952 info, n_value, ReferenceValue: pc.name);
4953 if (n_value != 0) {
4954 if (info->verbose && sym_name != nullptr)
4955 outs() << sym_name;
4956 else
4957 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4958 if (pc.name != 0)
4959 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.name);
4960 } else
4961 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.name);
4962 name = get_pointer_64(Address: pc.name + n_value, offset&: xoffset, left, S&: xS, info);
4963 if (name != nullptr)
4964 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4965 outs() << "\n";
4966
4967 outs() << "\t\t\tprotocols " << format(Fmt: "0x%" PRIx64, Vals: pc.protocols) << "\n";
4968
4969 outs() << "\t\t instanceMethods ";
4970 sym_name =
4971 get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, instanceMethods),
4972 S, info, n_value, ReferenceValue: pc.instanceMethods);
4973 if (n_value != 0) {
4974 if (info->verbose && sym_name != nullptr)
4975 outs() << sym_name;
4976 else
4977 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4978 if (pc.instanceMethods != 0)
4979 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.instanceMethods);
4980 } else
4981 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.instanceMethods);
4982 outs() << " (struct method_list_t *)\n";
4983 if (pc.instanceMethods + n_value != 0)
4984 print_method_list64_t(p: pc.instanceMethods + n_value, info, indent: "\t");
4985
4986 outs() << "\t\t classMethods ";
4987 sym_name =
4988 get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, classMethods), S,
4989 info, n_value, ReferenceValue: pc.classMethods);
4990 if (n_value != 0) {
4991 if (info->verbose && sym_name != nullptr)
4992 outs() << sym_name;
4993 else
4994 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4995 if (pc.classMethods != 0)
4996 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.classMethods);
4997 } else
4998 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.classMethods);
4999 outs() << " (struct method_list_t *)\n";
5000 if (pc.classMethods + n_value != 0)
5001 print_method_list64_t(p: pc.classMethods + n_value, info, indent: "\t");
5002
5003 outs() << "\t optionalInstanceMethods "
5004 << format(Fmt: "0x%" PRIx64, Vals: pc.optionalInstanceMethods) << "\n";
5005 outs() << "\t optionalClassMethods "
5006 << format(Fmt: "0x%" PRIx64, Vals: pc.optionalClassMethods) << "\n";
5007 outs() << "\t instanceProperties "
5008 << format(Fmt: "0x%" PRIx64, Vals: pc.instanceProperties) << "\n";
5009
5010 p += sizeof(uint64_t);
5011 offset += sizeof(uint64_t);
5012 }
5013}
5014
5015static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
5016 struct protocol_list32_t pl;
5017 uint32_t q;
5018 struct protocol32_t pc;
5019 const char *r;
5020 uint32_t offset, xoffset, left, i;
5021 SectionRef S, xS;
5022 const char *name;
5023
5024 r = get_pointer_32(Address: p, offset, left, S, info);
5025 if (r == nullptr)
5026 return;
5027 memset(s: &pl, c: '\0', n: sizeof(struct protocol_list32_t));
5028 if (left < sizeof(struct protocol_list32_t)) {
5029 memcpy(dest: &pl, src: r, n: left);
5030 outs() << " (protocol_list_t entends past the end of the section)\n";
5031 } else
5032 memcpy(dest: &pl, src: r, n: sizeof(struct protocol_list32_t));
5033 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5034 swapStruct(pl);
5035 outs() << " count " << pl.count << "\n";
5036
5037 p += sizeof(struct protocol_list32_t);
5038 offset += sizeof(struct protocol_list32_t);
5039 for (i = 0; i < pl.count; i++) {
5040 r = get_pointer_32(Address: p, offset, left, S, info);
5041 if (r == nullptr)
5042 return;
5043 q = 0;
5044 if (left < sizeof(uint32_t)) {
5045 memcpy(dest: &q, src: r, n: left);
5046 outs() << " (protocol_t * entends past the end of the section)\n";
5047 } else
5048 memcpy(dest: &q, src: r, n: sizeof(uint32_t));
5049 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5050 sys::swapByteOrder(Value&: q);
5051 outs() << "\t\t list[" << i << "] " << format(Fmt: "0x%" PRIx32, Vals: q)
5052 << " (struct protocol_t *)\n";
5053 r = get_pointer_32(Address: q, offset, left, S, info);
5054 if (r == nullptr)
5055 return;
5056 memset(s: &pc, c: '\0', n: sizeof(struct protocol32_t));
5057 if (left < sizeof(struct protocol32_t)) {
5058 memcpy(dest: &pc, src: r, n: left);
5059 outs() << " (protocol_t entends past the end of the section)\n";
5060 } else
5061 memcpy(dest: &pc, src: r, n: sizeof(struct protocol32_t));
5062 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5063 swapStruct(p&: pc);
5064 outs() << "\t\t\t isa " << format(Fmt: "0x%" PRIx32, Vals: pc.isa) << "\n";
5065 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: pc.name);
5066 name = get_pointer_32(Address: pc.name, offset&: xoffset, left, S&: xS, info);
5067 if (name != nullptr)
5068 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5069 outs() << "\n";
5070 outs() << "\t\t\tprotocols " << format(Fmt: "0x%" PRIx32, Vals: pc.protocols) << "\n";
5071 outs() << "\t\t instanceMethods "
5072 << format(Fmt: "0x%" PRIx32, Vals: pc.instanceMethods)
5073 << " (struct method_list_t *)\n";
5074 if (pc.instanceMethods != 0)
5075 print_method_list32_t(p: pc.instanceMethods, info, indent: "\t");
5076 outs() << "\t\t classMethods " << format(Fmt: "0x%" PRIx32, Vals: pc.classMethods)
5077 << " (struct method_list_t *)\n";
5078 if (pc.classMethods != 0)
5079 print_method_list32_t(p: pc.classMethods, info, indent: "\t");
5080 outs() << "\t optionalInstanceMethods "
5081 << format(Fmt: "0x%" PRIx32, Vals: pc.optionalInstanceMethods) << "\n";
5082 outs() << "\t optionalClassMethods "
5083 << format(Fmt: "0x%" PRIx32, Vals: pc.optionalClassMethods) << "\n";
5084 outs() << "\t instanceProperties "
5085 << format(Fmt: "0x%" PRIx32, Vals: pc.instanceProperties) << "\n";
5086 p += sizeof(uint32_t);
5087 offset += sizeof(uint32_t);
5088 }
5089}
5090
5091static void print_indent(uint32_t indent) {
5092 for (uint32_t i = 0; i < indent;) {
5093 if (indent - i >= 8) {
5094 outs() << "\t";
5095 i += 8;
5096 } else {
5097 for (uint32_t j = i; j < indent; j++)
5098 outs() << " ";
5099 return;
5100 }
5101 }
5102}
5103
5104static bool print_method_description_list(uint32_t p, uint32_t indent,
5105 struct DisassembleInfo *info) {
5106 uint32_t offset, left, xleft;
5107 SectionRef S;
5108 struct objc_method_description_list_t mdl;
5109 struct objc_method_description_t md;
5110 const char *r, *list, *name;
5111 int32_t i;
5112
5113 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5114 if (r == nullptr)
5115 return true;
5116
5117 outs() << "\n";
5118 if (left > sizeof(struct objc_method_description_list_t)) {
5119 memcpy(dest: &mdl, src: r, n: sizeof(struct objc_method_description_list_t));
5120 } else {
5121 print_indent(indent);
5122 outs() << " objc_method_description_list extends past end of the section\n";
5123 memset(s: &mdl, c: '\0', n: sizeof(struct objc_method_description_list_t));
5124 memcpy(dest: &mdl, src: r, n: left);
5125 }
5126 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5127 swapStruct(mdl);
5128
5129 print_indent(indent);
5130 outs() << " count " << mdl.count << "\n";
5131
5132 list = r + sizeof(struct objc_method_description_list_t);
5133 for (i = 0; i < mdl.count; i++) {
5134 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
5135 print_indent(indent);
5136 outs() << " remaining list entries extend past the of the section\n";
5137 break;
5138 }
5139 print_indent(indent);
5140 outs() << " list[" << i << "]\n";
5141 memcpy(dest: &md, src: list + i * sizeof(struct objc_method_description_t),
5142 n: sizeof(struct objc_method_description_t));
5143 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5144 swapStruct(md);
5145
5146 print_indent(indent);
5147 outs() << " name " << format(Fmt: "0x%08" PRIx32, Vals: md.name);
5148 if (info->verbose) {
5149 name = get_pointer_32(Address: md.name, offset, left&: xleft, S, info, objc_only: true);
5150 if (name != nullptr)
5151 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5152 else
5153 outs() << " (not in an __OBJC section)";
5154 }
5155 outs() << "\n";
5156
5157 print_indent(indent);
5158 outs() << " types " << format(Fmt: "0x%08" PRIx32, Vals: md.types);
5159 if (info->verbose) {
5160 name = get_pointer_32(Address: md.types, offset, left&: xleft, S, info, objc_only: true);
5161 if (name != nullptr)
5162 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5163 else
5164 outs() << " (not in an __OBJC section)";
5165 }
5166 outs() << "\n";
5167 }
5168 return false;
5169}
5170
5171static bool print_protocol_list(uint32_t p, uint32_t indent,
5172 struct DisassembleInfo *info);
5173
5174static bool print_protocol(uint32_t p, uint32_t indent,
5175 struct DisassembleInfo *info) {
5176 uint32_t offset, left;
5177 SectionRef S;
5178 struct objc_protocol_t protocol;
5179 const char *r, *name;
5180
5181 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5182 if (r == nullptr)
5183 return true;
5184
5185 outs() << "\n";
5186 if (left >= sizeof(struct objc_protocol_t)) {
5187 memcpy(dest: &protocol, src: r, n: sizeof(struct objc_protocol_t));
5188 } else {
5189 print_indent(indent);
5190 outs() << " Protocol extends past end of the section\n";
5191 memset(s: &protocol, c: '\0', n: sizeof(struct objc_protocol_t));
5192 memcpy(dest: &protocol, src: r, n: left);
5193 }
5194 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5195 swapStruct(protocol);
5196
5197 print_indent(indent);
5198 outs() << " isa " << format(Fmt: "0x%08" PRIx32, Vals: protocol.isa)
5199 << "\n";
5200
5201 print_indent(indent);
5202 outs() << " protocol_name "
5203 << format(Fmt: "0x%08" PRIx32, Vals: protocol.protocol_name);
5204 if (info->verbose) {
5205 name = get_pointer_32(Address: protocol.protocol_name, offset, left, S, info, objc_only: true);
5206 if (name != nullptr)
5207 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5208 else
5209 outs() << " (not in an __OBJC section)";
5210 }
5211 outs() << "\n";
5212
5213 print_indent(indent);
5214 outs() << " protocol_list "
5215 << format(Fmt: "0x%08" PRIx32, Vals: protocol.protocol_list);
5216 if (print_protocol_list(p: protocol.protocol_list, indent: indent + 4, info))
5217 outs() << " (not in an __OBJC section)\n";
5218
5219 print_indent(indent);
5220 outs() << " instance_methods "
5221 << format(Fmt: "0x%08" PRIx32, Vals: protocol.instance_methods);
5222 if (print_method_description_list(p: protocol.instance_methods, indent, info))
5223 outs() << " (not in an __OBJC section)\n";
5224
5225 print_indent(indent);
5226 outs() << " class_methods "
5227 << format(Fmt: "0x%08" PRIx32, Vals: protocol.class_methods);
5228 if (print_method_description_list(p: protocol.class_methods, indent, info))
5229 outs() << " (not in an __OBJC section)\n";
5230
5231 return false;
5232}
5233
5234static bool print_protocol_list(uint32_t p, uint32_t indent,
5235 struct DisassembleInfo *info) {
5236 uint32_t offset, left, l;
5237 SectionRef S;
5238 struct objc_protocol_list_t protocol_list;
5239 const char *r, *list;
5240 int32_t i;
5241
5242 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5243 if (r == nullptr)
5244 return true;
5245
5246 outs() << "\n";
5247 if (left > sizeof(struct objc_protocol_list_t)) {
5248 memcpy(dest: &protocol_list, src: r, n: sizeof(struct objc_protocol_list_t));
5249 } else {
5250 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
5251 memset(s: &protocol_list, c: '\0', n: sizeof(struct objc_protocol_list_t));
5252 memcpy(dest: &protocol_list, src: r, n: left);
5253 }
5254 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5255 swapStruct(protocol_list);
5256
5257 print_indent(indent);
5258 outs() << " next " << format(Fmt: "0x%08" PRIx32, Vals: protocol_list.next)
5259 << "\n";
5260 print_indent(indent);
5261 outs() << " count " << protocol_list.count << "\n";
5262
5263 list = r + sizeof(struct objc_protocol_list_t);
5264 for (i = 0; i < protocol_list.count; i++) {
5265 if ((i + 1) * sizeof(uint32_t) > left) {
5266 outs() << "\t\t remaining list entries extend past the of the section\n";
5267 break;
5268 }
5269 memcpy(dest: &l, src: list + i * sizeof(uint32_t), n: sizeof(uint32_t));
5270 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5271 sys::swapByteOrder(Value&: l);
5272
5273 print_indent(indent);
5274 outs() << " list[" << i << "] " << format(Fmt: "0x%08" PRIx32, Vals: l);
5275 if (print_protocol(p: l, indent, info))
5276 outs() << "(not in an __OBJC section)\n";
5277 }
5278 return false;
5279}
5280
5281static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
5282 struct ivar_list64_t il;
5283 struct ivar64_t i;
5284 const char *r;
5285 uint32_t offset, xoffset, left, j;
5286 SectionRef S, xS;
5287 const char *name, *sym_name, *ivar_offset_p;
5288 uint64_t ivar_offset, n_value;
5289
5290 r = get_pointer_64(Address: p, offset, left, S, info);
5291 if (r == nullptr)
5292 return;
5293 memset(s: &il, c: '\0', n: sizeof(struct ivar_list64_t));
5294 if (left < sizeof(struct ivar_list64_t)) {
5295 memcpy(dest: &il, src: r, n: left);
5296 outs() << " (ivar_list_t entends past the end of the section)\n";
5297 } else
5298 memcpy(dest: &il, src: r, n: sizeof(struct ivar_list64_t));
5299 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5300 swapStruct(il);
5301 outs() << " entsize " << il.entsize << "\n";
5302 outs() << " count " << il.count << "\n";
5303
5304 p += sizeof(struct ivar_list64_t);
5305 offset += sizeof(struct ivar_list64_t);
5306 for (j = 0; j < il.count; j++) {
5307 r = get_pointer_64(Address: p, offset, left, S, info);
5308 if (r == nullptr)
5309 return;
5310 memset(s: &i, c: '\0', n: sizeof(struct ivar64_t));
5311 if (left < sizeof(struct ivar64_t)) {
5312 memcpy(dest: &i, src: r, n: left);
5313 outs() << " (ivar_t entends past the end of the section)\n";
5314 } else
5315 memcpy(dest: &i, src: r, n: sizeof(struct ivar64_t));
5316 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5317 swapStruct(i);
5318
5319 outs() << "\t\t\t offset ";
5320 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, offset), S,
5321 info, n_value, ReferenceValue: i.offset);
5322 if (n_value != 0) {
5323 if (info->verbose && sym_name != nullptr)
5324 outs() << sym_name;
5325 else
5326 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5327 if (i.offset != 0)
5328 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.offset);
5329 } else
5330 outs() << format(Fmt: "0x%" PRIx64, Vals: i.offset);
5331 ivar_offset_p = get_pointer_64(Address: i.offset + n_value, offset&: xoffset, left, S&: xS, info);
5332 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5333 memcpy(dest: &ivar_offset, src: ivar_offset_p, n: sizeof(ivar_offset));
5334 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5335 sys::swapByteOrder(Value&: ivar_offset);
5336 outs() << " " << ivar_offset << "\n";
5337 } else
5338 outs() << "\n";
5339
5340 outs() << "\t\t\t name ";
5341 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, name), S, info,
5342 n_value, ReferenceValue: i.name);
5343 if (n_value != 0) {
5344 if (info->verbose && sym_name != nullptr)
5345 outs() << sym_name;
5346 else
5347 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5348 if (i.name != 0)
5349 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.name);
5350 } else
5351 outs() << format(Fmt: "0x%" PRIx64, Vals: i.name);
5352 name = get_pointer_64(Address: i.name + n_value, offset&: xoffset, left, S&: xS, info);
5353 if (name != nullptr)
5354 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5355 outs() << "\n";
5356
5357 outs() << "\t\t\t type ";
5358 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, type), S, info,
5359 n_value, ReferenceValue: i.name);
5360 name = get_pointer_64(Address: i.type + n_value, offset&: xoffset, left, S&: xS, info);
5361 if (n_value != 0) {
5362 if (info->verbose && sym_name != nullptr)
5363 outs() << sym_name;
5364 else
5365 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5366 if (i.type != 0)
5367 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.type);
5368 } else
5369 outs() << format(Fmt: "0x%" PRIx64, Vals: i.type);
5370 if (name != nullptr)
5371 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5372 outs() << "\n";
5373
5374 outs() << "\t\t\talignment " << i.alignment << "\n";
5375 outs() << "\t\t\t size " << i.size << "\n";
5376
5377 p += sizeof(struct ivar64_t);
5378 offset += sizeof(struct ivar64_t);
5379 }
5380}
5381
5382static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
5383 struct ivar_list32_t il;
5384 struct ivar32_t i;
5385 const char *r;
5386 uint32_t offset, xoffset, left, j;
5387 SectionRef S, xS;
5388 const char *name, *ivar_offset_p;
5389 uint32_t ivar_offset;
5390
5391 r = get_pointer_32(Address: p, offset, left, S, info);
5392 if (r == nullptr)
5393 return;
5394 memset(s: &il, c: '\0', n: sizeof(struct ivar_list32_t));
5395 if (left < sizeof(struct ivar_list32_t)) {
5396 memcpy(dest: &il, src: r, n: left);
5397 outs() << " (ivar_list_t entends past the end of the section)\n";
5398 } else
5399 memcpy(dest: &il, src: r, n: sizeof(struct ivar_list32_t));
5400 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5401 swapStruct(il);
5402 outs() << " entsize " << il.entsize << "\n";
5403 outs() << " count " << il.count << "\n";
5404
5405 p += sizeof(struct ivar_list32_t);
5406 offset += sizeof(struct ivar_list32_t);
5407 for (j = 0; j < il.count; j++) {
5408 r = get_pointer_32(Address: p, offset, left, S, info);
5409 if (r == nullptr)
5410 return;
5411 memset(s: &i, c: '\0', n: sizeof(struct ivar32_t));
5412 if (left < sizeof(struct ivar32_t)) {
5413 memcpy(dest: &i, src: r, n: left);
5414 outs() << " (ivar_t entends past the end of the section)\n";
5415 } else
5416 memcpy(dest: &i, src: r, n: sizeof(struct ivar32_t));
5417 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5418 swapStruct(i);
5419
5420 outs() << "\t\t\t offset " << format(Fmt: "0x%" PRIx32, Vals: i.offset);
5421 ivar_offset_p = get_pointer_32(Address: i.offset, offset&: xoffset, left, S&: xS, info);
5422 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5423 memcpy(dest: &ivar_offset, src: ivar_offset_p, n: sizeof(ivar_offset));
5424 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5425 sys::swapByteOrder(Value&: ivar_offset);
5426 outs() << " " << ivar_offset << "\n";
5427 } else
5428 outs() << "\n";
5429
5430 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: i.name);
5431 name = get_pointer_32(Address: i.name, offset&: xoffset, left, S&: xS, info);
5432 if (name != nullptr)
5433 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5434 outs() << "\n";
5435
5436 outs() << "\t\t\t type " << format(Fmt: "0x%" PRIx32, Vals: i.type);
5437 name = get_pointer_32(Address: i.type, offset&: xoffset, left, S&: xS, info);
5438 if (name != nullptr)
5439 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5440 outs() << "\n";
5441
5442 outs() << "\t\t\talignment " << i.alignment << "\n";
5443 outs() << "\t\t\t size " << i.size << "\n";
5444
5445 p += sizeof(struct ivar32_t);
5446 offset += sizeof(struct ivar32_t);
5447 }
5448}
5449
5450static void print_objc_property_list64(uint64_t p,
5451 struct DisassembleInfo *info) {
5452 struct objc_property_list64 opl;
5453 struct objc_property64 op;
5454 const char *r;
5455 uint32_t offset, xoffset, left, j;
5456 SectionRef S, xS;
5457 const char *name, *sym_name;
5458 uint64_t n_value;
5459
5460 r = get_pointer_64(Address: p, offset, left, S, info);
5461 if (r == nullptr)
5462 return;
5463 memset(s: &opl, c: '\0', n: sizeof(struct objc_property_list64));
5464 if (left < sizeof(struct objc_property_list64)) {
5465 memcpy(dest: &opl, src: r, n: left);
5466 outs() << " (objc_property_list entends past the end of the section)\n";
5467 } else
5468 memcpy(dest: &opl, src: r, n: sizeof(struct objc_property_list64));
5469 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5470 swapStruct(pl&: opl);
5471 outs() << " entsize " << opl.entsize << "\n";
5472 outs() << " count " << opl.count << "\n";
5473
5474 p += sizeof(struct objc_property_list64);
5475 offset += sizeof(struct objc_property_list64);
5476 for (j = 0; j < opl.count; j++) {
5477 r = get_pointer_64(Address: p, offset, left, S, info);
5478 if (r == nullptr)
5479 return;
5480 memset(s: &op, c: '\0', n: sizeof(struct objc_property64));
5481 if (left < sizeof(struct objc_property64)) {
5482 memcpy(dest: &op, src: r, n: left);
5483 outs() << " (objc_property entends past the end of the section)\n";
5484 } else
5485 memcpy(dest: &op, src: r, n: sizeof(struct objc_property64));
5486 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5487 swapStruct(op);
5488
5489 outs() << "\t\t\t name ";
5490 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct objc_property64, name), S,
5491 info, n_value, ReferenceValue: op.name);
5492 if (n_value != 0) {
5493 if (info->verbose && sym_name != nullptr)
5494 outs() << sym_name;
5495 else
5496 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5497 if (op.name != 0)
5498 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: op.name);
5499 } else
5500 outs() << format(Fmt: "0x%" PRIx64, Vals: op.name);
5501 name = get_pointer_64(Address: op.name + n_value, offset&: xoffset, left, S&: xS, info);
5502 if (name != nullptr)
5503 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5504 outs() << "\n";
5505
5506 outs() << "\t\t\tattributes ";
5507 sym_name =
5508 get_symbol_64(sect_offset: offset + offsetof(struct objc_property64, attributes), S,
5509 info, n_value, ReferenceValue: op.attributes);
5510 if (n_value != 0) {
5511 if (info->verbose && sym_name != nullptr)
5512 outs() << sym_name;
5513 else
5514 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5515 if (op.attributes != 0)
5516 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: op.attributes);
5517 } else
5518 outs() << format(Fmt: "0x%" PRIx64, Vals: op.attributes);
5519 name = get_pointer_64(Address: op.attributes + n_value, offset&: xoffset, left, S&: xS, info);
5520 if (name != nullptr)
5521 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5522 outs() << "\n";
5523
5524 p += sizeof(struct objc_property64);
5525 offset += sizeof(struct objc_property64);
5526 }
5527}
5528
5529static void print_objc_property_list32(uint32_t p,
5530 struct DisassembleInfo *info) {
5531 struct objc_property_list32 opl;
5532 struct objc_property32 op;
5533 const char *r;
5534 uint32_t offset, xoffset, left, j;
5535 SectionRef S, xS;
5536 const char *name;
5537
5538 r = get_pointer_32(Address: p, offset, left, S, info);
5539 if (r == nullptr)
5540 return;
5541 memset(s: &opl, c: '\0', n: sizeof(struct objc_property_list32));
5542 if (left < sizeof(struct objc_property_list32)) {
5543 memcpy(dest: &opl, src: r, n: left);
5544 outs() << " (objc_property_list entends past the end of the section)\n";
5545 } else
5546 memcpy(dest: &opl, src: r, n: sizeof(struct objc_property_list32));
5547 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5548 swapStruct(pl&: opl);
5549 outs() << " entsize " << opl.entsize << "\n";
5550 outs() << " count " << opl.count << "\n";
5551
5552 p += sizeof(struct objc_property_list32);
5553 offset += sizeof(struct objc_property_list32);
5554 for (j = 0; j < opl.count; j++) {
5555 r = get_pointer_32(Address: p, offset, left, S, info);
5556 if (r == nullptr)
5557 return;
5558 memset(s: &op, c: '\0', n: sizeof(struct objc_property32));
5559 if (left < sizeof(struct objc_property32)) {
5560 memcpy(dest: &op, src: r, n: left);
5561 outs() << " (objc_property entends past the end of the section)\n";
5562 } else
5563 memcpy(dest: &op, src: r, n: sizeof(struct objc_property32));
5564 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5565 swapStruct(op);
5566
5567 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: op.name);
5568 name = get_pointer_32(Address: op.name, offset&: xoffset, left, S&: xS, info);
5569 if (name != nullptr)
5570 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5571 outs() << "\n";
5572
5573 outs() << "\t\t\tattributes " << format(Fmt: "0x%" PRIx32, Vals: op.attributes);
5574 name = get_pointer_32(Address: op.attributes, offset&: xoffset, left, S&: xS, info);
5575 if (name != nullptr)
5576 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5577 outs() << "\n";
5578
5579 p += sizeof(struct objc_property32);
5580 offset += sizeof(struct objc_property32);
5581 }
5582}
5583
5584static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5585 bool &is_meta_class) {
5586 struct class_ro64_t cro;
5587 const char *r;
5588 uint32_t offset, xoffset, left;
5589 SectionRef S, xS;
5590 const char *name, *sym_name;
5591 uint64_t n_value;
5592
5593 r = get_pointer_64(Address: p, offset, left, S, info);
5594 if (r == nullptr || left < sizeof(struct class_ro64_t))
5595 return false;
5596 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro64_t));
5597 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5598 swapStruct(cro);
5599 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: cro.flags);
5600 if (cro.flags & RO_META)
5601 outs() << " RO_META";
5602 if (cro.flags & RO_ROOT)
5603 outs() << " RO_ROOT";
5604 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5605 outs() << " RO_HAS_CXX_STRUCTORS";
5606 outs() << "\n";
5607 outs() << " instanceStart " << cro.instanceStart << "\n";
5608 outs() << " instanceSize " << cro.instanceSize << "\n";
5609 outs() << " reserved " << format(Fmt: "0x%" PRIx32, Vals: cro.reserved)
5610 << "\n";
5611 outs() << " ivarLayout " << format(Fmt: "0x%" PRIx64, Vals: cro.ivarLayout)
5612 << "\n";
5613 print_layout_map64(p: cro.ivarLayout, info);
5614
5615 outs() << " name ";
5616 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, name), S,
5617 info, n_value, ReferenceValue: cro.name);
5618 if (n_value != 0) {
5619 if (info->verbose && sym_name != nullptr)
5620 outs() << sym_name;
5621 else
5622 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5623 if (cro.name != 0)
5624 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.name);
5625 } else
5626 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.name);
5627 name = get_pointer_64(Address: cro.name + n_value, offset&: xoffset, left, S&: xS, info);
5628 if (name != nullptr)
5629 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5630 outs() << "\n";
5631
5632 outs() << " baseMethods ";
5633 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseMethods),
5634 S, info, n_value, ReferenceValue: cro.baseMethods);
5635 if (n_value != 0) {
5636 if (info->verbose && sym_name != nullptr)
5637 outs() << sym_name;
5638 else
5639 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5640 if (cro.baseMethods != 0)
5641 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseMethods);
5642 } else
5643 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseMethods);
5644 outs() << " (struct method_list_t *)\n";
5645 if (cro.baseMethods + n_value != 0)
5646 print_method_list64_t(p: cro.baseMethods + n_value, info, indent: "");
5647
5648 outs() << " baseProtocols ";
5649 sym_name =
5650 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseProtocols), S,
5651 info, n_value, ReferenceValue: cro.baseProtocols);
5652 if (n_value != 0) {
5653 if (info->verbose && sym_name != nullptr)
5654 outs() << sym_name;
5655 else
5656 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5657 if (cro.baseProtocols != 0)
5658 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseProtocols);
5659 } else
5660 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseProtocols);
5661 outs() << "\n";
5662 if (cro.baseProtocols + n_value != 0)
5663 print_protocol_list64_t(p: cro.baseProtocols + n_value, info);
5664
5665 outs() << " ivars ";
5666 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, ivars), S,
5667 info, n_value, ReferenceValue: cro.ivars);
5668 if (n_value != 0) {
5669 if (info->verbose && sym_name != nullptr)
5670 outs() << sym_name;
5671 else
5672 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5673 if (cro.ivars != 0)
5674 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.ivars);
5675 } else
5676 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.ivars);
5677 outs() << "\n";
5678 if (cro.ivars + n_value != 0)
5679 print_ivar_list64_t(p: cro.ivars + n_value, info);
5680
5681 outs() << " weakIvarLayout ";
5682 sym_name =
5683 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5684 info, n_value, ReferenceValue: cro.weakIvarLayout);
5685 if (n_value != 0) {
5686 if (info->verbose && sym_name != nullptr)
5687 outs() << sym_name;
5688 else
5689 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5690 if (cro.weakIvarLayout != 0)
5691 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.weakIvarLayout);
5692 } else
5693 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.weakIvarLayout);
5694 outs() << "\n";
5695 print_layout_map64(p: cro.weakIvarLayout + n_value, info);
5696
5697 outs() << " baseProperties ";
5698 sym_name =
5699 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseProperties), S,
5700 info, n_value, ReferenceValue: cro.baseProperties);
5701 if (n_value != 0) {
5702 if (info->verbose && sym_name != nullptr)
5703 outs() << sym_name;
5704 else
5705 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5706 if (cro.baseProperties != 0)
5707 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseProperties);
5708 } else
5709 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseProperties);
5710 outs() << "\n";
5711 if (cro.baseProperties + n_value != 0)
5712 print_objc_property_list64(p: cro.baseProperties + n_value, info);
5713
5714 is_meta_class = (cro.flags & RO_META) != 0;
5715 return true;
5716}
5717
5718static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5719 bool &is_meta_class) {
5720 struct class_ro32_t cro;
5721 const char *r;
5722 uint32_t offset, xoffset, left;
5723 SectionRef S, xS;
5724 const char *name;
5725
5726 r = get_pointer_32(Address: p, offset, left, S, info);
5727 if (r == nullptr)
5728 return false;
5729 memset(s: &cro, c: '\0', n: sizeof(struct class_ro32_t));
5730 if (left < sizeof(struct class_ro32_t)) {
5731 memcpy(dest: &cro, src: r, n: left);
5732 outs() << " (class_ro_t entends past the end of the section)\n";
5733 } else
5734 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro32_t));
5735 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5736 swapStruct(cro);
5737 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: cro.flags);
5738 if (cro.flags & RO_META)
5739 outs() << " RO_META";
5740 if (cro.flags & RO_ROOT)
5741 outs() << " RO_ROOT";
5742 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5743 outs() << " RO_HAS_CXX_STRUCTORS";
5744 outs() << "\n";
5745 outs() << " instanceStart " << cro.instanceStart << "\n";
5746 outs() << " instanceSize " << cro.instanceSize << "\n";
5747 outs() << " ivarLayout " << format(Fmt: "0x%" PRIx32, Vals: cro.ivarLayout)
5748 << "\n";
5749 print_layout_map32(p: cro.ivarLayout, info);
5750
5751 outs() << " name " << format(Fmt: "0x%" PRIx32, Vals: cro.name);
5752 name = get_pointer_32(Address: cro.name, offset&: xoffset, left, S&: xS, info);
5753 if (name != nullptr)
5754 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5755 outs() << "\n";
5756
5757 outs() << " baseMethods "
5758 << format(Fmt: "0x%" PRIx32, Vals: cro.baseMethods)
5759 << " (struct method_list_t *)\n";
5760 if (cro.baseMethods != 0)
5761 print_method_list32_t(p: cro.baseMethods, info, indent: "");
5762
5763 outs() << " baseProtocols "
5764 << format(Fmt: "0x%" PRIx32, Vals: cro.baseProtocols) << "\n";
5765 if (cro.baseProtocols != 0)
5766 print_protocol_list32_t(p: cro.baseProtocols, info);
5767 outs() << " ivars " << format(Fmt: "0x%" PRIx32, Vals: cro.ivars)
5768 << "\n";
5769 if (cro.ivars != 0)
5770 print_ivar_list32_t(p: cro.ivars, info);
5771 outs() << " weakIvarLayout "
5772 << format(Fmt: "0x%" PRIx32, Vals: cro.weakIvarLayout) << "\n";
5773 print_layout_map32(p: cro.weakIvarLayout, info);
5774 outs() << " baseProperties "
5775 << format(Fmt: "0x%" PRIx32, Vals: cro.baseProperties) << "\n";
5776 if (cro.baseProperties != 0)
5777 print_objc_property_list32(p: cro.baseProperties, info);
5778 is_meta_class = (cro.flags & RO_META) != 0;
5779 return true;
5780}
5781
5782static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5783 struct class64_t c;
5784 const char *r;
5785 uint32_t offset, left;
5786 SectionRef S;
5787 const char *name;
5788 uint64_t isa_n_value, n_value;
5789
5790 r = get_pointer_64(Address: p, offset, left, S, info);
5791 if (r == nullptr || left < sizeof(struct class64_t))
5792 return;
5793 memcpy(dest: &c, src: r, n: sizeof(struct class64_t));
5794 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5795 swapStruct(c);
5796
5797 outs() << " isa " << format(Fmt: "0x%" PRIx64, Vals: c.isa);
5798 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, isa), S, info,
5799 n_value&: isa_n_value, ReferenceValue: c.isa);
5800 if (name != nullptr)
5801 outs() << " " << name;
5802 outs() << "\n";
5803
5804 outs() << " superclass " << format(Fmt: "0x%" PRIx64, Vals: c.superclass);
5805 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, superclass), S, info,
5806 n_value, ReferenceValue: c.superclass);
5807 if (name != nullptr)
5808 outs() << " " << name;
5809 else {
5810 name = get_dyld_bind_info_symbolname(ReferenceValue: S.getAddress() +
5811 offset + offsetof(struct class64_t, superclass), info);
5812 if (name != nullptr)
5813 outs() << " " << name;
5814 }
5815 outs() << "\n";
5816
5817 outs() << " cache " << format(Fmt: "0x%" PRIx64, Vals: c.cache);
5818 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, cache), S, info,
5819 n_value, ReferenceValue: c.cache);
5820 if (name != nullptr)
5821 outs() << " " << name;
5822 outs() << "\n";
5823
5824 outs() << " vtable " << format(Fmt: "0x%" PRIx64, Vals: c.vtable);
5825 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, vtable), S, info,
5826 n_value, ReferenceValue: c.vtable);
5827 if (name != nullptr)
5828 outs() << " " << name;
5829 outs() << "\n";
5830
5831 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, data), S, info,
5832 n_value, ReferenceValue: c.data);
5833 outs() << " data ";
5834 if (n_value != 0) {
5835 if (info->verbose && name != nullptr)
5836 outs() << name;
5837 else
5838 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5839 if (c.data != 0)
5840 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.data);
5841 } else
5842 outs() << format(Fmt: "0x%" PRIx64, Vals: c.data);
5843 outs() << " (struct class_ro_t *)";
5844
5845 // This is a Swift class if some of the low bits of the pointer are set.
5846 if ((c.data + n_value) & 0x7)
5847 outs() << " Swift class";
5848 outs() << "\n";
5849 bool is_meta_class;
5850 if (!print_class_ro64_t(p: (c.data + n_value) & ~0x7, info, is_meta_class))
5851 return;
5852
5853 if (!is_meta_class &&
5854 c.isa + isa_n_value != p &&
5855 c.isa + isa_n_value != 0 &&
5856 info->depth < 100) {
5857 info->depth++;
5858 outs() << "Meta Class\n";
5859 print_class64_t(p: c.isa + isa_n_value, info);
5860 }
5861}
5862
5863static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5864 struct class32_t c;
5865 const char *r;
5866 uint32_t offset, left;
5867 SectionRef S;
5868 const char *name;
5869
5870 r = get_pointer_32(Address: p, offset, left, S, info);
5871 if (r == nullptr)
5872 return;
5873 memset(s: &c, c: '\0', n: sizeof(struct class32_t));
5874 if (left < sizeof(struct class32_t)) {
5875 memcpy(dest: &c, src: r, n: left);
5876 outs() << " (class_t entends past the end of the section)\n";
5877 } else
5878 memcpy(dest: &c, src: r, n: sizeof(struct class32_t));
5879 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5880 swapStruct(c);
5881
5882 outs() << " isa " << format(Fmt: "0x%" PRIx32, Vals: c.isa);
5883 name =
5884 get_symbol_32(sect_offset: offset + offsetof(struct class32_t, isa), S, info, ReferenceValue: c.isa);
5885 if (name != nullptr)
5886 outs() << " " << name;
5887 outs() << "\n";
5888
5889 outs() << " superclass " << format(Fmt: "0x%" PRIx32, Vals: c.superclass);
5890 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, superclass), S, info,
5891 ReferenceValue: c.superclass);
5892 if (name != nullptr)
5893 outs() << " " << name;
5894 outs() << "\n";
5895
5896 outs() << " cache " << format(Fmt: "0x%" PRIx32, Vals: c.cache);
5897 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, cache), S, info,
5898 ReferenceValue: c.cache);
5899 if (name != nullptr)
5900 outs() << " " << name;
5901 outs() << "\n";
5902
5903 outs() << " vtable " << format(Fmt: "0x%" PRIx32, Vals: c.vtable);
5904 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, vtable), S, info,
5905 ReferenceValue: c.vtable);
5906 if (name != nullptr)
5907 outs() << " " << name;
5908 outs() << "\n";
5909
5910 name =
5911 get_symbol_32(sect_offset: offset + offsetof(struct class32_t, data), S, info, ReferenceValue: c.data);
5912 outs() << " data " << format(Fmt: "0x%" PRIx32, Vals: c.data)
5913 << " (struct class_ro_t *)";
5914
5915 // This is a Swift class if some of the low bits of the pointer are set.
5916 if (c.data & 0x3)
5917 outs() << " Swift class";
5918 outs() << "\n";
5919 bool is_meta_class;
5920 if (!print_class_ro32_t(p: c.data & ~0x3, info, is_meta_class))
5921 return;
5922
5923 if (!is_meta_class) {
5924 outs() << "Meta Class\n";
5925 print_class32_t(p: c.isa, info);
5926 }
5927}
5928
5929static void print_objc_class_t(struct objc_class_t *objc_class,
5930 struct DisassembleInfo *info) {
5931 uint32_t offset, left, xleft;
5932 const char *name, *p, *ivar_list;
5933 SectionRef S;
5934 int32_t i;
5935 struct objc_ivar_list_t objc_ivar_list;
5936 struct objc_ivar_t ivar;
5937
5938 outs() << "\t\t isa " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->isa);
5939 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5940 name = get_pointer_32(Address: objc_class->isa, offset, left, S, info, objc_only: true);
5941 if (name != nullptr)
5942 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5943 else
5944 outs() << " (not in an __OBJC section)";
5945 }
5946 outs() << "\n";
5947
5948 outs() << "\t super_class "
5949 << format(Fmt: "0x%08" PRIx32, Vals: objc_class->super_class);
5950 if (info->verbose) {
5951 name = get_pointer_32(Address: objc_class->super_class, offset, left, S, info, objc_only: true);
5952 if (name != nullptr)
5953 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5954 else
5955 outs() << " (not in an __OBJC section)";
5956 }
5957 outs() << "\n";
5958
5959 outs() << "\t\t name " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->name);
5960 if (info->verbose) {
5961 name = get_pointer_32(Address: objc_class->name, offset, left, S, info, objc_only: true);
5962 if (name != nullptr)
5963 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5964 else
5965 outs() << " (not in an __OBJC section)";
5966 }
5967 outs() << "\n";
5968
5969 outs() << "\t\t version " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->version)
5970 << "\n";
5971
5972 outs() << "\t\t info " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->info);
5973 if (info->verbose) {
5974 if (CLS_GETINFO(objc_class, CLS_CLASS))
5975 outs() << " CLS_CLASS";
5976 else if (CLS_GETINFO(objc_class, CLS_META))
5977 outs() << " CLS_META";
5978 }
5979 outs() << "\n";
5980
5981 outs() << "\t instance_size "
5982 << format(Fmt: "0x%08" PRIx32, Vals: objc_class->instance_size) << "\n";
5983
5984 p = get_pointer_32(Address: objc_class->ivars, offset, left, S, info, objc_only: true);
5985 outs() << "\t\t ivars " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->ivars);
5986 if (p != nullptr) {
5987 if (left > sizeof(struct objc_ivar_list_t)) {
5988 outs() << "\n";
5989 memcpy(dest: &objc_ivar_list, src: p, n: sizeof(struct objc_ivar_list_t));
5990 } else {
5991 outs() << " (entends past the end of the section)\n";
5992 memset(s: &objc_ivar_list, c: '\0', n: sizeof(struct objc_ivar_list_t));
5993 memcpy(dest: &objc_ivar_list, src: p, n: left);
5994 }
5995 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5996 swapStruct(objc_ivar_list);
5997 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5998 ivar_list = p + sizeof(struct objc_ivar_list_t);
5999 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
6000 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
6001 outs() << "\t\t remaining ivar's extend past the of the section\n";
6002 break;
6003 }
6004 memcpy(dest: &ivar, src: ivar_list + i * sizeof(struct objc_ivar_t),
6005 n: sizeof(struct objc_ivar_t));
6006 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6007 swapStruct(objc_ivar&: ivar);
6008
6009 outs() << "\t\t\tivar_name " << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_name);
6010 if (info->verbose) {
6011 name = get_pointer_32(Address: ivar.ivar_name, offset, left&: xleft, S, info, objc_only: true);
6012 if (name != nullptr)
6013 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
6014 else
6015 outs() << " (not in an __OBJC section)";
6016 }
6017 outs() << "\n";
6018
6019 outs() << "\t\t\tivar_type " << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_type);
6020 if (info->verbose) {
6021 name = get_pointer_32(Address: ivar.ivar_type, offset, left&: xleft, S, info, objc_only: true);
6022 if (name != nullptr)
6023 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
6024 else
6025 outs() << " (not in an __OBJC section)";
6026 }
6027 outs() << "\n";
6028
6029 outs() << "\t\t ivar_offset "
6030 << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_offset) << "\n";
6031 }
6032 } else {
6033 outs() << " (not in an __OBJC section)\n";
6034 }
6035
6036 outs() << "\t\t methods " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->methodLists);
6037 if (print_method_list(p: objc_class->methodLists, info))
6038 outs() << " (not in an __OBJC section)\n";
6039
6040 outs() << "\t\t cache " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->cache)
6041 << "\n";
6042
6043 outs() << "\t\tprotocols " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->protocols);
6044 if (print_protocol_list(p: objc_class->protocols, indent: 16, info))
6045 outs() << " (not in an __OBJC section)\n";
6046}
6047
6048static void print_objc_objc_category_t(struct objc_category_t *objc_category,
6049 struct DisassembleInfo *info) {
6050 uint32_t offset, left;
6051 const char *name;
6052 SectionRef S;
6053
6054 outs() << "\t category name "
6055 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->category_name);
6056 if (info->verbose) {
6057 name = get_pointer_32(Address: objc_category->category_name, offset, left, S, info,
6058 objc_only: true);
6059 if (name != nullptr)
6060 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6061 else
6062 outs() << " (not in an __OBJC section)";
6063 }
6064 outs() << "\n";
6065
6066 outs() << "\t\t class name "
6067 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->class_name);
6068 if (info->verbose) {
6069 name =
6070 get_pointer_32(Address: objc_category->class_name, offset, left, S, info, objc_only: true);
6071 if (name != nullptr)
6072 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6073 else
6074 outs() << " (not in an __OBJC section)";
6075 }
6076 outs() << "\n";
6077
6078 outs() << "\t instance methods "
6079 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->instance_methods);
6080 if (print_method_list(p: objc_category->instance_methods, info))
6081 outs() << " (not in an __OBJC section)\n";
6082
6083 outs() << "\t class methods "
6084 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->class_methods);
6085 if (print_method_list(p: objc_category->class_methods, info))
6086 outs() << " (not in an __OBJC section)\n";
6087}
6088
6089static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
6090 struct category64_t c;
6091 const char *r;
6092 uint32_t offset, xoffset, left;
6093 SectionRef S, xS;
6094 const char *name, *sym_name;
6095 uint64_t n_value;
6096
6097 r = get_pointer_64(Address: p, offset, left, S, info);
6098 if (r == nullptr)
6099 return;
6100 memset(s: &c, c: '\0', n: sizeof(struct category64_t));
6101 if (left < sizeof(struct category64_t)) {
6102 memcpy(dest: &c, src: r, n: left);
6103 outs() << " (category_t entends past the end of the section)\n";
6104 } else
6105 memcpy(dest: &c, src: r, n: sizeof(struct category64_t));
6106 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6107 swapStruct(c);
6108
6109 outs() << " name ";
6110 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, name), S,
6111 info, n_value, ReferenceValue: c.name);
6112 if (n_value != 0) {
6113 if (info->verbose && sym_name != nullptr)
6114 outs() << sym_name;
6115 else
6116 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6117 if (c.name != 0)
6118 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.name);
6119 } else
6120 outs() << format(Fmt: "0x%" PRIx64, Vals: c.name);
6121 name = get_pointer_64(Address: c.name + n_value, offset&: xoffset, left, S&: xS, info);
6122 if (name != nullptr)
6123 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6124 outs() << "\n";
6125
6126 outs() << " cls ";
6127 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, cls), S, info,
6128 n_value, ReferenceValue: c.cls);
6129 if (n_value != 0) {
6130 if (info->verbose && sym_name != nullptr)
6131 outs() << sym_name;
6132 else
6133 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6134 if (c.cls != 0)
6135 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.cls);
6136 } else
6137 outs() << format(Fmt: "0x%" PRIx64, Vals: c.cls);
6138 outs() << "\n";
6139 if (c.cls + n_value != 0)
6140 print_class64_t(p: c.cls + n_value, info);
6141
6142 outs() << " instanceMethods ";
6143 sym_name =
6144 get_symbol_64(sect_offset: offset + offsetof(struct category64_t, instanceMethods), S,
6145 info, n_value, ReferenceValue: c.instanceMethods);
6146 if (n_value != 0) {
6147 if (info->verbose && sym_name != nullptr)
6148 outs() << sym_name;
6149 else
6150 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6151 if (c.instanceMethods != 0)
6152 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.instanceMethods);
6153 } else
6154 outs() << format(Fmt: "0x%" PRIx64, Vals: c.instanceMethods);
6155 outs() << "\n";
6156 if (c.instanceMethods + n_value != 0)
6157 print_method_list64_t(p: c.instanceMethods + n_value, info, indent: "");
6158
6159 outs() << " classMethods ";
6160 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, classMethods),
6161 S, info, n_value, ReferenceValue: c.classMethods);
6162 if (n_value != 0) {
6163 if (info->verbose && sym_name != nullptr)
6164 outs() << sym_name;
6165 else
6166 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6167 if (c.classMethods != 0)
6168 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.classMethods);
6169 } else
6170 outs() << format(Fmt: "0x%" PRIx64, Vals: c.classMethods);
6171 outs() << "\n";
6172 if (c.classMethods + n_value != 0)
6173 print_method_list64_t(p: c.classMethods + n_value, info, indent: "");
6174
6175 outs() << " protocols ";
6176 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, protocols), S,
6177 info, n_value, ReferenceValue: c.protocols);
6178 if (n_value != 0) {
6179 if (info->verbose && sym_name != nullptr)
6180 outs() << sym_name;
6181 else
6182 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6183 if (c.protocols != 0)
6184 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.protocols);
6185 } else
6186 outs() << format(Fmt: "0x%" PRIx64, Vals: c.protocols);
6187 outs() << "\n";
6188 if (c.protocols + n_value != 0)
6189 print_protocol_list64_t(p: c.protocols + n_value, info);
6190
6191 outs() << "instanceProperties ";
6192 sym_name =
6193 get_symbol_64(sect_offset: offset + offsetof(struct category64_t, instanceProperties),
6194 S, info, n_value, ReferenceValue: c.instanceProperties);
6195 if (n_value != 0) {
6196 if (info->verbose && sym_name != nullptr)
6197 outs() << sym_name;
6198 else
6199 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6200 if (c.instanceProperties != 0)
6201 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.instanceProperties);
6202 } else
6203 outs() << format(Fmt: "0x%" PRIx64, Vals: c.instanceProperties);
6204 outs() << "\n";
6205 if (c.instanceProperties + n_value != 0)
6206 print_objc_property_list64(p: c.instanceProperties + n_value, info);
6207}
6208
6209static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
6210 struct category32_t c;
6211 const char *r;
6212 uint32_t offset, left;
6213 SectionRef S, xS;
6214 const char *name;
6215
6216 r = get_pointer_32(Address: p, offset, left, S, info);
6217 if (r == nullptr)
6218 return;
6219 memset(s: &c, c: '\0', n: sizeof(struct category32_t));
6220 if (left < sizeof(struct category32_t)) {
6221 memcpy(dest: &c, src: r, n: left);
6222 outs() << " (category_t entends past the end of the section)\n";
6223 } else
6224 memcpy(dest: &c, src: r, n: sizeof(struct category32_t));
6225 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6226 swapStruct(c);
6227
6228 outs() << " name " << format(Fmt: "0x%" PRIx32, Vals: c.name);
6229 name = get_symbol_32(sect_offset: offset + offsetof(struct category32_t, name), S, info,
6230 ReferenceValue: c.name);
6231 if (name)
6232 outs() << " " << name;
6233 outs() << "\n";
6234
6235 outs() << " cls " << format(Fmt: "0x%" PRIx32, Vals: c.cls) << "\n";
6236 if (c.cls != 0)
6237 print_class32_t(p: c.cls, info);
6238 outs() << " instanceMethods " << format(Fmt: "0x%" PRIx32, Vals: c.instanceMethods)
6239 << "\n";
6240 if (c.instanceMethods != 0)
6241 print_method_list32_t(p: c.instanceMethods, info, indent: "");
6242 outs() << " classMethods " << format(Fmt: "0x%" PRIx32, Vals: c.classMethods)
6243 << "\n";
6244 if (c.classMethods != 0)
6245 print_method_list32_t(p: c.classMethods, info, indent: "");
6246 outs() << " protocols " << format(Fmt: "0x%" PRIx32, Vals: c.protocols) << "\n";
6247 if (c.protocols != 0)
6248 print_protocol_list32_t(p: c.protocols, info);
6249 outs() << "instanceProperties " << format(Fmt: "0x%" PRIx32, Vals: c.instanceProperties)
6250 << "\n";
6251 if (c.instanceProperties != 0)
6252 print_objc_property_list32(p: c.instanceProperties, info);
6253}
6254
6255static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
6256 uint32_t i, left, offset, xoffset;
6257 uint64_t p, n_value;
6258 struct message_ref64 mr;
6259 const char *name, *sym_name;
6260 const char *r;
6261 SectionRef xS;
6262
6263 if (S == SectionRef())
6264 return;
6265
6266 StringRef SectName;
6267 Expected<StringRef> SecNameOrErr = S.getName();
6268 if (SecNameOrErr)
6269 SectName = *SecNameOrErr;
6270 else
6271 consumeError(Err: SecNameOrErr.takeError());
6272
6273 DataRefImpl Ref = S.getRawDataRefImpl();
6274 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6275 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6276 offset = 0;
6277 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6278 p = S.getAddress() + i;
6279 r = get_pointer_64(Address: p, offset, left, S, info);
6280 if (r == nullptr)
6281 return;
6282 memset(s: &mr, c: '\0', n: sizeof(struct message_ref64));
6283 if (left < sizeof(struct message_ref64)) {
6284 memcpy(dest: &mr, src: r, n: left);
6285 outs() << " (message_ref entends past the end of the section)\n";
6286 } else
6287 memcpy(dest: &mr, src: r, n: sizeof(struct message_ref64));
6288 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6289 swapStruct(mr);
6290
6291 outs() << " imp ";
6292 name = get_symbol_64(sect_offset: offset + offsetof(struct message_ref64, imp), S, info,
6293 n_value, ReferenceValue: mr.imp);
6294 if (n_value != 0) {
6295 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value) << " ";
6296 if (mr.imp != 0)
6297 outs() << "+ " << format(Fmt: "0x%" PRIx64, Vals: mr.imp) << " ";
6298 } else
6299 outs() << format(Fmt: "0x%" PRIx64, Vals: mr.imp) << " ";
6300 if (name != nullptr)
6301 outs() << " " << name;
6302 outs() << "\n";
6303
6304 outs() << " sel ";
6305 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct message_ref64, sel), S,
6306 info, n_value, ReferenceValue: mr.sel);
6307 if (n_value != 0) {
6308 if (info->verbose && sym_name != nullptr)
6309 outs() << sym_name;
6310 else
6311 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6312 if (mr.sel != 0)
6313 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: mr.sel);
6314 } else
6315 outs() << format(Fmt: "0x%" PRIx64, Vals: mr.sel);
6316 name = get_pointer_64(Address: mr.sel + n_value, offset&: xoffset, left, S&: xS, info);
6317 if (name != nullptr)
6318 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6319 outs() << "\n";
6320
6321 offset += sizeof(struct message_ref64);
6322 }
6323}
6324
6325static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
6326 uint32_t i, left, offset, xoffset, p;
6327 struct message_ref32 mr;
6328 const char *name, *r;
6329 SectionRef xS;
6330
6331 if (S == SectionRef())
6332 return;
6333
6334 StringRef SectName;
6335 Expected<StringRef> SecNameOrErr = S.getName();
6336 if (SecNameOrErr)
6337 SectName = *SecNameOrErr;
6338 else
6339 consumeError(Err: SecNameOrErr.takeError());
6340
6341 DataRefImpl Ref = S.getRawDataRefImpl();
6342 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6343 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6344 offset = 0;
6345 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6346 p = S.getAddress() + i;
6347 r = get_pointer_32(Address: p, offset, left, S, info);
6348 if (r == nullptr)
6349 return;
6350 memset(s: &mr, c: '\0', n: sizeof(struct message_ref32));
6351 if (left < sizeof(struct message_ref32)) {
6352 memcpy(dest: &mr, src: r, n: left);
6353 outs() << " (message_ref entends past the end of the section)\n";
6354 } else
6355 memcpy(dest: &mr, src: r, n: sizeof(struct message_ref32));
6356 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6357 swapStruct(mr);
6358
6359 outs() << " imp " << format(Fmt: "0x%" PRIx32, Vals: mr.imp);
6360 name = get_symbol_32(sect_offset: offset + offsetof(struct message_ref32, imp), S, info,
6361 ReferenceValue: mr.imp);
6362 if (name != nullptr)
6363 outs() << " " << name;
6364 outs() << "\n";
6365
6366 outs() << " sel " << format(Fmt: "0x%" PRIx32, Vals: mr.sel);
6367 name = get_pointer_32(Address: mr.sel, offset&: xoffset, left, S&: xS, info);
6368 if (name != nullptr)
6369 outs() << " " << name;
6370 outs() << "\n";
6371
6372 offset += sizeof(struct message_ref32);
6373 }
6374}
6375
6376static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
6377 uint32_t left, offset, swift_version;
6378 uint64_t p;
6379 struct objc_image_info64 o;
6380 const char *r;
6381
6382 if (S == SectionRef())
6383 return;
6384
6385 StringRef SectName;
6386 Expected<StringRef> SecNameOrErr = S.getName();
6387 if (SecNameOrErr)
6388 SectName = *SecNameOrErr;
6389 else
6390 consumeError(Err: SecNameOrErr.takeError());
6391
6392 DataRefImpl Ref = S.getRawDataRefImpl();
6393 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6394 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6395 p = S.getAddress();
6396 r = get_pointer_64(Address: p, offset, left, S, info);
6397 if (r == nullptr)
6398 return;
6399 memset(s: &o, c: '\0', n: sizeof(struct objc_image_info64));
6400 if (left < sizeof(struct objc_image_info64)) {
6401 memcpy(dest: &o, src: r, n: left);
6402 outs() << " (objc_image_info entends past the end of the section)\n";
6403 } else
6404 memcpy(dest: &o, src: r, n: sizeof(struct objc_image_info64));
6405 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6406 swapStruct(o);
6407 outs() << " version " << o.version << "\n";
6408 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6409 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6410 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6411 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6412 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6413 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
6414 outs() << " OBJC_IMAGE_IS_SIMULATED";
6415 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
6416 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
6417 swift_version = (o.flags >> 8) & 0xff;
6418 if (swift_version != 0) {
6419 if (swift_version == 1)
6420 outs() << " Swift 1.0";
6421 else if (swift_version == 2)
6422 outs() << " Swift 1.1";
6423 else if(swift_version == 3)
6424 outs() << " Swift 2.0";
6425 else if(swift_version == 4)
6426 outs() << " Swift 3.0";
6427 else if(swift_version == 5)
6428 outs() << " Swift 4.0";
6429 else if(swift_version == 6)
6430 outs() << " Swift 4.1/Swift 4.2";
6431 else if(swift_version == 7)
6432 outs() << " Swift 5 or later";
6433 else
6434 outs() << " unknown future Swift version (" << swift_version << ")";
6435 }
6436 outs() << "\n";
6437}
6438
6439static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6440 uint32_t left, offset, swift_version, p;
6441 struct objc_image_info32 o;
6442 const char *r;
6443
6444 if (S == SectionRef())
6445 return;
6446
6447 StringRef SectName;
6448 Expected<StringRef> SecNameOrErr = S.getName();
6449 if (SecNameOrErr)
6450 SectName = *SecNameOrErr;
6451 else
6452 consumeError(Err: SecNameOrErr.takeError());
6453
6454 DataRefImpl Ref = S.getRawDataRefImpl();
6455 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6456 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6457 p = S.getAddress();
6458 r = get_pointer_32(Address: p, offset, left, S, info);
6459 if (r == nullptr)
6460 return;
6461 memset(s: &o, c: '\0', n: sizeof(struct objc_image_info32));
6462 if (left < sizeof(struct objc_image_info32)) {
6463 memcpy(dest: &o, src: r, n: left);
6464 outs() << " (objc_image_info entends past the end of the section)\n";
6465 } else
6466 memcpy(dest: &o, src: r, n: sizeof(struct objc_image_info32));
6467 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6468 swapStruct(o);
6469 outs() << " version " << o.version << "\n";
6470 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6471 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6472 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6473 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6474 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6475 swift_version = (o.flags >> 8) & 0xff;
6476 if (swift_version != 0) {
6477 if (swift_version == 1)
6478 outs() << " Swift 1.0";
6479 else if (swift_version == 2)
6480 outs() << " Swift 1.1";
6481 else if(swift_version == 3)
6482 outs() << " Swift 2.0";
6483 else if(swift_version == 4)
6484 outs() << " Swift 3.0";
6485 else if(swift_version == 5)
6486 outs() << " Swift 4.0";
6487 else if(swift_version == 6)
6488 outs() << " Swift 4.1/Swift 4.2";
6489 else if(swift_version == 7)
6490 outs() << " Swift 5 or later";
6491 else
6492 outs() << " unknown future Swift version (" << swift_version << ")";
6493 }
6494 outs() << "\n";
6495}
6496
6497static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6498 uint32_t left, offset, p;
6499 struct imageInfo_t o;
6500 const char *r;
6501
6502 StringRef SectName;
6503 Expected<StringRef> SecNameOrErr = S.getName();
6504 if (SecNameOrErr)
6505 SectName = *SecNameOrErr;
6506 else
6507 consumeError(Err: SecNameOrErr.takeError());
6508
6509 DataRefImpl Ref = S.getRawDataRefImpl();
6510 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6511 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6512 p = S.getAddress();
6513 r = get_pointer_32(Address: p, offset, left, S, info);
6514 if (r == nullptr)
6515 return;
6516 memset(s: &o, c: '\0', n: sizeof(struct imageInfo_t));
6517 if (left < sizeof(struct imageInfo_t)) {
6518 memcpy(dest: &o, src: r, n: left);
6519 outs() << " (imageInfo entends past the end of the section)\n";
6520 } else
6521 memcpy(dest: &o, src: r, n: sizeof(struct imageInfo_t));
6522 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6523 swapStruct(o);
6524 outs() << " version " << o.version << "\n";
6525 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6526 if (o.flags & 0x1)
6527 outs() << " F&C";
6528 if (o.flags & 0x2)
6529 outs() << " GC";
6530 if (o.flags & 0x4)
6531 outs() << " GC-only";
6532 else
6533 outs() << " RR";
6534 outs() << "\n";
6535}
6536
6537static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6538 SymbolAddressMap AddrMap;
6539 if (verbose)
6540 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6541
6542 std::vector<SectionRef> Sections;
6543 append_range(C&: Sections, R: O->sections());
6544
6545 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6546
6547 SectionRef CL = get_section(O, segname: "__OBJC2", sectname: "__class_list");
6548 if (CL == SectionRef())
6549 CL = get_section(O, segname: "__DATA", sectname: "__objc_classlist");
6550 if (CL == SectionRef())
6551 CL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classlist");
6552 if (CL == SectionRef())
6553 CL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classlist");
6554 info.S = CL;
6555 walk_pointer_list_64(listname: "class", S: CL, O, info: &info, func: print_class64_t);
6556
6557 SectionRef CR = get_section(O, segname: "__OBJC2", sectname: "__class_refs");
6558 if (CR == SectionRef())
6559 CR = get_section(O, segname: "__DATA", sectname: "__objc_classrefs");
6560 if (CR == SectionRef())
6561 CR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classrefs");
6562 if (CR == SectionRef())
6563 CR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classrefs");
6564 info.S = CR;
6565 walk_pointer_list_64(listname: "class refs", S: CR, O, info: &info, func: nullptr);
6566
6567 SectionRef SR = get_section(O, segname: "__OBJC2", sectname: "__super_refs");
6568 if (SR == SectionRef())
6569 SR = get_section(O, segname: "__DATA", sectname: "__objc_superrefs");
6570 if (SR == SectionRef())
6571 SR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_superrefs");
6572 if (SR == SectionRef())
6573 SR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_superrefs");
6574 info.S = SR;
6575 walk_pointer_list_64(listname: "super refs", S: SR, O, info: &info, func: nullptr);
6576
6577 SectionRef CA = get_section(O, segname: "__OBJC2", sectname: "__category_list");
6578 if (CA == SectionRef())
6579 CA = get_section(O, segname: "__DATA", sectname: "__objc_catlist");
6580 if (CA == SectionRef())
6581 CA = get_section(O, segname: "__DATA_CONST", sectname: "__objc_catlist");
6582 if (CA == SectionRef())
6583 CA = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_catlist");
6584 info.S = CA;
6585 walk_pointer_list_64(listname: "category", S: CA, O, info: &info, func: print_category64_t);
6586
6587 SectionRef PL = get_section(O, segname: "__OBJC2", sectname: "__protocol_list");
6588 if (PL == SectionRef())
6589 PL = get_section(O, segname: "__DATA", sectname: "__objc_protolist");
6590 if (PL == SectionRef())
6591 PL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_protolist");
6592 if (PL == SectionRef())
6593 PL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_protolist");
6594 info.S = PL;
6595 walk_pointer_list_64(listname: "protocol", S: PL, O, info: &info, func: nullptr);
6596
6597 SectionRef MR = get_section(O, segname: "__OBJC2", sectname: "__message_refs");
6598 if (MR == SectionRef())
6599 MR = get_section(O, segname: "__DATA", sectname: "__objc_msgrefs");
6600 if (MR == SectionRef())
6601 MR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_msgrefs");
6602 if (MR == SectionRef())
6603 MR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_msgrefs");
6604 info.S = MR;
6605 print_message_refs64(S: MR, info: &info);
6606
6607 SectionRef II = get_section(O, segname: "__OBJC2", sectname: "__image_info");
6608 if (II == SectionRef())
6609 II = get_section(O, segname: "__DATA", sectname: "__objc_imageinfo");
6610 if (II == SectionRef())
6611 II = get_section(O, segname: "__DATA_CONST", sectname: "__objc_imageinfo");
6612 if (II == SectionRef())
6613 II = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_imageinfo");
6614 info.S = II;
6615 print_image_info64(S: II, info: &info);
6616}
6617
6618static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6619 SymbolAddressMap AddrMap;
6620 if (verbose)
6621 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6622
6623 std::vector<SectionRef> Sections;
6624 append_range(C&: Sections, R: O->sections());
6625
6626 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6627
6628 SectionRef CL = get_section(O, segname: "__OBJC2", sectname: "__class_list");
6629 if (CL == SectionRef())
6630 CL = get_section(O, segname: "__DATA", sectname: "__objc_classlist");
6631 if (CL == SectionRef())
6632 CL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classlist");
6633 if (CL == SectionRef())
6634 CL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classlist");
6635 info.S = CL;
6636 walk_pointer_list_32(listname: "class", S: CL, O, info: &info, func: print_class32_t);
6637
6638 SectionRef CR = get_section(O, segname: "__OBJC2", sectname: "__class_refs");
6639 if (CR == SectionRef())
6640 CR = get_section(O, segname: "__DATA", sectname: "__objc_classrefs");
6641 if (CR == SectionRef())
6642 CR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classrefs");
6643 if (CR == SectionRef())
6644 CR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classrefs");
6645 info.S = CR;
6646 walk_pointer_list_32(listname: "class refs", S: CR, O, info: &info, func: nullptr);
6647
6648 SectionRef SR = get_section(O, segname: "__OBJC2", sectname: "__super_refs");
6649 if (SR == SectionRef())
6650 SR = get_section(O, segname: "__DATA", sectname: "__objc_superrefs");
6651 if (SR == SectionRef())
6652 SR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_superrefs");
6653 if (SR == SectionRef())
6654 SR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_superrefs");
6655 info.S = SR;
6656 walk_pointer_list_32(listname: "super refs", S: SR, O, info: &info, func: nullptr);
6657
6658 SectionRef CA = get_section(O, segname: "__OBJC2", sectname: "__category_list");
6659 if (CA == SectionRef())
6660 CA = get_section(O, segname: "__DATA", sectname: "__objc_catlist");
6661 if (CA == SectionRef())
6662 CA = get_section(O, segname: "__DATA_CONST", sectname: "__objc_catlist");
6663 if (CA == SectionRef())
6664 CA = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_catlist");
6665 info.S = CA;
6666 walk_pointer_list_32(listname: "category", S: CA, O, info: &info, func: print_category32_t);
6667
6668 SectionRef PL = get_section(O, segname: "__OBJC2", sectname: "__protocol_list");
6669 if (PL == SectionRef())
6670 PL = get_section(O, segname: "__DATA", sectname: "__objc_protolist");
6671 if (PL == SectionRef())
6672 PL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_protolist");
6673 if (PL == SectionRef())
6674 PL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_protolist");
6675 info.S = PL;
6676 walk_pointer_list_32(listname: "protocol", S: PL, O, info: &info, func: nullptr);
6677
6678 SectionRef MR = get_section(O, segname: "__OBJC2", sectname: "__message_refs");
6679 if (MR == SectionRef())
6680 MR = get_section(O, segname: "__DATA", sectname: "__objc_msgrefs");
6681 if (MR == SectionRef())
6682 MR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_msgrefs");
6683 if (MR == SectionRef())
6684 MR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_msgrefs");
6685 info.S = MR;
6686 print_message_refs32(S: MR, info: &info);
6687
6688 SectionRef II = get_section(O, segname: "__OBJC2", sectname: "__image_info");
6689 if (II == SectionRef())
6690 II = get_section(O, segname: "__DATA", sectname: "__objc_imageinfo");
6691 if (II == SectionRef())
6692 II = get_section(O, segname: "__DATA_CONST", sectname: "__objc_imageinfo");
6693 if (II == SectionRef())
6694 II = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_imageinfo");
6695 info.S = II;
6696 print_image_info32(S: II, info: &info);
6697}
6698
6699static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6700 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6701 const char *r, *name, *defs;
6702 struct objc_module_t module;
6703 SectionRef S, xS;
6704 struct objc_symtab_t symtab;
6705 struct objc_class_t objc_class;
6706 struct objc_category_t objc_category;
6707
6708 outs() << "Objective-C segment\n";
6709 S = get_section(O, segname: "__OBJC", sectname: "__module_info");
6710 if (S == SectionRef())
6711 return false;
6712
6713 SymbolAddressMap AddrMap;
6714 if (verbose)
6715 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6716
6717 std::vector<SectionRef> Sections;
6718 append_range(C&: Sections, R: O->sections());
6719
6720 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6721
6722 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6723 p = S.getAddress() + i;
6724 r = get_pointer_32(Address: p, offset, left, S, info: &info, objc_only: true);
6725 if (r == nullptr)
6726 return true;
6727 memset(s: &module, c: '\0', n: sizeof(struct objc_module_t));
6728 if (left < sizeof(struct objc_module_t)) {
6729 memcpy(dest: &module, src: r, n: left);
6730 outs() << " (module extends past end of __module_info section)\n";
6731 } else
6732 memcpy(dest: &module, src: r, n: sizeof(struct objc_module_t));
6733 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6734 swapStruct(module);
6735
6736 outs() << "Module " << format(Fmt: "0x%" PRIx32, Vals: p) << "\n";
6737 outs() << " version " << module.version << "\n";
6738 outs() << " size " << module.size << "\n";
6739 outs() << " name ";
6740 name = get_pointer_32(Address: module.name, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6741 if (name != nullptr)
6742 outs() << format(Fmt: "%.*s", Vals: left, Vals: name);
6743 else
6744 outs() << format(Fmt: "0x%08" PRIx32, Vals: module.name)
6745 << "(not in an __OBJC section)";
6746 outs() << "\n";
6747
6748 r = get_pointer_32(Address: module.symtab, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6749 if (module.symtab == 0 || r == nullptr) {
6750 outs() << " symtab " << format(Fmt: "0x%08" PRIx32, Vals: module.symtab)
6751 << " (not in an __OBJC section)\n";
6752 continue;
6753 }
6754 outs() << " symtab " << format(Fmt: "0x%08" PRIx32, Vals: module.symtab) << "\n";
6755 memset(s: &symtab, c: '\0', n: sizeof(struct objc_symtab_t));
6756 defs_left = 0;
6757 defs = nullptr;
6758 if (left < sizeof(struct objc_symtab_t)) {
6759 memcpy(dest: &symtab, src: r, n: left);
6760 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6761 } else {
6762 memcpy(dest: &symtab, src: r, n: sizeof(struct objc_symtab_t));
6763 if (left > sizeof(struct objc_symtab_t)) {
6764 defs_left = left - sizeof(struct objc_symtab_t);
6765 defs = r + sizeof(struct objc_symtab_t);
6766 }
6767 }
6768 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6769 swapStruct(symtab);
6770
6771 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6772 r = get_pointer_32(Address: symtab.refs, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6773 outs() << "\trefs " << format(Fmt: "0x%08" PRIx32, Vals: symtab.refs);
6774 if (r == nullptr)
6775 outs() << " (not in an __OBJC section)";
6776 outs() << "\n";
6777 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6778 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6779 if (symtab.cls_def_cnt > 0)
6780 outs() << "\tClass Definitions\n";
6781 for (j = 0; j < symtab.cls_def_cnt; j++) {
6782 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6783 outs() << "\t(remaining class defs entries entends past the end of the "
6784 << "section)\n";
6785 break;
6786 }
6787 memcpy(dest: &def, src: defs + j * sizeof(uint32_t), n: sizeof(uint32_t));
6788 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6789 sys::swapByteOrder(Value&: def);
6790
6791 r = get_pointer_32(Address: def, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6792 outs() << "\tdefs[" << j << "] " << format(Fmt: "0x%08" PRIx32, Vals: def);
6793 if (r != nullptr) {
6794 if (left > sizeof(struct objc_class_t)) {
6795 outs() << "\n";
6796 memcpy(dest: &objc_class, src: r, n: sizeof(struct objc_class_t));
6797 } else {
6798 outs() << " (entends past the end of the section)\n";
6799 memset(s: &objc_class, c: '\0', n: sizeof(struct objc_class_t));
6800 memcpy(dest: &objc_class, src: r, n: left);
6801 }
6802 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6803 swapStruct(objc_class);
6804 print_objc_class_t(objc_class: &objc_class, info: &info);
6805 } else {
6806 outs() << "(not in an __OBJC section)\n";
6807 }
6808
6809 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6810 outs() << "\tMeta Class";
6811 r = get_pointer_32(Address: objc_class.isa, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6812 if (r != nullptr) {
6813 if (left > sizeof(struct objc_class_t)) {
6814 outs() << "\n";
6815 memcpy(dest: &objc_class, src: r, n: sizeof(struct objc_class_t));
6816 } else {
6817 outs() << " (entends past the end of the section)\n";
6818 memset(s: &objc_class, c: '\0', n: sizeof(struct objc_class_t));
6819 memcpy(dest: &objc_class, src: r, n: left);
6820 }
6821 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6822 swapStruct(objc_class);
6823 print_objc_class_t(objc_class: &objc_class, info: &info);
6824 } else {
6825 outs() << "(not in an __OBJC section)\n";
6826 }
6827 }
6828 }
6829 if (symtab.cat_def_cnt > 0)
6830 outs() << "\tCategory Definitions\n";
6831 for (j = 0; j < symtab.cat_def_cnt; j++) {
6832 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6833 outs() << "\t(remaining category defs entries entends past the end of "
6834 << "the section)\n";
6835 break;
6836 }
6837 memcpy(dest: &def, src: defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6838 n: sizeof(uint32_t));
6839 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6840 sys::swapByteOrder(Value&: def);
6841
6842 r = get_pointer_32(Address: def, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6843 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6844 << format(Fmt: "0x%08" PRIx32, Vals: def);
6845 if (r != nullptr) {
6846 if (left > sizeof(struct objc_category_t)) {
6847 outs() << "\n";
6848 memcpy(dest: &objc_category, src: r, n: sizeof(struct objc_category_t));
6849 } else {
6850 outs() << " (entends past the end of the section)\n";
6851 memset(s: &objc_category, c: '\0', n: sizeof(struct objc_category_t));
6852 memcpy(dest: &objc_category, src: r, n: left);
6853 }
6854 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6855 swapStruct(objc_category);
6856 print_objc_objc_category_t(objc_category: &objc_category, info: &info);
6857 } else {
6858 outs() << "(not in an __OBJC section)\n";
6859 }
6860 }
6861 }
6862 const SectionRef II = get_section(O, segname: "__OBJC", sectname: "__image_info");
6863 if (II != SectionRef())
6864 print_image_info(S: II, info: &info);
6865
6866 return true;
6867}
6868
6869static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6870 uint32_t size, uint32_t addr) {
6871 SymbolAddressMap AddrMap;
6872 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6873
6874 std::vector<SectionRef> Sections;
6875 append_range(C&: Sections, R: O->sections());
6876
6877 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6878
6879 const char *p;
6880 struct objc_protocol_t protocol;
6881 uint32_t left, paddr;
6882 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6883 memset(s: &protocol, c: '\0', n: sizeof(struct objc_protocol_t));
6884 left = size - (p - sect);
6885 if (left < sizeof(struct objc_protocol_t)) {
6886 outs() << "Protocol extends past end of __protocol section\n";
6887 memcpy(dest: &protocol, src: p, n: left);
6888 } else
6889 memcpy(dest: &protocol, src: p, n: sizeof(struct objc_protocol_t));
6890 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6891 swapStruct(protocol);
6892 paddr = addr + (p - sect);
6893 outs() << "Protocol " << format(Fmt: "0x%" PRIx32, Vals: paddr);
6894 if (print_protocol(p: paddr, indent: 0, info: &info))
6895 outs() << "(not in an __OBJC section)\n";
6896 }
6897}
6898
6899static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6900 if (O->is64Bit())
6901 printObjc2_64bit_MetaData(O, verbose);
6902 else {
6903 MachO::mach_header H;
6904 H = O->getHeader();
6905 if (H.cputype == MachO::CPU_TYPE_ARM)
6906 printObjc2_32bit_MetaData(O, verbose);
6907 else {
6908 // This is the 32-bit non-arm cputype case. Which is normally
6909 // the first Objective-C ABI. But it may be the case of a
6910 // binary for the iOS simulator which is the second Objective-C
6911 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6912 // and return false.
6913 if (!printObjc1_32bit_MetaData(O, verbose))
6914 printObjc2_32bit_MetaData(O, verbose);
6915 }
6916 }
6917}
6918
6919// GuessLiteralPointer returns a string which for the item in the Mach-O file
6920// for the address passed in as ReferenceValue for printing as a comment with
6921// the instruction and also returns the corresponding type of that item
6922// indirectly through ReferenceType.
6923//
6924// If ReferenceValue is an address of literal cstring then a pointer to the
6925// cstring is returned and ReferenceType is set to
6926// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6927//
6928// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6929// Class ref that name is returned and the ReferenceType is set accordingly.
6930//
6931// Lastly, literals which are Symbol address in a literal pool are looked for
6932// and if found the symbol name is returned and ReferenceType is set to
6933// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6934//
6935// If there is no item in the Mach-O file for the address passed in as
6936// ReferenceValue nullptr is returned and ReferenceType is unchanged.
6937static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6938 uint64_t ReferencePC,
6939 uint64_t *ReferenceType,
6940 struct DisassembleInfo *info) {
6941 // First see if there is an external relocation entry at the ReferencePC.
6942 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6943 uint64_t sect_addr = info->S.getAddress();
6944 uint64_t sect_offset = ReferencePC - sect_addr;
6945 bool reloc_found = false;
6946 DataRefImpl Rel;
6947 MachO::any_relocation_info RE;
6948 bool isExtern = false;
6949 SymbolRef Symbol;
6950 for (const RelocationRef &Reloc : info->S.relocations()) {
6951 uint64_t RelocOffset = Reloc.getOffset();
6952 if (RelocOffset == sect_offset) {
6953 Rel = Reloc.getRawDataRefImpl();
6954 RE = info->O->getRelocation(Rel);
6955 if (info->O->isRelocationScattered(RE))
6956 continue;
6957 isExtern = info->O->getPlainRelocationExternal(RE);
6958 if (isExtern) {
6959 symbol_iterator RelocSym = Reloc.getSymbol();
6960 Symbol = *RelocSym;
6961 }
6962 reloc_found = true;
6963 break;
6964 }
6965 }
6966 // If there is an external relocation entry for a symbol in a section
6967 // then used that symbol's value for the value of the reference.
6968 if (reloc_found && isExtern) {
6969 if (info->O->getAnyRelocationPCRel(RE)) {
6970 unsigned Type = info->O->getAnyRelocationType(RE);
6971 if (Type == MachO::X86_64_RELOC_SIGNED) {
6972 ReferenceValue = cantFail(ValOrErr: Symbol.getValue());
6973 }
6974 }
6975 }
6976 }
6977
6978 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6979 // Message refs and Class refs.
6980 bool classref, selref, msgref, cfstring;
6981 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6982 selref, msgref, cfstring);
6983 if (classref && pointer_value == 0) {
6984 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6985 // And the pointer_value in that section is typically zero as it will be
6986 // set by dyld as part of the "bind information".
6987 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6988 if (name != nullptr) {
6989 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6990 const char *class_name = strrchr(s: name, c: '$');
6991 if (class_name != nullptr && class_name[1] == '_' &&
6992 class_name[2] != '\0') {
6993 info->class_name = class_name + 2;
6994 return name;
6995 }
6996 }
6997 }
6998
6999 if (classref) {
7000 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
7001 const char *name =
7002 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
7003 if (name != nullptr)
7004 info->class_name = name;
7005 else
7006 name = "bad class ref";
7007 return name;
7008 }
7009
7010 if (cfstring) {
7011 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
7012 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
7013 return name;
7014 }
7015
7016 if (selref && pointer_value == 0)
7017 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
7018
7019 if (pointer_value != 0)
7020 ReferenceValue = pointer_value;
7021
7022 const char *name = GuessCstringPointer(ReferenceValue, info);
7023 if (name) {
7024 if (pointer_value != 0 && selref) {
7025 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
7026 info->selector_name = name;
7027 } else if (pointer_value != 0 && msgref) {
7028 info->class_name = nullptr;
7029 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
7030 info->selector_name = name;
7031 } else
7032 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
7033 return name;
7034 }
7035
7036 // Lastly look for an indirect symbol with this ReferenceValue which is in
7037 // a literal pool. If found return that symbol name.
7038 name = GuessIndirectSymbol(ReferenceValue, info);
7039 if (name) {
7040 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
7041 return name;
7042 }
7043
7044 return nullptr;
7045}
7046
7047// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
7048// the Symbolizer. It looks up the ReferenceValue using the info passed via the
7049// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
7050// is created and returns the symbol name that matches the ReferenceValue or
7051// nullptr if none. The ReferenceType is passed in for the IN type of
7052// reference the instruction is making from the values in defined in the header
7053// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
7054// Out type and the ReferenceName will also be set which is added as a comment
7055// to the disassembled instruction.
7056//
7057// If the symbol name is a C++ mangled name then the demangled name is
7058// returned through ReferenceName and ReferenceType is set to
7059// LLVMDisassembler_ReferenceType_DeMangled_Name .
7060//
7061// When this is called to get a symbol name for a branch target then the
7062// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7063// SymbolValue will be looked for in the indirect symbol table to determine if
7064// it is an address for a symbol stub. If so then the symbol name for that
7065// stub is returned indirectly through ReferenceName and then ReferenceType is
7066// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7067//
7068// When this is called with an value loaded via a PC relative load then
7069// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7070// SymbolValue is checked to be an address of literal pointer, symbol pointer,
7071// or an Objective-C meta data reference. If so the output ReferenceType is
7072// set to correspond to that as well as setting the ReferenceName.
7073static const char *SymbolizerSymbolLookUp(void *DisInfo,
7074 uint64_t ReferenceValue,
7075 uint64_t *ReferenceType,
7076 uint64_t ReferencePC,
7077 const char **ReferenceName) {
7078 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7079 // If no verbose symbolic information is wanted then just return nullptr.
7080 if (!info->verbose) {
7081 *ReferenceName = nullptr;
7082 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7083 return nullptr;
7084 }
7085
7086 const char *SymbolName = GuessSymbolName(value: ReferenceValue, AddrMap: info->AddrMap);
7087
7088 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7089 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7090 if (*ReferenceName != nullptr) {
7091 method_reference(info, ReferenceType, ReferenceName);
7092 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7093 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7094 } else if (SymbolName != nullptr && strncmp(s1: SymbolName, s2: "__Z", n: 3) == 0) {
7095 if (info->demangled_name != nullptr)
7096 free(ptr: info->demangled_name);
7097 info->demangled_name = itaniumDemangle(mangled_name: SymbolName + 1);
7098 if (info->demangled_name != nullptr) {
7099 *ReferenceName = info->demangled_name;
7100 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7101 } else
7102 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7103 } else
7104 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7105 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7106 *ReferenceName =
7107 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7108 if (*ReferenceName)
7109 method_reference(info, ReferenceType, ReferenceName);
7110 else
7111 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7112 // If this is arm64 and the reference is an adrp instruction save the
7113 // instruction, passed in ReferenceValue and the address of the instruction
7114 // for use later if we see and add immediate instruction.
7115 } else if ((info->O->getArch() == Triple::aarch64 ||
7116 info->O->getArch() == Triple::aarch64_32) &&
7117 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7118 info->adrp_inst = ReferenceValue;
7119 info->adrp_addr = ReferencePC;
7120 SymbolName = nullptr;
7121 *ReferenceName = nullptr;
7122 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7123 // If this is arm64 and reference is an add immediate instruction and we
7124 // have
7125 // seen an adrp instruction just before it and the adrp's Xd register
7126 // matches
7127 // this add's Xn register reconstruct the value being referenced and look to
7128 // see if it is a literal pointer. Note the add immediate instruction is
7129 // passed in ReferenceValue.
7130 } else if ((info->O->getArch() == Triple::aarch64 ||
7131 info->O->getArch() == Triple::aarch64_32) &&
7132 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7133 ReferencePC - 4 == info->adrp_addr &&
7134 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7135 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7136 uint32_t addxri_inst;
7137 uint64_t adrp_imm, addxri_imm;
7138
7139 adrp_imm =
7140 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7141 if (info->adrp_inst & 0x0200000)
7142 adrp_imm |= 0xfffffffffc000000LL;
7143
7144 addxri_inst = ReferenceValue;
7145 addxri_imm = (addxri_inst >> 10) & 0xfff;
7146 if (((addxri_inst >> 22) & 0x3) == 1)
7147 addxri_imm <<= 12;
7148
7149 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7150 (adrp_imm << 12) + addxri_imm;
7151
7152 *ReferenceName =
7153 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7154 if (*ReferenceName == nullptr)
7155 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7156 // If this is arm64 and the reference is a load register instruction and we
7157 // have seen an adrp instruction just before it and the adrp's Xd register
7158 // matches this add's Xn register reconstruct the value being referenced and
7159 // look to see if it is a literal pointer. Note the load register
7160 // instruction is passed in ReferenceValue.
7161 } else if ((info->O->getArch() == Triple::aarch64 ||
7162 info->O->getArch() == Triple::aarch64_32) &&
7163 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7164 ReferencePC - 4 == info->adrp_addr &&
7165 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7166 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7167 uint32_t ldrxui_inst;
7168 uint64_t adrp_imm, ldrxui_imm;
7169
7170 adrp_imm =
7171 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7172 if (info->adrp_inst & 0x0200000)
7173 adrp_imm |= 0xfffffffffc000000LL;
7174
7175 ldrxui_inst = ReferenceValue;
7176 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7177
7178 // The size field (bits [31:30]) determines the scaling.
7179 unsigned Scale = (ldrxui_inst >> 30) & 0x3;
7180 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7181 (adrp_imm << 12) + (ldrxui_imm << Scale);
7182
7183 *ReferenceName =
7184 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7185 if (*ReferenceName == nullptr)
7186 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7187 }
7188 // If this arm64 and is an load register (PC-relative) instruction the
7189 // ReferenceValue is the PC plus the immediate value.
7190 else if ((info->O->getArch() == Triple::aarch64 ||
7191 info->O->getArch() == Triple::aarch64_32) &&
7192 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7193 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7194 *ReferenceName =
7195 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7196 if (*ReferenceName == nullptr)
7197 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7198 } else if (SymbolName != nullptr && strncmp(s1: SymbolName, s2: "__Z", n: 3) == 0) {
7199 if (info->demangled_name != nullptr)
7200 free(ptr: info->demangled_name);
7201 info->demangled_name = itaniumDemangle(mangled_name: SymbolName + 1);
7202 if (info->demangled_name != nullptr) {
7203 *ReferenceName = info->demangled_name;
7204 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7205 }
7206 } else {
7207 *ReferenceName = nullptr;
7208 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7209 }
7210
7211 return SymbolName;
7212}
7213
7214/// Emits the comments that are stored in the CommentStream.
7215/// Each comment in the CommentStream must end with a newline.
7216static void emitComments(raw_svector_ostream &CommentStream,
7217 SmallString<128> &CommentsToEmit,
7218 formatted_raw_ostream &FormattedOS,
7219 const MCAsmInfo &MAI) {
7220 // Flush the stream before taking its content.
7221 StringRef Comments = CommentsToEmit.str();
7222 // Get the default information for printing a comment.
7223 StringRef CommentBegin = MAI.getCommentString();
7224 unsigned CommentColumn = MAI.getCommentColumn();
7225 ListSeparator LS("\n");
7226 while (!Comments.empty()) {
7227 FormattedOS << LS;
7228 // Emit a line of comments.
7229 FormattedOS.PadToColumn(NewCol: CommentColumn);
7230 size_t Position = Comments.find(C: '\n');
7231 FormattedOS << CommentBegin << ' ' << Comments.substr(Start: 0, N: Position);
7232 // Move after the newline character.
7233 Comments = Comments.substr(Start: Position + 1);
7234 }
7235 FormattedOS.flush();
7236
7237 // Tell the comment stream that the vector changed underneath it.
7238 CommentsToEmit.clear();
7239}
7240
7241const MachOObjectFile *
7242objdump::getMachODSymObject(const MachOObjectFile *MachOOF, StringRef Filename,
7243 std::unique_ptr<Binary> &DSYMBinary,
7244 std::unique_ptr<MemoryBuffer> &DSYMBuf) {
7245 const MachOObjectFile *DbgObj = MachOOF;
7246 std::string DSYMPath;
7247
7248 // Auto-detect w/o --dsym.
7249 if (DSYMFile.empty()) {
7250 sys::fs::file_status DSYMStatus;
7251 Twine FilenameDSYM = Filename + ".dSYM";
7252 if (!status(path: FilenameDSYM, result&: DSYMStatus)) {
7253 if (sys::fs::is_directory(status: DSYMStatus)) {
7254 SmallString<1024> Path;
7255 FilenameDSYM.toVector(Out&: Path);
7256 sys::path::append(path&: Path, a: "Contents", b: "Resources", c: "DWARF",
7257 d: sys::path::filename(path: Filename));
7258 DSYMPath = std::string(Path);
7259 } else if (sys::fs::is_regular_file(status: DSYMStatus)) {
7260 DSYMPath = FilenameDSYM.str();
7261 }
7262 }
7263 }
7264
7265 if (DSYMPath.empty() && !DSYMFile.empty()) {
7266 // If DSYMPath is a .dSYM directory, append the Mach-O file.
7267 if (sys::fs::is_directory(Path: DSYMFile) &&
7268 sys::path::extension(path: DSYMFile) == ".dSYM") {
7269 SmallString<128> ShortName(sys::path::filename(path: DSYMFile));
7270 sys::path::replace_extension(path&: ShortName, extension: "");
7271 SmallString<1024> FullPath(DSYMFile);
7272 sys::path::append(path&: FullPath, a: "Contents", b: "Resources", c: "DWARF", d: ShortName);
7273 DSYMPath = FullPath.str();
7274 } else {
7275 DSYMPath = DSYMFile;
7276 }
7277 }
7278
7279 if (!DSYMPath.empty()) {
7280 // Load the file.
7281 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7282 MemoryBuffer::getFileOrSTDIN(Filename: DSYMPath);
7283 if (std::error_code EC = BufOrErr.getError()) {
7284 reportError(E: errorCodeToError(EC), FileName: DSYMPath);
7285 return nullptr;
7286 }
7287
7288 // We need to keep the file alive, because we're replacing DbgObj with it.
7289 DSYMBuf = std::move(BufOrErr.get());
7290
7291 Expected<std::unique_ptr<Binary>> BinaryOrErr =
7292 createBinary(Source: DSYMBuf->getMemBufferRef());
7293 if (!BinaryOrErr) {
7294 reportError(E: BinaryOrErr.takeError(), FileName: DSYMPath);
7295 return nullptr;
7296 }
7297
7298 // We need to keep the Binary alive with the buffer
7299 DSYMBinary = std::move(BinaryOrErr.get());
7300 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: DSYMBinary.get())) {
7301 // this is a Mach-O object file, use it
7302 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(Val: &*O)) {
7303 DbgObj = MachDSYM;
7304 } else {
7305 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
7306 << DSYMPath << " is not a Mach-O file type.\n";
7307 return nullptr;
7308 }
7309 } else if (auto *UB = dyn_cast<MachOUniversalBinary>(Val: DSYMBinary.get())) {
7310 // this is a Universal Binary, find a Mach-O for this architecture
7311 uint32_t CPUType, CPUSubType;
7312 const char *ArchFlag;
7313 if (MachOOF->is64Bit()) {
7314 const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7315 CPUType = H_64.cputype;
7316 CPUSubType = H_64.cpusubtype;
7317 } else {
7318 const MachO::mach_header H = MachOOF->getHeader();
7319 CPUType = H.cputype;
7320 CPUSubType = H.cpusubtype;
7321 }
7322 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, McpuDefault: nullptr,
7323 ArchFlag: &ArchFlag);
7324 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7325 UB->getMachOObjectForArch(ArchName: ArchFlag);
7326 if (!MachDSYM) {
7327 reportError(E: MachDSYM.takeError(), FileName: DSYMPath);
7328 return nullptr;
7329 }
7330
7331 // We need to keep the Binary alive with the buffer
7332 DbgObj = &*MachDSYM.get();
7333 DSYMBinary = std::move(*MachDSYM);
7334 } else {
7335 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
7336 << DSYMPath << " is not a Mach-O or Universal file type.\n";
7337 return nullptr;
7338 }
7339 }
7340 return DbgObj;
7341}
7342
7343static bool shouldInstPrinterUseColor() {
7344 switch (DisassemblyColor) {
7345 case ColorOutput::Enable:
7346 return true;
7347 case ColorOutput::Auto:
7348 return outs().has_colors();
7349 case ColorOutput::Disable:
7350 case ColorOutput::Invalid:
7351 return false;
7352 }
7353 return false;
7354}
7355
7356static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7357 StringRef DisSegName, StringRef DisSectName) {
7358 const char *McpuDefault = nullptr;
7359 const Target *ThumbTarget = nullptr;
7360 Triple ThumbTriple;
7361 const Target *TheTarget =
7362 GetTarget(MachOObj: MachOOF, McpuDefault: &McpuDefault, ThumbTarget: &ThumbTarget, ThumbTriple);
7363 if (!TheTarget) {
7364 // GetTarget prints out stuff.
7365 return;
7366 }
7367 std::string MachOMCPU;
7368 if (MCPU.empty() && McpuDefault)
7369 MachOMCPU = McpuDefault;
7370 else
7371 MachOMCPU = MCPU;
7372
7373#define CHECK_TARGET_INFO_CREATION(NAME) \
7374 do { \
7375 if (!NAME) { \
7376 WithColor::error(errs(), "llvm-objdump") \
7377 << "couldn't initialize disassembler for target " << TripleName \
7378 << '\n'; \
7379 return; \
7380 } \
7381 } while (false)
7382#define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \
7383 do { \
7384 if (!NAME) { \
7385 WithColor::error(errs(), "llvm-objdump") \
7386 << "couldn't initialize disassembler for target " << ThumbTripleName \
7387 << '\n'; \
7388 return; \
7389 } \
7390 } while (false)
7391
7392 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7393 CHECK_TARGET_INFO_CREATION(InstrInfo);
7394 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7395 if (ThumbTarget) {
7396 ThumbInstrInfo.reset(p: ThumbTarget->createMCInstrInfo());
7397 CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7398 }
7399
7400 // Package up features to be passed to target/subtarget
7401 std::string FeaturesStr;
7402 if (!MAttrs.empty()) {
7403 SubtargetFeatures Features;
7404 for (unsigned i = 0; i != MAttrs.size(); ++i)
7405 Features.AddFeature(String: MAttrs[i]);
7406 FeaturesStr = Features.getString();
7407 }
7408
7409 Triple TheTriple(TripleName);
7410
7411 MCTargetOptions MCOptions;
7412 MCOptions.LibraryOptions = &LibraryOptions;
7413 // Set up disassembler.
7414 std::unique_ptr<const MCRegisterInfo> MRI(
7415 TheTarget->createMCRegInfo(TT: TheTriple));
7416 CHECK_TARGET_INFO_CREATION(MRI);
7417 std::unique_ptr<const MCAsmInfo> AsmInfo(
7418 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
7419 CHECK_TARGET_INFO_CREATION(AsmInfo);
7420 std::unique_ptr<const MCSubtargetInfo> STI(
7421 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MachOMCPU, Features: FeaturesStr));
7422 CHECK_TARGET_INFO_CREATION(STI);
7423 MCContext Ctx(TheTriple, *AsmInfo, *MRI, *STI);
7424 std::unique_ptr<MCDisassembler> DisAsm(
7425 TheTarget->createMCDisassembler(STI: *STI, Ctx));
7426 CHECK_TARGET_INFO_CREATION(DisAsm);
7427 std::unique_ptr<MCSymbolizer> Symbolizer;
7428 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7429 std::unique_ptr<MCRelocationInfo> RelInfo(
7430 TheTarget->createMCRelocationInfo(TT: TheTriple, Ctx));
7431 if (RelInfo) {
7432 Symbolizer.reset(p: TheTarget->createMCSymbolizer(
7433 TT: TheTriple, GetOpInfo: SymbolizerGetOpInfo, SymbolLookUp: SymbolizerSymbolLookUp, DisInfo: &SymbolizerInfo,
7434 Ctx: &Ctx, RelInfo: std::move(RelInfo)));
7435 DisAsm->setSymbolizer(std::move(Symbolizer));
7436 }
7437 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7438 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7439 T: TheTriple, SyntaxVariant: AsmPrinterVariant, MAI: *AsmInfo, MII: *InstrInfo, MRI: *MRI));
7440 CHECK_TARGET_INFO_CREATION(IP);
7441 IP->setPrintImmHex(PrintImmHex);
7442 IP->setUseColor(shouldInstPrinterUseColor());
7443
7444 // Comment stream and backing vector.
7445 SmallString<128> CommentsToEmit;
7446 raw_svector_ostream CommentStream(CommentsToEmit);
7447 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7448 // if it is done then arm64 comments for string literals don't get printed
7449 // and some constant get printed instead and not setting it causes intel
7450 // (32-bit and 64-bit) comments printed with different spacing before the
7451 // comment causing different diffs with the 'C' disassembler library API.
7452 // IP->setCommentStream(CommentStream);
7453
7454 for (StringRef Opt : DisassemblerOptions)
7455 if (!IP->applyTargetSpecificCLOption(Opt))
7456 reportError(File: Filename, Message: "unrecognized disassembler option: " + Opt);
7457
7458 // Set up separate thumb disassembler if needed.
7459 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7460 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7461 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7462 std::unique_ptr<MCDisassembler> ThumbDisAsm;
7463 std::unique_ptr<MCInstPrinter> ThumbIP;
7464 std::unique_ptr<MCContext> ThumbCtx;
7465 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7466 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7467 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7468 if (ThumbTarget) {
7469 ThumbMRI.reset(p: ThumbTarget->createMCRegInfo(TT: ThumbTriple));
7470 CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7471 ThumbAsmInfo.reset(
7472 p: ThumbTarget->createMCAsmInfo(MRI: *ThumbMRI, TheTriple: ThumbTriple, Options: MCOptions));
7473 CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7474 ThumbSTI.reset(p: ThumbTarget->createMCSubtargetInfo(TheTriple: ThumbTriple, CPU: MachOMCPU,
7475 Features: FeaturesStr));
7476 CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7477 ThumbCtx.reset(
7478 p: new MCContext(ThumbTriple, *ThumbAsmInfo, *ThumbMRI, *ThumbSTI));
7479 ThumbDisAsm.reset(p: ThumbTarget->createMCDisassembler(STI: *ThumbSTI, Ctx&: *ThumbCtx));
7480 CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7481 MCContext *PtrThumbCtx = ThumbCtx.get();
7482 ThumbRelInfo.reset(
7483 p: ThumbTarget->createMCRelocationInfo(TT: ThumbTriple, Ctx&: *PtrThumbCtx));
7484 if (ThumbRelInfo) {
7485 ThumbSymbolizer.reset(p: ThumbTarget->createMCSymbolizer(
7486 TT: ThumbTriple, GetOpInfo: SymbolizerGetOpInfo, SymbolLookUp: SymbolizerSymbolLookUp,
7487 DisInfo: &ThumbSymbolizerInfo, Ctx: PtrThumbCtx, RelInfo: std::move(ThumbRelInfo)));
7488 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7489 }
7490 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7491 ThumbIP.reset(p: ThumbTarget->createMCInstPrinter(
7492 T: ThumbTriple, SyntaxVariant: ThumbAsmPrinterVariant, MAI: *ThumbAsmInfo, MII: *ThumbInstrInfo,
7493 MRI: *ThumbMRI));
7494 CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7495 ThumbIP->setPrintImmHex(PrintImmHex);
7496 ThumbIP->setUseColor(shouldInstPrinterUseColor());
7497 }
7498
7499#undef CHECK_TARGET_INFO_CREATION
7500#undef CHECK_THUMB_TARGET_INFO_CREATION
7501
7502 MachO::mach_header Header = MachOOF->getHeader();
7503
7504 // FIXME: Using the -cfg command line option, this code used to be able to
7505 // annotate relocations with the referenced symbol's name, and if this was
7506 // inside a __[cf]string section, the data it points to. This is now replaced
7507 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7508 std::vector<SectionRef> Sections;
7509 std::vector<SymbolRef> Symbols;
7510 SmallVector<uint64_t, 8> FoundFns;
7511 uint64_t BaseSegmentAddress = 0;
7512
7513 getSectionsAndSymbols(MachOObj: MachOOF, Sections, Symbols, FoundFns,
7514 BaseSegmentAddress);
7515
7516 // Sort the symbols by address, just in case they didn't come in that way.
7517 llvm::stable_sort(Range&: Symbols, C: SymbolSorter());
7518
7519 // Build a data in code table that is sorted on by the address of each entry.
7520 uint64_t BaseAddress = 0;
7521 if (Header.filetype == MachO::MH_OBJECT)
7522 BaseAddress = Sections[0].getAddress();
7523 else
7524 BaseAddress = BaseSegmentAddress;
7525 DiceTable Dices;
7526 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7527 DI != DE; ++DI) {
7528 uint32_t Offset;
7529 DI->getOffset(Result&: Offset);
7530 Dices.push_back(x: std::make_pair(x: BaseAddress + Offset, y: *DI));
7531 }
7532 array_pod_sort(Start: Dices.begin(), End: Dices.end());
7533
7534 // Try to find debug info and set up the DIContext for it.
7535 std::unique_ptr<DIContext> diContext;
7536 std::unique_ptr<Binary> DSYMBinary;
7537 std::unique_ptr<MemoryBuffer> DSYMBuf;
7538 const ObjectFile *DbgObj = MachOOF;
7539 if (UseDbg || PrintSource || PrintLines) {
7540 // Look for debug info in external dSYM file or embedded in the object.
7541 // getMachODSymObject returns MachOOF by default if no external dSYM found.
7542 const ObjectFile *DSym =
7543 getMachODSymObject(MachOOF, Filename, DSYMBinary, DSYMBuf);
7544 if (!DSym)
7545 return;
7546 DbgObj = DSym;
7547 if (UseDbg || PrintLines) {
7548 // Setup the DIContext
7549 diContext = DWARFContext::create(Obj: *DbgObj);
7550 }
7551 }
7552
7553 std::optional<SourcePrinter> SP;
7554 std::optional<LiveElementPrinter> LEP;
7555 if (PrintSource || PrintLines) {
7556 SP.emplace(args&: DbgObj, args: TheTarget->getName());
7557 LEP.emplace(args: *MRI, args: *STI);
7558 }
7559
7560 if (FilterSections.empty())
7561 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7562
7563 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7564 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7565 if (!SecNameOrErr) {
7566 consumeError(Err: SecNameOrErr.takeError());
7567 continue;
7568 }
7569 if (*SecNameOrErr != DisSectName)
7570 continue;
7571
7572 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7573
7574 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(Sec: DR);
7575 if (SegmentName != DisSegName)
7576 continue;
7577
7578 StringRef BytesStr =
7579 unwrapOrError(EO: Sections[SectIdx].getContents(), Args&: Filename);
7580 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(Input: BytesStr);
7581 uint64_t SectAddress = Sections[SectIdx].getAddress();
7582
7583 bool symbolTableWorked = false;
7584
7585 // Create a map of symbol addresses to symbol names for use by
7586 // the SymbolizerSymbolLookUp() routine.
7587 SymbolAddressMap AddrMap;
7588 bool DisSymNameFound = false;
7589 for (const SymbolRef &Symbol : MachOOF->symbols()) {
7590 SymbolRef::Type ST =
7591 unwrapOrError(EO: Symbol.getType(), Args: MachOOF->getFileName());
7592 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7593 ST == SymbolRef::ST_Other) {
7594 uint64_t Address = cantFail(ValOrErr: Symbol.getValue());
7595 StringRef SymName =
7596 unwrapOrError(EO: Symbol.getName(), Args: MachOOF->getFileName());
7597 AddrMap[Address] = SymName;
7598 if (!DisSymName.empty() && DisSymName == SymName)
7599 DisSymNameFound = true;
7600 }
7601 }
7602 if (!DisSymName.empty() && !DisSymNameFound) {
7603 outs() << "Can't find " << (IsOtool ? "-p symbol" : "--dis-symname")
7604 << ": " << DisSymName << "\n";
7605 return;
7606 }
7607 // Set up the block of info used by the Symbolizer call backs.
7608 SymbolizerInfo.verbose = SymbolicOperands;
7609 SymbolizerInfo.O = MachOOF;
7610 SymbolizerInfo.S = Sections[SectIdx];
7611 SymbolizerInfo.AddrMap = &AddrMap;
7612 SymbolizerInfo.Sections = &Sections;
7613 // Same for the ThumbSymbolizer
7614 ThumbSymbolizerInfo.verbose = SymbolicOperands;
7615 ThumbSymbolizerInfo.O = MachOOF;
7616 ThumbSymbolizerInfo.S = Sections[SectIdx];
7617 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7618 ThumbSymbolizerInfo.Sections = &Sections;
7619
7620 unsigned int Arch = MachOOF->getArch();
7621
7622 // Skip all symbols if this is a stubs file.
7623 if (Bytes.empty())
7624 return;
7625
7626 // If the section has symbols but no symbol at the start of the section
7627 // these are used to make sure the bytes before the first symbol are
7628 // disassembled.
7629 bool FirstSymbol = true;
7630 bool FirstSymbolAtSectionStart = true;
7631
7632 // Disassemble symbol by symbol.
7633 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7634 StringRef SymName =
7635 unwrapOrError(EO: Symbols[SymIdx].getName(), Args: MachOOF->getFileName());
7636 SymbolRef::Type ST =
7637 unwrapOrError(EO: Symbols[SymIdx].getType(), Args: MachOOF->getFileName());
7638 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7639 continue;
7640
7641 // Make sure the symbol is defined in this section.
7642 bool containsSym = Sections[SectIdx].containsSymbol(S: Symbols[SymIdx]);
7643 if (!containsSym) {
7644 if (!DisSymName.empty() && DisSymName == SymName) {
7645 outs() << (IsOtool ? "-p symbol" : "--dis-symname") << ": "
7646 << DisSymName << " not in the section\n";
7647 return;
7648 }
7649 continue;
7650 }
7651 // The __mh_execute_header is special and we need to deal with that fact
7652 // this symbol is before the start of the (__TEXT,__text) section and at the
7653 // address of the start of the __TEXT segment. This is because this symbol
7654 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7655 // start of the section in a standard MH_EXECUTE filetype.
7656 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7657 outs() << (IsOtool ? "-p symbol" : "--dis-symname")
7658 << ": __mh_execute_header not in any section\n";
7659 return;
7660 }
7661 // When this code is trying to disassemble a symbol at a time and in the
7662 // case there is only the __mh_execute_header symbol left as in a stripped
7663 // executable, we need to deal with this by ignoring this symbol so the
7664 // whole section is disassembled and this symbol is then not displayed.
7665 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7666 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7667 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7668 continue;
7669
7670 // If we are only disassembling one symbol see if this is that symbol.
7671 if (!DisSymName.empty() && DisSymName != SymName)
7672 continue;
7673
7674 // Start at the address of the symbol relative to the section's address.
7675 uint64_t SectSize = Sections[SectIdx].getSize();
7676 uint64_t Start = cantFail(ValOrErr: Symbols[SymIdx].getValue());
7677 uint64_t SectionAddress = Sections[SectIdx].getAddress();
7678 Start -= SectionAddress;
7679
7680 if (Start > SectSize) {
7681 outs() << "section data ends, " << SymName
7682 << " lies outside valid range\n";
7683 return;
7684 }
7685
7686 // Stop disassembling either at the beginning of the next symbol or at
7687 // the end of the section.
7688 bool containsNextSym = false;
7689 uint64_t NextSym = 0;
7690 uint64_t NextSymIdx = SymIdx + 1;
7691 while (Symbols.size() > NextSymIdx) {
7692 SymbolRef::Type NextSymType = unwrapOrError(
7693 EO: Symbols[NextSymIdx].getType(), Args: MachOOF->getFileName());
7694 if (NextSymType == SymbolRef::ST_Function) {
7695 containsNextSym =
7696 Sections[SectIdx].containsSymbol(S: Symbols[NextSymIdx]);
7697 NextSym = cantFail(ValOrErr: Symbols[NextSymIdx].getValue());
7698 NextSym -= SectionAddress;
7699 break;
7700 }
7701 ++NextSymIdx;
7702 }
7703
7704 uint64_t End = containsNextSym ? std::min(a: NextSym, b: SectSize) : SectSize;
7705 uint64_t Size;
7706
7707 symbolTableWorked = true;
7708
7709 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7710 uint32_t SymbolFlags = cantFail(ValOrErr: MachOOF->getSymbolFlags(Symb));
7711 bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7712
7713 // We only need the dedicated Thumb target if there's a real choice
7714 // (i.e. we're not targeting M-class) and the function is Thumb.
7715 bool UseThumbTarget = IsThumb && ThumbTarget;
7716
7717 // If we are not specifying a symbol to start disassembly with and this
7718 // is the first symbol in the section but not at the start of the section
7719 // then move the disassembly index to the start of the section and
7720 // don't print the symbol name just yet. This is so the bytes before the
7721 // first symbol are disassembled.
7722 uint64_t SymbolStart = Start;
7723 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7724 FirstSymbolAtSectionStart = false;
7725 Start = 0;
7726 }
7727 else
7728 outs() << SymName << ":\n";
7729
7730 DILineInfo lastLine;
7731 for (uint64_t Index = Start; Index < End; Index += Size) {
7732 MCInst Inst;
7733
7734 // If this is the first symbol in the section and it was not at the
7735 // start of the section, see if we are at its Index now and if so print
7736 // the symbol name.
7737 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7738 outs() << SymName << ":\n";
7739
7740 uint64_t PC = SectAddress + Index;
7741
7742 if (PrintSource || PrintLines) {
7743 formatted_raw_ostream FOS(outs());
7744 SP->printSourceLine(OS&: FOS, Address: {.Address: PC, .SectionIndex: SectIdx}, ObjectFilename: Filename, LEP&: *LEP);
7745 }
7746
7747 if (LeadingAddr) {
7748 if (FullLeadingAddr) {
7749 if (MachOOF->is64Bit())
7750 outs() << format(Fmt: "%016" PRIx64, Vals: PC);
7751 else
7752 outs() << format(Fmt: "%08" PRIx64, Vals: PC);
7753 } else {
7754 outs() << format(Fmt: "%8" PRIx64 ":", Vals: PC);
7755 }
7756 }
7757 if (ShowRawInsn || Arch == Triple::arm)
7758 outs() << "\t";
7759
7760 if (DumpAndSkipDataInCode(PC, bytes: Bytes.data() + Index, Dices, InstSize&: Size))
7761 continue;
7762
7763 SmallVector<char, 64> AnnotationsBytes;
7764 raw_svector_ostream Annotations(AnnotationsBytes);
7765
7766 bool gotInst;
7767 if (UseThumbTarget)
7768 gotInst = ThumbDisAsm->getInstruction(Instr&: Inst, Size, Bytes: Bytes.slice(N: Index),
7769 Address: PC, CStream&: Annotations);
7770 else
7771 gotInst = DisAsm->getInstruction(Instr&: Inst, Size, Bytes: Bytes.slice(N: Index), Address: PC,
7772 CStream&: Annotations);
7773 if (gotInst) {
7774 if (ShowRawInsn || Arch == Triple::arm) {
7775 dumpBytes(Bytes: ArrayRef(Bytes.data() + Index, Size), OS&: outs());
7776 }
7777 formatted_raw_ostream FormattedOS(outs());
7778 StringRef AnnotationsStr = Annotations.str();
7779 if (UseThumbTarget)
7780 ThumbIP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *ThumbSTI,
7781 OS&: FormattedOS);
7782 else
7783 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *STI, OS&: FormattedOS);
7784 emitComments(CommentStream, CommentsToEmit, FormattedOS, MAI: *AsmInfo);
7785
7786 // Print debug info.
7787 if (diContext) {
7788 DILineInfo dli = diContext->getLineInfoForAddress(Address: {.Address: PC, .SectionIndex: SectIdx})
7789 .value_or(u: DILineInfo());
7790 // Print valid line info if it changed.
7791 if (dli != lastLine && dli.Line != 0)
7792 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7793 << dli.Column;
7794 lastLine = dli;
7795 }
7796 outs() << "\n";
7797 } else {
7798 if (MachOOF->getArchTriple().isX86()) {
7799 outs() << format(Fmt: "\t.byte 0x%02x #bad opcode\n",
7800 Vals: *(Bytes.data() + Index) & 0xff);
7801 Size = 1; // skip exactly one illegible byte and move on.
7802 } else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32 ||
7803 (Arch == Triple::arm && !IsThumb)) {
7804 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7805 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7806 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7807 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7808 outs() << format(Fmt: "\t.long\t0x%08x\n", Vals: opcode);
7809 Size = 4;
7810 } else if (Arch == Triple::arm) {
7811 assert(IsThumb && "ARM mode should have been dealt with above");
7812 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7813 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7814 outs() << format(Fmt: "\t.short\t0x%04x\n", Vals: opcode);
7815 Size = 2;
7816 } else {
7817 WithColor::warning(OS&: errs(), Prefix: "llvm-objdump")
7818 << "invalid instruction encoding\n";
7819 if (Size == 0)
7820 Size = 1; // skip illegible bytes
7821 }
7822 }
7823 }
7824 // Now that we are done disassembled the first symbol set the bool that
7825 // were doing this to false.
7826 FirstSymbol = false;
7827 }
7828 if (!symbolTableWorked) {
7829 // Reading the symbol table didn't work, disassemble the whole section.
7830 uint64_t SectAddress = Sections[SectIdx].getAddress();
7831 uint64_t SectSize = Sections[SectIdx].getSize();
7832 uint64_t InstSize;
7833 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7834 MCInst Inst;
7835
7836 uint64_t PC = SectAddress + Index;
7837
7838 if (PrintSource || PrintLines) {
7839 formatted_raw_ostream FOS(outs());
7840 SP->printSourceLine(OS&: FOS, Address: {.Address: PC, .SectionIndex: SectIdx}, ObjectFilename: Filename, LEP&: *LEP);
7841 }
7842
7843 if (DumpAndSkipDataInCode(PC, bytes: Bytes.data() + Index, Dices, InstSize))
7844 continue;
7845
7846 SmallVector<char, 64> AnnotationsBytes;
7847 raw_svector_ostream Annotations(AnnotationsBytes);
7848 if (DisAsm->getInstruction(Instr&: Inst, Size&: InstSize, Bytes: Bytes.slice(N: Index), Address: PC,
7849 CStream&: Annotations)) {
7850 if (LeadingAddr) {
7851 if (FullLeadingAddr) {
7852 if (MachOOF->is64Bit())
7853 outs() << format(Fmt: "%016" PRIx64, Vals: PC);
7854 else
7855 outs() << format(Fmt: "%08" PRIx64, Vals: PC);
7856 } else {
7857 outs() << format(Fmt: "%8" PRIx64 ":", Vals: PC);
7858 }
7859 }
7860 if (ShowRawInsn || Arch == Triple::arm) {
7861 outs() << "\t";
7862 dumpBytes(Bytes: ArrayRef(Bytes.data() + Index, InstSize), OS&: outs());
7863 }
7864 StringRef AnnotationsStr = Annotations.str();
7865 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *STI, OS&: outs());
7866 outs() << "\n";
7867 } else {
7868 if (MachOOF->getArchTriple().isX86()) {
7869 outs() << format(Fmt: "\t.byte 0x%02x #bad opcode\n",
7870 Vals: *(Bytes.data() + Index) & 0xff);
7871 InstSize = 1; // skip exactly one illegible byte and move on.
7872 } else {
7873 WithColor::warning(OS&: errs(), Prefix: "llvm-objdump")
7874 << "invalid instruction encoding\n";
7875 if (InstSize == 0)
7876 InstSize = 1; // skip illegible bytes
7877 }
7878 }
7879 }
7880 }
7881 // The TripleName's need to be reset if we are called again for a different
7882 // architecture.
7883 TripleName = "";
7884 ThumbTripleName = "";
7885
7886 if (SymbolizerInfo.demangled_name != nullptr)
7887 free(ptr: SymbolizerInfo.demangled_name);
7888 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7889 free(ptr: ThumbSymbolizerInfo.demangled_name);
7890 }
7891}
7892
7893//===----------------------------------------------------------------------===//
7894// __compact_unwind section dumping
7895//===----------------------------------------------------------------------===//
7896
7897namespace {
7898
7899template <typename T>
7900static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7901 if (Offset + sizeof(T) > Contents.size()) {
7902 outs() << "warning: attempt to read past end of buffer\n";
7903 return T();
7904 }
7905
7906 uint64_t Val = support::endian::read<T, llvm::endianness::little>(
7907 Contents.data() + Offset);
7908 return Val;
7909}
7910
7911template <typename T>
7912static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7913 T Val = read<T>(Contents, Offset);
7914 Offset += sizeof(T);
7915 return Val;
7916}
7917
7918struct CompactUnwindEntry {
7919 uint32_t OffsetInSection;
7920
7921 uint64_t FunctionAddr;
7922 uint32_t Length;
7923 uint32_t CompactEncoding;
7924 uint64_t PersonalityAddr;
7925 uint64_t LSDAAddr;
7926
7927 RelocationRef FunctionReloc;
7928 RelocationRef PersonalityReloc;
7929 RelocationRef LSDAReloc;
7930
7931 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7932 : OffsetInSection(Offset) {
7933 if (Is64)
7934 read<uint64_t>(Contents, Offset);
7935 else
7936 read<uint32_t>(Contents, Offset);
7937 }
7938
7939private:
7940 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7941 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7942 Length = readNext<uint32_t>(Contents, Offset);
7943 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7944 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7945 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7946 }
7947};
7948}
7949
7950/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7951/// and data being relocated, determine the best base Name and Addend to use for
7952/// display purposes.
7953///
7954/// 1. An Extern relocation will directly reference a symbol (and the data is
7955/// then already an addend), so use that.
7956/// 2. Otherwise the data is an offset in the object file's layout; try to find
7957// a symbol before it in the same section, and use the offset from there.
7958/// 3. Finally, if all that fails, fall back to an offset from the start of the
7959/// referenced section.
7960static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7961 std::map<uint64_t, SymbolRef> &Symbols,
7962 const RelocationRef &Reloc, uint64_t Addr,
7963 StringRef &Name, uint64_t &Addend) {
7964 if (Reloc.getSymbol() != Obj->symbol_end()) {
7965 Name = unwrapOrError(EO: Reloc.getSymbol()->getName(), Args: Obj->getFileName());
7966 Addend = Addr;
7967 return;
7968 }
7969
7970 auto RE = Obj->getRelocation(Rel: Reloc.getRawDataRefImpl());
7971 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7972
7973 uint64_t SectionAddr = RelocSection.getAddress();
7974
7975 auto Sym = Symbols.upper_bound(x: Addr);
7976 if (Sym == Symbols.begin()) {
7977 // The first symbol in the object is after this reference, the best we can
7978 // do is section-relative notation.
7979 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7980 Name = *NameOrErr;
7981 else
7982 consumeError(Err: NameOrErr.takeError());
7983
7984 Addend = Addr - SectionAddr;
7985 return;
7986 }
7987
7988 // Go back one so that SymbolAddress <= Addr.
7989 --Sym;
7990
7991 section_iterator SymSection =
7992 unwrapOrError(EO: Sym->second.getSection(), Args: Obj->getFileName());
7993 if (RelocSection == *SymSection) {
7994 // There's a valid symbol in the same section before this reference.
7995 Name = unwrapOrError(EO: Sym->second.getName(), Args: Obj->getFileName());
7996 Addend = Addr - Sym->first;
7997 return;
7998 }
7999
8000 // There is a symbol before this reference, but it's in a different
8001 // section. Probably not helpful to mention it, so use the section name.
8002 if (Expected<StringRef> NameOrErr = RelocSection.getName())
8003 Name = *NameOrErr;
8004 else
8005 consumeError(Err: NameOrErr.takeError());
8006
8007 Addend = Addr - SectionAddr;
8008}
8009
8010static void printUnwindRelocDest(const MachOObjectFile *Obj,
8011 std::map<uint64_t, SymbolRef> &Symbols,
8012 const RelocationRef &Reloc, uint64_t Addr) {
8013 StringRef Name;
8014 uint64_t Addend;
8015
8016 if (!Reloc.getObject())
8017 return;
8018
8019 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
8020
8021 outs() << Name;
8022 if (Addend)
8023 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: Addend);
8024}
8025
8026static void
8027printMachOCompactUnwindSection(const MachOObjectFile *Obj,
8028 std::map<uint64_t, SymbolRef> &Symbols,
8029 const SectionRef &CompactUnwind) {
8030
8031 if (!Obj->isLittleEndian()) {
8032 outs() << "Skipping big-endian __compact_unwind section\n";
8033 return;
8034 }
8035
8036 bool Is64 = Obj->is64Bit();
8037 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
8038 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
8039
8040 StringRef Contents =
8041 unwrapOrError(EO: CompactUnwind.getContents(), Args: Obj->getFileName());
8042 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
8043
8044 // First populate the initial raw offsets, encodings and so on from the entry.
8045 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
8046 CompactUnwindEntry Entry(Contents, Offset, Is64);
8047 CompactUnwinds.push_back(Elt: Entry);
8048 }
8049
8050 // Next we need to look at the relocations to find out what objects are
8051 // actually being referred to.
8052 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
8053 uint64_t RelocAddress = Reloc.getOffset();
8054
8055 uint32_t EntryIdx = RelocAddress / EntrySize;
8056 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
8057 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
8058
8059 if (OffsetInEntry == 0)
8060 Entry.FunctionReloc = Reloc;
8061 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
8062 Entry.PersonalityReloc = Reloc;
8063 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
8064 Entry.LSDAReloc = Reloc;
8065 else {
8066 outs() << "Invalid relocation in __compact_unwind section\n";
8067 return;
8068 }
8069 }
8070
8071 // Finally, we're ready to print the data we've gathered.
8072 outs() << "Contents of __compact_unwind section:\n";
8073 for (auto &Entry : CompactUnwinds) {
8074 outs() << " Entry at offset "
8075 << format(Fmt: "0x%" PRIx32, Vals: Entry.OffsetInSection) << ":\n";
8076
8077 // 1. Start of the region this entry applies to.
8078 outs() << " start: " << format(Fmt: "0x%" PRIx64,
8079 Vals: Entry.FunctionAddr) << ' ';
8080 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.FunctionReloc, Addr: Entry.FunctionAddr);
8081 outs() << '\n';
8082
8083 // 2. Length of the region this entry applies to.
8084 outs() << " length: " << format(Fmt: "0x%" PRIx32, Vals: Entry.Length)
8085 << '\n';
8086 // 3. The 32-bit compact encoding.
8087 outs() << " compact encoding: "
8088 << format(Fmt: "0x%08" PRIx32, Vals: Entry.CompactEncoding) << '\n';
8089
8090 // 4. The personality function, if present.
8091 if (Entry.PersonalityReloc.getObject()) {
8092 outs() << " personality function: "
8093 << format(Fmt: "0x%" PRIx64, Vals: Entry.PersonalityAddr) << ' ';
8094 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.PersonalityReloc,
8095 Addr: Entry.PersonalityAddr);
8096 outs() << '\n';
8097 }
8098
8099 // 5. This entry's language-specific data area.
8100 if (Entry.LSDAReloc.getObject()) {
8101 outs() << " LSDA: " << format(Fmt: "0x%" PRIx64,
8102 Vals: Entry.LSDAAddr) << ' ';
8103 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.LSDAReloc, Addr: Entry.LSDAAddr);
8104 outs() << '\n';
8105 }
8106 }
8107}
8108
8109//===----------------------------------------------------------------------===//
8110// __unwind_info section dumping
8111//===----------------------------------------------------------------------===//
8112
8113static void printRegularSecondLevelUnwindPage(StringRef PageData) {
8114 ptrdiff_t Pos = 0;
8115 uint32_t Kind = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8116 (void)Kind;
8117 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
8118
8119 uint16_t EntriesStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8120 uint16_t NumEntries = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8121
8122 Pos = EntriesStart;
8123 for (unsigned i = 0; i < NumEntries; ++i) {
8124 uint32_t FunctionOffset = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8125 uint32_t Encoding = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8126
8127 outs() << " [" << i << "]: "
8128 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8129 << ", "
8130 << "encoding=" << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8131 }
8132}
8133
8134static void printCompressedSecondLevelUnwindPage(
8135 StringRef PageData, uint32_t FunctionBase,
8136 const SmallVectorImpl<uint32_t> &CommonEncodings) {
8137 ptrdiff_t Pos = 0;
8138 uint32_t Kind = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8139 (void)Kind;
8140 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8141
8142 uint32_t NumCommonEncodings = CommonEncodings.size();
8143 uint16_t EntriesStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8144 uint16_t NumEntries = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8145
8146 uint16_t PageEncodingsStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8147 uint16_t NumPageEncodings = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8148 SmallVector<uint32_t, 64> PageEncodings;
8149 if (NumPageEncodings) {
8150 outs() << " Page encodings: (count = " << NumPageEncodings << ")\n";
8151 Pos = PageEncodingsStart;
8152 for (unsigned i = 0; i < NumPageEncodings; ++i) {
8153 uint32_t Encoding = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8154 PageEncodings.push_back(Elt: Encoding);
8155 outs() << " encoding[" << (i + NumCommonEncodings)
8156 << "]: " << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8157 }
8158 }
8159
8160 Pos = EntriesStart;
8161 for (unsigned i = 0; i < NumEntries; ++i) {
8162 uint32_t Entry = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8163 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8164 uint32_t EncodingIdx = Entry >> 24;
8165
8166 uint32_t Encoding;
8167 if (EncodingIdx < NumCommonEncodings)
8168 Encoding = CommonEncodings[EncodingIdx];
8169 else
8170 Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
8171
8172 outs() << " [" << i << "]: "
8173 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8174 << ", "
8175 << "encoding[" << EncodingIdx
8176 << "]=" << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8177 }
8178}
8179
8180static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8181 std::map<uint64_t, SymbolRef> &Symbols,
8182 const SectionRef &UnwindInfo) {
8183
8184 if (!Obj->isLittleEndian()) {
8185 outs() << "Skipping big-endian __unwind_info section\n";
8186 return;
8187 }
8188
8189 outs() << "Contents of __unwind_info section:\n";
8190
8191 StringRef Contents =
8192 unwrapOrError(EO: UnwindInfo.getContents(), Args: Obj->getFileName());
8193 ptrdiff_t Pos = 0;
8194
8195 //===----------------------------------
8196 // Section header
8197 //===----------------------------------
8198
8199 uint32_t Version = readNext<uint32_t>(Contents, Offset&: Pos);
8200 outs() << " Version: "
8201 << format(Fmt: "0x%" PRIx32, Vals: Version) << '\n';
8202 if (Version != 1) {
8203 outs() << " Skipping section with unknown version\n";
8204 return;
8205 }
8206
8207 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Offset&: Pos);
8208 outs() << " Common encodings array section offset: "
8209 << format(Fmt: "0x%" PRIx32, Vals: CommonEncodingsStart) << '\n';
8210 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Offset&: Pos);
8211 outs() << " Number of common encodings in array: "
8212 << format(Fmt: "0x%" PRIx32, Vals: NumCommonEncodings) << '\n';
8213
8214 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Offset&: Pos);
8215 outs() << " Personality function array section offset: "
8216 << format(Fmt: "0x%" PRIx32, Vals: PersonalitiesStart) << '\n';
8217 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Offset&: Pos);
8218 outs() << " Number of personality functions in array: "
8219 << format(Fmt: "0x%" PRIx32, Vals: NumPersonalities) << '\n';
8220
8221 uint32_t IndicesStart = readNext<uint32_t>(Contents, Offset&: Pos);
8222 outs() << " Index array section offset: "
8223 << format(Fmt: "0x%" PRIx32, Vals: IndicesStart) << '\n';
8224 uint32_t NumIndices = readNext<uint32_t>(Contents, Offset&: Pos);
8225 outs() << " Number of indices in array: "
8226 << format(Fmt: "0x%" PRIx32, Vals: NumIndices) << '\n';
8227
8228 //===----------------------------------
8229 // A shared list of common encodings
8230 //===----------------------------------
8231
8232 // These occupy indices in the range [0, N] whenever an encoding is referenced
8233 // from a compressed 2nd level index table. In practice the linker only
8234 // creates ~128 of these, so that indices are available to embed encodings in
8235 // the 2nd level index.
8236
8237 SmallVector<uint32_t, 64> CommonEncodings;
8238 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
8239 Pos = CommonEncodingsStart;
8240 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8241 uint32_t Encoding = readNext<uint32_t>(Contents, Offset&: Pos);
8242 CommonEncodings.push_back(Elt: Encoding);
8243
8244 outs() << " encoding[" << i << "]: " << format(Fmt: "0x%08" PRIx32, Vals: Encoding)
8245 << '\n';
8246 }
8247
8248 //===----------------------------------
8249 // Personality functions used in this executable
8250 //===----------------------------------
8251
8252 // There should be only a handful of these (one per source language,
8253 // roughly). Particularly since they only get 2 bits in the compact encoding.
8254
8255 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
8256 Pos = PersonalitiesStart;
8257 for (unsigned i = 0; i < NumPersonalities; ++i) {
8258 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Offset&: Pos);
8259 outs() << " personality[" << i + 1
8260 << "]: " << format(Fmt: "0x%08" PRIx32, Vals: PersonalityFn) << '\n';
8261 }
8262
8263 //===----------------------------------
8264 // The level 1 index entries
8265 //===----------------------------------
8266
8267 // These specify an approximate place to start searching for the more detailed
8268 // information, sorted by PC.
8269
8270 struct IndexEntry {
8271 uint32_t FunctionOffset;
8272 uint32_t SecondLevelPageStart;
8273 uint32_t LSDAStart;
8274 };
8275
8276 SmallVector<IndexEntry, 4> IndexEntries;
8277
8278 outs() << " Top level indices: (count = " << NumIndices << ")\n";
8279 Pos = IndicesStart;
8280 for (unsigned i = 0; i < NumIndices; ++i) {
8281 IndexEntry Entry;
8282
8283 Entry.FunctionOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8284 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Offset&: Pos);
8285 Entry.LSDAStart = readNext<uint32_t>(Contents, Offset&: Pos);
8286 IndexEntries.push_back(Elt: Entry);
8287
8288 outs() << " [" << i << "]: "
8289 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: Entry.FunctionOffset)
8290 << ", "
8291 << "2nd level page offset="
8292 << format(Fmt: "0x%08" PRIx32, Vals: Entry.SecondLevelPageStart) << ", "
8293 << "LSDA offset=" << format(Fmt: "0x%08" PRIx32, Vals: Entry.LSDAStart) << '\n';
8294 }
8295
8296 //===----------------------------------
8297 // Next come the LSDA tables
8298 //===----------------------------------
8299
8300 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8301 // the first top-level index's LSDAOffset to the last (sentinel).
8302
8303 outs() << " LSDA descriptors:\n";
8304 Pos = IndexEntries[0].LSDAStart;
8305 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8306 int NumLSDAs =
8307 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8308
8309 for (int i = 0; i < NumLSDAs; ++i) {
8310 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8311 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8312 outs() << " [" << i << "]: "
8313 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8314 << ", "
8315 << "LSDA offset=" << format(Fmt: "0x%08" PRIx32, Vals: LSDAOffset) << '\n';
8316 }
8317
8318 //===----------------------------------
8319 // Finally, the 2nd level indices
8320 //===----------------------------------
8321
8322 // Generally these are 4K in size, and have 2 possible forms:
8323 // + Regular stores up to 511 entries with disparate encodings
8324 // + Compressed stores up to 1021 entries if few enough compact encoding
8325 // values are used.
8326 outs() << " Second level indices:\n";
8327 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8328 // The final sentinel top-level index has no associated 2nd level page
8329 if (IndexEntries[i].SecondLevelPageStart == 0)
8330 break;
8331
8332 outs() << " Second level index[" << i << "]: "
8333 << "offset in section="
8334 << format(Fmt: "0x%08" PRIx32, Vals: IndexEntries[i].SecondLevelPageStart)
8335 << ", "
8336 << "base function offset="
8337 << format(Fmt: "0x%08" PRIx32, Vals: IndexEntries[i].FunctionOffset) << '\n';
8338
8339 Pos = IndexEntries[i].SecondLevelPageStart;
8340 if (Pos + sizeof(uint32_t) > Contents.size()) {
8341 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8342 continue;
8343 }
8344
8345 uint32_t Kind =
8346 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8347 if (Kind == 2)
8348 printRegularSecondLevelUnwindPage(PageData: Contents.substr(Start: Pos, N: 4096));
8349 else if (Kind == 3)
8350 printCompressedSecondLevelUnwindPage(PageData: Contents.substr(Start: Pos, N: 4096),
8351 FunctionBase: IndexEntries[i].FunctionOffset,
8352 CommonEncodings);
8353 else
8354 outs() << " Skipping 2nd level page with unknown kind " << Kind
8355 << '\n';
8356 }
8357}
8358
8359void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8360 std::map<uint64_t, SymbolRef> Symbols;
8361 for (const SymbolRef &SymRef : Obj->symbols()) {
8362 // Discard any undefined or absolute symbols. They're not going to take part
8363 // in the convenience lookup for unwind info and just take up resources.
8364 auto SectOrErr = SymRef.getSection();
8365 if (!SectOrErr) {
8366 // TODO: Actually report errors helpfully.
8367 consumeError(Err: SectOrErr.takeError());
8368 continue;
8369 }
8370 section_iterator Section = *SectOrErr;
8371 if (Section == Obj->section_end())
8372 continue;
8373
8374 uint64_t Addr = cantFail(ValOrErr: SymRef.getValue());
8375 Symbols.insert(x: std::make_pair(x&: Addr, y: SymRef));
8376 }
8377
8378 for (const SectionRef &Section : Obj->sections()) {
8379 StringRef SectName;
8380 if (Expected<StringRef> NameOrErr = Section.getName())
8381 SectName = *NameOrErr;
8382 else
8383 consumeError(Err: NameOrErr.takeError());
8384
8385 if (SectName == "__compact_unwind")
8386 printMachOCompactUnwindSection(Obj, Symbols, CompactUnwind: Section);
8387 else if (SectName == "__unwind_info")
8388 printMachOUnwindInfoSection(Obj, Symbols, UnwindInfo: Section);
8389 }
8390}
8391
8392static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8393 uint32_t cpusubtype, uint32_t filetype,
8394 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8395 bool verbose) {
8396 outs() << "Mach header\n";
8397 outs() << " magic cputype cpusubtype caps filetype ncmds "
8398 "sizeofcmds flags\n";
8399 if (verbose) {
8400 if (magic == MachO::MH_MAGIC)
8401 outs() << " MH_MAGIC";
8402 else if (magic == MachO::MH_MAGIC_64)
8403 outs() << "MH_MAGIC_64";
8404 else
8405 outs() << format(Fmt: " 0x%08" PRIx32, Vals: magic);
8406 switch (cputype) {
8407 case MachO::CPU_TYPE_I386:
8408 outs() << " I386";
8409 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8410 case MachO::CPU_SUBTYPE_I386_ALL:
8411 outs() << " ALL";
8412 break;
8413 default:
8414 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8415 break;
8416 }
8417 break;
8418 case MachO::CPU_TYPE_X86_64:
8419 outs() << " X86_64";
8420 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8421 case MachO::CPU_SUBTYPE_X86_64_ALL:
8422 outs() << " ALL";
8423 break;
8424 case MachO::CPU_SUBTYPE_X86_64_H:
8425 outs() << " Haswell";
8426 break;
8427 default:
8428 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8429 break;
8430 }
8431 break;
8432 case MachO::CPU_TYPE_ARM:
8433 outs() << " ARM";
8434 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8435 case MachO::CPU_SUBTYPE_ARM_ALL:
8436 outs() << " ALL";
8437 break;
8438 case MachO::CPU_SUBTYPE_ARM_V4T:
8439 outs() << " V4T";
8440 break;
8441 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8442 outs() << " V5TEJ";
8443 break;
8444 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8445 outs() << " XSCALE";
8446 break;
8447 case MachO::CPU_SUBTYPE_ARM_V6:
8448 outs() << " V6";
8449 break;
8450 case MachO::CPU_SUBTYPE_ARM_V6M:
8451 outs() << " V6M";
8452 break;
8453 case MachO::CPU_SUBTYPE_ARM_V7:
8454 outs() << " V7";
8455 break;
8456 case MachO::CPU_SUBTYPE_ARM_V7EM:
8457 outs() << " V7EM";
8458 break;
8459 case MachO::CPU_SUBTYPE_ARM_V7K:
8460 outs() << " V7K";
8461 break;
8462 case MachO::CPU_SUBTYPE_ARM_V7M:
8463 outs() << " V7M";
8464 break;
8465 case MachO::CPU_SUBTYPE_ARM_V7S:
8466 outs() << " V7S";
8467 break;
8468 case MachO::CPU_SUBTYPE_ARM_V8M_MAIN:
8469 outs() << " V8M_MAIN";
8470 break;
8471 case MachO::CPU_SUBTYPE_ARM_V8M_BASE:
8472 outs() << " V8M_BASE";
8473 break;
8474 case MachO::CPU_SUBTYPE_ARM_V8_1M_MAIN:
8475 outs() << " V8_1M_MAIN";
8476 break;
8477 default:
8478 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8479 break;
8480 }
8481 break;
8482 case MachO::CPU_TYPE_ARM64:
8483 outs() << " ARM64";
8484 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8485 case MachO::CPU_SUBTYPE_ARM64_ALL:
8486 outs() << " ALL";
8487 break;
8488 case MachO::CPU_SUBTYPE_ARM64_V8:
8489 outs() << " V8";
8490 break;
8491 case MachO::CPU_SUBTYPE_ARM64E:
8492 outs() << " E";
8493 break;
8494 case MachO::CPU_SUBTYPE_ARM64E_X1:
8495 outs() << " E.X1";
8496 break;
8497 default:
8498 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8499 break;
8500 }
8501 break;
8502 case MachO::CPU_TYPE_ARM64_32:
8503 outs() << " ARM64_32";
8504 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8505 case MachO::CPU_SUBTYPE_ARM64_32_V8:
8506 outs() << " V8";
8507 break;
8508 default:
8509 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8510 break;
8511 }
8512 break;
8513 case MachO::CPU_TYPE_POWERPC:
8514 outs() << " PPC";
8515 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8516 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8517 outs() << " ALL";
8518 break;
8519 default:
8520 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8521 break;
8522 }
8523 break;
8524 case MachO::CPU_TYPE_POWERPC64:
8525 outs() << " PPC64";
8526 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8527 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8528 outs() << " ALL";
8529 break;
8530 default:
8531 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8532 break;
8533 }
8534 break;
8535 default:
8536 outs() << format(Fmt: " %7d", Vals: cputype);
8537 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8538 break;
8539 }
8540
8541 if (cputype == MachO::CPU_TYPE_ARM64 &&
8542 MachO::CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(ST: cpusubtype)) {
8543 const char *Format =
8544 MachO::CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(ST: cpusubtype)
8545 ? " PAK%02d"
8546 : " PAC%02d";
8547 outs() << format(Fmt: Format,
8548 Vals: MachO::CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(ST: cpusubtype));
8549 } else if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) ==
8550 MachO::CPU_SUBTYPE_LIB64) {
8551 outs() << " LIB64";
8552 } else {
8553 outs() << format(Fmt: " 0x%02" PRIx32,
8554 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8555 }
8556 switch (filetype) {
8557 case MachO::MH_OBJECT:
8558 outs() << " OBJECT";
8559 break;
8560 case MachO::MH_EXECUTE:
8561 outs() << " EXECUTE";
8562 break;
8563 case MachO::MH_FVMLIB:
8564 outs() << " FVMLIB";
8565 break;
8566 case MachO::MH_CORE:
8567 outs() << " CORE";
8568 break;
8569 case MachO::MH_PRELOAD:
8570 outs() << " PRELOAD";
8571 break;
8572 case MachO::MH_DYLIB:
8573 outs() << " DYLIB";
8574 break;
8575 case MachO::MH_DYLIB_STUB:
8576 outs() << " DYLIB_STUB";
8577 break;
8578 case MachO::MH_DYLINKER:
8579 outs() << " DYLINKER";
8580 break;
8581 case MachO::MH_BUNDLE:
8582 outs() << " BUNDLE";
8583 break;
8584 case MachO::MH_DSYM:
8585 outs() << " DSYM";
8586 break;
8587 case MachO::MH_KEXT_BUNDLE:
8588 outs() << " KEXTBUNDLE";
8589 break;
8590 case MachO::MH_FILESET:
8591 outs() << " FILESET";
8592 break;
8593 default:
8594 outs() << format(Fmt: " %10u", Vals: filetype);
8595 break;
8596 }
8597 outs() << format(Fmt: " %5u", Vals: ncmds);
8598 outs() << format(Fmt: " %10u", Vals: sizeofcmds);
8599 uint32_t f = flags;
8600 if (f & MachO::MH_NOUNDEFS) {
8601 outs() << " NOUNDEFS";
8602 f &= ~MachO::MH_NOUNDEFS;
8603 }
8604 if (f & MachO::MH_INCRLINK) {
8605 outs() << " INCRLINK";
8606 f &= ~MachO::MH_INCRLINK;
8607 }
8608 if (f & MachO::MH_DYLDLINK) {
8609 outs() << " DYLDLINK";
8610 f &= ~MachO::MH_DYLDLINK;
8611 }
8612 if (f & MachO::MH_BINDATLOAD) {
8613 outs() << " BINDATLOAD";
8614 f &= ~MachO::MH_BINDATLOAD;
8615 }
8616 if (f & MachO::MH_PREBOUND) {
8617 outs() << " PREBOUND";
8618 f &= ~MachO::MH_PREBOUND;
8619 }
8620 if (f & MachO::MH_SPLIT_SEGS) {
8621 outs() << " SPLIT_SEGS";
8622 f &= ~MachO::MH_SPLIT_SEGS;
8623 }
8624 if (f & MachO::MH_LAZY_INIT) {
8625 outs() << " LAZY_INIT";
8626 f &= ~MachO::MH_LAZY_INIT;
8627 }
8628 if (f & MachO::MH_TWOLEVEL) {
8629 outs() << " TWOLEVEL";
8630 f &= ~MachO::MH_TWOLEVEL;
8631 }
8632 if (f & MachO::MH_FORCE_FLAT) {
8633 outs() << " FORCE_FLAT";
8634 f &= ~MachO::MH_FORCE_FLAT;
8635 }
8636 if (f & MachO::MH_NOMULTIDEFS) {
8637 outs() << " NOMULTIDEFS";
8638 f &= ~MachO::MH_NOMULTIDEFS;
8639 }
8640 if (f & MachO::MH_NOFIXPREBINDING) {
8641 outs() << " NOFIXPREBINDING";
8642 f &= ~MachO::MH_NOFIXPREBINDING;
8643 }
8644 if (f & MachO::MH_PREBINDABLE) {
8645 outs() << " PREBINDABLE";
8646 f &= ~MachO::MH_PREBINDABLE;
8647 }
8648 if (f & MachO::MH_ALLMODSBOUND) {
8649 outs() << " ALLMODSBOUND";
8650 f &= ~MachO::MH_ALLMODSBOUND;
8651 }
8652 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8653 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8654 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8655 }
8656 if (f & MachO::MH_CANONICAL) {
8657 outs() << " CANONICAL";
8658 f &= ~MachO::MH_CANONICAL;
8659 }
8660 if (f & MachO::MH_WEAK_DEFINES) {
8661 outs() << " WEAK_DEFINES";
8662 f &= ~MachO::MH_WEAK_DEFINES;
8663 }
8664 if (f & MachO::MH_BINDS_TO_WEAK) {
8665 outs() << " BINDS_TO_WEAK";
8666 f &= ~MachO::MH_BINDS_TO_WEAK;
8667 }
8668 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8669 outs() << " ALLOW_STACK_EXECUTION";
8670 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8671 }
8672 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8673 outs() << " DEAD_STRIPPABLE_DYLIB";
8674 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8675 }
8676 if (f & MachO::MH_PIE) {
8677 outs() << " PIE";
8678 f &= ~MachO::MH_PIE;
8679 }
8680 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8681 outs() << " NO_REEXPORTED_DYLIBS";
8682 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8683 }
8684 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8685 outs() << " MH_HAS_TLV_DESCRIPTORS";
8686 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8687 }
8688 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8689 outs() << " MH_NO_HEAP_EXECUTION";
8690 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8691 }
8692 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8693 outs() << " APP_EXTENSION_SAFE";
8694 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8695 }
8696 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8697 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8698 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8699 }
8700 if (f != 0 || flags == 0)
8701 outs() << format(Fmt: " 0x%08" PRIx32, Vals: f);
8702 } else {
8703 outs() << format(Fmt: " 0x%08" PRIx32, Vals: magic);
8704 outs() << format(Fmt: " %7d", Vals: cputype);
8705 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8706 outs() << format(Fmt: " 0x%02" PRIx32,
8707 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8708 outs() << format(Fmt: " %10u", Vals: filetype);
8709 outs() << format(Fmt: " %5u", Vals: ncmds);
8710 outs() << format(Fmt: " %10u", Vals: sizeofcmds);
8711 outs() << format(Fmt: " 0x%08" PRIx32, Vals: flags);
8712 }
8713 outs() << "\n";
8714}
8715
8716static void PrintLoadCommand(uint32_t Cmd, uint32_t CmdSize, bool IsSizeCorrect,
8717 unsigned LabelWidth) {
8718 outs() << right_justify(Str: "cmd", Width: LabelWidth) << ' ';
8719 switch (Cmd) {
8720#define HANDLE_LOAD_COMMAND(Name, Value, Struct) \
8721 case MachO::Name: \
8722 outs() << #Name; \
8723 break;
8724#include "llvm/BinaryFormat/MachO.def"
8725 default:
8726 outs() << format(Fmt: "?(0x%08" PRIx32 ")", Vals: Cmd);
8727 }
8728 outs() << '\n'
8729 << right_justify(Str: "cmdsize", Width: LabelWidth) << ' ' << CmdSize
8730 << (IsSizeCorrect ? "\n" : " Incorrect size\n");
8731}
8732
8733static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8734 StringRef SegName, uint64_t vmaddr,
8735 uint64_t vmsize, uint64_t fileoff,
8736 uint64_t filesize, uint32_t maxprot,
8737 uint32_t initprot, uint32_t nsects,
8738 uint32_t flags, uint32_t object_size,
8739 bool verbose) {
8740 uint64_t expected_cmdsize;
8741 if (cmd == MachO::LC_SEGMENT) {
8742 expected_cmdsize = nsects;
8743 expected_cmdsize *= sizeof(struct MachO::section);
8744 expected_cmdsize += sizeof(struct MachO::segment_command);
8745 } else {
8746 expected_cmdsize = nsects;
8747 expected_cmdsize *= sizeof(struct MachO::section_64);
8748 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8749 }
8750 PrintLoadCommand(Cmd: cmd, CmdSize: cmdsize, IsSizeCorrect: cmdsize == expected_cmdsize,
8751 /*LabelWidth=*/9);
8752 outs() << " segname " << SegName << "\n";
8753 if (cmd == MachO::LC_SEGMENT_64) {
8754 outs() << " vmaddr " << format(Fmt: "0x%016" PRIx64, Vals: vmaddr) << "\n";
8755 outs() << " vmsize " << format(Fmt: "0x%016" PRIx64, Vals: vmsize) << "\n";
8756 } else {
8757 outs() << " vmaddr " << format(Fmt: "0x%08" PRIx64, Vals: vmaddr) << "\n";
8758 outs() << " vmsize " << format(Fmt: "0x%08" PRIx64, Vals: vmsize) << "\n";
8759 }
8760 outs() << " fileoff " << fileoff;
8761 if (fileoff > object_size)
8762 outs() << " (past end of file)\n";
8763 else
8764 outs() << "\n";
8765 outs() << " filesize " << filesize;
8766 if (fileoff + filesize > object_size)
8767 outs() << " (past end of file)\n";
8768 else
8769 outs() << "\n";
8770 if (verbose) {
8771 if ((maxprot &
8772 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8773 MachO::VM_PROT_EXECUTE)) != 0)
8774 outs() << " maxprot ?" << format(Fmt: "0x%08" PRIx32, Vals: maxprot) << "\n";
8775 else {
8776 outs() << " maxprot ";
8777 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8778 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8779 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8780 }
8781 if ((initprot &
8782 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8783 MachO::VM_PROT_EXECUTE)) != 0)
8784 outs() << " initprot ?" << format(Fmt: "0x%08" PRIx32, Vals: initprot) << "\n";
8785 else {
8786 outs() << " initprot ";
8787 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8788 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8789 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8790 }
8791 } else {
8792 outs() << " maxprot " << format(Fmt: "0x%08" PRIx32, Vals: maxprot) << "\n";
8793 outs() << " initprot " << format(Fmt: "0x%08" PRIx32, Vals: initprot) << "\n";
8794 }
8795 outs() << " nsects " << nsects << "\n";
8796 if (verbose) {
8797 outs() << " flags";
8798 if (flags == 0)
8799 outs() << " (none)\n";
8800 else {
8801 if (flags & MachO::SG_HIGHVM) {
8802 outs() << " HIGHVM";
8803 flags &= ~MachO::SG_HIGHVM;
8804 }
8805 if (flags & MachO::SG_FVMLIB) {
8806 outs() << " FVMLIB";
8807 flags &= ~MachO::SG_FVMLIB;
8808 }
8809 if (flags & MachO::SG_NORELOC) {
8810 outs() << " NORELOC";
8811 flags &= ~MachO::SG_NORELOC;
8812 }
8813 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8814 outs() << " PROTECTED_VERSION_1";
8815 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8816 }
8817 if (flags & MachO::SG_READ_ONLY) {
8818 // Apple's otool prints the SG_ prefix for this flag, but not for the
8819 // others.
8820 outs() << " SG_READ_ONLY";
8821 flags &= ~MachO::SG_READ_ONLY;
8822 }
8823 if (flags)
8824 outs() << format(Fmt: " 0x%08" PRIx32, Vals: flags) << " (unknown flags)\n";
8825 else
8826 outs() << "\n";
8827 }
8828 } else {
8829 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: flags) << "\n";
8830 }
8831}
8832
8833static void PrintSection(const char *sectname, const char *segname,
8834 uint64_t addr, uint64_t size, uint32_t offset,
8835 uint32_t align, uint32_t reloff, uint32_t nreloc,
8836 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8837 uint32_t cmd, const char *sg_segname,
8838 uint32_t filetype, uint32_t object_size,
8839 bool verbose) {
8840 outs() << "Section\n";
8841 outs() << " sectname " << format(Fmt: "%.16s\n", Vals: sectname);
8842 outs() << " segname " << format(Fmt: "%.16s", Vals: segname);
8843 if (filetype != MachO::MH_OBJECT && strncmp(s1: sg_segname, s2: segname, n: 16) != 0)
8844 outs() << " (does not match segment)\n";
8845 else
8846 outs() << "\n";
8847 if (cmd == MachO::LC_SEGMENT_64) {
8848 outs() << " addr " << format(Fmt: "0x%016" PRIx64, Vals: addr) << "\n";
8849 outs() << " size " << format(Fmt: "0x%016" PRIx64, Vals: size);
8850 } else {
8851 outs() << " addr " << format(Fmt: "0x%08" PRIx64, Vals: addr) << "\n";
8852 outs() << " size " << format(Fmt: "0x%08" PRIx64, Vals: size);
8853 }
8854 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8855 outs() << " (past end of file)\n";
8856 else
8857 outs() << "\n";
8858 outs() << " offset " << offset;
8859 if (offset > object_size)
8860 outs() << " (past end of file)\n";
8861 else
8862 outs() << "\n";
8863 uint32_t align_shifted = 1 << align;
8864 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8865 outs() << " reloff " << reloff;
8866 if (reloff > object_size)
8867 outs() << " (past end of file)\n";
8868 else
8869 outs() << "\n";
8870 outs() << " nreloc " << nreloc;
8871 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8872 outs() << " (past end of file)\n";
8873 else
8874 outs() << "\n";
8875 uint32_t section_type = flags & MachO::SECTION_TYPE;
8876 if (verbose) {
8877 outs() << " type";
8878 if (section_type == MachO::S_REGULAR)
8879 outs() << " S_REGULAR\n";
8880 else if (section_type == MachO::S_ZEROFILL)
8881 outs() << " S_ZEROFILL\n";
8882 else if (section_type == MachO::S_CSTRING_LITERALS)
8883 outs() << " S_CSTRING_LITERALS\n";
8884 else if (section_type == MachO::S_4BYTE_LITERALS)
8885 outs() << " S_4BYTE_LITERALS\n";
8886 else if (section_type == MachO::S_8BYTE_LITERALS)
8887 outs() << " S_8BYTE_LITERALS\n";
8888 else if (section_type == MachO::S_16BYTE_LITERALS)
8889 outs() << " S_16BYTE_LITERALS\n";
8890 else if (section_type == MachO::S_LITERAL_POINTERS)
8891 outs() << " S_LITERAL_POINTERS\n";
8892 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8893 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8894 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8895 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8896 else if (section_type == MachO::S_SYMBOL_STUBS)
8897 outs() << " S_SYMBOL_STUBS\n";
8898 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8899 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8900 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8901 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8902 else if (section_type == MachO::S_COALESCED)
8903 outs() << " S_COALESCED\n";
8904 else if (section_type == MachO::S_INTERPOSING)
8905 outs() << " S_INTERPOSING\n";
8906 else if (section_type == MachO::S_DTRACE_DOF)
8907 outs() << " S_DTRACE_DOF\n";
8908 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8909 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8910 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8911 outs() << " S_THREAD_LOCAL_REGULAR\n";
8912 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8913 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8914 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8915 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8916 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8917 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8918 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8919 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8920 else if (section_type == MachO::S_INIT_FUNC_OFFSETS)
8921 outs() << " S_INIT_FUNC_OFFSETS\n";
8922 else
8923 outs() << format(Fmt: "0x%08" PRIx32, Vals: section_type) << "\n";
8924 outs() << "attributes";
8925 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8926 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8927 outs() << " PURE_INSTRUCTIONS";
8928 if (section_attributes & MachO::S_ATTR_NO_TOC)
8929 outs() << " NO_TOC";
8930 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8931 outs() << " STRIP_STATIC_SYMS";
8932 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8933 outs() << " NO_DEAD_STRIP";
8934 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8935 outs() << " LIVE_SUPPORT";
8936 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8937 outs() << " SELF_MODIFYING_CODE";
8938 if (section_attributes & MachO::S_ATTR_DEBUG)
8939 outs() << " DEBUG";
8940 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8941 outs() << " SOME_INSTRUCTIONS";
8942 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8943 outs() << " EXT_RELOC";
8944 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8945 outs() << " LOC_RELOC";
8946 if (section_attributes == 0)
8947 outs() << " (none)";
8948 outs() << "\n";
8949 } else
8950 outs() << " flags " << format(Fmt: "0x%08" PRIx32, Vals: flags) << "\n";
8951 outs() << " reserved1 " << reserved1;
8952 if (section_type == MachO::S_SYMBOL_STUBS ||
8953 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8954 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8955 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8956 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8957 outs() << " (index into indirect symbol table)\n";
8958 else
8959 outs() << "\n";
8960 outs() << " reserved2 " << reserved2;
8961 if (section_type == MachO::S_SYMBOL_STUBS)
8962 outs() << " (size of stubs)\n";
8963 else
8964 outs() << "\n";
8965}
8966
8967static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8968 uint32_t object_size) {
8969 PrintLoadCommand(Cmd: st.cmd, CmdSize: st.cmdsize,
8970 IsSizeCorrect: st.cmdsize == sizeof(struct MachO::symtab_command),
8971 /*LabelWidth=*/8);
8972 outs() << " symoff " << st.symoff;
8973 if (st.symoff > object_size)
8974 outs() << " (past end of file)\n";
8975 else
8976 outs() << "\n";
8977 outs() << " nsyms " << st.nsyms;
8978 uint64_t big_size;
8979 if (Is64Bit) {
8980 big_size = st.nsyms;
8981 big_size *= sizeof(struct MachO::nlist_64);
8982 big_size += st.symoff;
8983 if (big_size > object_size)
8984 outs() << " (past end of file)\n";
8985 else
8986 outs() << "\n";
8987 } else {
8988 big_size = st.nsyms;
8989 big_size *= sizeof(struct MachO::nlist);
8990 big_size += st.symoff;
8991 if (big_size > object_size)
8992 outs() << " (past end of file)\n";
8993 else
8994 outs() << "\n";
8995 }
8996 outs() << " stroff " << st.stroff;
8997 if (st.stroff > object_size)
8998 outs() << " (past end of file)\n";
8999 else
9000 outs() << "\n";
9001 outs() << " strsize " << st.strsize;
9002 big_size = st.stroff;
9003 big_size += st.strsize;
9004 if (big_size > object_size)
9005 outs() << " (past end of file)\n";
9006 else
9007 outs() << "\n";
9008}
9009
9010static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
9011 uint32_t nsyms, uint32_t object_size,
9012 bool Is64Bit) {
9013 PrintLoadCommand(Cmd: dyst.cmd, CmdSize: dyst.cmdsize,
9014 IsSizeCorrect: dyst.cmdsize == sizeof(struct MachO::dysymtab_command),
9015 /*LabelWidth=*/15);
9016 outs() << " ilocalsym " << dyst.ilocalsym;
9017 if (dyst.ilocalsym > nsyms)
9018 outs() << " (greater than the number of symbols)\n";
9019 else
9020 outs() << "\n";
9021 outs() << " nlocalsym " << dyst.nlocalsym;
9022 uint64_t big_size;
9023 big_size = dyst.ilocalsym;
9024 big_size += dyst.nlocalsym;
9025 if (big_size > nsyms)
9026 outs() << " (past the end of the symbol table)\n";
9027 else
9028 outs() << "\n";
9029 outs() << " iextdefsym " << dyst.iextdefsym;
9030 if (dyst.iextdefsym > nsyms)
9031 outs() << " (greater than the number of symbols)\n";
9032 else
9033 outs() << "\n";
9034 outs() << " nextdefsym " << dyst.nextdefsym;
9035 big_size = dyst.iextdefsym;
9036 big_size += dyst.nextdefsym;
9037 if (big_size > nsyms)
9038 outs() << " (past the end of the symbol table)\n";
9039 else
9040 outs() << "\n";
9041 outs() << " iundefsym " << dyst.iundefsym;
9042 if (dyst.iundefsym > nsyms)
9043 outs() << " (greater than the number of symbols)\n";
9044 else
9045 outs() << "\n";
9046 outs() << " nundefsym " << dyst.nundefsym;
9047 big_size = dyst.iundefsym;
9048 big_size += dyst.nundefsym;
9049 if (big_size > nsyms)
9050 outs() << " (past the end of the symbol table)\n";
9051 else
9052 outs() << "\n";
9053 outs() << " tocoff " << dyst.tocoff;
9054 if (dyst.tocoff > object_size)
9055 outs() << " (past end of file)\n";
9056 else
9057 outs() << "\n";
9058 outs() << " ntoc " << dyst.ntoc;
9059 big_size = dyst.ntoc;
9060 big_size *= sizeof(struct MachO::dylib_table_of_contents);
9061 big_size += dyst.tocoff;
9062 if (big_size > object_size)
9063 outs() << " (past end of file)\n";
9064 else
9065 outs() << "\n";
9066 outs() << " modtaboff " << dyst.modtaboff;
9067 if (dyst.modtaboff > object_size)
9068 outs() << " (past end of file)\n";
9069 else
9070 outs() << "\n";
9071 outs() << " nmodtab " << dyst.nmodtab;
9072 uint64_t modtabend;
9073 if (Is64Bit) {
9074 modtabend = dyst.nmodtab;
9075 modtabend *= sizeof(struct MachO::dylib_module_64);
9076 modtabend += dyst.modtaboff;
9077 } else {
9078 modtabend = dyst.nmodtab;
9079 modtabend *= sizeof(struct MachO::dylib_module);
9080 modtabend += dyst.modtaboff;
9081 }
9082 if (modtabend > object_size)
9083 outs() << " (past end of file)\n";
9084 else
9085 outs() << "\n";
9086 outs() << " extrefsymoff " << dyst.extrefsymoff;
9087 if (dyst.extrefsymoff > object_size)
9088 outs() << " (past end of file)\n";
9089 else
9090 outs() << "\n";
9091 outs() << " nextrefsyms " << dyst.nextrefsyms;
9092 big_size = dyst.nextrefsyms;
9093 big_size *= sizeof(struct MachO::dylib_reference);
9094 big_size += dyst.extrefsymoff;
9095 if (big_size > object_size)
9096 outs() << " (past end of file)\n";
9097 else
9098 outs() << "\n";
9099 outs() << " indirectsymoff " << dyst.indirectsymoff;
9100 if (dyst.indirectsymoff > object_size)
9101 outs() << " (past end of file)\n";
9102 else
9103 outs() << "\n";
9104 outs() << " nindirectsyms " << dyst.nindirectsyms;
9105 big_size = dyst.nindirectsyms;
9106 big_size *= sizeof(uint32_t);
9107 big_size += dyst.indirectsymoff;
9108 if (big_size > object_size)
9109 outs() << " (past end of file)\n";
9110 else
9111 outs() << "\n";
9112 outs() << " extreloff " << dyst.extreloff;
9113 if (dyst.extreloff > object_size)
9114 outs() << " (past end of file)\n";
9115 else
9116 outs() << "\n";
9117 outs() << " nextrel " << dyst.nextrel;
9118 big_size = dyst.nextrel;
9119 big_size *= sizeof(struct MachO::relocation_info);
9120 big_size += dyst.extreloff;
9121 if (big_size > object_size)
9122 outs() << " (past end of file)\n";
9123 else
9124 outs() << "\n";
9125 outs() << " locreloff " << dyst.locreloff;
9126 if (dyst.locreloff > object_size)
9127 outs() << " (past end of file)\n";
9128 else
9129 outs() << "\n";
9130 outs() << " nlocrel " << dyst.nlocrel;
9131 big_size = dyst.nlocrel;
9132 big_size *= sizeof(struct MachO::relocation_info);
9133 big_size += dyst.locreloff;
9134 if (big_size > object_size)
9135 outs() << " (past end of file)\n";
9136 else
9137 outs() << "\n";
9138}
9139
9140static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
9141 uint32_t object_size) {
9142 PrintLoadCommand(Cmd: dc.cmd, CmdSize: dc.cmdsize,
9143 IsSizeCorrect: dc.cmdsize == sizeof(struct MachO::dyld_info_command),
9144 /*LabelWidth=*/15);
9145 outs() << " rebase_off " << dc.rebase_off;
9146 if (dc.rebase_off > object_size)
9147 outs() << " (past end of file)\n";
9148 else
9149 outs() << "\n";
9150 outs() << " rebase_size " << dc.rebase_size;
9151 uint64_t big_size;
9152 big_size = dc.rebase_off;
9153 big_size += dc.rebase_size;
9154 if (big_size > object_size)
9155 outs() << " (past end of file)\n";
9156 else
9157 outs() << "\n";
9158 outs() << " bind_off " << dc.bind_off;
9159 if (dc.bind_off > object_size)
9160 outs() << " (past end of file)\n";
9161 else
9162 outs() << "\n";
9163 outs() << " bind_size " << dc.bind_size;
9164 big_size = dc.bind_off;
9165 big_size += dc.bind_size;
9166 if (big_size > object_size)
9167 outs() << " (past end of file)\n";
9168 else
9169 outs() << "\n";
9170 outs() << " weak_bind_off " << dc.weak_bind_off;
9171 if (dc.weak_bind_off > object_size)
9172 outs() << " (past end of file)\n";
9173 else
9174 outs() << "\n";
9175 outs() << " weak_bind_size " << dc.weak_bind_size;
9176 big_size = dc.weak_bind_off;
9177 big_size += dc.weak_bind_size;
9178 if (big_size > object_size)
9179 outs() << " (past end of file)\n";
9180 else
9181 outs() << "\n";
9182 outs() << " lazy_bind_off " << dc.lazy_bind_off;
9183 if (dc.lazy_bind_off > object_size)
9184 outs() << " (past end of file)\n";
9185 else
9186 outs() << "\n";
9187 outs() << " lazy_bind_size " << dc.lazy_bind_size;
9188 big_size = dc.lazy_bind_off;
9189 big_size += dc.lazy_bind_size;
9190 if (big_size > object_size)
9191 outs() << " (past end of file)\n";
9192 else
9193 outs() << "\n";
9194 outs() << " export_off " << dc.export_off;
9195 if (dc.export_off > object_size)
9196 outs() << " (past end of file)\n";
9197 else
9198 outs() << "\n";
9199 outs() << " export_size " << dc.export_size;
9200 big_size = dc.export_off;
9201 big_size += dc.export_size;
9202 if (big_size > object_size)
9203 outs() << " (past end of file)\n";
9204 else
9205 outs() << "\n";
9206}
9207
9208static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9209 const char *Ptr) {
9210 PrintLoadCommand(Cmd: dyld.cmd, CmdSize: dyld.cmdsize,
9211 IsSizeCorrect: dyld.cmdsize >= sizeof(struct MachO::dylinker_command),
9212 /*LabelWidth=*/13);
9213 if (dyld.name >= dyld.cmdsize)
9214 outs() << " name ?(bad offset " << dyld.name << ")\n";
9215 else {
9216 const char *P = Ptr + dyld.name;
9217 outs() << " name " << P << " (offset " << dyld.name << ")\n";
9218 }
9219}
9220
9221static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9222 PrintLoadCommand(Cmd: uuid.cmd, CmdSize: uuid.cmdsize,
9223 IsSizeCorrect: uuid.cmdsize == sizeof(struct MachO::uuid_command),
9224 /*LabelWidth=*/8);
9225 outs() << " uuid ";
9226 for (int i = 0; i < 16; ++i) {
9227 outs() << format(Fmt: "%02" PRIX32, Vals: uuid.uuid[i]);
9228 if (i == 3 || i == 5 || i == 7 || i == 9)
9229 outs() << "-";
9230 }
9231 outs() << "\n";
9232}
9233
9234static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9235 PrintLoadCommand(Cmd: rpath.cmd, CmdSize: rpath.cmdsize,
9236 IsSizeCorrect: rpath.cmdsize >= sizeof(struct MachO::rpath_command),
9237 /*LabelWidth=*/13);
9238 if (rpath.path >= rpath.cmdsize)
9239 outs() << " path ?(bad offset " << rpath.path << ")\n";
9240 else {
9241 const char *P = Ptr + rpath.path;
9242 outs() << " path " << P << " (offset " << rpath.path << ")\n";
9243 }
9244}
9245
9246static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9247 PrintLoadCommand(Cmd: vd.cmd, CmdSize: vd.cmdsize,
9248 IsSizeCorrect: vd.cmdsize == sizeof(struct MachO::version_min_command),
9249 /*LabelWidth=*/9);
9250 outs() << " version "
9251 << MachOObjectFile::getVersionMinMajor(C&: vd, SDK: false) << "."
9252 << MachOObjectFile::getVersionMinMinor(C&: vd, SDK: false);
9253 uint32_t Update = MachOObjectFile::getVersionMinUpdate(C&: vd, SDK: false);
9254 if (Update != 0)
9255 outs() << "." << Update;
9256 outs() << "\n";
9257 if (vd.sdk == 0)
9258 outs() << " sdk n/a";
9259 else {
9260 outs() << " sdk "
9261 << MachOObjectFile::getVersionMinMajor(C&: vd, SDK: true) << "."
9262 << MachOObjectFile::getVersionMinMinor(C&: vd, SDK: true);
9263 }
9264 Update = MachOObjectFile::getVersionMinUpdate(C&: vd, SDK: true);
9265 if (Update != 0)
9266 outs() << "." << Update;
9267 outs() << "\n";
9268}
9269
9270static void PrintNoteLoadCommand(MachO::note_command Nt) {
9271 PrintLoadCommand(Cmd: Nt.cmd, CmdSize: Nt.cmdsize,
9272 IsSizeCorrect: Nt.cmdsize == sizeof(struct MachO::note_command),
9273 /*LabelWidth=*/10);
9274 const char *d = Nt.data_owner;
9275 outs() << "data_owner " << format(Fmt: "%.16s\n", Vals: d);
9276 outs() << " offset " << Nt.offset << "\n";
9277 outs() << " size " << Nt.size << "\n";
9278}
9279
9280static void PrintBuildToolVersion(MachO::build_tool_version bv, bool verbose) {
9281 outs() << " tool ";
9282 if (verbose)
9283 outs() << MachOObjectFile::getBuildTool(tools: bv.tool);
9284 else
9285 outs() << bv.tool;
9286 outs() << "\n";
9287 outs() << " version " << MachOObjectFile::getVersionString(version: bv.version)
9288 << "\n";
9289}
9290
9291static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9292 MachO::build_version_command bd,
9293 bool verbose) {
9294 PrintLoadCommand(Cmd: bd.cmd, CmdSize: bd.cmdsize,
9295 IsSizeCorrect: bd.cmdsize ==
9296 sizeof(struct MachO::build_version_command) +
9297 bd.ntools * sizeof(struct MachO::build_tool_version),
9298 /*LabelWidth=*/10);
9299 outs() << " platform ";
9300 if (verbose)
9301 outs() << MachOObjectFile::getBuildPlatform(platform: bd.platform);
9302 else
9303 outs() << bd.platform;
9304 outs() << "\n";
9305 if (bd.sdk)
9306 outs() << " sdk " << MachOObjectFile::getVersionString(version: bd.sdk)
9307 << "\n";
9308 else
9309 outs() << " sdk n/a\n";
9310 outs() << " minos " << MachOObjectFile::getVersionString(version: bd.minos)
9311 << "\n";
9312 outs() << " ntools " << bd.ntools << "\n";
9313 for (unsigned i = 0; i < bd.ntools; ++i) {
9314 MachO::build_tool_version bv = obj->getBuildToolVersion(index: i);
9315 PrintBuildToolVersion(bv, verbose);
9316 }
9317}
9318
9319static void PrintTargetTripleCommand(MachO::target_triple_command tt,
9320 const char *Ptr) {
9321 PrintLoadCommand(Cmd: tt.cmd, CmdSize: tt.cmdsize,
9322 IsSizeCorrect: tt.cmdsize >= sizeof(struct MachO::target_triple_command),
9323 /*LabelWidth=*/8);
9324 if (tt.triple < tt.cmdsize) {
9325 const char *P = Ptr + tt.triple;
9326 outs() << " triple " << P << " (offset " << tt.triple << ")\n";
9327 } else {
9328 outs() << " triple ?(bad offset " << tt.triple << ")\n";
9329 }
9330}
9331
9332static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9333 PrintLoadCommand(Cmd: sd.cmd, CmdSize: sd.cmdsize,
9334 IsSizeCorrect: sd.cmdsize == sizeof(struct MachO::source_version_command),
9335 /*LabelWidth=*/9);
9336 uint64_t a = (sd.version >> 40) & 0xffffff;
9337 uint64_t b = (sd.version >> 30) & 0x3ff;
9338 uint64_t c = (sd.version >> 20) & 0x3ff;
9339 uint64_t d = (sd.version >> 10) & 0x3ff;
9340 uint64_t e = sd.version & 0x3ff;
9341 outs() << " version " << a << "." << b;
9342 if (e != 0)
9343 outs() << "." << c << "." << d << "." << e;
9344 else if (d != 0)
9345 outs() << "." << c << "." << d;
9346 else if (c != 0)
9347 outs() << "." << c;
9348 outs() << "\n";
9349}
9350
9351static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9352 PrintLoadCommand(Cmd: ep.cmd, CmdSize: ep.cmdsize,
9353 IsSizeCorrect: ep.cmdsize == sizeof(struct MachO::entry_point_command),
9354 /*LabelWidth=*/10);
9355 outs() << " entryoff " << ep.entryoff << "\n";
9356 outs() << " stacksize " << ep.stacksize << "\n";
9357}
9358
9359static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9360 uint32_t object_size) {
9361 PrintLoadCommand(Cmd: ec.cmd, CmdSize: ec.cmdsize,
9362 IsSizeCorrect: ec.cmdsize == sizeof(struct MachO::encryption_info_command),
9363 /*LabelWidth=*/13);
9364 outs() << " cryptoff " << ec.cryptoff;
9365 if (ec.cryptoff > object_size)
9366 outs() << " (past end of file)\n";
9367 else
9368 outs() << "\n";
9369 outs() << " cryptsize " << ec.cryptsize;
9370 if (ec.cryptsize > object_size)
9371 outs() << " (past end of file)\n";
9372 else
9373 outs() << "\n";
9374 outs() << " cryptid " << ec.cryptid << "\n";
9375}
9376
9377static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9378 uint32_t object_size) {
9379 PrintLoadCommand(Cmd: ec.cmd, CmdSize: ec.cmdsize,
9380 IsSizeCorrect: ec.cmdsize ==
9381 sizeof(struct MachO::encryption_info_command_64),
9382 /*LabelWidth=*/13);
9383 outs() << " cryptoff " << ec.cryptoff;
9384 if (ec.cryptoff > object_size)
9385 outs() << " (past end of file)\n";
9386 else
9387 outs() << "\n";
9388 outs() << " cryptsize " << ec.cryptsize;
9389 if (ec.cryptsize > object_size)
9390 outs() << " (past end of file)\n";
9391 else
9392 outs() << "\n";
9393 outs() << " cryptid " << ec.cryptid << "\n";
9394 outs() << " pad " << ec.pad << "\n";
9395}
9396
9397static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9398 const char *Ptr) {
9399 PrintLoadCommand(Cmd: lo.cmd, CmdSize: lo.cmdsize,
9400 IsSizeCorrect: lo.cmdsize >= sizeof(struct MachO::linker_option_command),
9401 /*LabelWidth=*/8);
9402 outs() << " count " << lo.count << "\n";
9403 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9404 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9405 uint32_t i = 0;
9406 while (left > 0) {
9407 while (*string == '\0' && left > 0) {
9408 string++;
9409 left--;
9410 }
9411 if (left > 0) {
9412 i++;
9413 outs() << " string #" << i << " " << format(Fmt: "%.*s\n", Vals: left, Vals: string);
9414 uint32_t NullPos = StringRef(string, left).find(C: '\0');
9415 uint32_t len = std::min(a: NullPos, b: left) + 1;
9416 string += len;
9417 left -= len;
9418 }
9419 }
9420 if (lo.count != i)
9421 outs() << " count " << lo.count << " does not match number of strings "
9422 << i << "\n";
9423}
9424
9425static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9426 const char *Ptr) {
9427 PrintLoadCommand(Cmd: sub.cmd, CmdSize: sub.cmdsize,
9428 IsSizeCorrect: sub.cmdsize >= sizeof(struct MachO::sub_framework_command),
9429 /*LabelWidth=*/13);
9430 if (sub.umbrella < sub.cmdsize) {
9431 const char *P = Ptr + sub.umbrella;
9432 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9433 } else {
9434 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9435 }
9436}
9437
9438static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9439 const char *Ptr) {
9440 PrintLoadCommand(Cmd: sub.cmd, CmdSize: sub.cmdsize,
9441 IsSizeCorrect: sub.cmdsize >= sizeof(struct MachO::sub_umbrella_command),
9442 /*LabelWidth=*/13);
9443 if (sub.sub_umbrella < sub.cmdsize) {
9444 const char *P = Ptr + sub.sub_umbrella;
9445 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9446 } else {
9447 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9448 }
9449}
9450
9451static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9452 const char *Ptr) {
9453 PrintLoadCommand(Cmd: sub.cmd, CmdSize: sub.cmdsize,
9454 IsSizeCorrect: sub.cmdsize >= sizeof(struct MachO::sub_library_command),
9455 /*LabelWidth=*/13);
9456 if (sub.sub_library < sub.cmdsize) {
9457 const char *P = Ptr + sub.sub_library;
9458 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9459 } else {
9460 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9461 }
9462}
9463
9464static void PrintSubClientCommand(MachO::sub_client_command sub,
9465 const char *Ptr) {
9466 PrintLoadCommand(Cmd: sub.cmd, CmdSize: sub.cmdsize,
9467 IsSizeCorrect: sub.cmdsize >= sizeof(struct MachO::sub_client_command),
9468 /*LabelWidth=*/13);
9469 if (sub.client < sub.cmdsize) {
9470 const char *P = Ptr + sub.client;
9471 outs() << " client " << P << " (offset " << sub.client << ")\n";
9472 } else {
9473 outs() << " client ?(bad offset " << sub.client << ")\n";
9474 }
9475}
9476
9477static void PrintRoutinesCommand(MachO::routines_command r) {
9478 PrintLoadCommand(Cmd: r.cmd, CmdSize: r.cmdsize,
9479 IsSizeCorrect: r.cmdsize == sizeof(struct MachO::routines_command),
9480 /*LabelWidth=*/13);
9481 outs() << " init_address " << format(Fmt: "0x%08" PRIx32, Vals: r.init_address) << "\n";
9482 outs() << " init_module " << r.init_module << "\n";
9483 outs() << " reserved1 " << r.reserved1 << "\n";
9484 outs() << " reserved2 " << r.reserved2 << "\n";
9485 outs() << " reserved3 " << r.reserved3 << "\n";
9486 outs() << " reserved4 " << r.reserved4 << "\n";
9487 outs() << " reserved5 " << r.reserved5 << "\n";
9488 outs() << " reserved6 " << r.reserved6 << "\n";
9489}
9490
9491static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9492 PrintLoadCommand(Cmd: r.cmd, CmdSize: r.cmdsize,
9493 IsSizeCorrect: r.cmdsize == sizeof(struct MachO::routines_command_64),
9494 /*LabelWidth=*/13);
9495 outs() << " init_address " << format(Fmt: "0x%016" PRIx64, Vals: r.init_address) << "\n";
9496 outs() << " init_module " << r.init_module << "\n";
9497 outs() << " reserved1 " << r.reserved1 << "\n";
9498 outs() << " reserved2 " << r.reserved2 << "\n";
9499 outs() << " reserved3 " << r.reserved3 << "\n";
9500 outs() << " reserved4 " << r.reserved4 << "\n";
9501 outs() << " reserved5 " << r.reserved5 << "\n";
9502 outs() << " reserved6 " << r.reserved6 << "\n";
9503}
9504
9505static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9506 outs() << "\t eax " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eax);
9507 outs() << " ebx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ebx);
9508 outs() << " ecx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ecx);
9509 outs() << " edx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.edx) << "\n";
9510 outs() << "\t edi " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.edi);
9511 outs() << " esi " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.esi);
9512 outs() << " ebp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ebp);
9513 outs() << " esp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.esp) << "\n";
9514 outs() << "\t ss " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ss);
9515 outs() << " eflags " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eflags);
9516 outs() << " eip " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eip);
9517 outs() << " cs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.cs) << "\n";
9518 outs() << "\t ds " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ds);
9519 outs() << " es " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.es);
9520 outs() << " fs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.fs);
9521 outs() << " gs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.gs) << "\n";
9522}
9523
9524static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9525 outs() << " rax " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rax);
9526 outs() << " rbx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rbx);
9527 outs() << " rcx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rcx) << "\n";
9528 outs() << " rdx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rdx);
9529 outs() << " rdi " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rdi);
9530 outs() << " rsi " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rsi) << "\n";
9531 outs() << " rbp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rbp);
9532 outs() << " rsp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rsp);
9533 outs() << " r8 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r8) << "\n";
9534 outs() << " r9 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r9);
9535 outs() << " r10 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r10);
9536 outs() << " r11 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r11) << "\n";
9537 outs() << " r12 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r12);
9538 outs() << " r13 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r13);
9539 outs() << " r14 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r14) << "\n";
9540 outs() << " r15 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r15);
9541 outs() << " rip " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rip) << "\n";
9542 outs() << "rflags " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rflags);
9543 outs() << " cs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.cs);
9544 outs() << " fs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.fs) << "\n";
9545 outs() << " gs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.gs) << "\n";
9546}
9547
9548static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9549 uint32_t f;
9550 outs() << "\t mmst_reg ";
9551 for (f = 0; f < 10; f++)
9552 outs() << format(Fmt: "%02" PRIx32, Vals: (r.mmst_reg[f] & 0xff)) << " ";
9553 outs() << "\n";
9554 outs() << "\t mmst_rsrv ";
9555 for (f = 0; f < 6; f++)
9556 outs() << format(Fmt: "%02" PRIx32, Vals: (r.mmst_rsrv[f] & 0xff)) << " ";
9557 outs() << "\n";
9558}
9559
9560static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9561 uint32_t f;
9562 outs() << "\t xmm_reg ";
9563 for (f = 0; f < 16; f++)
9564 outs() << format(Fmt: "%02" PRIx32, Vals: (r.xmm_reg[f] & 0xff)) << " ";
9565 outs() << "\n";
9566}
9567
9568static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9569 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9570 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9571 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9572 outs() << " denorm " << fpu.fpu_fcw.denorm;
9573 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9574 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9575 outs() << " undfl " << fpu.fpu_fcw.undfl;
9576 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9577 outs() << "\t\t pc ";
9578 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9579 outs() << "FP_PREC_24B ";
9580 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9581 outs() << "FP_PREC_53B ";
9582 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9583 outs() << "FP_PREC_64B ";
9584 else
9585 outs() << fpu.fpu_fcw.pc << " ";
9586 outs() << "rc ";
9587 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9588 outs() << "FP_RND_NEAR ";
9589 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9590 outs() << "FP_RND_DOWN ";
9591 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9592 outs() << "FP_RND_UP ";
9593 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9594 outs() << "FP_CHOP ";
9595 outs() << "\n";
9596 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9597 outs() << " denorm " << fpu.fpu_fsw.denorm;
9598 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9599 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9600 outs() << " undfl " << fpu.fpu_fsw.undfl;
9601 outs() << " precis " << fpu.fpu_fsw.precis;
9602 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9603 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9604 outs() << " c0 " << fpu.fpu_fsw.c0;
9605 outs() << " c1 " << fpu.fpu_fsw.c1;
9606 outs() << " c2 " << fpu.fpu_fsw.c2;
9607 outs() << " tos " << fpu.fpu_fsw.tos;
9608 outs() << " c3 " << fpu.fpu_fsw.c3;
9609 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9610 outs() << "\t fpu_ftw " << format(Fmt: "0x%02" PRIx32, Vals: fpu.fpu_ftw);
9611 outs() << " fpu_rsrv1 " << format(Fmt: "0x%02" PRIx32, Vals: fpu.fpu_rsrv1);
9612 outs() << " fpu_fop " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_fop);
9613 outs() << " fpu_ip " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_ip) << "\n";
9614 outs() << "\t fpu_cs " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_cs);
9615 outs() << " fpu_rsrv2 " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_rsrv2);
9616 outs() << " fpu_dp " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_dp);
9617 outs() << " fpu_ds " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_ds) << "\n";
9618 outs() << "\t fpu_rsrv3 " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_rsrv3);
9619 outs() << " fpu_mxcsr " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_mxcsr);
9620 outs() << " fpu_mxcsrmask " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_mxcsrmask);
9621 outs() << "\n";
9622 outs() << "\t fpu_stmm0:\n";
9623 Print_mmst_reg(r&: fpu.fpu_stmm0);
9624 outs() << "\t fpu_stmm1:\n";
9625 Print_mmst_reg(r&: fpu.fpu_stmm1);
9626 outs() << "\t fpu_stmm2:\n";
9627 Print_mmst_reg(r&: fpu.fpu_stmm2);
9628 outs() << "\t fpu_stmm3:\n";
9629 Print_mmst_reg(r&: fpu.fpu_stmm3);
9630 outs() << "\t fpu_stmm4:\n";
9631 Print_mmst_reg(r&: fpu.fpu_stmm4);
9632 outs() << "\t fpu_stmm5:\n";
9633 Print_mmst_reg(r&: fpu.fpu_stmm5);
9634 outs() << "\t fpu_stmm6:\n";
9635 Print_mmst_reg(r&: fpu.fpu_stmm6);
9636 outs() << "\t fpu_stmm7:\n";
9637 Print_mmst_reg(r&: fpu.fpu_stmm7);
9638 outs() << "\t fpu_xmm0:\n";
9639 Print_xmm_reg(r&: fpu.fpu_xmm0);
9640 outs() << "\t fpu_xmm1:\n";
9641 Print_xmm_reg(r&: fpu.fpu_xmm1);
9642 outs() << "\t fpu_xmm2:\n";
9643 Print_xmm_reg(r&: fpu.fpu_xmm2);
9644 outs() << "\t fpu_xmm3:\n";
9645 Print_xmm_reg(r&: fpu.fpu_xmm3);
9646 outs() << "\t fpu_xmm4:\n";
9647 Print_xmm_reg(r&: fpu.fpu_xmm4);
9648 outs() << "\t fpu_xmm5:\n";
9649 Print_xmm_reg(r&: fpu.fpu_xmm5);
9650 outs() << "\t fpu_xmm6:\n";
9651 Print_xmm_reg(r&: fpu.fpu_xmm6);
9652 outs() << "\t fpu_xmm7:\n";
9653 Print_xmm_reg(r&: fpu.fpu_xmm7);
9654 outs() << "\t fpu_xmm8:\n";
9655 Print_xmm_reg(r&: fpu.fpu_xmm8);
9656 outs() << "\t fpu_xmm9:\n";
9657 Print_xmm_reg(r&: fpu.fpu_xmm9);
9658 outs() << "\t fpu_xmm10:\n";
9659 Print_xmm_reg(r&: fpu.fpu_xmm10);
9660 outs() << "\t fpu_xmm11:\n";
9661 Print_xmm_reg(r&: fpu.fpu_xmm11);
9662 outs() << "\t fpu_xmm12:\n";
9663 Print_xmm_reg(r&: fpu.fpu_xmm12);
9664 outs() << "\t fpu_xmm13:\n";
9665 Print_xmm_reg(r&: fpu.fpu_xmm13);
9666 outs() << "\t fpu_xmm14:\n";
9667 Print_xmm_reg(r&: fpu.fpu_xmm14);
9668 outs() << "\t fpu_xmm15:\n";
9669 Print_xmm_reg(r&: fpu.fpu_xmm15);
9670 outs() << "\t fpu_rsrv4:\n";
9671 for (uint32_t f = 0; f < 6; f++) {
9672 outs() << "\t ";
9673 for (uint32_t g = 0; g < 16; g++)
9674 outs() << format(Fmt: "%02" PRIx32, Vals: fpu.fpu_rsrv4[f * g]) << " ";
9675 outs() << "\n";
9676 }
9677 outs() << "\t fpu_reserved1 " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_reserved1);
9678 outs() << "\n";
9679}
9680
9681static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9682 outs() << "\t trapno " << format(Fmt: "0x%08" PRIx32, Vals: exc64.trapno);
9683 outs() << " err " << format(Fmt: "0x%08" PRIx32, Vals: exc64.err);
9684 outs() << " faultvaddr " << format(Fmt: "0x%016" PRIx64, Vals: exc64.faultvaddr) << "\n";
9685}
9686
9687static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9688 outs() << "\t r0 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[0]);
9689 outs() << " r1 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[1]);
9690 outs() << " r2 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[2]);
9691 outs() << " r3 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[3]) << "\n";
9692 outs() << "\t r4 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[4]);
9693 outs() << " r5 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[5]);
9694 outs() << " r6 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[6]);
9695 outs() << " r7 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[7]) << "\n";
9696 outs() << "\t r8 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[8]);
9697 outs() << " r9 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[9]);
9698 outs() << " r10 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[10]);
9699 outs() << " r11 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[11]) << "\n";
9700 outs() << "\t r12 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[12]);
9701 outs() << " sp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.sp);
9702 outs() << " lr " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.lr);
9703 outs() << " pc " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.pc) << "\n";
9704 outs() << "\t cpsr " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.cpsr) << "\n";
9705}
9706
9707static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9708 outs() << "\t x0 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[0]);
9709 outs() << " x1 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[1]);
9710 outs() << " x2 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[2]) << "\n";
9711 outs() << "\t x3 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[3]);
9712 outs() << " x4 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[4]);
9713 outs() << " x5 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[5]) << "\n";
9714 outs() << "\t x6 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[6]);
9715 outs() << " x7 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[7]);
9716 outs() << " x8 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[8]) << "\n";
9717 outs() << "\t x9 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[9]);
9718 outs() << " x10 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[10]);
9719 outs() << " x11 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[11]) << "\n";
9720 outs() << "\t x12 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[12]);
9721 outs() << " x13 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[13]);
9722 outs() << " x14 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[14]) << "\n";
9723 outs() << "\t x15 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[15]);
9724 outs() << " x16 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[16]);
9725 outs() << " x17 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[17]) << "\n";
9726 outs() << "\t x18 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[18]);
9727 outs() << " x19 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[19]);
9728 outs() << " x20 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[20]) << "\n";
9729 outs() << "\t x21 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[21]);
9730 outs() << " x22 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[22]);
9731 outs() << " x23 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[23]) << "\n";
9732 outs() << "\t x24 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[24]);
9733 outs() << " x25 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[25]);
9734 outs() << " x26 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[26]) << "\n";
9735 outs() << "\t x27 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[27]);
9736 outs() << " x28 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[28]);
9737 outs() << " fp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.fp) << "\n";
9738 outs() << "\t lr " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.lr);
9739 outs() << " sp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.sp);
9740 outs() << " pc " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.pc) << "\n";
9741 outs() << "\t cpsr " << format(Fmt: "0x%08" PRIx32, Vals: cpu64.cpsr) << "\n";
9742}
9743
9744static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9745 bool isLittleEndian, uint32_t cputype) {
9746 PrintLoadCommand(Cmd: t.cmd, CmdSize: t.cmdsize,
9747 IsSizeCorrect: t.cmdsize >= sizeof(struct MachO::thread_command) +
9748 2 * sizeof(uint32_t),
9749 /*LabelWidth=*/11);
9750
9751 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9752 const char *end = Ptr + t.cmdsize;
9753 uint32_t flavor, count, left;
9754 if (cputype == MachO::CPU_TYPE_I386) {
9755 while (begin < end) {
9756 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9757 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9758 begin += sizeof(uint32_t);
9759 } else {
9760 flavor = 0;
9761 begin = end;
9762 }
9763 if (isLittleEndian != sys::IsLittleEndianHost)
9764 sys::swapByteOrder(Value&: flavor);
9765 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9766 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9767 begin += sizeof(uint32_t);
9768 } else {
9769 count = 0;
9770 begin = end;
9771 }
9772 if (isLittleEndian != sys::IsLittleEndianHost)
9773 sys::swapByteOrder(Value&: count);
9774 if (flavor == MachO::x86_THREAD_STATE32) {
9775 outs() << " flavor i386_THREAD_STATE\n";
9776 if (count == MachO::x86_THREAD_STATE32_COUNT)
9777 outs() << " count i386_THREAD_STATE_COUNT\n";
9778 else
9779 outs() << " count " << count
9780 << " (not x86_THREAD_STATE32_COUNT)\n";
9781 MachO::x86_thread_state32_t cpu32;
9782 left = end - begin;
9783 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9784 memcpy(dest: &cpu32, src: begin, n: sizeof(MachO::x86_thread_state32_t));
9785 begin += sizeof(MachO::x86_thread_state32_t);
9786 } else {
9787 memset(s: &cpu32, c: '\0', n: sizeof(MachO::x86_thread_state32_t));
9788 memcpy(dest: &cpu32, src: begin, n: left);
9789 begin += left;
9790 }
9791 if (isLittleEndian != sys::IsLittleEndianHost)
9792 swapStruct(x&: cpu32);
9793 Print_x86_thread_state32_t(cpu32);
9794 } else if (flavor == MachO::x86_THREAD_STATE) {
9795 outs() << " flavor x86_THREAD_STATE\n";
9796 if (count == MachO::x86_THREAD_STATE_COUNT)
9797 outs() << " count x86_THREAD_STATE_COUNT\n";
9798 else
9799 outs() << " count " << count
9800 << " (not x86_THREAD_STATE_COUNT)\n";
9801 struct MachO::x86_thread_state_t ts;
9802 left = end - begin;
9803 if (left >= sizeof(MachO::x86_thread_state_t)) {
9804 memcpy(dest: &ts, src: begin, n: sizeof(MachO::x86_thread_state_t));
9805 begin += sizeof(MachO::x86_thread_state_t);
9806 } else {
9807 memset(s: &ts, c: '\0', n: sizeof(MachO::x86_thread_state_t));
9808 memcpy(dest: &ts, src: begin, n: left);
9809 begin += left;
9810 }
9811 if (isLittleEndian != sys::IsLittleEndianHost)
9812 swapStruct(x&: ts);
9813 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9814 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9815 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9816 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9817 else
9818 outs() << "tsh.count " << ts.tsh.count
9819 << " (not x86_THREAD_STATE32_COUNT\n";
9820 Print_x86_thread_state32_t(cpu32&: ts.uts.ts32);
9821 } else {
9822 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9823 << ts.tsh.count << "\n";
9824 }
9825 } else {
9826 outs() << " flavor " << flavor << " (unknown)\n";
9827 outs() << " count " << count << "\n";
9828 outs() << " state (unknown)\n";
9829 begin += count * sizeof(uint32_t);
9830 }
9831 }
9832 } else if (cputype == MachO::CPU_TYPE_X86_64) {
9833 while (begin < end) {
9834 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9835 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9836 begin += sizeof(uint32_t);
9837 } else {
9838 flavor = 0;
9839 begin = end;
9840 }
9841 if (isLittleEndian != sys::IsLittleEndianHost)
9842 sys::swapByteOrder(Value&: flavor);
9843 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9844 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9845 begin += sizeof(uint32_t);
9846 } else {
9847 count = 0;
9848 begin = end;
9849 }
9850 if (isLittleEndian != sys::IsLittleEndianHost)
9851 sys::swapByteOrder(Value&: count);
9852 if (flavor == MachO::x86_THREAD_STATE64) {
9853 outs() << " flavor x86_THREAD_STATE64\n";
9854 if (count == MachO::x86_THREAD_STATE64_COUNT)
9855 outs() << " count x86_THREAD_STATE64_COUNT\n";
9856 else
9857 outs() << " count " << count
9858 << " (not x86_THREAD_STATE64_COUNT)\n";
9859 MachO::x86_thread_state64_t cpu64;
9860 left = end - begin;
9861 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9862 memcpy(dest: &cpu64, src: begin, n: sizeof(MachO::x86_thread_state64_t));
9863 begin += sizeof(MachO::x86_thread_state64_t);
9864 } else {
9865 memset(s: &cpu64, c: '\0', n: sizeof(MachO::x86_thread_state64_t));
9866 memcpy(dest: &cpu64, src: begin, n: left);
9867 begin += left;
9868 }
9869 if (isLittleEndian != sys::IsLittleEndianHost)
9870 swapStruct(x&: cpu64);
9871 Print_x86_thread_state64_t(cpu64);
9872 } else if (flavor == MachO::x86_THREAD_STATE) {
9873 outs() << " flavor x86_THREAD_STATE\n";
9874 if (count == MachO::x86_THREAD_STATE_COUNT)
9875 outs() << " count x86_THREAD_STATE_COUNT\n";
9876 else
9877 outs() << " count " << count
9878 << " (not x86_THREAD_STATE_COUNT)\n";
9879 struct MachO::x86_thread_state_t ts;
9880 left = end - begin;
9881 if (left >= sizeof(MachO::x86_thread_state_t)) {
9882 memcpy(dest: &ts, src: begin, n: sizeof(MachO::x86_thread_state_t));
9883 begin += sizeof(MachO::x86_thread_state_t);
9884 } else {
9885 memset(s: &ts, c: '\0', n: sizeof(MachO::x86_thread_state_t));
9886 memcpy(dest: &ts, src: begin, n: left);
9887 begin += left;
9888 }
9889 if (isLittleEndian != sys::IsLittleEndianHost)
9890 swapStruct(x&: ts);
9891 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9892 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9893 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9894 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9895 else
9896 outs() << "tsh.count " << ts.tsh.count
9897 << " (not x86_THREAD_STATE64_COUNT\n";
9898 Print_x86_thread_state64_t(cpu64&: ts.uts.ts64);
9899 } else {
9900 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9901 << ts.tsh.count << "\n";
9902 }
9903 } else if (flavor == MachO::x86_FLOAT_STATE) {
9904 outs() << " flavor x86_FLOAT_STATE\n";
9905 if (count == MachO::x86_FLOAT_STATE_COUNT)
9906 outs() << " count x86_FLOAT_STATE_COUNT\n";
9907 else
9908 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9909 struct MachO::x86_float_state_t fs;
9910 left = end - begin;
9911 if (left >= sizeof(MachO::x86_float_state_t)) {
9912 memcpy(dest: &fs, src: begin, n: sizeof(MachO::x86_float_state_t));
9913 begin += sizeof(MachO::x86_float_state_t);
9914 } else {
9915 memset(s: &fs, c: '\0', n: sizeof(MachO::x86_float_state_t));
9916 memcpy(dest: &fs, src: begin, n: left);
9917 begin += left;
9918 }
9919 if (isLittleEndian != sys::IsLittleEndianHost)
9920 swapStruct(x&: fs);
9921 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9922 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
9923 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9924 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9925 else
9926 outs() << "fsh.count " << fs.fsh.count
9927 << " (not x86_FLOAT_STATE64_COUNT\n";
9928 Print_x86_float_state_t(fpu&: fs.ufs.fs64);
9929 } else {
9930 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9931 << fs.fsh.count << "\n";
9932 }
9933 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9934 outs() << " flavor x86_EXCEPTION_STATE\n";
9935 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9936 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9937 else
9938 outs() << " count " << count
9939 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9940 struct MachO::x86_exception_state_t es;
9941 left = end - begin;
9942 if (left >= sizeof(MachO::x86_exception_state_t)) {
9943 memcpy(dest: &es, src: begin, n: sizeof(MachO::x86_exception_state_t));
9944 begin += sizeof(MachO::x86_exception_state_t);
9945 } else {
9946 memset(s: &es, c: '\0', n: sizeof(MachO::x86_exception_state_t));
9947 memcpy(dest: &es, src: begin, n: left);
9948 begin += left;
9949 }
9950 if (isLittleEndian != sys::IsLittleEndianHost)
9951 swapStruct(x&: es);
9952 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9953 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
9954 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9955 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9956 else
9957 outs() << "\t esh.count " << es.esh.count
9958 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9959 Print_x86_exception_state_t(exc64&: es.ues.es64);
9960 } else {
9961 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9962 << es.esh.count << "\n";
9963 }
9964 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9965 outs() << " flavor x86_EXCEPTION_STATE64\n";
9966 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9967 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9968 else
9969 outs() << " count " << count
9970 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9971 struct MachO::x86_exception_state64_t es64;
9972 left = end - begin;
9973 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9974 memcpy(dest: &es64, src: begin, n: sizeof(MachO::x86_exception_state64_t));
9975 begin += sizeof(MachO::x86_exception_state64_t);
9976 } else {
9977 memset(s: &es64, c: '\0', n: sizeof(MachO::x86_exception_state64_t));
9978 memcpy(dest: &es64, src: begin, n: left);
9979 begin += left;
9980 }
9981 if (isLittleEndian != sys::IsLittleEndianHost)
9982 swapStruct(x&: es64);
9983 Print_x86_exception_state_t(exc64&: es64);
9984 } else {
9985 outs() << " flavor " << flavor << " (unknown)\n";
9986 outs() << " count " << count << "\n";
9987 outs() << " state (unknown)\n";
9988 begin += count * sizeof(uint32_t);
9989 }
9990 }
9991 } else if (cputype == MachO::CPU_TYPE_ARM) {
9992 while (begin < end) {
9993 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9994 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9995 begin += sizeof(uint32_t);
9996 } else {
9997 flavor = 0;
9998 begin = end;
9999 }
10000 if (isLittleEndian != sys::IsLittleEndianHost)
10001 sys::swapByteOrder(Value&: flavor);
10002 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10003 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10004 begin += sizeof(uint32_t);
10005 } else {
10006 count = 0;
10007 begin = end;
10008 }
10009 if (isLittleEndian != sys::IsLittleEndianHost)
10010 sys::swapByteOrder(Value&: count);
10011 if (flavor == MachO::ARM_THREAD_STATE) {
10012 outs() << " flavor ARM_THREAD_STATE\n";
10013 if (count == MachO::ARM_THREAD_STATE_COUNT)
10014 outs() << " count ARM_THREAD_STATE_COUNT\n";
10015 else
10016 outs() << " count " << count
10017 << " (not ARM_THREAD_STATE_COUNT)\n";
10018 MachO::arm_thread_state32_t cpu32;
10019 left = end - begin;
10020 if (left >= sizeof(MachO::arm_thread_state32_t)) {
10021 memcpy(dest: &cpu32, src: begin, n: sizeof(MachO::arm_thread_state32_t));
10022 begin += sizeof(MachO::arm_thread_state32_t);
10023 } else {
10024 memset(s: &cpu32, c: '\0', n: sizeof(MachO::arm_thread_state32_t));
10025 memcpy(dest: &cpu32, src: begin, n: left);
10026 begin += left;
10027 }
10028 if (isLittleEndian != sys::IsLittleEndianHost)
10029 swapStruct(x&: cpu32);
10030 Print_arm_thread_state32_t(cpu32);
10031 } else {
10032 outs() << " flavor " << flavor << " (unknown)\n";
10033 outs() << " count " << count << "\n";
10034 outs() << " state (unknown)\n";
10035 begin += count * sizeof(uint32_t);
10036 }
10037 }
10038 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
10039 cputype == MachO::CPU_TYPE_ARM64_32) {
10040 while (begin < end) {
10041 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10042 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
10043 begin += sizeof(uint32_t);
10044 } else {
10045 flavor = 0;
10046 begin = end;
10047 }
10048 if (isLittleEndian != sys::IsLittleEndianHost)
10049 sys::swapByteOrder(Value&: flavor);
10050 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10051 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10052 begin += sizeof(uint32_t);
10053 } else {
10054 count = 0;
10055 begin = end;
10056 }
10057 if (isLittleEndian != sys::IsLittleEndianHost)
10058 sys::swapByteOrder(Value&: count);
10059 if (flavor == MachO::ARM_THREAD_STATE64) {
10060 outs() << " flavor ARM_THREAD_STATE64\n";
10061 if (count == MachO::ARM_THREAD_STATE64_COUNT)
10062 outs() << " count ARM_THREAD_STATE64_COUNT\n";
10063 else
10064 outs() << " count " << count
10065 << " (not ARM_THREAD_STATE64_COUNT)\n";
10066 MachO::arm_thread_state64_t cpu64;
10067 left = end - begin;
10068 if (left >= sizeof(MachO::arm_thread_state64_t)) {
10069 memcpy(dest: &cpu64, src: begin, n: sizeof(MachO::arm_thread_state64_t));
10070 begin += sizeof(MachO::arm_thread_state64_t);
10071 } else {
10072 memset(s: &cpu64, c: '\0', n: sizeof(MachO::arm_thread_state64_t));
10073 memcpy(dest: &cpu64, src: begin, n: left);
10074 begin += left;
10075 }
10076 if (isLittleEndian != sys::IsLittleEndianHost)
10077 swapStruct(x&: cpu64);
10078 Print_arm_thread_state64_t(cpu64);
10079 } else {
10080 outs() << " flavor " << flavor << " (unknown)\n";
10081 outs() << " count " << count << "\n";
10082 outs() << " state (unknown)\n";
10083 begin += count * sizeof(uint32_t);
10084 }
10085 }
10086 } else {
10087 while (begin < end) {
10088 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10089 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
10090 begin += sizeof(uint32_t);
10091 } else {
10092 flavor = 0;
10093 begin = end;
10094 }
10095 if (isLittleEndian != sys::IsLittleEndianHost)
10096 sys::swapByteOrder(Value&: flavor);
10097 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10098 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10099 begin += sizeof(uint32_t);
10100 } else {
10101 count = 0;
10102 begin = end;
10103 }
10104 if (isLittleEndian != sys::IsLittleEndianHost)
10105 sys::swapByteOrder(Value&: count);
10106 outs() << " flavor " << flavor << "\n";
10107 outs() << " count " << count << "\n";
10108 outs() << " state (Unknown cputype/cpusubtype)\n";
10109 begin += count * sizeof(uint32_t);
10110 }
10111 }
10112}
10113
10114static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10115 PrintLoadCommand(Cmd: dl.cmd, CmdSize: dl.cmdsize,
10116 IsSizeCorrect: dl.cmdsize >= sizeof(struct MachO::dylib_command),
10117 /*LabelWidth=*/13);
10118 if (dl.dylib.name < dl.cmdsize) {
10119 const char *P = Ptr + dl.dylib.name;
10120 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
10121 } else {
10122 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
10123 }
10124 outs() << " time stamp " << dl.dylib.timestamp << " ";
10125 time_t t = dl.dylib.timestamp;
10126 outs() << ctime(timer: &t);
10127 outs() << " current version ";
10128 if (dl.dylib.current_version == 0xffffffff)
10129 outs() << "n/a\n";
10130 else
10131 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10132 << ((dl.dylib.current_version >> 8) & 0xff) << "."
10133 << (dl.dylib.current_version & 0xff) << "\n";
10134 outs() << "compatibility version ";
10135 if (dl.dylib.compatibility_version == 0xffffffff)
10136 outs() << "n/a\n";
10137 else
10138 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10139 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10140 << (dl.dylib.compatibility_version & 0xff) << "\n";
10141}
10142
10143static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10144 uint32_t object_size) {
10145 PrintLoadCommand(Cmd: ld.cmd, CmdSize: ld.cmdsize,
10146 IsSizeCorrect: ld.cmdsize == sizeof(struct MachO::linkedit_data_command),
10147 /*LabelWidth=*/8);
10148 outs() << " dataoff " << ld.dataoff;
10149 if (ld.dataoff > object_size)
10150 outs() << " (past end of file)\n";
10151 else
10152 outs() << "\n";
10153 outs() << " datasize " << ld.datasize;
10154 uint64_t big_size = ld.dataoff;
10155 big_size += ld.datasize;
10156 if (big_size > object_size)
10157 outs() << " (past end of file)\n";
10158 else
10159 outs() << "\n";
10160}
10161
10162static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10163 uint32_t cputype, bool verbose) {
10164 StringRef Buf = Obj->getData();
10165 unsigned Index = 0;
10166 for (const auto &Command : Obj->load_commands()) {
10167 outs() << "Load command " << Index++ << "\n";
10168 if (Command.C.cmd == MachO::LC_SEGMENT) {
10169 MachO::segment_command SLC = Obj->getSegmentLoadCommand(L: Command);
10170 const char *sg_segname = SLC.segname;
10171 PrintSegmentCommand(cmd: SLC.cmd, cmdsize: SLC.cmdsize, SegName: SLC.segname, vmaddr: SLC.vmaddr,
10172 vmsize: SLC.vmsize, fileoff: SLC.fileoff, filesize: SLC.filesize, maxprot: SLC.maxprot,
10173 initprot: SLC.initprot, nsects: SLC.nsects, flags: SLC.flags, object_size: Buf.size(),
10174 verbose);
10175 for (unsigned j = 0; j < SLC.nsects; j++) {
10176 MachO::section S = Obj->getSection(L: Command, Index: j);
10177 PrintSection(sectname: S.sectname, segname: S.segname, addr: S.addr, size: S.size, offset: S.offset, align: S.align,
10178 reloff: S.reloff, nreloc: S.nreloc, flags: S.flags, reserved1: S.reserved1, reserved2: S.reserved2,
10179 cmd: SLC.cmd, sg_segname, filetype, object_size: Buf.size(), verbose);
10180 }
10181 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10182 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(L: Command);
10183 const char *sg_segname = SLC_64.segname;
10184 PrintSegmentCommand(cmd: SLC_64.cmd, cmdsize: SLC_64.cmdsize, SegName: SLC_64.segname,
10185 vmaddr: SLC_64.vmaddr, vmsize: SLC_64.vmsize, fileoff: SLC_64.fileoff,
10186 filesize: SLC_64.filesize, maxprot: SLC_64.maxprot, initprot: SLC_64.initprot,
10187 nsects: SLC_64.nsects, flags: SLC_64.flags, object_size: Buf.size(), verbose);
10188 for (unsigned j = 0; j < SLC_64.nsects; j++) {
10189 MachO::section_64 S_64 = Obj->getSection64(L: Command, Index: j);
10190 PrintSection(sectname: S_64.sectname, segname: S_64.segname, addr: S_64.addr, size: S_64.size,
10191 offset: S_64.offset, align: S_64.align, reloff: S_64.reloff, nreloc: S_64.nreloc,
10192 flags: S_64.flags, reserved1: S_64.reserved1, reserved2: S_64.reserved2, cmd: SLC_64.cmd,
10193 sg_segname, filetype, object_size: Buf.size(), verbose);
10194 }
10195 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10196 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10197 PrintSymtabLoadCommand(st: Symtab, Is64Bit: Obj->is64Bit(), object_size: Buf.size());
10198 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10199 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10200 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10201 PrintDysymtabLoadCommand(dyst: Dysymtab, nsyms: Symtab.nsyms, object_size: Buf.size(),
10202 Is64Bit: Obj->is64Bit());
10203 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10204 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10205 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(L: Command);
10206 PrintDyldInfoLoadCommand(dc: DyldInfo, object_size: Buf.size());
10207 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10208 Command.C.cmd == MachO::LC_ID_DYLINKER ||
10209 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10210 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(L: Command);
10211 PrintDyldLoadCommand(dyld: Dyld, Ptr: Command.Ptr);
10212 } else if (Command.C.cmd == MachO::LC_UUID) {
10213 MachO::uuid_command Uuid = Obj->getUuidCommand(L: Command);
10214 PrintUuidLoadCommand(uuid: Uuid);
10215 } else if (Command.C.cmd == MachO::LC_RPATH) {
10216 MachO::rpath_command Rpath = Obj->getRpathCommand(L: Command);
10217 PrintRpathLoadCommand(rpath: Rpath, Ptr: Command.Ptr);
10218 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10219 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10220 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10221 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10222 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(L: Command);
10223 PrintVersionMinLoadCommand(vd: Vd);
10224 } else if (Command.C.cmd == MachO::LC_NOTE) {
10225 MachO::note_command Nt = Obj->getNoteLoadCommand(L: Command);
10226 PrintNoteLoadCommand(Nt);
10227 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10228 MachO::build_version_command Bv =
10229 Obj->getBuildVersionLoadCommand(L: Command);
10230 PrintBuildVersionLoadCommand(obj: Obj, bd: Bv, verbose);
10231 } else if (Command.C.cmd == MachO::LC_TARGET_TRIPLE) {
10232 MachO::target_triple_command Tt =
10233 Obj->getTargetTripleLoadCommand(L: Command);
10234 PrintTargetTripleCommand(tt: Tt, Ptr: Command.Ptr);
10235 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10236 MachO::source_version_command Sd = Obj->getSourceVersionCommand(L: Command);
10237 PrintSourceVersionCommand(sd: Sd);
10238 } else if (Command.C.cmd == MachO::LC_MAIN) {
10239 MachO::entry_point_command Ep = Obj->getEntryPointCommand(L: Command);
10240 PrintEntryPointCommand(ep: Ep);
10241 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10242 MachO::encryption_info_command Ei =
10243 Obj->getEncryptionInfoCommand(L: Command);
10244 PrintEncryptionInfoCommand(ec: Ei, object_size: Buf.size());
10245 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10246 MachO::encryption_info_command_64 Ei =
10247 Obj->getEncryptionInfoCommand64(L: Command);
10248 PrintEncryptionInfoCommand64(ec: Ei, object_size: Buf.size());
10249 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10250 MachO::linker_option_command Lo =
10251 Obj->getLinkerOptionLoadCommand(L: Command);
10252 PrintLinkerOptionCommand(lo: Lo, Ptr: Command.Ptr);
10253 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10254 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(L: Command);
10255 PrintSubFrameworkCommand(sub: Sf, Ptr: Command.Ptr);
10256 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10257 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(L: Command);
10258 PrintSubUmbrellaCommand(sub: Sf, Ptr: Command.Ptr);
10259 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10260 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(L: Command);
10261 PrintSubLibraryCommand(sub: Sl, Ptr: Command.Ptr);
10262 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10263 MachO::sub_client_command Sc = Obj->getSubClientCommand(L: Command);
10264 PrintSubClientCommand(sub: Sc, Ptr: Command.Ptr);
10265 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10266 MachO::routines_command Rc = Obj->getRoutinesCommand(L: Command);
10267 PrintRoutinesCommand(r: Rc);
10268 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10269 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(L: Command);
10270 PrintRoutinesCommand64(r: Rc);
10271 } else if (Command.C.cmd == MachO::LC_THREAD ||
10272 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10273 MachO::thread_command Tc = Obj->getThreadCommand(L: Command);
10274 PrintThreadCommand(t: Tc, Ptr: Command.Ptr, isLittleEndian: Obj->isLittleEndian(), cputype);
10275 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10276 Command.C.cmd == MachO::LC_ID_DYLIB ||
10277 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10278 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10279 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10280 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10281 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(L: Command);
10282 PrintDylibCommand(dl: Dl, Ptr: Command.Ptr);
10283 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10284 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10285 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10286 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10287 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10288 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT ||
10289 Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE ||
10290 Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS ||
10291 Command.C.cmd == MachO::LC_ATOM_INFO) {
10292 MachO::linkedit_data_command Ld =
10293 Obj->getLinkeditDataLoadCommand(L: Command);
10294 PrintLinkEditDataCommand(ld: Ld, object_size: Buf.size());
10295 } else {
10296 PrintLoadCommand(Cmd: Command.C.cmd, CmdSize: Command.C.cmdsize, IsSizeCorrect: true,
10297 /*LabelWidth=*/9);
10298 // TODO: get and print the raw bytes of the load command.
10299 }
10300 // TODO: print all the other kinds of load commands.
10301 }
10302}
10303
10304static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10305 if (Obj->is64Bit()) {
10306 MachO::mach_header_64 H_64;
10307 H_64 = Obj->getHeader64();
10308 PrintMachHeader(magic: H_64.magic, cputype: H_64.cputype, cpusubtype: H_64.cpusubtype, filetype: H_64.filetype,
10309 ncmds: H_64.ncmds, sizeofcmds: H_64.sizeofcmds, flags: H_64.flags, verbose);
10310 } else {
10311 MachO::mach_header H;
10312 H = Obj->getHeader();
10313 PrintMachHeader(magic: H.magic, cputype: H.cputype, cpusubtype: H.cpusubtype, filetype: H.filetype, ncmds: H.ncmds,
10314 sizeofcmds: H.sizeofcmds, flags: H.flags, verbose);
10315 }
10316}
10317
10318void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10319 const MachOObjectFile *file = cast<const MachOObjectFile>(Val: Obj);
10320 PrintMachHeader(Obj: file, verbose: Verbose);
10321}
10322
10323void MachODumper::printPrivateHeaders() {
10324 printMachOFileHeader(Obj: &Obj);
10325 if (!FirstPrivateHeader)
10326 printMachOLoadCommands(O: &Obj);
10327}
10328
10329void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10330 const MachOObjectFile *file = cast<const MachOObjectFile>(Val: Obj);
10331 uint32_t filetype = 0;
10332 uint32_t cputype = 0;
10333 if (file->is64Bit()) {
10334 MachO::mach_header_64 H_64;
10335 H_64 = file->getHeader64();
10336 filetype = H_64.filetype;
10337 cputype = H_64.cputype;
10338 } else {
10339 MachO::mach_header H;
10340 H = file->getHeader();
10341 filetype = H.filetype;
10342 cputype = H.cputype;
10343 }
10344 PrintLoadCommands(Obj: file, filetype, cputype, verbose: Verbose);
10345}
10346
10347//===----------------------------------------------------------------------===//
10348// export trie dumping
10349//===----------------------------------------------------------------------===//
10350
10351static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10352 uint64_t BaseSegmentAddress = 0;
10353 for (const auto &Command : Obj->load_commands()) {
10354 if (Command.C.cmd == MachO::LC_SEGMENT) {
10355 MachO::segment_command Seg = Obj->getSegmentLoadCommand(L: Command);
10356 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10357 BaseSegmentAddress = Seg.vmaddr;
10358 break;
10359 }
10360 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10361 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(L: Command);
10362 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10363 BaseSegmentAddress = Seg.vmaddr;
10364 break;
10365 }
10366 }
10367 }
10368 Error Err = Error::success();
10369 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10370 uint64_t Flags = Entry.flags();
10371 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10372 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10373 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10374 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10375 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10376 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10377 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10378 if (ReExport)
10379 outs() << "[re-export] ";
10380 else
10381 outs() << format(Fmt: "0x%08llX ",
10382 Vals: Entry.address() + BaseSegmentAddress);
10383 outs() << Entry.name();
10384 if (WeakDef || ThreadLocal || Resolver || Abs) {
10385 ListSeparator LS;
10386 outs() << " [";
10387 if (WeakDef)
10388 outs() << LS << "weak_def";
10389 if (ThreadLocal)
10390 outs() << LS << "per-thread";
10391 if (Abs)
10392 outs() << LS << "absolute";
10393 if (Resolver)
10394 outs() << LS << format(Fmt: "resolver=0x%08llX", Vals: Entry.other());
10395 outs() << "]";
10396 }
10397 if (ReExport) {
10398 StringRef DylibName = "unknown";
10399 int Ordinal = Entry.other() - 1;
10400 Obj->getLibraryShortNameByIndex(Index: Ordinal, DylibName);
10401 if (Entry.otherName().empty())
10402 outs() << " (from " << DylibName << ")";
10403 else
10404 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10405 }
10406 outs() << "\n";
10407 }
10408 if (Err)
10409 reportError(E: std::move(Err), FileName: Obj->getFileName());
10410}
10411
10412//===----------------------------------------------------------------------===//
10413// rebase table dumping
10414//===----------------------------------------------------------------------===//
10415
10416static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10417 outs() << "segment section address type\n";
10418 Error Err = Error::success();
10419 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10420 StringRef SegmentName = Entry.segmentName();
10421 StringRef SectionName = Entry.sectionName();
10422 uint64_t Address = Entry.address();
10423
10424 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
10425 outs() << format(Fmt: "%-8s %-18s 0x%08" PRIX64 " %s\n",
10426 Vals: SegmentName.str().c_str(), Vals: SectionName.str().c_str(),
10427 Vals: Address, Vals: Entry.typeName().str().c_str());
10428 }
10429 if (Err)
10430 reportError(E: std::move(Err), FileName: Obj->getFileName());
10431}
10432
10433static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10434 StringRef DylibName;
10435 switch (Ordinal) {
10436 case MachO::BIND_SPECIAL_DYLIB_SELF:
10437 return "this-image";
10438 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10439 return "main-executable";
10440 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10441 return "flat-namespace";
10442 case MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP:
10443 return "weak";
10444 default:
10445 if (Ordinal > 0) {
10446 std::error_code EC =
10447 Obj->getLibraryShortNameByIndex(Index: Ordinal - 1, DylibName);
10448 if (EC)
10449 return "<<bad library ordinal>>";
10450 return DylibName;
10451 }
10452 }
10453 return "<<unknown special ordinal>>";
10454}
10455
10456//===----------------------------------------------------------------------===//
10457// bind table dumping
10458//===----------------------------------------------------------------------===//
10459
10460static void printMachOBindTable(object::MachOObjectFile *Obj) {
10461 // Build table of sections so names can used in final output.
10462 outs() << "segment section address type "
10463 "addend dylib symbol\n";
10464 Error Err = Error::success();
10465 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10466 StringRef SegmentName = Entry.segmentName();
10467 StringRef SectionName = Entry.sectionName();
10468 uint64_t Address = Entry.address();
10469
10470 // Table lines look like:
10471 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
10472 StringRef Attr;
10473 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10474 Attr = " (weak_import)";
10475 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10476 << left_justify(Str: SectionName, Width: 18) << " "
10477 << format_hex(N: Address, Width: 10, Upper: true) << " "
10478 << left_justify(Str: Entry.typeName(), Width: 8) << " "
10479 << format_decimal(N: Entry.addend(), Width: 8) << " "
10480 << left_justify(Str: ordinalName(Obj, Ordinal: Entry.ordinal()), Width: 16) << " "
10481 << Entry.symbolName() << Attr << "\n";
10482 }
10483 if (Err)
10484 reportError(E: std::move(Err), FileName: Obj->getFileName());
10485}
10486
10487//===----------------------------------------------------------------------===//
10488// lazy bind table dumping
10489//===----------------------------------------------------------------------===//
10490
10491static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10492 outs() << "segment section address "
10493 "dylib symbol\n";
10494 Error Err = Error::success();
10495 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10496 StringRef SegmentName = Entry.segmentName();
10497 StringRef SectionName = Entry.sectionName();
10498 uint64_t Address = Entry.address();
10499
10500 // Table lines look like:
10501 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
10502 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10503 << left_justify(Str: SectionName, Width: 18) << " "
10504 << format_hex(N: Address, Width: 10, Upper: true) << " "
10505 << left_justify(Str: ordinalName(Obj, Ordinal: Entry.ordinal()), Width: 16) << " "
10506 << Entry.symbolName() << "\n";
10507 }
10508 if (Err)
10509 reportError(E: std::move(Err), FileName: Obj->getFileName());
10510}
10511
10512//===----------------------------------------------------------------------===//
10513// weak bind table dumping
10514//===----------------------------------------------------------------------===//
10515
10516static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10517 outs() << "segment section address "
10518 "type addend symbol\n";
10519 Error Err = Error::success();
10520 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10521 // Strong symbols don't have a location to update.
10522 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10523 outs() << " strong "
10524 << Entry.symbolName() << "\n";
10525 continue;
10526 }
10527 StringRef SegmentName = Entry.segmentName();
10528 StringRef SectionName = Entry.sectionName();
10529 uint64_t Address = Entry.address();
10530
10531 // Table lines look like:
10532 // __DATA __data 0x00001000 pointer 0 _foo
10533 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10534 << left_justify(Str: SectionName, Width: 18) << " "
10535 << format_hex(N: Address, Width: 10, Upper: true) << " "
10536 << left_justify(Str: Entry.typeName(), Width: 8) << " "
10537 << format_decimal(N: Entry.addend(), Width: 8) << " " << Entry.symbolName()
10538 << "\n";
10539 }
10540 if (Err)
10541 reportError(E: std::move(Err), FileName: Obj->getFileName());
10542}
10543
10544// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10545// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10546// information for that address. If the address is found its binding symbol
10547// name is returned. If not nullptr is returned.
10548static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10549 struct DisassembleInfo *info) {
10550 if (info->bindtable == nullptr) {
10551 info->bindtable = std::make_unique<SymbolAddressMap>();
10552 Error Err = Error::success();
10553 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10554 uint64_t Address = Entry.address();
10555 StringRef name = Entry.symbolName();
10556 if (!name.empty())
10557 (*info->bindtable)[Address] = name;
10558 }
10559 if (Err)
10560 reportError(E: std::move(Err), FileName: info->O->getFileName());
10561 }
10562 auto name = info->bindtable->lookup(Val: ReferenceValue);
10563 return !name.empty() ? name.data() : nullptr;
10564}
10565
10566void objdump::printLazyBindTable(ObjectFile *o) {
10567 outs() << "\nLazy bind table:\n";
10568 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10569 printMachOLazyBindTable(Obj: MachO);
10570 else
10571 WithColor::error()
10572 << "This operation is only currently supported "
10573 "for Mach-O executable files.\n";
10574}
10575
10576void objdump::printWeakBindTable(ObjectFile *o) {
10577 outs() << "\nWeak bind table:\n";
10578 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10579 printMachOWeakBindTable(Obj: MachO);
10580 else
10581 WithColor::error()
10582 << "This operation is only currently supported "
10583 "for Mach-O executable files.\n";
10584}
10585
10586void objdump::printExportsTrie(const ObjectFile *o) {
10587 outs() << "\nExports trie:\n";
10588 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10589 printMachOExportsTrie(Obj: MachO);
10590 else
10591 WithColor::error()
10592 << "This operation is only currently supported "
10593 "for Mach-O executable files.\n";
10594}
10595
10596void objdump::printRebaseTable(ObjectFile *o) {
10597 outs() << "\nRebase table:\n";
10598 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10599 printMachORebaseTable(Obj: MachO);
10600 else
10601 WithColor::error()
10602 << "This operation is only currently supported "
10603 "for Mach-O executable files.\n";
10604}
10605
10606void objdump::printBindTable(ObjectFile *o) {
10607 outs() << "\nBind table:\n";
10608 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10609 printMachOBindTable(Obj: MachO);
10610 else
10611 WithColor::error()
10612 << "This operation is only currently supported "
10613 "for Mach-O executable files.\n";
10614}
10615