1//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the MachO-specific dumper for llvm-objdump.
10//
11//===----------------------------------------------------------------------===//
12
13#include "MachODump.h"
14
15#include "ObjdumpOptID.h"
16#include "SourcePrinter.h"
17#include "llvm-objdump.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/BinaryFormat/MachO.h"
21#include "llvm/Config/config.h"
22#include "llvm/DebugInfo/DIContext.h"
23#include "llvm/DebugInfo/DWARF/DWARFContext.h"
24#include "llvm/Demangle/Demangle.h"
25#include "llvm/MC/MCAsmInfo.h"
26#include "llvm/MC/MCContext.h"
27#include "llvm/MC/MCDisassembler/MCDisassembler.h"
28#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCInstPrinter.h"
30#include "llvm/MC/MCInstrDesc.h"
31#include "llvm/MC/MCInstrInfo.h"
32#include "llvm/MC/MCRegisterInfo.h"
33#include "llvm/MC/MCSubtargetInfo.h"
34#include "llvm/MC/MCTargetOptions.h"
35#include "llvm/MC/TargetRegistry.h"
36#include "llvm/Object/MachO.h"
37#include "llvm/Object/MachOUniversal.h"
38#include "llvm/Option/ArgList.h"
39#include "llvm/Support/Casting.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/Endian.h"
42#include "llvm/Support/Format.h"
43#include "llvm/Support/FormattedStream.h"
44#include "llvm/Support/LEB128.h"
45#include "llvm/Support/MemoryBuffer.h"
46#include "llvm/Support/WithColor.h"
47#include "llvm/Support/raw_ostream.h"
48#include "llvm/TargetParser/Triple.h"
49#include <algorithm>
50#include <cstring>
51#include <system_error>
52
53using namespace llvm;
54using namespace llvm::object;
55using namespace llvm::objdump;
56
57bool objdump::FirstPrivateHeader;
58bool objdump::ExportsTrie;
59bool objdump::Rebase;
60bool objdump::Rpaths;
61bool objdump::Bind;
62bool objdump::LazyBind;
63bool objdump::WeakBind;
64static bool UseDbg;
65static std::string DSYMFile;
66bool objdump::FullLeadingAddr;
67bool objdump::LeadingHeaders;
68bool objdump::UniversalHeaders;
69static bool ArchiveMemberOffsets;
70bool objdump::IndirectSymbols;
71bool objdump::DataInCode;
72FunctionStartsMode objdump::FunctionStartsType =
73 objdump::FunctionStartsMode::None;
74bool objdump::LinkOptHints;
75bool objdump::InfoPlist;
76bool objdump::ChainedFixups;
77bool objdump::DyldInfo;
78bool objdump::DylibsUsed;
79bool objdump::DylibId;
80bool objdump::Verbose;
81bool objdump::ObjcMetaData;
82std::string objdump::DisSymName;
83bool objdump::IsOtool;
84bool objdump::UseMemberSyntax;
85bool objdump::SymbolicOperands;
86std::vector<std::string> objdump::ArchFlags;
87
88static bool ArchAll = false;
89static std::string ArchiveMemberFilter;
90static std::string ThumbTripleName;
91
92static StringRef ordinalName(const object::MachOObjectFile *, int);
93
94void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) {
95 FirstPrivateHeader = InputArgs.hasArg(Ids: OBJDUMP_private_header);
96 ExportsTrie = InputArgs.hasArg(Ids: OBJDUMP_exports_trie);
97 Rebase = InputArgs.hasArg(Ids: OBJDUMP_rebase);
98 Rpaths = InputArgs.hasArg(Ids: OBJDUMP_rpaths);
99 Bind = InputArgs.hasArg(Ids: OBJDUMP_bind);
100 LazyBind = InputArgs.hasArg(Ids: OBJDUMP_lazy_bind);
101 WeakBind = InputArgs.hasArg(Ids: OBJDUMP_weak_bind);
102 UseDbg = InputArgs.hasArg(Ids: OBJDUMP_g);
103 DSYMFile = InputArgs.getLastArgValue(Id: OBJDUMP_dsym_EQ).str();
104 FullLeadingAddr = InputArgs.hasArg(Ids: OBJDUMP_full_leading_addr);
105 LeadingHeaders = !InputArgs.hasArg(Ids: OBJDUMP_no_leading_headers);
106 UniversalHeaders = InputArgs.hasArg(Ids: OBJDUMP_universal_headers);
107 ArchiveMemberOffsets = InputArgs.hasArg(Ids: OBJDUMP_archive_member_offsets);
108 IndirectSymbols = InputArgs.hasArg(Ids: OBJDUMP_indirect_symbols);
109 DataInCode = InputArgs.hasArg(Ids: OBJDUMP_data_in_code);
110 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_function_starts_EQ)) {
111 FunctionStartsType = StringSwitch<FunctionStartsMode>(A->getValue())
112 .Case(S: "addrs", Value: FunctionStartsMode::Addrs)
113 .Case(S: "names", Value: FunctionStartsMode::Names)
114 .Case(S: "both", Value: FunctionStartsMode::Both)
115 .Default(Value: FunctionStartsMode::None);
116 if (FunctionStartsType == FunctionStartsMode::None)
117 invalidArgValue(A);
118 }
119 LinkOptHints = InputArgs.hasArg(Ids: OBJDUMP_link_opt_hints);
120 InfoPlist = InputArgs.hasArg(Ids: OBJDUMP_info_plist);
121 ChainedFixups = InputArgs.hasArg(Ids: OBJDUMP_chained_fixups);
122 DyldInfo = InputArgs.hasArg(Ids: OBJDUMP_dyld_info);
123 DylibsUsed = InputArgs.hasArg(Ids: OBJDUMP_dylibs_used);
124 DylibId = InputArgs.hasArg(Ids: OBJDUMP_dylib_id);
125 Verbose = !InputArgs.hasArg(Ids: OBJDUMP_non_verbose);
126 ObjcMetaData = InputArgs.hasArg(Ids: OBJDUMP_objc_meta_data);
127 DisSymName = InputArgs.getLastArgValue(Id: OBJDUMP_dis_symname).str();
128 SymbolicOperands = !InputArgs.hasArg(Ids: OBJDUMP_no_symbolic_operands);
129 ArchFlags = InputArgs.getAllArgValues(Id: OBJDUMP_arch_EQ);
130}
131
132static const Target *GetTarget(const MachOObjectFile *MachOObj,
133 const char **McpuDefault,
134 const Target **ThumbTarget,
135 Triple &ThumbTriple) {
136 // Figure out the target triple.
137 Triple TT(TripleName);
138 if (TripleName.empty()) {
139 TT = MachOObj->getArchTriple(McpuDefault);
140 TripleName = TT.str();
141 }
142
143 if (TT.getArch() == Triple::arm) {
144 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
145 // that support ARM are also capable of Thumb mode.
146 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(Start: 3)).str();
147 ThumbTriple = TT;
148 ThumbTriple.setArchName(ThumbName);
149 ThumbTripleName = ThumbTriple.str();
150 }
151
152 // Get the target specific parser.
153 std::string Error;
154 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple: TT, Error);
155 if (TheTarget && ThumbTripleName.empty())
156 return TheTarget;
157
158 *ThumbTarget = TargetRegistry::lookupTarget(TheTriple: ThumbTriple, Error);
159 if (*ThumbTarget)
160 return TheTarget;
161
162 WithColor::error(OS&: errs(), Prefix: "llvm-objdump") << "unable to get target for '";
163 if (!TheTarget)
164 errs() << TripleName;
165 else
166 errs() << ThumbTripleName;
167 errs() << "', see --version and --triple.\n";
168 return nullptr;
169}
170
171namespace {
172struct SymbolSorter {
173 bool operator()(const SymbolRef &A, const SymbolRef &B) {
174 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
175 if (!ATypeOrErr)
176 reportError(E: ATypeOrErr.takeError(), FileName: A.getObject()->getFileName());
177 SymbolRef::Type AType = *ATypeOrErr;
178 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
179 if (!BTypeOrErr)
180 reportError(E: BTypeOrErr.takeError(), FileName: B.getObject()->getFileName());
181 SymbolRef::Type BType = *BTypeOrErr;
182 uint64_t AAddr =
183 (AType != SymbolRef::ST_Function) ? 0 : cantFail(ValOrErr: A.getValue());
184 uint64_t BAddr =
185 (BType != SymbolRef::ST_Function) ? 0 : cantFail(ValOrErr: B.getValue());
186 return AAddr < BAddr;
187 }
188};
189
190class MachODumper : public Dumper {
191 const object::MachOObjectFile &Obj;
192
193public:
194 MachODumper(const object::MachOObjectFile &O) : Dumper(O), Obj(O) {}
195 void printPrivateHeaders() override;
196};
197} // namespace
198
199std::unique_ptr<Dumper>
200objdump::createMachODumper(const object::MachOObjectFile &Obj) {
201 return std::make_unique<MachODumper>(args: Obj);
202}
203
204// Types for the storted data in code table that is built before disassembly
205// and the predicate function to sort them.
206typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
207typedef std::vector<DiceTableEntry> DiceTable;
208typedef DiceTable::iterator dice_table_iterator;
209
210// This is used to search for a data in code table entry for the PC being
211// disassembled. The j parameter has the PC in j.first. A single data in code
212// table entry can cover many bytes for each of its Kind's. So if the offset,
213// aka the i.first value, of the data in code table entry plus its Length
214// covers the PC being searched for this will return true. If not it will
215// return false.
216static bool compareDiceTableEntries(const DiceTableEntry &i,
217 const DiceTableEntry &j) {
218 uint16_t Length;
219 i.second.getLength(Result&: Length);
220
221 return j.first >= i.first && j.first < i.first + Length;
222}
223
224static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
225 unsigned short Kind) {
226 uint32_t Value, Size = 1;
227
228 switch (Kind) {
229 default:
230 case MachO::DICE_KIND_DATA:
231 if (Length >= 4) {
232 if (ShowRawInsn)
233 dumpBytes(Bytes: ArrayRef(bytes, 4), OS&: outs());
234 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
235 outs() << "\t.long " << Value;
236 Size = 4;
237 } else if (Length >= 2) {
238 if (ShowRawInsn)
239 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
240 Value = bytes[1] << 8 | bytes[0];
241 outs() << "\t.short " << Value;
242 Size = 2;
243 } else {
244 if (ShowRawInsn)
245 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
246 Value = bytes[0];
247 outs() << "\t.byte " << Value;
248 Size = 1;
249 }
250 if (Kind == MachO::DICE_KIND_DATA)
251 outs() << "\t@ KIND_DATA\n";
252 else
253 outs() << "\t@ data in code kind = " << Kind << "\n";
254 break;
255 case MachO::DICE_KIND_JUMP_TABLE8:
256 if (ShowRawInsn)
257 dumpBytes(Bytes: ArrayRef(bytes, 1), OS&: outs());
258 Value = bytes[0];
259 outs() << "\t.byte " << format(Fmt: "%3u", Vals: Value) << "\t@ KIND_JUMP_TABLE8\n";
260 Size = 1;
261 break;
262 case MachO::DICE_KIND_JUMP_TABLE16:
263 if (ShowRawInsn)
264 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
265 Value = bytes[1] << 8 | bytes[0];
266 outs() << "\t.short " << format(Fmt: "%5u", Vals: Value & 0xffff)
267 << "\t@ KIND_JUMP_TABLE16\n";
268 Size = 2;
269 break;
270 case MachO::DICE_KIND_JUMP_TABLE32:
271 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
272 if (ShowRawInsn)
273 dumpBytes(Bytes: ArrayRef(bytes, 4), OS&: outs());
274 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
275 outs() << "\t.long " << Value;
276 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
277 outs() << "\t@ KIND_JUMP_TABLE32\n";
278 else
279 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
280 Size = 4;
281 break;
282 }
283 return Size;
284}
285
286static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
287 std::vector<SectionRef> &Sections,
288 std::vector<SymbolRef> &Symbols,
289 SmallVectorImpl<uint64_t> &FoundFns,
290 uint64_t &BaseSegmentAddress) {
291 const StringRef FileName = MachOObj->getFileName();
292 for (const SymbolRef &Symbol : MachOObj->symbols()) {
293 StringRef SymName = unwrapOrError(EO: Symbol.getName(), Args: FileName);
294 if (!SymName.starts_with(Prefix: "ltmp"))
295 Symbols.push_back(x: Symbol);
296 }
297
298 append_range(C&: Sections, R: MachOObj->sections());
299
300 bool BaseSegmentAddressSet = false;
301 for (const auto &Command : MachOObj->load_commands()) {
302 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
303 // We found a function starts segment, parse the addresses for later
304 // consumption.
305 MachO::linkedit_data_command LLC =
306 MachOObj->getLinkeditDataLoadCommand(L: Command);
307
308 MachOObj->ReadULEB128s(Index: LLC.dataoff, Out&: FoundFns);
309 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
310 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(L: Command);
311 StringRef SegName = SLC.segname;
312 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
313 BaseSegmentAddressSet = true;
314 BaseSegmentAddress = SLC.vmaddr;
315 }
316 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
317 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(L: Command);
318 StringRef SegName = SLC.segname;
319 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
320 BaseSegmentAddressSet = true;
321 BaseSegmentAddress = SLC.vmaddr;
322 }
323 }
324 }
325}
326
327static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
328 DiceTable &Dices, uint64_t &InstSize) {
329 // Check the data in code table here to see if this is data not an
330 // instruction to be disassembled.
331 DiceTable Dice;
332 Dice.push_back(x: std::make_pair(x&: PC, y: DiceRef()));
333 dice_table_iterator DTI =
334 std::search(first1: Dices.begin(), last1: Dices.end(), first2: Dice.begin(), last2: Dice.end(),
335 predicate: compareDiceTableEntries);
336 if (DTI != Dices.end()) {
337 uint16_t Length;
338 DTI->second.getLength(Result&: Length);
339 uint16_t Kind;
340 DTI->second.getKind(Result&: Kind);
341 InstSize = DumpDataInCode(bytes, Length, Kind);
342 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
343 (PC == (DTI->first + Length - 1)) && (Length & 1))
344 InstSize++;
345 return true;
346 }
347 return false;
348}
349
350static void printRelocationTargetName(const MachOObjectFile *O,
351 const MachO::any_relocation_info &RE,
352 raw_string_ostream &Fmt) {
353 // Target of a scattered relocation is an address. In the interest of
354 // generating pretty output, scan through the symbol table looking for a
355 // symbol that aligns with that address. If we find one, print it.
356 // Otherwise, we just print the hex address of the target.
357 const StringRef FileName = O->getFileName();
358 if (O->isRelocationScattered(RE)) {
359 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
360
361 for (const SymbolRef &Symbol : O->symbols()) {
362 uint64_t Addr = unwrapOrError(EO: Symbol.getAddress(), Args: FileName);
363 if (Addr != Val)
364 continue;
365 Fmt << unwrapOrError(EO: Symbol.getName(), Args: FileName);
366 return;
367 }
368
369 // If we couldn't find a symbol that this relocation refers to, try
370 // to find a section beginning instead.
371 for (const SectionRef &Section : ToolSectionFilter(O: *O)) {
372 uint64_t Addr = Section.getAddress();
373 if (Addr != Val)
374 continue;
375 StringRef NameOrErr = unwrapOrError(EO: Section.getName(), Args: O->getFileName());
376 Fmt << NameOrErr;
377 return;
378 }
379
380 Fmt << format(Fmt: "0x%x", Vals: Val);
381 return;
382 }
383
384 StringRef S;
385 bool isExtern = O->getPlainRelocationExternal(RE);
386 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
387
388 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
389 Triple(O->getArchTriple()).isAArch64()) {
390 Fmt << format(Fmt: "0x%0" PRIx64, Vals: Val);
391 return;
392 }
393
394 if (O->getAnyRelocationType(RE) == MachO::RISCV_RELOC_ADDEND &&
395 O->getArch() == Triple::riscv32) {
396 Fmt << format(Fmt: "0x%0" PRIx64, Vals: Val);
397 return;
398 }
399
400 if (isExtern) {
401 symbol_iterator SI = O->symbol_begin();
402 std::advance(i&: SI, n: Val);
403 S = unwrapOrError(EO: SI->getName(), Args: FileName);
404 } else {
405 section_iterator SI = O->section_begin();
406 // Adjust for the fact that sections are 1-indexed.
407 if (Val == 0) {
408 Fmt << "0 (?,?)";
409 return;
410 }
411 uint32_t I = Val - 1;
412 while (I != 0 && SI != O->section_end()) {
413 --I;
414 std::advance(i&: SI, n: 1);
415 }
416 if (SI == O->section_end()) {
417 Fmt << Val << " (?,?)";
418 } else {
419 if (Expected<StringRef> NameOrErr = SI->getName())
420 S = *NameOrErr;
421 else
422 consumeError(Err: NameOrErr.takeError());
423 }
424 }
425
426 Fmt << S;
427}
428
429Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
430 const RelocationRef &RelRef,
431 SmallVectorImpl<char> &Result) {
432 DataRefImpl Rel = RelRef.getRawDataRefImpl();
433 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
434
435 unsigned Arch = Obj->getArch();
436
437 std::string FmtBuf;
438 raw_string_ostream Fmt(FmtBuf);
439 unsigned Type = Obj->getAnyRelocationType(RE);
440 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
441
442 // Determine any addends that should be displayed with the relocation.
443 // These require decoding the relocation type, which is triple-specific.
444
445 // X86_64 has entirely custom relocation types.
446 if (Arch == Triple::x86_64) {
447 switch (Type) {
448 case MachO::X86_64_RELOC_GOT_LOAD:
449 case MachO::X86_64_RELOC_GOT: {
450 printRelocationTargetName(O: Obj, RE, Fmt);
451 Fmt << "@GOT";
452 if (IsPCRel)
453 Fmt << "PCREL";
454 break;
455 }
456 case MachO::X86_64_RELOC_SUBTRACTOR: {
457 DataRefImpl RelNext = Rel;
458 Obj->moveRelocationNext(Rel&: RelNext);
459 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
460
461 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
462 // X86_64_RELOC_UNSIGNED.
463 // NOTE: Scattered relocations don't exist on x86_64.
464 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
465 if (RType != MachO::X86_64_RELOC_UNSIGNED)
466 reportError(File: Obj->getFileName(), Message: "Expected X86_64_RELOC_UNSIGNED after "
467 "X86_64_RELOC_SUBTRACTOR.");
468
469 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
470 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
471 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
472 Fmt << "-";
473 printRelocationTargetName(O: Obj, RE, Fmt);
474 break;
475 }
476 case MachO::X86_64_RELOC_TLV:
477 printRelocationTargetName(O: Obj, RE, Fmt);
478 Fmt << "@TLV";
479 if (IsPCRel)
480 Fmt << "P";
481 break;
482 case MachO::X86_64_RELOC_SIGNED_1:
483 printRelocationTargetName(O: Obj, RE, Fmt);
484 Fmt << "-1";
485 break;
486 case MachO::X86_64_RELOC_SIGNED_2:
487 printRelocationTargetName(O: Obj, RE, Fmt);
488 Fmt << "-2";
489 break;
490 case MachO::X86_64_RELOC_SIGNED_4:
491 printRelocationTargetName(O: Obj, RE, Fmt);
492 Fmt << "-4";
493 break;
494 default:
495 printRelocationTargetName(O: Obj, RE, Fmt);
496 break;
497 }
498 // X86 and ARM share some relocation types in common.
499 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
500 Arch == Triple::ppc) {
501 // Generic relocation types...
502 switch (Type) {
503 case MachO::GENERIC_RELOC_PAIR: // prints no info
504 return Error::success();
505 case MachO::GENERIC_RELOC_SECTDIFF: {
506 DataRefImpl RelNext = Rel;
507 Obj->moveRelocationNext(Rel&: RelNext);
508 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
509
510 // X86 sect diff's must be followed by a relocation of type
511 // GENERIC_RELOC_PAIR.
512 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
513
514 if (RType != MachO::GENERIC_RELOC_PAIR)
515 reportError(File: Obj->getFileName(), Message: "Expected GENERIC_RELOC_PAIR after "
516 "GENERIC_RELOC_SECTDIFF.");
517
518 printRelocationTargetName(O: Obj, RE, Fmt);
519 Fmt << "-";
520 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
521 break;
522 }
523 }
524
525 if (Arch == Triple::x86 || Arch == Triple::ppc) {
526 switch (Type) {
527 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
528 DataRefImpl RelNext = Rel;
529 Obj->moveRelocationNext(Rel&: RelNext);
530 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
531
532 // X86 sect diff's must be followed by a relocation of type
533 // GENERIC_RELOC_PAIR.
534 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
535 if (RType != MachO::GENERIC_RELOC_PAIR)
536 reportError(File: Obj->getFileName(), Message: "Expected GENERIC_RELOC_PAIR after "
537 "GENERIC_RELOC_LOCAL_SECTDIFF.");
538
539 printRelocationTargetName(O: Obj, RE, Fmt);
540 Fmt << "-";
541 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
542 break;
543 }
544 case MachO::GENERIC_RELOC_TLV: {
545 printRelocationTargetName(O: Obj, RE, Fmt);
546 Fmt << "@TLV";
547 if (IsPCRel)
548 Fmt << "P";
549 break;
550 }
551 default:
552 printRelocationTargetName(O: Obj, RE, Fmt);
553 }
554 } else { // ARM-specific relocations
555 switch (Type) {
556 case MachO::ARM_RELOC_HALF:
557 case MachO::ARM_RELOC_HALF_SECTDIFF: {
558 // Half relocations steal a bit from the length field to encode
559 // whether this is an upper16 or a lower16 relocation.
560 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
561
562 if (isUpper)
563 Fmt << ":upper16:(";
564 else
565 Fmt << ":lower16:(";
566 printRelocationTargetName(O: Obj, RE, Fmt);
567
568 DataRefImpl RelNext = Rel;
569 Obj->moveRelocationNext(Rel&: RelNext);
570 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
571
572 // ARM half relocs must be followed by a relocation of type
573 // ARM_RELOC_PAIR.
574 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
575 if (RType != MachO::ARM_RELOC_PAIR)
576 reportError(File: Obj->getFileName(), Message: "Expected ARM_RELOC_PAIR after "
577 "ARM_RELOC_HALF");
578
579 // NOTE: The half of the target virtual address is stashed in the
580 // address field of the secondary relocation, but we can't reverse
581 // engineer the constant offset from it without decoding the movw/movt
582 // instruction to find the other half in its immediate field.
583
584 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
585 // symbol/section pointer of the follow-on relocation.
586 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
587 Fmt << "-";
588 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
589 }
590
591 Fmt << ")";
592 break;
593 }
594 default: {
595 printRelocationTargetName(O: Obj, RE, Fmt);
596 }
597 }
598 }
599 } else
600 printRelocationTargetName(O: Obj, RE, Fmt);
601
602 Result.append(in_start: FmtBuf.begin(), in_end: FmtBuf.end());
603 return Error::success();
604}
605
606static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
607 uint32_t n, uint32_t count,
608 uint32_t stride, uint64_t addr) {
609 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
610 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
611 if (n > nindirectsyms)
612 outs() << " (entries start past the end of the indirect symbol "
613 "table) (reserved1 field greater than the table size)";
614 else if (n + count > nindirectsyms)
615 outs() << " (entries extends past the end of the indirect symbol "
616 "table)";
617 outs() << "\n";
618 uint32_t cputype = O->getHeader().cputype;
619 if (cputype & MachO::CPU_ARCH_ABI64)
620 outs() << "address index";
621 else
622 outs() << "address index";
623 if (verbose)
624 outs() << " name\n";
625 else
626 outs() << "\n";
627 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
628 if (cputype & MachO::CPU_ARCH_ABI64)
629 outs() << format(Fmt: "0x%016" PRIx64, Vals: addr + j * stride) << " ";
630 else
631 outs() << format(Fmt: "0x%08" PRIx32, Vals: (uint32_t)addr + j * stride) << " ";
632 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
633 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: n + j);
634 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
635 outs() << "LOCAL\n";
636 continue;
637 }
638 if (indirect_symbol ==
639 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
640 outs() << "LOCAL ABSOLUTE\n";
641 continue;
642 }
643 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
644 outs() << "ABSOLUTE\n";
645 continue;
646 }
647 outs() << format(Fmt: "%5u ", Vals: indirect_symbol);
648 if (verbose) {
649 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
650 if (indirect_symbol < Symtab.nsyms) {
651 symbol_iterator Sym = O->getSymbolByIndex(Index: indirect_symbol);
652 SymbolRef Symbol = *Sym;
653 outs() << unwrapOrError(EO: Symbol.getName(), Args: O->getFileName());
654 } else {
655 outs() << "?";
656 }
657 }
658 outs() << "\n";
659 }
660}
661
662static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
663 for (const auto &Load : O->load_commands()) {
664 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
665 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(L: Load);
666 for (unsigned J = 0; J < Seg.nsects; ++J) {
667 MachO::section_64 Sec = O->getSection64(L: Load, Index: J);
668 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
669 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
670 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
671 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
672 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
673 section_type == MachO::S_SYMBOL_STUBS) {
674 uint32_t stride;
675 if (section_type == MachO::S_SYMBOL_STUBS)
676 stride = Sec.reserved2;
677 else
678 stride = 8;
679 if (stride == 0) {
680 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
681 << Sec.sectname << ") "
682 << "(size of stubs in reserved2 field is zero)\n";
683 continue;
684 }
685 uint32_t count = Sec.size / stride;
686 outs() << "Indirect symbols for (" << Sec.segname << ","
687 << Sec.sectname << ") " << count << " entries";
688 uint32_t n = Sec.reserved1;
689 PrintIndirectSymbolTable(O, verbose, n, count, stride, addr: Sec.addr);
690 }
691 }
692 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
693 MachO::segment_command Seg = O->getSegmentLoadCommand(L: Load);
694 for (unsigned J = 0; J < Seg.nsects; ++J) {
695 MachO::section Sec = O->getSection(L: Load, Index: J);
696 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
697 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
698 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
699 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
700 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
701 section_type == MachO::S_SYMBOL_STUBS) {
702 uint32_t stride;
703 if (section_type == MachO::S_SYMBOL_STUBS)
704 stride = Sec.reserved2;
705 else
706 stride = 4;
707 if (stride == 0) {
708 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
709 << Sec.sectname << ") "
710 << "(size of stubs in reserved2 field is zero)\n";
711 continue;
712 }
713 uint32_t count = Sec.size / stride;
714 outs() << "Indirect symbols for (" << Sec.segname << ","
715 << Sec.sectname << ") " << count << " entries";
716 uint32_t n = Sec.reserved1;
717 PrintIndirectSymbolTable(O, verbose, n, count, stride, addr: Sec.addr);
718 }
719 }
720 }
721 }
722}
723
724static void PrintRType(const uint64_t cputype, const unsigned r_type) {
725 static char const *generic_r_types[] = {
726 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
727 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
728 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
729 };
730 static char const *x86_64_r_types[] = {
731 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
732 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
733 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
734 };
735 static char const *arm_r_types[] = {
736 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
737 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
738 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
739 };
740 static char const *arm64_r_types[] = {
741 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
742 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
743 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
744 };
745
746 if (r_type > 0xf){
747 outs() << format(Fmt: "%-7u", Vals: r_type) << " ";
748 return;
749 }
750 switch (cputype) {
751 case MachO::CPU_TYPE_I386:
752 outs() << generic_r_types[r_type];
753 break;
754 case MachO::CPU_TYPE_X86_64:
755 outs() << x86_64_r_types[r_type];
756 break;
757 case MachO::CPU_TYPE_ARM:
758 outs() << arm_r_types[r_type];
759 break;
760 case MachO::CPU_TYPE_ARM64:
761 case MachO::CPU_TYPE_ARM64_32:
762 outs() << arm64_r_types[r_type];
763 break;
764 default:
765 outs() << format(Fmt: "%-7u ", Vals: r_type);
766 }
767}
768
769static void PrintRLength(const uint64_t cputype, const unsigned r_type,
770 const unsigned r_length, const bool previous_arm_half){
771 if (cputype == MachO::CPU_TYPE_ARM &&
772 (r_type == MachO::ARM_RELOC_HALF ||
773 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
774 if ((r_length & 0x1) == 0)
775 outs() << "lo/";
776 else
777 outs() << "hi/";
778 if ((r_length & 0x1) == 0)
779 outs() << "arm ";
780 else
781 outs() << "thm ";
782 } else {
783 switch (r_length) {
784 case 0:
785 outs() << "byte ";
786 break;
787 case 1:
788 outs() << "word ";
789 break;
790 case 2:
791 outs() << "long ";
792 break;
793 case 3:
794 if (cputype == MachO::CPU_TYPE_X86_64)
795 outs() << "quad ";
796 else
797 outs() << format(Fmt: "?(%2d) ", Vals: r_length);
798 break;
799 default:
800 outs() << format(Fmt: "?(%2d) ", Vals: r_length);
801 }
802 }
803}
804
805static void PrintRelocationEntries(const MachOObjectFile *O,
806 const relocation_iterator Begin,
807 const relocation_iterator End,
808 const uint64_t cputype,
809 const bool verbose) {
810 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
811 bool previous_arm_half = false;
812 bool previous_sectdiff = false;
813 uint32_t sectdiff_r_type = 0;
814
815 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
816 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
817 const MachO::any_relocation_info RE = O->getRelocation(Rel);
818 const unsigned r_type = O->getAnyRelocationType(RE);
819 const bool r_scattered = O->isRelocationScattered(RE);
820 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
821 const unsigned r_length = O->getAnyRelocationLength(RE);
822 const unsigned r_address = O->getAnyRelocationAddress(RE);
823 const bool r_extern = (r_scattered ? false :
824 O->getPlainRelocationExternal(RE));
825 const uint32_t r_value = (r_scattered ?
826 O->getScatteredRelocationValue(RE) : 0);
827 const unsigned r_symbolnum = (r_scattered ? 0 :
828 O->getPlainRelocationSymbolNum(RE));
829
830 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
831 if (verbose) {
832 // scattered: address
833 if ((cputype == MachO::CPU_TYPE_I386 &&
834 r_type == MachO::GENERIC_RELOC_PAIR) ||
835 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
836 outs() << " ";
837 else
838 outs() << format(Fmt: "%08x ", Vals: (unsigned int)r_address);
839
840 // scattered: pcrel
841 if (r_pcrel)
842 outs() << "True ";
843 else
844 outs() << "False ";
845
846 // scattered: length
847 PrintRLength(cputype, r_type, r_length, previous_arm_half);
848
849 // scattered: extern & type
850 outs() << "n/a ";
851 PrintRType(cputype, r_type);
852
853 // scattered: scattered & value
854 outs() << format(Fmt: "True 0x%08x", Vals: (unsigned int)r_value);
855 if (previous_sectdiff == false) {
856 if ((cputype == MachO::CPU_TYPE_ARM &&
857 r_type == MachO::ARM_RELOC_PAIR))
858 outs() << format(Fmt: " half = 0x%04x ", Vals: (unsigned int)r_address);
859 } else if (cputype == MachO::CPU_TYPE_ARM &&
860 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
861 outs() << format(Fmt: " other_half = 0x%04x ", Vals: (unsigned int)r_address);
862 if ((cputype == MachO::CPU_TYPE_I386 &&
863 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
864 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
865 (cputype == MachO::CPU_TYPE_ARM &&
866 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
867 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
868 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
869 previous_sectdiff = true;
870 sectdiff_r_type = r_type;
871 } else {
872 previous_sectdiff = false;
873 sectdiff_r_type = 0;
874 }
875 if (cputype == MachO::CPU_TYPE_ARM &&
876 (r_type == MachO::ARM_RELOC_HALF ||
877 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
878 previous_arm_half = true;
879 else
880 previous_arm_half = false;
881 outs() << "\n";
882 }
883 else {
884 // scattered: address pcrel length extern type scattered value
885 outs() << format(Fmt: "%08x %1d %-2d n/a %-7d 1 0x%08x\n",
886 Vals: (unsigned int)r_address, Vals: r_pcrel, Vals: r_length, Vals: r_type,
887 Vals: (unsigned int)r_value);
888 }
889 }
890 else {
891 if (verbose) {
892 // plain: address
893 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
894 outs() << " ";
895 else
896 outs() << format(Fmt: "%08x ", Vals: (unsigned int)r_address);
897
898 // plain: pcrel
899 if (r_pcrel)
900 outs() << "True ";
901 else
902 outs() << "False ";
903
904 // plain: length
905 PrintRLength(cputype, r_type, r_length, previous_arm_half);
906
907 if (r_extern) {
908 // plain: extern & type & scattered
909 outs() << "True ";
910 PrintRType(cputype, r_type);
911 outs() << "False ";
912
913 // plain: symbolnum/value
914 if (r_symbolnum > Symtab.nsyms)
915 outs() << format(Fmt: "?(%d)\n", Vals: r_symbolnum);
916 else {
917 SymbolRef Symbol = *O->getSymbolByIndex(Index: r_symbolnum);
918 Expected<StringRef> SymNameNext = Symbol.getName();
919 const char *name = nullptr;
920 if (SymNameNext)
921 name = SymNameNext->data();
922 if (name == nullptr)
923 outs() << format(Fmt: "?(%d)\n", Vals: r_symbolnum);
924 else
925 outs() << name << "\n";
926 }
927 }
928 else {
929 // plain: extern & type & scattered
930 outs() << "False ";
931 PrintRType(cputype, r_type);
932 outs() << "False ";
933
934 // plain: symbolnum/value
935 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
936 outs() << format(Fmt: "other_half = 0x%04x\n", Vals: (unsigned int)r_address);
937 else if ((cputype == MachO::CPU_TYPE_ARM64 ||
938 cputype == MachO::CPU_TYPE_ARM64_32) &&
939 r_type == MachO::ARM64_RELOC_ADDEND)
940 outs() << format(Fmt: "addend = 0x%06x\n", Vals: (unsigned int)r_symbolnum);
941 else if (cputype == MachO::CPU_TYPE_RISCV &&
942 r_type == MachO::RISCV_RELOC_ADDEND)
943 outs() << format(Fmt: "addend = 0x%06x\n", Vals: (unsigned int)r_symbolnum);
944 else {
945 outs() << format(Fmt: "%d ", Vals: r_symbolnum);
946 if (r_symbolnum == MachO::R_ABS)
947 outs() << "R_ABS\n";
948 else {
949 // in this case, r_symbolnum is actually a 1-based section number
950 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
951 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
952 object::DataRefImpl DRI;
953 DRI.d.a = r_symbolnum-1;
954 StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
955 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
956 outs() << "(" << SegName << "," << *NameOrErr << ")\n";
957 else
958 outs() << "(?,?)\n";
959 }
960 else {
961 outs() << "(?,?)\n";
962 }
963 }
964 }
965 }
966 if (cputype == MachO::CPU_TYPE_ARM &&
967 (r_type == MachO::ARM_RELOC_HALF ||
968 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
969 previous_arm_half = true;
970 else
971 previous_arm_half = false;
972 }
973 else {
974 // plain: address pcrel length extern type scattered symbolnum/section
975 outs() << format(Fmt: "%08x %1d %-2d %1d %-7d 0 %d\n",
976 Vals: (unsigned int)r_address, Vals: r_pcrel, Vals: r_length, Vals: r_extern,
977 Vals: r_type, Vals: r_symbolnum);
978 }
979 }
980 }
981}
982
983static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
984 const uint64_t cputype = O->getHeader().cputype;
985 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
986 if (Dysymtab.nextrel != 0) {
987 outs() << "External relocation information " << Dysymtab.nextrel
988 << " entries";
989 outs() << "\naddress pcrel length extern type scattered "
990 "symbolnum/value\n";
991 PrintRelocationEntries(O, Begin: O->extrel_begin(), End: O->extrel_end(), cputype,
992 verbose);
993 }
994 if (Dysymtab.nlocrel != 0) {
995 outs() << format(Fmt: "Local relocation information %u entries",
996 Vals: Dysymtab.nlocrel);
997 outs() << "\naddress pcrel length extern type scattered "
998 "symbolnum/value\n";
999 PrintRelocationEntries(O, Begin: O->locrel_begin(), End: O->locrel_end(), cputype,
1000 verbose);
1001 }
1002 for (const auto &Load : O->load_commands()) {
1003 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1004 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(L: Load);
1005 for (unsigned J = 0; J < Seg.nsects; ++J) {
1006 const MachO::section_64 Sec = O->getSection64(L: Load, Index: J);
1007 if (Sec.nreloc != 0) {
1008 DataRefImpl DRI;
1009 DRI.d.a = J;
1010 const StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
1011 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
1012 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1013 << format(Fmt: ") %u entries", Vals: Sec.nreloc);
1014 else
1015 outs() << "Relocation information (" << SegName << ",?) "
1016 << format(Fmt: "%u entries", Vals: Sec.nreloc);
1017 outs() << "\naddress pcrel length extern type scattered "
1018 "symbolnum/value\n";
1019 PrintRelocationEntries(O, Begin: O->section_rel_begin(Sec: DRI),
1020 End: O->section_rel_end(Sec: DRI), cputype, verbose);
1021 }
1022 }
1023 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1024 const MachO::segment_command Seg = O->getSegmentLoadCommand(L: Load);
1025 for (unsigned J = 0; J < Seg.nsects; ++J) {
1026 const MachO::section Sec = O->getSection(L: Load, Index: J);
1027 if (Sec.nreloc != 0) {
1028 DataRefImpl DRI;
1029 DRI.d.a = J;
1030 const StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
1031 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
1032 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1033 << format(Fmt: ") %u entries", Vals: Sec.nreloc);
1034 else
1035 outs() << "Relocation information (" << SegName << ",?) "
1036 << format(Fmt: "%u entries", Vals: Sec.nreloc);
1037 outs() << "\naddress pcrel length extern type scattered "
1038 "symbolnum/value\n";
1039 PrintRelocationEntries(O, Begin: O->section_rel_begin(Sec: DRI),
1040 End: O->section_rel_end(Sec: DRI), cputype, verbose);
1041 }
1042 }
1043 }
1044 }
1045}
1046
1047static void PrintFunctionStarts(MachOObjectFile *O) {
1048 uint64_t BaseSegmentAddress = 0;
1049 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1050 if (Command.C.cmd == MachO::LC_SEGMENT) {
1051 MachO::segment_command SLC = O->getSegmentLoadCommand(L: Command);
1052 if (StringRef(SLC.segname) == "__TEXT") {
1053 BaseSegmentAddress = SLC.vmaddr;
1054 break;
1055 }
1056 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1057 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(L: Command);
1058 if (StringRef(SLC.segname) == "__TEXT") {
1059 BaseSegmentAddress = SLC.vmaddr;
1060 break;
1061 }
1062 }
1063 }
1064
1065 SmallVector<uint64_t, 8> FunctionStarts;
1066 for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) {
1067 if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) {
1068 MachO::linkedit_data_command FunctionStartsLC =
1069 O->getLinkeditDataLoadCommand(L: LC);
1070 O->ReadULEB128s(Index: FunctionStartsLC.dataoff, Out&: FunctionStarts);
1071 break;
1072 }
1073 }
1074
1075 DenseMap<uint64_t, StringRef> SymbolNames;
1076 if (FunctionStartsType == FunctionStartsMode::Names ||
1077 FunctionStartsType == FunctionStartsMode::Both) {
1078 for (SymbolRef Sym : O->symbols()) {
1079 if (Expected<uint64_t> Addr = Sym.getAddress()) {
1080 if (Expected<StringRef> Name = Sym.getName()) {
1081 SymbolNames[*Addr] = *Name;
1082 }
1083 }
1084 }
1085 }
1086
1087 for (uint64_t S : FunctionStarts) {
1088 uint64_t Addr = BaseSegmentAddress + S;
1089 if (FunctionStartsType == FunctionStartsMode::Names) {
1090 auto It = SymbolNames.find(Val: Addr);
1091 if (It != SymbolNames.end())
1092 outs() << It->second << "\n";
1093 } else {
1094 if (O->is64Bit())
1095 outs() << format(Fmt: "%016" PRIx64, Vals: Addr);
1096 else
1097 outs() << format(Fmt: "%08" PRIx32, Vals: static_cast<uint32_t>(Addr));
1098
1099 if (FunctionStartsType == FunctionStartsMode::Both) {
1100 auto It = SymbolNames.find(Val: Addr);
1101 if (It != SymbolNames.end())
1102 outs() << " " << It->second;
1103 else
1104 outs() << " ?";
1105 }
1106 outs() << "\n";
1107 }
1108 }
1109}
1110
1111static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1112 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1113 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1114 outs() << "Data in code table (" << nentries << " entries)\n";
1115 outs() << "offset length kind\n";
1116 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1117 ++DI) {
1118 uint32_t Offset;
1119 DI->getOffset(Result&: Offset);
1120 outs() << format(Fmt: "0x%08" PRIx32, Vals: Offset) << " ";
1121 uint16_t Length;
1122 DI->getLength(Result&: Length);
1123 outs() << format(Fmt: "%6u", Vals: Length) << " ";
1124 uint16_t Kind;
1125 DI->getKind(Result&: Kind);
1126 if (verbose) {
1127 switch (Kind) {
1128 case MachO::DICE_KIND_DATA:
1129 outs() << "DATA";
1130 break;
1131 case MachO::DICE_KIND_JUMP_TABLE8:
1132 outs() << "JUMP_TABLE8";
1133 break;
1134 case MachO::DICE_KIND_JUMP_TABLE16:
1135 outs() << "JUMP_TABLE16";
1136 break;
1137 case MachO::DICE_KIND_JUMP_TABLE32:
1138 outs() << "JUMP_TABLE32";
1139 break;
1140 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1141 outs() << "ABS_JUMP_TABLE32";
1142 break;
1143 default:
1144 outs() << format(Fmt: "0x%04" PRIx32, Vals: Kind);
1145 break;
1146 }
1147 } else
1148 outs() << format(Fmt: "0x%04" PRIx32, Vals: Kind);
1149 outs() << "\n";
1150 }
1151}
1152
1153static void PrintLinkOptHints(MachOObjectFile *O) {
1154 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1155 const char *loh = O->getData().substr(Start: LohLC.dataoff, N: 1).data();
1156 uint32_t nloh = LohLC.datasize;
1157 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1158 for (uint32_t i = 0; i < nloh;) {
1159 unsigned n;
1160 uint64_t identifier = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1161 i += n;
1162 outs() << " identifier " << identifier << " ";
1163 if (i >= nloh)
1164 return;
1165 switch (identifier) {
1166 case 1:
1167 outs() << "AdrpAdrp\n";
1168 break;
1169 case 2:
1170 outs() << "AdrpLdr\n";
1171 break;
1172 case 3:
1173 outs() << "AdrpAddLdr\n";
1174 break;
1175 case 4:
1176 outs() << "AdrpLdrGotLdr\n";
1177 break;
1178 case 5:
1179 outs() << "AdrpAddStr\n";
1180 break;
1181 case 6:
1182 outs() << "AdrpLdrGotStr\n";
1183 break;
1184 case 7:
1185 outs() << "AdrpAdd\n";
1186 break;
1187 case 8:
1188 outs() << "AdrpLdrGot\n";
1189 break;
1190 default:
1191 outs() << "Unknown identifier value\n";
1192 break;
1193 }
1194 uint64_t narguments = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1195 i += n;
1196 outs() << " narguments " << narguments << "\n";
1197 if (i >= nloh)
1198 return;
1199
1200 for (uint32_t j = 0; j < narguments; j++) {
1201 uint64_t value = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1202 i += n;
1203 outs() << "\tvalue " << format(Fmt: "0x%" PRIx64, Vals: value) << "\n";
1204 if (i >= nloh)
1205 return;
1206 }
1207 }
1208}
1209
1210static SmallVector<std::string> GetSegmentNames(object::MachOObjectFile *O) {
1211 SmallVector<std::string> Ret;
1212 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1213 if (Command.C.cmd == MachO::LC_SEGMENT) {
1214 MachO::segment_command SLC = O->getSegmentLoadCommand(L: Command);
1215 Ret.push_back(Elt: SLC.segname);
1216 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1217 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(L: Command);
1218 Ret.push_back(Elt: SLC.segname);
1219 }
1220 }
1221 return Ret;
1222}
1223
1224static void
1225PrintChainedFixupsHeader(const MachO::dyld_chained_fixups_header &H) {
1226 outs() << "chained fixups header (LC_DYLD_CHAINED_FIXUPS)\n";
1227 outs() << " fixups_version = " << H.fixups_version << '\n';
1228 outs() << " starts_offset = " << H.starts_offset << '\n';
1229 outs() << " imports_offset = " << H.imports_offset << '\n';
1230 outs() << " symbols_offset = " << H.symbols_offset << '\n';
1231 outs() << " imports_count = " << H.imports_count << '\n';
1232
1233 outs() << " imports_format = " << H.imports_format;
1234 switch (H.imports_format) {
1235 case llvm::MachO::DYLD_CHAINED_IMPORT:
1236 outs() << " (DYLD_CHAINED_IMPORT)";
1237 break;
1238 case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND:
1239 outs() << " (DYLD_CHAINED_IMPORT_ADDEND)";
1240 break;
1241 case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND64:
1242 outs() << " (DYLD_CHAINED_IMPORT_ADDEND64)";
1243 break;
1244 }
1245 outs() << '\n';
1246
1247 outs() << " symbols_format = " << H.symbols_format;
1248 if (H.symbols_format == llvm::MachO::DYLD_CHAINED_SYMBOL_ZLIB)
1249 outs() << " (zlib compressed)";
1250 outs() << '\n';
1251}
1252
1253static constexpr std::array<StringRef, 13> PointerFormats{
1254 "DYLD_CHAINED_PTR_ARM64E",
1255 "DYLD_CHAINED_PTR_64",
1256 "DYLD_CHAINED_PTR_32",
1257 "DYLD_CHAINED_PTR_32_CACHE",
1258 "DYLD_CHAINED_PTR_32_FIRMWARE",
1259 "DYLD_CHAINED_PTR_64_OFFSET",
1260 "DYLD_CHAINED_PTR_ARM64E_KERNEL",
1261 "DYLD_CHAINED_PTR_64_KERNEL_CACHE",
1262 "DYLD_CHAINED_PTR_ARM64E_USERLAND",
1263 "DYLD_CHAINED_PTR_ARM64E_FIRMWARE",
1264 "DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE",
1265 "DYLD_CHAINED_PTR_ARM64E_USERLAND24",
1266};
1267
1268static void PrintChainedFixupsSegment(const ChainedFixupsSegment &Segment,
1269 StringRef SegName) {
1270 outs() << "chained starts in segment " << Segment.SegIdx << " (" << SegName
1271 << ")\n";
1272 outs() << " size = " << Segment.Header.size << '\n';
1273 outs() << " page_size = " << format(Fmt: "0x%0" PRIx16, Vals: Segment.Header.page_size)
1274 << '\n';
1275
1276 outs() << " pointer_format = " << Segment.Header.pointer_format;
1277 if ((Segment.Header.pointer_format - 1) <
1278 MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24)
1279 outs() << " (" << PointerFormats[Segment.Header.pointer_format - 1] << ")";
1280 outs() << '\n';
1281
1282 outs() << " segment_offset = "
1283 << format(Fmt: "0x%0" PRIx64, Vals: Segment.Header.segment_offset) << '\n';
1284 outs() << " max_valid_pointer = " << Segment.Header.max_valid_pointer
1285 << '\n';
1286 outs() << " page_count = " << Segment.Header.page_count << '\n';
1287 for (auto [Index, PageStart] : enumerate(First: Segment.PageStarts)) {
1288 outs() << " page_start[" << Index << "] = " << PageStart;
1289 // FIXME: Support DYLD_CHAINED_PTR_START_MULTI (32-bit only)
1290 if (PageStart == MachO::DYLD_CHAINED_PTR_START_NONE)
1291 outs() << " (DYLD_CHAINED_PTR_START_NONE)";
1292 outs() << '\n';
1293 }
1294}
1295
1296static void PrintChainedFixupTarget(ChainedFixupTarget &Target, size_t Idx,
1297 int Format, MachOObjectFile *O) {
1298 if (Format == MachO::DYLD_CHAINED_IMPORT)
1299 outs() << "dyld chained import";
1300 else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND)
1301 outs() << "dyld chained import addend";
1302 else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND64)
1303 outs() << "dyld chained import addend64";
1304 // FIXME: otool prints the encoded value as well.
1305 outs() << '[' << Idx << "]\n";
1306
1307 outs() << " lib_ordinal = " << Target.libOrdinal() << " ("
1308 << ordinalName(O, Target.libOrdinal()) << ")\n";
1309 outs() << " weak_import = " << Target.weakImport() << '\n';
1310 outs() << " name_offset = " << Target.nameOffset() << " ("
1311 << Target.symbolName() << ")\n";
1312 if (Format != MachO::DYLD_CHAINED_IMPORT)
1313 outs() << " addend = " << (int64_t)Target.addend() << '\n';
1314}
1315
1316static void PrintChainedFixups(MachOObjectFile *O) {
1317 // MachOObjectFile::getChainedFixupsHeader() reads LC_DYLD_CHAINED_FIXUPS.
1318 // FIXME: Support chained fixups in __TEXT,__chain_starts section too.
1319 auto ChainedFixupHeader =
1320 unwrapOrError(EO: O->getChainedFixupsHeader(), Args: O->getFileName());
1321 if (!ChainedFixupHeader)
1322 return;
1323
1324 PrintChainedFixupsHeader(H: *ChainedFixupHeader);
1325
1326 auto [SegCount, Segments] =
1327 unwrapOrError(EO: O->getChainedFixupsSegments(), Args: O->getFileName());
1328
1329 auto SegNames = GetSegmentNames(O);
1330
1331 size_t StartsIdx = 0;
1332 outs() << "chained starts in image\n";
1333 outs() << " seg_count = " << SegCount << '\n';
1334 for (size_t I = 0; I < SegCount; ++I) {
1335 uint64_t SegOffset = 0;
1336 if (StartsIdx < Segments.size() && I == Segments[StartsIdx].SegIdx) {
1337 SegOffset = Segments[StartsIdx].Offset;
1338 ++StartsIdx;
1339 }
1340
1341 outs() << " seg_offset[" << I << "] = " << SegOffset << " ("
1342 << SegNames[I] << ")\n";
1343 }
1344
1345 for (const ChainedFixupsSegment &S : Segments)
1346 PrintChainedFixupsSegment(Segment: S, SegName: SegNames[S.SegIdx]);
1347
1348 auto FixupTargets =
1349 unwrapOrError(EO: O->getDyldChainedFixupTargets(), Args: O->getFileName());
1350
1351 uint32_t ImportsFormat = ChainedFixupHeader->imports_format;
1352 for (auto [Idx, Target] : enumerate(First&: FixupTargets))
1353 PrintChainedFixupTarget(Target, Idx, Format: ImportsFormat, O);
1354}
1355
1356static void PrintDyldInfo(MachOObjectFile *O) {
1357 Error Err = Error::success();
1358
1359 size_t SegmentWidth = strlen(s: "segment");
1360 size_t SectionWidth = strlen(s: "section");
1361 size_t AddressWidth = strlen(s: "address");
1362 size_t AddendWidth = strlen(s: "addend");
1363 size_t DylibWidth = strlen(s: "dylib");
1364 const size_t PointerWidth = 2 + O->getBytesInAddress() * 2;
1365
1366 auto HexLength = [](uint64_t Num) {
1367 return Num ? (size_t)divideCeil(Numerator: Log2_64(Value: Num), Denominator: 4) : 1;
1368 };
1369 for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1370 SegmentWidth = std::max(a: SegmentWidth, b: Entry.segmentName().size());
1371 SectionWidth = std::max(a: SectionWidth, b: Entry.sectionName().size());
1372 AddressWidth = std::max(a: AddressWidth, b: HexLength(Entry.address()) + 2);
1373 if (Entry.isBind()) {
1374 AddendWidth = std::max(a: AddendWidth, b: HexLength(Entry.addend()) + 2);
1375 DylibWidth = std::max(a: DylibWidth, b: Entry.symbolName().size());
1376 }
1377 }
1378 // Errors will be handled when printing the table.
1379 if (Err)
1380 consumeError(Err: std::move(Err));
1381
1382 outs() << "dyld information:\n";
1383 outs() << left_justify(Str: "segment", Width: SegmentWidth) << ' '
1384 << left_justify(Str: "section", Width: SectionWidth) << ' '
1385 << left_justify(Str: "address", Width: AddressWidth) << ' '
1386 << left_justify(Str: "pointer", Width: PointerWidth) << " type "
1387 << left_justify(Str: "addend", Width: AddendWidth) << ' '
1388 << left_justify(Str: "dylib", Width: DylibWidth) << " symbol/vm address\n";
1389 for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1390 outs() << left_justify(Str: Entry.segmentName(), Width: SegmentWidth) << ' '
1391 << left_justify(Str: Entry.sectionName(), Width: SectionWidth) << ' ' << "0x"
1392 << left_justify(Str: utohexstr(X: Entry.address()), Width: AddressWidth - 2) << ' '
1393 << format_hex(N: Entry.rawValue(), Width: PointerWidth, Upper: true) << ' ';
1394 if (Entry.isBind()) {
1395 outs() << "bind "
1396 << "0x" << left_justify(Str: utohexstr(X: Entry.addend()), Width: AddendWidth - 2)
1397 << ' ' << left_justify(Str: ordinalName(O, Entry.ordinal()), Width: DylibWidth)
1398 << ' ' << Entry.symbolName();
1399 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
1400 outs() << " (weak import)";
1401 outs() << '\n';
1402 } else {
1403 assert(Entry.isRebase());
1404 outs() << "rebase";
1405 outs().indent(NumSpaces: AddendWidth + DylibWidth + 2);
1406 outs() << format(Fmt: "0x%" PRIX64, Vals: Entry.pointerValue()) << '\n';
1407 }
1408 }
1409 if (Err)
1410 reportError(E: std::move(Err), FileName: O->getFileName());
1411
1412 // TODO: Print opcode-based fixups if the object uses those.
1413}
1414
1415static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1416 unsigned Index = 0;
1417 for (const auto &Load : O->load_commands()) {
1418 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1419 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1420 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1421 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1422 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1423 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1424 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1425 MachO::dylib_command dl = O->getDylibIDLoadCommand(L: Load);
1426 if (dl.dylib.name < dl.cmdsize) {
1427 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1428 if (JustId)
1429 outs() << p << "\n";
1430 else {
1431 outs() << "\t" << p;
1432 outs() << " (compatibility version "
1433 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1434 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1435 << (dl.dylib.compatibility_version & 0xff) << ",";
1436 outs() << " current version "
1437 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1438 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1439 << (dl.dylib.current_version & 0xff);
1440 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1441 outs() << ", weak";
1442 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1443 outs() << ", reexport";
1444 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1445 outs() << ", upward";
1446 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1447 outs() << ", lazy";
1448 outs() << ")\n";
1449 }
1450 } else {
1451 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1452 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1453 outs() << "LC_ID_DYLIB ";
1454 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1455 outs() << "LC_LOAD_DYLIB ";
1456 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1457 outs() << "LC_LOAD_WEAK_DYLIB ";
1458 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1459 outs() << "LC_LAZY_LOAD_DYLIB ";
1460 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1461 outs() << "LC_REEXPORT_DYLIB ";
1462 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1463 outs() << "LC_LOAD_UPWARD_DYLIB ";
1464 else
1465 outs() << "LC_??? ";
1466 outs() << "command " << Index++ << "\n";
1467 }
1468 }
1469 }
1470}
1471
1472static void printRpaths(MachOObjectFile *O) {
1473 for (const auto &Command : O->load_commands()) {
1474 if (Command.C.cmd == MachO::LC_RPATH) {
1475 auto Rpath = O->getRpathCommand(L: Command);
1476 const char *P = (const char *)(Command.Ptr) + Rpath.path;
1477 outs() << P << "\n";
1478 }
1479 }
1480}
1481
1482typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1483
1484static void CreateSymbolAddressMap(MachOObjectFile *O,
1485 SymbolAddressMap *AddrMap) {
1486 // Create a map of symbol addresses to symbol names.
1487 const StringRef FileName = O->getFileName();
1488 for (const SymbolRef &Symbol : O->symbols()) {
1489 SymbolRef::Type ST = unwrapOrError(EO: Symbol.getType(), Args: FileName);
1490 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1491 ST == SymbolRef::ST_Other) {
1492 uint64_t Address = cantFail(ValOrErr: Symbol.getValue());
1493 StringRef SymName = unwrapOrError(EO: Symbol.getName(), Args: FileName);
1494 if (!SymName.starts_with(Prefix: ".objc"))
1495 (*AddrMap)[Address] = SymName;
1496 }
1497 }
1498}
1499
1500// GuessSymbolName is passed the address of what might be a symbol and a
1501// pointer to the SymbolAddressMap. It returns the name of a symbol
1502// with that address or nullptr if no symbol is found with that address.
1503static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1504 const char *SymbolName = nullptr;
1505 // A DenseMap can't lookup up some values.
1506 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1507 StringRef name = AddrMap->lookup(Val: value);
1508 if (!name.empty())
1509 SymbolName = name.data();
1510 }
1511 return SymbolName;
1512}
1513
1514static void DumpCstringChar(const char c) {
1515 char p[2];
1516 p[0] = c;
1517 p[1] = '\0';
1518 outs().write_escaped(Str: p);
1519}
1520
1521static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1522 uint32_t sect_size, uint64_t sect_addr,
1523 bool print_addresses) {
1524 for (uint32_t i = 0; i < sect_size; i++) {
1525 if (print_addresses) {
1526 if (O->is64Bit())
1527 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1528 else
1529 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1530 }
1531 for (; i < sect_size && sect[i] != '\0'; i++)
1532 DumpCstringChar(c: sect[i]);
1533 if (i < sect_size && sect[i] == '\0')
1534 outs() << "\n";
1535 }
1536}
1537
1538static void DumpLiteral4(uint32_t l, float f) {
1539 outs() << format(Fmt: "0x%08" PRIx32, Vals: l);
1540 if ((l & 0x7f800000) != 0x7f800000)
1541 outs() << format(Fmt: " (%.16e)\n", Vals: f);
1542 else {
1543 if (l == 0x7f800000)
1544 outs() << " (+Infinity)\n";
1545 else if (l == 0xff800000)
1546 outs() << " (-Infinity)\n";
1547 else if ((l & 0x00400000) == 0x00400000)
1548 outs() << " (non-signaling Not-a-Number)\n";
1549 else
1550 outs() << " (signaling Not-a-Number)\n";
1551 }
1552}
1553
1554static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1555 uint32_t sect_size, uint64_t sect_addr,
1556 bool print_addresses) {
1557 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1558 if (print_addresses) {
1559 if (O->is64Bit())
1560 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1561 else
1562 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1563 }
1564 float f;
1565 memcpy(dest: &f, src: sect + i, n: sizeof(float));
1566 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1567 sys::swapByteOrder(Value&: f);
1568 uint32_t l;
1569 memcpy(dest: &l, src: sect + i, n: sizeof(uint32_t));
1570 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1571 sys::swapByteOrder(Value&: l);
1572 DumpLiteral4(l, f);
1573 }
1574}
1575
1576static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1577 double d) {
1578 outs() << format(Fmt: "0x%08" PRIx32, Vals: l0) << " " << format(Fmt: "0x%08" PRIx32, Vals: l1);
1579 uint32_t Hi, Lo;
1580 Hi = (O->isLittleEndian()) ? l1 : l0;
1581 Lo = (O->isLittleEndian()) ? l0 : l1;
1582
1583 // Hi is the high word, so this is equivalent to if(isfinite(d))
1584 if ((Hi & 0x7ff00000) != 0x7ff00000)
1585 outs() << format(Fmt: " (%.16e)\n", Vals: d);
1586 else {
1587 if (Hi == 0x7ff00000 && Lo == 0)
1588 outs() << " (+Infinity)\n";
1589 else if (Hi == 0xfff00000 && Lo == 0)
1590 outs() << " (-Infinity)\n";
1591 else if ((Hi & 0x00080000) == 0x00080000)
1592 outs() << " (non-signaling Not-a-Number)\n";
1593 else
1594 outs() << " (signaling Not-a-Number)\n";
1595 }
1596}
1597
1598static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1599 uint32_t sect_size, uint64_t sect_addr,
1600 bool print_addresses) {
1601 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1602 if (print_addresses) {
1603 if (O->is64Bit())
1604 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1605 else
1606 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1607 }
1608 double d;
1609 memcpy(dest: &d, src: sect + i, n: sizeof(double));
1610 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1611 sys::swapByteOrder(Value&: d);
1612 uint32_t l0, l1;
1613 memcpy(dest: &l0, src: sect + i, n: sizeof(uint32_t));
1614 memcpy(dest: &l1, src: sect + i + sizeof(uint32_t), n: sizeof(uint32_t));
1615 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1616 sys::swapByteOrder(Value&: l0);
1617 sys::swapByteOrder(Value&: l1);
1618 }
1619 DumpLiteral8(O, l0, l1, d);
1620 }
1621}
1622
1623static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1624 outs() << format(Fmt: "0x%08" PRIx32, Vals: l0) << " ";
1625 outs() << format(Fmt: "0x%08" PRIx32, Vals: l1) << " ";
1626 outs() << format(Fmt: "0x%08" PRIx32, Vals: l2) << " ";
1627 outs() << format(Fmt: "0x%08" PRIx32, Vals: l3) << "\n";
1628}
1629
1630static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1631 uint32_t sect_size, uint64_t sect_addr,
1632 bool print_addresses) {
1633 for (uint32_t i = 0; i < sect_size; i += 16) {
1634 if (print_addresses) {
1635 if (O->is64Bit())
1636 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1637 else
1638 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1639 }
1640 uint32_t l0, l1, l2, l3;
1641 memcpy(dest: &l0, src: sect + i, n: sizeof(uint32_t));
1642 memcpy(dest: &l1, src: sect + i + sizeof(uint32_t), n: sizeof(uint32_t));
1643 memcpy(dest: &l2, src: sect + i + 2 * sizeof(uint32_t), n: sizeof(uint32_t));
1644 memcpy(dest: &l3, src: sect + i + 3 * sizeof(uint32_t), n: sizeof(uint32_t));
1645 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1646 sys::swapByteOrder(Value&: l0);
1647 sys::swapByteOrder(Value&: l1);
1648 sys::swapByteOrder(Value&: l2);
1649 sys::swapByteOrder(Value&: l3);
1650 }
1651 DumpLiteral16(l0, l1, l2, l3);
1652 }
1653}
1654
1655static void DumpLiteralPointerSection(MachOObjectFile *O,
1656 const SectionRef &Section,
1657 const char *sect, uint32_t sect_size,
1658 uint64_t sect_addr,
1659 bool print_addresses) {
1660 // Collect the literal sections in this Mach-O file.
1661 std::vector<SectionRef> LiteralSections;
1662 for (const SectionRef &Section : O->sections()) {
1663 DataRefImpl Ref = Section.getRawDataRefImpl();
1664 uint32_t section_type;
1665 if (O->is64Bit()) {
1666 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1667 section_type = Sec.flags & MachO::SECTION_TYPE;
1668 } else {
1669 const MachO::section Sec = O->getSection(DRI: Ref);
1670 section_type = Sec.flags & MachO::SECTION_TYPE;
1671 }
1672 if (section_type == MachO::S_CSTRING_LITERALS ||
1673 section_type == MachO::S_4BYTE_LITERALS ||
1674 section_type == MachO::S_8BYTE_LITERALS ||
1675 section_type == MachO::S_16BYTE_LITERALS)
1676 LiteralSections.push_back(x: Section);
1677 }
1678
1679 // Set the size of the literal pointer.
1680 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1681
1682 // Collect the external relocation symbols for the literal pointers.
1683 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1684 for (const RelocationRef &Reloc : Section.relocations()) {
1685 DataRefImpl Rel;
1686 MachO::any_relocation_info RE;
1687 bool isExtern = false;
1688 Rel = Reloc.getRawDataRefImpl();
1689 RE = O->getRelocation(Rel);
1690 isExtern = O->getPlainRelocationExternal(RE);
1691 if (isExtern) {
1692 uint64_t RelocOffset = Reloc.getOffset();
1693 symbol_iterator RelocSym = Reloc.getSymbol();
1694 Relocs.push_back(x: std::make_pair(x&: RelocOffset, y: *RelocSym));
1695 }
1696 }
1697 array_pod_sort(Start: Relocs.begin(), End: Relocs.end());
1698
1699 // Dump each literal pointer.
1700 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1701 if (print_addresses) {
1702 if (O->is64Bit())
1703 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1704 else
1705 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1706 }
1707 uint64_t lp;
1708 if (O->is64Bit()) {
1709 memcpy(dest: &lp, src: sect + i, n: sizeof(uint64_t));
1710 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1711 sys::swapByteOrder(Value&: lp);
1712 } else {
1713 uint32_t li;
1714 memcpy(dest: &li, src: sect + i, n: sizeof(uint32_t));
1715 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1716 sys::swapByteOrder(Value&: li);
1717 lp = li;
1718 }
1719
1720 // First look for an external relocation entry for this literal pointer.
1721 auto Reloc = find_if(Range&: Relocs, P: [&](const std::pair<uint64_t, SymbolRef> &P) {
1722 return P.first == i;
1723 });
1724 if (Reloc != Relocs.end()) {
1725 symbol_iterator RelocSym = Reloc->second;
1726 StringRef SymName = unwrapOrError(EO: RelocSym->getName(), Args: O->getFileName());
1727 outs() << "external relocation entry for symbol:" << SymName << "\n";
1728 continue;
1729 }
1730
1731 // For local references see what the section the literal pointer points to.
1732 auto Sect = find_if(Range&: LiteralSections, P: [&](const SectionRef &R) {
1733 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1734 });
1735 if (Sect == LiteralSections.end()) {
1736 outs() << format(Fmt: "0x%" PRIx64, Vals: lp) << " (not in a literal section)\n";
1737 continue;
1738 }
1739
1740 uint64_t SectAddress = Sect->getAddress();
1741 uint64_t SectSize = Sect->getSize();
1742
1743 StringRef SectName;
1744 Expected<StringRef> SectNameOrErr = Sect->getName();
1745 if (SectNameOrErr)
1746 SectName = *SectNameOrErr;
1747 else
1748 consumeError(Err: SectNameOrErr.takeError());
1749
1750 DataRefImpl Ref = Sect->getRawDataRefImpl();
1751 StringRef SegmentName = O->getSectionFinalSegmentName(Sec: Ref);
1752 outs() << SegmentName << ":" << SectName << ":";
1753
1754 uint32_t section_type;
1755 if (O->is64Bit()) {
1756 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1757 section_type = Sec.flags & MachO::SECTION_TYPE;
1758 } else {
1759 const MachO::section Sec = O->getSection(DRI: Ref);
1760 section_type = Sec.flags & MachO::SECTION_TYPE;
1761 }
1762
1763 StringRef BytesStr = unwrapOrError(EO: Sect->getContents(), Args: O->getFileName());
1764
1765 const char *Contents = BytesStr.data();
1766
1767 switch (section_type) {
1768 case MachO::S_CSTRING_LITERALS:
1769 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1770 i++) {
1771 DumpCstringChar(c: Contents[i]);
1772 }
1773 outs() << "\n";
1774 break;
1775 case MachO::S_4BYTE_LITERALS:
1776 float f;
1777 memcpy(dest: &f, src: Contents + (lp - SectAddress), n: sizeof(float));
1778 uint32_t l;
1779 memcpy(dest: &l, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1780 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1781 sys::swapByteOrder(Value&: f);
1782 sys::swapByteOrder(Value&: l);
1783 }
1784 DumpLiteral4(l, f);
1785 break;
1786 case MachO::S_8BYTE_LITERALS: {
1787 double d;
1788 memcpy(dest: &d, src: Contents + (lp - SectAddress), n: sizeof(double));
1789 uint32_t l0, l1;
1790 memcpy(dest: &l0, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1791 memcpy(dest: &l1, src: Contents + (lp - SectAddress) + sizeof(uint32_t),
1792 n: sizeof(uint32_t));
1793 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1794 sys::swapByteOrder(Value&: f);
1795 sys::swapByteOrder(Value&: l0);
1796 sys::swapByteOrder(Value&: l1);
1797 }
1798 DumpLiteral8(O, l0, l1, d);
1799 break;
1800 }
1801 case MachO::S_16BYTE_LITERALS: {
1802 uint32_t l0, l1, l2, l3;
1803 memcpy(dest: &l0, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1804 memcpy(dest: &l1, src: Contents + (lp - SectAddress) + sizeof(uint32_t),
1805 n: sizeof(uint32_t));
1806 memcpy(dest: &l2, src: Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1807 n: sizeof(uint32_t));
1808 memcpy(dest: &l3, src: Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1809 n: sizeof(uint32_t));
1810 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1811 sys::swapByteOrder(Value&: l0);
1812 sys::swapByteOrder(Value&: l1);
1813 sys::swapByteOrder(Value&: l2);
1814 sys::swapByteOrder(Value&: l3);
1815 }
1816 DumpLiteral16(l0, l1, l2, l3);
1817 break;
1818 }
1819 }
1820 }
1821}
1822
1823static void DumpInitTermPointerSection(MachOObjectFile *O,
1824 const SectionRef &Section,
1825 const char *sect,
1826 uint32_t sect_size, uint64_t sect_addr,
1827 SymbolAddressMap *AddrMap,
1828 bool verbose) {
1829 uint32_t stride;
1830 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1831
1832 // Collect the external relocation symbols for the pointers.
1833 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1834 for (const RelocationRef &Reloc : Section.relocations()) {
1835 DataRefImpl Rel;
1836 MachO::any_relocation_info RE;
1837 bool isExtern = false;
1838 Rel = Reloc.getRawDataRefImpl();
1839 RE = O->getRelocation(Rel);
1840 isExtern = O->getPlainRelocationExternal(RE);
1841 if (isExtern) {
1842 uint64_t RelocOffset = Reloc.getOffset();
1843 symbol_iterator RelocSym = Reloc.getSymbol();
1844 Relocs.push_back(x: std::make_pair(x&: RelocOffset, y: *RelocSym));
1845 }
1846 }
1847 array_pod_sort(Start: Relocs.begin(), End: Relocs.end());
1848
1849 for (uint32_t i = 0; i < sect_size; i += stride) {
1850 const char *SymbolName = nullptr;
1851 uint64_t p;
1852 if (O->is64Bit()) {
1853 outs() << format(Fmt: "0x%016" PRIx64, Vals: sect_addr + i * stride) << " ";
1854 uint64_t pointer_value;
1855 memcpy(dest: &pointer_value, src: sect + i, n: stride);
1856 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1857 sys::swapByteOrder(Value&: pointer_value);
1858 outs() << format(Fmt: "0x%016" PRIx64, Vals: pointer_value);
1859 p = pointer_value;
1860 } else {
1861 outs() << format(Fmt: "0x%08" PRIx64, Vals: sect_addr + i * stride) << " ";
1862 uint32_t pointer_value;
1863 memcpy(dest: &pointer_value, src: sect + i, n: stride);
1864 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1865 sys::swapByteOrder(Value&: pointer_value);
1866 outs() << format(Fmt: "0x%08" PRIx32, Vals: pointer_value);
1867 p = pointer_value;
1868 }
1869 if (verbose) {
1870 // First look for an external relocation entry for this pointer.
1871 auto Reloc = find_if(Range&: Relocs, P: [&](const std::pair<uint64_t, SymbolRef> &P) {
1872 return P.first == i;
1873 });
1874 if (Reloc != Relocs.end()) {
1875 symbol_iterator RelocSym = Reloc->second;
1876 outs() << " " << unwrapOrError(EO: RelocSym->getName(), Args: O->getFileName());
1877 } else {
1878 SymbolName = GuessSymbolName(value: p, AddrMap);
1879 if (SymbolName)
1880 outs() << " " << SymbolName;
1881 }
1882 }
1883 outs() << "\n";
1884 }
1885}
1886
1887static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1888 uint32_t size, uint64_t addr) {
1889 uint32_t cputype = O->getHeader().cputype;
1890 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1891 uint32_t j;
1892 for (uint32_t i = 0; i < size; i += j, addr += j) {
1893 if (O->is64Bit())
1894 outs() << format(Fmt: "%016" PRIx64, Vals: addr) << "\t";
1895 else
1896 outs() << format(Fmt: "%08" PRIx64, Vals: addr) << "\t";
1897 for (j = 0; j < 16 && i + j < size; j++) {
1898 uint8_t byte_word = *(sect + i + j);
1899 outs() << format(Fmt: "%02" PRIx32, Vals: (uint32_t)byte_word) << " ";
1900 }
1901 outs() << "\n";
1902 }
1903 } else {
1904 uint32_t j;
1905 for (uint32_t i = 0; i < size; i += j, addr += j) {
1906 if (O->is64Bit())
1907 outs() << format(Fmt: "%016" PRIx64, Vals: addr) << "\t";
1908 else
1909 outs() << format(Fmt: "%08" PRIx64, Vals: addr) << "\t";
1910 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1911 j += sizeof(int32_t)) {
1912 if (i + j + sizeof(int32_t) <= size) {
1913 uint32_t long_word;
1914 memcpy(dest: &long_word, src: sect + i + j, n: sizeof(int32_t));
1915 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1916 sys::swapByteOrder(Value&: long_word);
1917 outs() << format(Fmt: "%08" PRIx32, Vals: long_word) << " ";
1918 } else {
1919 for (uint32_t k = 0; i + j + k < size; k++) {
1920 uint8_t byte_word = *(sect + i + j + k);
1921 outs() << format(Fmt: "%02" PRIx32, Vals: (uint32_t)byte_word) << " ";
1922 }
1923 }
1924 }
1925 outs() << "\n";
1926 }
1927 }
1928}
1929
1930static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1931 StringRef DisSegName, StringRef DisSectName);
1932static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1933 uint32_t size, uint32_t addr);
1934static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1935 bool verbose) {
1936 SymbolAddressMap AddrMap;
1937 if (verbose)
1938 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
1939
1940 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1941 StringRef DumpSection = FilterSections[i];
1942 std::pair<StringRef, StringRef> DumpSegSectName;
1943 DumpSegSectName = DumpSection.split(Separator: ',');
1944 StringRef DumpSegName, DumpSectName;
1945 if (!DumpSegSectName.second.empty()) {
1946 DumpSegName = DumpSegSectName.first;
1947 DumpSectName = DumpSegSectName.second;
1948 } else {
1949 DumpSegName = "";
1950 DumpSectName = DumpSegSectName.first;
1951 }
1952 for (const SectionRef &Section : O->sections()) {
1953 StringRef SectName;
1954 Expected<StringRef> SecNameOrErr = Section.getName();
1955 if (SecNameOrErr)
1956 SectName = *SecNameOrErr;
1957 else
1958 consumeError(Err: SecNameOrErr.takeError());
1959
1960 if (!DumpSection.empty())
1961 FoundSectionSet.insert(key: DumpSection);
1962
1963 DataRefImpl Ref = Section.getRawDataRefImpl();
1964 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
1965 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1966 (SectName == DumpSectName)) {
1967
1968 uint32_t section_flags;
1969 if (O->is64Bit()) {
1970 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1971 section_flags = Sec.flags;
1972
1973 } else {
1974 const MachO::section Sec = O->getSection(DRI: Ref);
1975 section_flags = Sec.flags;
1976 }
1977 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1978
1979 StringRef BytesStr =
1980 unwrapOrError(EO: Section.getContents(), Args: O->getFileName());
1981 const char *sect = BytesStr.data();
1982 uint32_t sect_size = BytesStr.size();
1983 uint64_t sect_addr = Section.getAddress();
1984
1985 if (LeadingHeaders)
1986 outs() << "Contents of (" << SegName << "," << SectName
1987 << ") section\n";
1988
1989 if (verbose) {
1990 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1991 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1992 DisassembleMachO(Filename, MachOOF: O, DisSegName: SegName, DisSectName: SectName);
1993 continue;
1994 }
1995 if (SegName == "__TEXT" && SectName == "__info_plist") {
1996 outs() << sect;
1997 continue;
1998 }
1999 if (SegName == "__OBJC" && SectName == "__protocol") {
2000 DumpProtocolSection(O, sect, size: sect_size, addr: sect_addr);
2001 continue;
2002 }
2003 switch (section_type) {
2004 case MachO::S_REGULAR:
2005 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2006 break;
2007 case MachO::S_ZEROFILL:
2008 outs() << "zerofill section and has no contents in the file\n";
2009 break;
2010 case MachO::S_CSTRING_LITERALS:
2011 DumpCstringSection(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2012 break;
2013 case MachO::S_4BYTE_LITERALS:
2014 DumpLiteral4Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2015 break;
2016 case MachO::S_8BYTE_LITERALS:
2017 DumpLiteral8Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2018 break;
2019 case MachO::S_16BYTE_LITERALS:
2020 DumpLiteral16Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2021 break;
2022 case MachO::S_LITERAL_POINTERS:
2023 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
2024 print_addresses: LeadingAddr);
2025 break;
2026 case MachO::S_MOD_INIT_FUNC_POINTERS:
2027 case MachO::S_MOD_TERM_FUNC_POINTERS:
2028 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
2029 AddrMap: &AddrMap, verbose);
2030 break;
2031 default:
2032 outs() << "Unknown section type ("
2033 << format(Fmt: "0x%08" PRIx32, Vals: section_type) << ")\n";
2034 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2035 break;
2036 }
2037 } else {
2038 if (section_type == MachO::S_ZEROFILL)
2039 outs() << "zerofill section and has no contents in the file\n";
2040 else
2041 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2042 }
2043 }
2044 }
2045 }
2046}
2047
2048static void DumpInfoPlistSectionContents(StringRef Filename,
2049 MachOObjectFile *O) {
2050 for (const SectionRef &Section : O->sections()) {
2051 StringRef SectName;
2052 Expected<StringRef> SecNameOrErr = Section.getName();
2053 if (SecNameOrErr)
2054 SectName = *SecNameOrErr;
2055 else
2056 consumeError(Err: SecNameOrErr.takeError());
2057
2058 DataRefImpl Ref = Section.getRawDataRefImpl();
2059 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
2060 if (SegName == "__TEXT" && SectName == "__info_plist") {
2061 if (LeadingHeaders)
2062 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
2063 StringRef BytesStr =
2064 unwrapOrError(EO: Section.getContents(), Args: O->getFileName());
2065 const char *sect = BytesStr.data();
2066 outs() << format(Fmt: "%.*s", Vals: BytesStr.size(), Vals: sect) << "\n";
2067 return;
2068 }
2069 }
2070}
2071
2072// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
2073// and if it is and there is a list of architecture flags is specified then
2074// check to make sure this Mach-O file is one of those architectures or all
2075// architectures were specified. If not then an error is generated and this
2076// routine returns false. Else it returns true.
2077static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
2078 auto *MachO = dyn_cast<MachOObjectFile>(Val: O);
2079
2080 if (!MachO || ArchAll || ArchFlags.empty())
2081 return true;
2082
2083 MachO::mach_header H;
2084 MachO::mach_header_64 H_64;
2085 Triple T;
2086 const char *McpuDefault, *ArchFlag;
2087 if (MachO->is64Bit()) {
2088 H_64 = MachO->MachOObjectFile::getHeader64();
2089 T = MachOObjectFile::getArchTriple(CPUType: H_64.cputype, CPUSubType: H_64.cpusubtype,
2090 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2091 } else {
2092 H = MachO->MachOObjectFile::getHeader();
2093 T = MachOObjectFile::getArchTriple(CPUType: H.cputype, CPUSubType: H.cpusubtype,
2094 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2095 }
2096 const std::string ArchFlagName(ArchFlag);
2097 if (!llvm::is_contained(Range&: ArchFlags, Element: ArchFlagName)) {
2098 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2099 << Filename << ": no architecture specified.\n";
2100 return false;
2101 }
2102 return true;
2103}
2104
2105static void printObjcMetaData(MachOObjectFile *O, bool verbose);
2106
2107// ProcessMachO() is passed a single opened Mach-O file, which may be an
2108// archive member and or in a slice of a universal file. It prints the
2109// the file name and header info and then processes it according to the
2110// command line options.
2111static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
2112 StringRef ArchiveMemberName = StringRef(),
2113 StringRef ArchitectureName = StringRef()) {
2114 std::unique_ptr<Dumper> D = createMachODumper(Obj: *MachOOF);
2115
2116 // If we are doing some processing here on the Mach-O file print the header
2117 // info. And don't print it otherwise like in the case of printing the
2118 // UniversalHeaders or ArchiveHeaders.
2119 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
2120 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
2121 DataInCode || FunctionStartsType != FunctionStartsMode::None ||
2122 LinkOptHints || ChainedFixups || DyldInfo || DylibsUsed || DylibId ||
2123 Rpaths || ObjcMetaData || (!FilterSections.empty())) {
2124 if (LeadingHeaders) {
2125 outs() << Name;
2126 if (!ArchiveMemberName.empty())
2127 outs() << '(' << ArchiveMemberName << ')';
2128 if (!ArchitectureName.empty())
2129 outs() << " (architecture " << ArchitectureName << ")";
2130 outs() << ":\n";
2131 }
2132 }
2133 // To use the report_error() form with an ArchiveName and FileName set
2134 // these up based on what is passed for Name and ArchiveMemberName.
2135 StringRef ArchiveName;
2136 StringRef FileName;
2137 if (!ArchiveMemberName.empty()) {
2138 ArchiveName = Name;
2139 FileName = ArchiveMemberName;
2140 } else {
2141 ArchiveName = StringRef();
2142 FileName = Name;
2143 }
2144
2145 // If we need the symbol table to do the operation then check it here to
2146 // produce a good error message as to where the Mach-O file comes from in
2147 // the error message.
2148 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
2149 if (Error Err = MachOOF->checkSymbolTable())
2150 reportError(E: std::move(Err), FileName, ArchiveName, ArchitectureName);
2151
2152 if (DisassembleAll) {
2153 for (const SectionRef &Section : MachOOF->sections()) {
2154 StringRef SectName;
2155 if (Expected<StringRef> NameOrErr = Section.getName())
2156 SectName = *NameOrErr;
2157 else
2158 consumeError(Err: NameOrErr.takeError());
2159
2160 if (SectName == "__text") {
2161 DataRefImpl Ref = Section.getRawDataRefImpl();
2162 StringRef SegName = MachOOF->getSectionFinalSegmentName(Sec: Ref);
2163 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: SegName, DisSectName: SectName);
2164 }
2165 }
2166 }
2167 else if (Disassemble) {
2168 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
2169 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
2170 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: "__TEXT_EXEC", DisSectName: "__text");
2171 else
2172 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: "__TEXT", DisSectName: "__text");
2173 }
2174 if (IndirectSymbols)
2175 PrintIndirectSymbols(O: MachOOF, verbose: Verbose);
2176 if (DataInCode)
2177 PrintDataInCodeTable(O: MachOOF, verbose: Verbose);
2178 if (FunctionStartsType != FunctionStartsMode::None)
2179 PrintFunctionStarts(O: MachOOF);
2180 if (LinkOptHints)
2181 PrintLinkOptHints(O: MachOOF);
2182 if (Relocations)
2183 PrintRelocations(O: MachOOF, verbose: Verbose);
2184 if (SectionHeaders)
2185 printSectionHeaders(O&: *MachOOF);
2186 if (SectionContents)
2187 printSectionContents(O: MachOOF);
2188 if (!FilterSections.empty())
2189 DumpSectionContents(Filename: FileName, O: MachOOF, verbose: Verbose);
2190 if (InfoPlist)
2191 DumpInfoPlistSectionContents(Filename: FileName, O: MachOOF);
2192 if (DyldInfo)
2193 PrintDyldInfo(O: MachOOF);
2194 if (ChainedFixups)
2195 PrintChainedFixups(O: MachOOF);
2196 if (DylibsUsed)
2197 PrintDylibs(O: MachOOF, JustId: false);
2198 if (DylibId)
2199 PrintDylibs(O: MachOOF, JustId: true);
2200 if (SymbolTable)
2201 D->printSymbolTable(ArchiveName, ArchitectureName);
2202 if (UnwindInfo)
2203 printMachOUnwindInfo(O: MachOOF);
2204 if (PrivateHeaders) {
2205 printMachOFileHeader(O: MachOOF);
2206 printMachOLoadCommands(O: MachOOF);
2207 }
2208 if (FirstPrivateHeader)
2209 printMachOFileHeader(O: MachOOF);
2210 if (ObjcMetaData)
2211 printObjcMetaData(O: MachOOF, verbose: Verbose);
2212 if (ExportsTrie)
2213 printExportsTrie(O: MachOOF);
2214 if (Rebase)
2215 printRebaseTable(O: MachOOF);
2216 if (Rpaths)
2217 printRpaths(O: MachOOF);
2218 if (Bind)
2219 printBindTable(O: MachOOF);
2220 if (LazyBind)
2221 printLazyBindTable(O: MachOOF);
2222 if (WeakBind)
2223 printWeakBindTable(O: MachOOF);
2224
2225 if (DwarfDumpType != DIDT_Null) {
2226 std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj: *MachOOF);
2227 // Dump the complete DWARF structure.
2228 DIDumpOptions DumpOpts;
2229 DumpOpts.DumpType = DwarfDumpType;
2230 DICtx->dump(OS&: outs(), DumpOpts);
2231 }
2232}
2233
2234// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2235static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2236 outs() << " cputype (" << cputype << ")\n";
2237 outs() << " cpusubtype (" << cpusubtype << ")\n";
2238}
2239
2240// printCPUType() helps print_fat_headers by printing the cputype and
2241// pusubtype (symbolically for the one's it knows about).
2242static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2243 switch (cputype) {
2244 case MachO::CPU_TYPE_I386:
2245 switch (cpusubtype) {
2246 case MachO::CPU_SUBTYPE_I386_ALL:
2247 outs() << " cputype CPU_TYPE_I386\n";
2248 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
2249 break;
2250 default:
2251 printUnknownCPUType(cputype, cpusubtype);
2252 break;
2253 }
2254 break;
2255 case MachO::CPU_TYPE_X86_64:
2256 switch (cpusubtype) {
2257 case MachO::CPU_SUBTYPE_X86_64_ALL:
2258 outs() << " cputype CPU_TYPE_X86_64\n";
2259 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2260 break;
2261 case MachO::CPU_SUBTYPE_X86_64_H:
2262 outs() << " cputype CPU_TYPE_X86_64\n";
2263 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2264 break;
2265 default:
2266 printUnknownCPUType(cputype, cpusubtype);
2267 break;
2268 }
2269 break;
2270 case MachO::CPU_TYPE_ARM:
2271 switch (cpusubtype) {
2272 case MachO::CPU_SUBTYPE_ARM_ALL:
2273 outs() << " cputype CPU_TYPE_ARM\n";
2274 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2275 break;
2276 case MachO::CPU_SUBTYPE_ARM_V4T:
2277 outs() << " cputype CPU_TYPE_ARM\n";
2278 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2279 break;
2280 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2281 outs() << " cputype CPU_TYPE_ARM\n";
2282 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2283 break;
2284 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2285 outs() << " cputype CPU_TYPE_ARM\n";
2286 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2287 break;
2288 case MachO::CPU_SUBTYPE_ARM_V6:
2289 outs() << " cputype CPU_TYPE_ARM\n";
2290 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2291 break;
2292 case MachO::CPU_SUBTYPE_ARM_V6M:
2293 outs() << " cputype CPU_TYPE_ARM\n";
2294 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2295 break;
2296 case MachO::CPU_SUBTYPE_ARM_V7:
2297 outs() << " cputype CPU_TYPE_ARM\n";
2298 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2299 break;
2300 case MachO::CPU_SUBTYPE_ARM_V7EM:
2301 outs() << " cputype CPU_TYPE_ARM\n";
2302 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2303 break;
2304 case MachO::CPU_SUBTYPE_ARM_V7K:
2305 outs() << " cputype CPU_TYPE_ARM\n";
2306 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2307 break;
2308 case MachO::CPU_SUBTYPE_ARM_V7M:
2309 outs() << " cputype CPU_TYPE_ARM\n";
2310 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2311 break;
2312 case MachO::CPU_SUBTYPE_ARM_V7S:
2313 outs() << " cputype CPU_TYPE_ARM\n";
2314 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2315 break;
2316 case MachO::CPU_SUBTYPE_ARM_V8M_MAIN:
2317 outs() << " cputype CPU_TYPE_ARM\n";
2318 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8M_MAIN\n";
2319 break;
2320 case MachO::CPU_SUBTYPE_ARM_V8M_BASE:
2321 outs() << " cputype CPU_TYPE_ARM\n";
2322 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8M_BASE\n";
2323 break;
2324 case MachO::CPU_SUBTYPE_ARM_V8_1M_MAIN:
2325 outs() << " cputype CPU_TYPE_ARM\n";
2326 outs() << " cpusubtype CPU_SUBTYPE_ARM_V8_1M_MAIN\n";
2327 break;
2328 default:
2329 printUnknownCPUType(cputype, cpusubtype);
2330 break;
2331 }
2332 break;
2333 case MachO::CPU_TYPE_ARM64:
2334 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2335 case MachO::CPU_SUBTYPE_ARM64_ALL:
2336 outs() << " cputype CPU_TYPE_ARM64\n";
2337 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2338 break;
2339 case MachO::CPU_SUBTYPE_ARM64_V8:
2340 outs() << " cputype CPU_TYPE_ARM64\n";
2341 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2342 break;
2343 case MachO::CPU_SUBTYPE_ARM64E:
2344 outs() << " cputype CPU_TYPE_ARM64\n";
2345 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2346 break;
2347 default:
2348 printUnknownCPUType(cputype, cpusubtype);
2349 break;
2350 }
2351 break;
2352 case MachO::CPU_TYPE_ARM64_32:
2353 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2354 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2355 outs() << " cputype CPU_TYPE_ARM64_32\n";
2356 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2357 break;
2358 default:
2359 printUnknownCPUType(cputype, cpusubtype);
2360 break;
2361 }
2362 break;
2363 default:
2364 printUnknownCPUType(cputype, cpusubtype);
2365 break;
2366 }
2367}
2368
2369static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2370 bool verbose) {
2371 outs() << "Fat headers\n";
2372 if (verbose) {
2373 if (UB->getMagic() == MachO::FAT_MAGIC)
2374 outs() << "fat_magic FAT_MAGIC\n";
2375 else // UB->getMagic() == MachO::FAT_MAGIC_64
2376 outs() << "fat_magic FAT_MAGIC_64\n";
2377 } else
2378 outs() << "fat_magic " << format(Fmt: "0x%" PRIx32, Vals: MachO::FAT_MAGIC) << "\n";
2379
2380 uint32_t nfat_arch = UB->getNumberOfObjects();
2381 StringRef Buf = UB->getData();
2382 uint64_t size = Buf.size();
2383 uint64_t big_size = sizeof(struct MachO::fat_header) +
2384 nfat_arch * sizeof(struct MachO::fat_arch);
2385 outs() << "nfat_arch " << UB->getNumberOfObjects();
2386 if (nfat_arch == 0)
2387 outs() << " (malformed, contains zero architecture types)\n";
2388 else if (big_size > size)
2389 outs() << " (malformed, architectures past end of file)\n";
2390 else
2391 outs() << "\n";
2392
2393 for (uint32_t i = 0; i < nfat_arch; ++i) {
2394 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2395 uint32_t cputype = OFA.getCPUType();
2396 uint32_t cpusubtype = OFA.getCPUSubType();
2397 outs() << "architecture ";
2398 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2399 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2400 uint32_t other_cputype = other_OFA.getCPUType();
2401 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2402 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2403 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2404 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2405 outs() << "(illegal duplicate architecture) ";
2406 break;
2407 }
2408 }
2409 if (verbose) {
2410 outs() << OFA.getArchFlagName() << "\n";
2411 printCPUType(cputype, cpusubtype: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2412 } else {
2413 outs() << i << "\n";
2414 outs() << " cputype " << cputype << "\n";
2415 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2416 << "\n";
2417 }
2418 if (verbose && cputype == MachO::CPU_TYPE_ARM64 &&
2419 MachO::CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(ST: cpusubtype)) {
2420 outs() << " capabilities CPU_SUBTYPE_ARM64E_";
2421 if (MachO::CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(ST: cpusubtype))
2422 outs() << "KERNEL_";
2423 outs() << format(Fmt: "PTRAUTH_VERSION %d",
2424 Vals: MachO::CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(ST: cpusubtype))
2425 << "\n";
2426 } else if (verbose && (cpusubtype & MachO::CPU_SUBTYPE_MASK) ==
2427 MachO::CPU_SUBTYPE_LIB64)
2428 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2429 else
2430 outs() << " capabilities "
2431 << format(Fmt: "0x%" PRIx32,
2432 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2433 outs() << " offset " << OFA.getOffset();
2434 if (OFA.getOffset() > size)
2435 outs() << " (past end of file)";
2436 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2437 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2438 outs() << "\n";
2439 outs() << " size " << OFA.getSize();
2440 big_size = OFA.getOffset() + OFA.getSize();
2441 if (big_size > size)
2442 outs() << " (past end of file)";
2443 outs() << "\n";
2444 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2445 << ")\n";
2446 }
2447}
2448
2449static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2450 size_t ChildIndex, bool verbose,
2451 bool print_offset,
2452 StringRef ArchitectureName = StringRef()) {
2453 if (print_offset)
2454 outs() << C.getChildOffset() << "\t";
2455 sys::fs::perms Mode =
2456 unwrapOrError(EO: C.getAccessMode(), Args: getFileNameForError(C, Index: ChildIndex),
2457 Args&: Filename, Args&: ArchitectureName);
2458 if (verbose) {
2459 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2460 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2461 outs() << "-";
2462 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2463 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2464 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2465 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2466 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2467 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2468 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2469 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2470 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2471 } else {
2472 outs() << format(Fmt: "0%o ", Vals: Mode);
2473 }
2474
2475 outs() << format(Fmt: "%3d/%-3d %5" PRId64 " ",
2476 Vals: unwrapOrError(EO: C.getUID(), Args: getFileNameForError(C, Index: ChildIndex),
2477 Args&: Filename, Args&: ArchitectureName),
2478 Vals: unwrapOrError(EO: C.getGID(), Args: getFileNameForError(C, Index: ChildIndex),
2479 Args&: Filename, Args&: ArchitectureName),
2480 Vals: unwrapOrError(EO: C.getRawSize(),
2481 Args: getFileNameForError(C, Index: ChildIndex), Args&: Filename,
2482 Args&: ArchitectureName));
2483
2484 StringRef RawLastModified = C.getRawLastModified();
2485 if (verbose) {
2486 unsigned Seconds;
2487 if (RawLastModified.getAsInteger(Radix: 10, Result&: Seconds))
2488 outs() << "(date: \"" << RawLastModified
2489 << "\" contains non-decimal chars) ";
2490 else {
2491 // Since cime(3) returns a 26 character string of the form:
2492 // "Sun Sep 16 01:03:52 1973\n\0"
2493 // just print 24 characters.
2494 time_t t = Seconds;
2495 outs() << format(Fmt: "%.24s ", Vals: ctime(timer: &t));
2496 }
2497 } else {
2498 outs() << RawLastModified << " ";
2499 }
2500
2501 if (verbose) {
2502 Expected<StringRef> NameOrErr = C.getName();
2503 if (!NameOrErr) {
2504 consumeError(Err: NameOrErr.takeError());
2505 outs() << unwrapOrError(EO: C.getRawName(),
2506 Args: getFileNameForError(C, Index: ChildIndex), Args&: Filename,
2507 Args&: ArchitectureName)
2508 << "\n";
2509 } else {
2510 StringRef Name = NameOrErr.get();
2511 outs() << Name << "\n";
2512 }
2513 } else {
2514 outs() << unwrapOrError(EO: C.getRawName(), Args: getFileNameForError(C, Index: ChildIndex),
2515 Args&: Filename, Args&: ArchitectureName)
2516 << "\n";
2517 }
2518}
2519
2520static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2521 bool print_offset,
2522 StringRef ArchitectureName = StringRef()) {
2523 Error Err = Error::success();
2524 size_t I = 0;
2525 for (const auto &C : A->children(Err, SkipInternal: false))
2526 printArchiveChild(Filename, C, ChildIndex: I++, verbose, print_offset,
2527 ArchitectureName);
2528
2529 if (Err)
2530 reportError(E: std::move(Err), FileName: Filename, ArchiveName: "", ArchitectureName);
2531}
2532
2533static bool ValidateArchFlags() {
2534 // Check for -arch all and verifiy the -arch flags are valid.
2535 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2536 if (ArchFlags[i] == "all") {
2537 ArchAll = true;
2538 } else {
2539 if (!MachOObjectFile::isValidArch(ArchFlag: ArchFlags[i])) {
2540 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2541 << "unknown architecture named '" + ArchFlags[i] +
2542 "'for the -arch option\n";
2543 return false;
2544 }
2545 }
2546 }
2547 return true;
2548}
2549
2550static bool skipArchiveMember(const object::Archive::Child &C,
2551 StringRef Filename) {
2552 if (ArchiveMemberFilter.empty())
2553 return false;
2554 Expected<StringRef> NameOrErr = C.getName();
2555 if (!NameOrErr) {
2556 reportError(E: NameOrErr.takeError(), FileName: Filename);
2557 return true;
2558 }
2559 return *NameOrErr != ArchiveMemberFilter;
2560}
2561
2562// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2563// -arch flags selecting just those slices as specified by them and also parses
2564// archive files. Then for each individual Mach-O file ProcessMachO() is
2565// called to process the file based on the command line options.
2566void objdump::parseInputMachO(StringRef Filename) {
2567 if (!ValidateArchFlags())
2568 return;
2569
2570 // In otool mode, support archive(member) syntax: if the filename ends
2571 // with ')' and contains '(', split it into the archive path and member
2572 // name. The -m option disables this parsing.
2573 ArchiveMemberFilter.clear();
2574 if (IsOtool && UseMemberSyntax && !Filename.empty() &&
2575 Filename.back() == ')') {
2576 auto Pos = Filename.rfind(C: '(');
2577 if (Pos != StringRef::npos && Pos > 0) {
2578 ArchiveMemberFilter = Filename.substr(Start: Pos + 1).drop_back().str();
2579 Filename = Filename.substr(Start: 0, N: Pos);
2580 }
2581 }
2582
2583 // Attempt to open the binary.
2584 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Path: Filename);
2585 if (!BinaryOrErr) {
2586 if (Error E = isNotObjectErrorInvalidFileType(Err: BinaryOrErr.takeError()))
2587 reportError(E: std::move(E), FileName: Filename);
2588 else
2589 outs() << Filename << ": is not an object file\n";
2590 return;
2591 }
2592 Binary &Bin = *BinaryOrErr.get().getBinary();
2593
2594 if (Archive *A = dyn_cast<Archive>(Val: &Bin)) {
2595 outs() << "Archive : " << Filename << "\n";
2596 if (ArchiveHeaders)
2597 printArchiveHeaders(Filename, A, verbose: Verbose, print_offset: ArchiveMemberOffsets);
2598
2599 Error Err = Error::success();
2600 unsigned I = -1;
2601 bool FoundMember = false;
2602 for (auto &C : A->children(Err)) {
2603 ++I;
2604 if (skipArchiveMember(C, Filename))
2605 continue;
2606 FoundMember = true;
2607 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2608 if (!ChildOrErr) {
2609 if (Error E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2610 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename);
2611 continue;
2612 }
2613 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get())) {
2614 if (!checkMachOAndArchFlags(O, Filename))
2615 return;
2616 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName());
2617 }
2618 }
2619 if (Err)
2620 reportError(E: std::move(Err), FileName: Filename);
2621 if (!FoundMember && !ArchiveMemberFilter.empty())
2622 reportError(File: Filename, Message: "archive does not contain a member named: " +
2623 ArchiveMemberFilter);
2624 return;
2625 }
2626 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Bin)) {
2627 parseInputMachO(UB);
2628 return;
2629 }
2630 if (!ArchiveMemberFilter.empty()) {
2631 reportError(File: Filename, Message: "not an archive (cannot extract member: " +
2632 ArchiveMemberFilter + ")");
2633 return;
2634 }
2635 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Bin)) {
2636 if (!checkMachOAndArchFlags(O, Filename))
2637 return;
2638 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &*O))
2639 ProcessMachO(Name: Filename, MachOOF);
2640 else
2641 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2642 << Filename << "': "
2643 << "object is not a Mach-O file type.\n";
2644 return;
2645 }
2646 llvm_unreachable("Input object can't be invalid at this point");
2647}
2648
2649void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2650 if (!ValidateArchFlags())
2651 return;
2652
2653 auto Filename = UB->getFileName();
2654
2655 if (UniversalHeaders)
2656 printMachOUniversalHeaders(UB, verbose: Verbose);
2657
2658 // If we have a list of architecture flags specified dump only those.
2659 if (!ArchAll && !ArchFlags.empty()) {
2660 // Look for a slice in the universal binary that matches each ArchFlag.
2661 bool ArchFound;
2662 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2663 ArchFound = false;
2664 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2665 E = UB->end_objects();
2666 I != E; ++I) {
2667 if (ArchFlags[i] == I->getArchFlagName()) {
2668 ArchFound = true;
2669 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2670 I->getAsObjectFile();
2671 std::string ArchitectureName;
2672 if (ArchFlags.size() > 1)
2673 ArchitectureName = I->getArchFlagName();
2674 if (ObjOrErr) {
2675 ObjectFile &O = *ObjOrErr.get();
2676 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &O))
2677 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: "", ArchitectureName);
2678 } else if (Error E = isNotObjectErrorInvalidFileType(
2679 Err: ObjOrErr.takeError())) {
2680 reportError(E: std::move(E), FileName: "", ArchiveName: Filename, ArchitectureName);
2681 continue;
2682 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2683 I->getAsArchive()) {
2684 std::unique_ptr<Archive> &A = *AOrErr;
2685 outs() << "Archive : " << Filename;
2686 if (!ArchitectureName.empty())
2687 outs() << " (architecture " << ArchitectureName << ")";
2688 outs() << "\n";
2689 if (ArchiveHeaders)
2690 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose,
2691 print_offset: ArchiveMemberOffsets, ArchitectureName);
2692 Error Err = Error::success();
2693 unsigned I = -1;
2694 bool FoundMember = false;
2695 for (auto &C : A->children(Err)) {
2696 ++I;
2697 if (skipArchiveMember(C, Filename))
2698 continue;
2699 FoundMember = true;
2700 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2701 if (!ChildOrErr) {
2702 if (Error E =
2703 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2704 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename,
2705 ArchitectureName);
2706 continue;
2707 }
2708 if (MachOObjectFile *O =
2709 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get()))
2710 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName(), ArchitectureName);
2711 }
2712 if (Err)
2713 reportError(E: std::move(Err), FileName: Filename);
2714 if (!FoundMember && !ArchiveMemberFilter.empty())
2715 reportError(File: Filename,
2716 Message: "archive does not contain a member named: " +
2717 ArchiveMemberFilter);
2718 } else {
2719 consumeError(Err: AOrErr.takeError());
2720 reportError(File: Filename,
2721 Message: "Mach-O universal file for architecture " +
2722 StringRef(I->getArchFlagName()) +
2723 " is not a Mach-O file or an archive file");
2724 }
2725 }
2726 }
2727 if (!ArchFound) {
2728 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2729 << "file: " + Filename + " does not contain "
2730 << "architecture: " + ArchFlags[i] + "\n";
2731 return;
2732 }
2733 }
2734 return;
2735 }
2736 // No architecture flags were specified so if this contains a slice that
2737 // matches the host architecture dump only that. For otool -a dump all
2738 // architectures to match classic otool behaviour.
2739 if (!ArchAll && !(IsOtool && ArchiveHeaders)) {
2740 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2741 E = UB->end_objects();
2742 I != E; ++I) {
2743 if (MachOObjectFile::getHostArch().getArchName() ==
2744 I->getArchFlagName()) {
2745 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2746 std::string ArchiveName;
2747 ArchiveName.clear();
2748 if (ObjOrErr) {
2749 ObjectFile &O = *ObjOrErr.get();
2750 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &O))
2751 ProcessMachO(Name: Filename, MachOOF);
2752 } else if (Error E =
2753 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2754 reportError(E: std::move(E), FileName: Filename);
2755 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2756 I->getAsArchive()) {
2757 std::unique_ptr<Archive> &A = *AOrErr;
2758 outs() << "Archive : " << Filename << "\n";
2759 if (ArchiveHeaders)
2760 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose,
2761 print_offset: ArchiveMemberOffsets);
2762 Error Err = Error::success();
2763 unsigned I = -1;
2764 bool FoundMember = false;
2765 for (auto &C : A->children(Err)) {
2766 ++I;
2767 if (skipArchiveMember(C, Filename))
2768 continue;
2769 FoundMember = true;
2770 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2771 if (!ChildOrErr) {
2772 if (Error E =
2773 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2774 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename);
2775 continue;
2776 }
2777 if (MachOObjectFile *O =
2778 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get()))
2779 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName());
2780 }
2781 if (Err)
2782 reportError(E: std::move(Err), FileName: Filename);
2783 if (!FoundMember && !ArchiveMemberFilter.empty())
2784 reportError(File: Filename, Message: "archive does not contain a member named: " +
2785 ArchiveMemberFilter);
2786 } else {
2787 consumeError(Err: AOrErr.takeError());
2788 reportError(File: Filename, Message: "Mach-O universal file for architecture " +
2789 StringRef(I->getArchFlagName()) +
2790 " is not a Mach-O file or an archive file");
2791 }
2792 return;
2793 }
2794 }
2795 }
2796 // Either all architectures have been specified or none have been specified
2797 // and this does not contain the host architecture so dump all the slices.
2798 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2799 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2800 E = UB->end_objects();
2801 I != E; ++I) {
2802 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2803 std::string ArchitectureName;
2804 if (moreThanOneArch)
2805 ArchitectureName = I->getArchFlagName();
2806 if (ObjOrErr) {
2807 ObjectFile &Obj = *ObjOrErr.get();
2808 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &Obj))
2809 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: "", ArchitectureName);
2810 } else if (Error E =
2811 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2812 reportError(E: std::move(E), FileName: Filename, ArchiveName: "", ArchitectureName);
2813 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2814 std::unique_ptr<Archive> &A = *AOrErr;
2815 outs() << "Archive : " << Filename;
2816 if (!ArchitectureName.empty())
2817 outs() << " (architecture " << ArchitectureName << ")";
2818 outs() << "\n";
2819 if (ArchiveHeaders)
2820 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose, print_offset: ArchiveMemberOffsets,
2821 ArchitectureName);
2822 Error Err = Error::success();
2823 unsigned I = -1;
2824 bool FoundMember = false;
2825 for (auto &C : A->children(Err)) {
2826 ++I;
2827 if (skipArchiveMember(C, Filename))
2828 continue;
2829 FoundMember = true;
2830 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2831 if (!ChildOrErr) {
2832 if (Error E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2833 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename,
2834 ArchitectureName);
2835 continue;
2836 }
2837 if (MachOObjectFile *O =
2838 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get())) {
2839 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName(), ArchitectureName);
2840 }
2841 }
2842 if (Err)
2843 reportError(E: std::move(Err), FileName: Filename);
2844 if (!FoundMember && !ArchiveMemberFilter.empty())
2845 reportError(File: Filename, Message: "archive does not contain a member named: " +
2846 ArchiveMemberFilter);
2847 } else {
2848 consumeError(Err: AOrErr.takeError());
2849 reportError(File: Filename, Message: "Mach-O universal file for architecture " +
2850 StringRef(I->getArchFlagName()) +
2851 " is not a Mach-O file or an archive file");
2852 }
2853 }
2854}
2855
2856namespace {
2857// The block of info used by the Symbolizer call backs.
2858struct DisassembleInfo {
2859 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2860 std::vector<SectionRef> *Sections, bool verbose)
2861 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2862 bool verbose;
2863 MachOObjectFile *O;
2864 SectionRef S;
2865 SymbolAddressMap *AddrMap;
2866 std::vector<SectionRef> *Sections;
2867 const char *class_name = nullptr;
2868 const char *selector_name = nullptr;
2869 std::unique_ptr<char[]> method = nullptr;
2870 char *demangled_name = nullptr;
2871 uint64_t adrp_addr = 0;
2872 uint32_t adrp_inst = 0;
2873 std::unique_ptr<SymbolAddressMap> bindtable;
2874 uint32_t depth = 0;
2875};
2876} // namespace
2877
2878// SymbolizerGetOpInfo() is the operand information call back function.
2879// This is called to get the symbolic information for operand(s) of an
2880// instruction when it is being done. This routine does this from
2881// the relocation information, symbol table, etc. That block of information
2882// is a pointer to the struct DisassembleInfo that was passed when the
2883// disassembler context was created and passed to back to here when
2884// called back by the disassembler for instruction operands that could have
2885// relocation information. The address of the instruction containing operand is
2886// at the Pc parameter. The immediate value the operand has is passed in
2887// op_info->Value and is at Offset past the start of the instruction and has a
2888// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2889// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2890// names and addends of the symbolic expression to add for the operand. The
2891// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2892// information is returned then this function returns 1 else it returns 0.
2893static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2894 uint64_t OpSize, uint64_t InstSize, int TagType,
2895 void *TagBuf) {
2896 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2897 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2898 uint64_t value = op_info->Value;
2899
2900 // Make sure all fields returned are zero if we don't set them.
2901 memset(s: (void *)op_info, c: '\0', n: sizeof(struct LLVMOpInfo1));
2902 op_info->Value = value;
2903
2904 // If the TagType is not the value 1 which it code knows about or if no
2905 // verbose symbolic information is wanted then just return 0, indicating no
2906 // information is being returned.
2907 if (TagType != 1 || !info->verbose)
2908 return 0;
2909
2910 unsigned int Arch = info->O->getArch();
2911 if (Arch == Triple::x86) {
2912 if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2913 return 0;
2914 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2915 // TODO:
2916 // Search the external relocation entries of a fully linked image
2917 // (if any) for an entry that matches this segment offset.
2918 // uint32_t seg_offset = (Pc + Offset);
2919 return 0;
2920 }
2921 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2922 // for an entry for this section offset.
2923 uint32_t sect_addr = info->S.getAddress();
2924 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2925 bool reloc_found = false;
2926 DataRefImpl Rel;
2927 MachO::any_relocation_info RE;
2928 bool isExtern = false;
2929 SymbolRef Symbol;
2930 bool r_scattered = false;
2931 uint32_t r_value, pair_r_value, r_type;
2932 for (const RelocationRef &Reloc : info->S.relocations()) {
2933 uint64_t RelocOffset = Reloc.getOffset();
2934 if (RelocOffset == sect_offset) {
2935 Rel = Reloc.getRawDataRefImpl();
2936 RE = info->O->getRelocation(Rel);
2937 r_type = info->O->getAnyRelocationType(RE);
2938 r_scattered = info->O->isRelocationScattered(RE);
2939 if (r_scattered) {
2940 r_value = info->O->getScatteredRelocationValue(RE);
2941 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2942 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2943 DataRefImpl RelNext = Rel;
2944 info->O->moveRelocationNext(Rel&: RelNext);
2945 MachO::any_relocation_info RENext;
2946 RENext = info->O->getRelocation(Rel: RelNext);
2947 if (info->O->isRelocationScattered(RE: RENext))
2948 pair_r_value = info->O->getScatteredRelocationValue(RE: RENext);
2949 else
2950 return 0;
2951 }
2952 } else {
2953 isExtern = info->O->getPlainRelocationExternal(RE);
2954 if (isExtern) {
2955 symbol_iterator RelocSym = Reloc.getSymbol();
2956 Symbol = *RelocSym;
2957 }
2958 }
2959 reloc_found = true;
2960 break;
2961 }
2962 }
2963 if (reloc_found && isExtern) {
2964 op_info->AddSymbol.Present = 1;
2965 op_info->AddSymbol.Name =
2966 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
2967 // For i386 extern relocation entries the value in the instruction is
2968 // the offset from the symbol, and value is already set in op_info->Value.
2969 return 1;
2970 }
2971 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2972 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2973 const char *add = GuessSymbolName(value: r_value, AddrMap: info->AddrMap);
2974 const char *sub = GuessSymbolName(value: pair_r_value, AddrMap: info->AddrMap);
2975 uint32_t offset = value - (r_value - pair_r_value);
2976 op_info->AddSymbol.Present = 1;
2977 if (add != nullptr)
2978 op_info->AddSymbol.Name = add;
2979 else
2980 op_info->AddSymbol.Value = r_value;
2981 op_info->SubtractSymbol.Present = 1;
2982 if (sub != nullptr)
2983 op_info->SubtractSymbol.Name = sub;
2984 else
2985 op_info->SubtractSymbol.Value = pair_r_value;
2986 op_info->Value = offset;
2987 return 1;
2988 }
2989 return 0;
2990 }
2991 if (Arch == Triple::x86_64) {
2992 if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2993 return 0;
2994 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2995 // relocation entries of a linked image (if any) for an entry that matches
2996 // this segment offset.
2997 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2998 uint64_t seg_offset = Pc + Offset;
2999 bool reloc_found = false;
3000 DataRefImpl Rel;
3001 MachO::any_relocation_info RE;
3002 bool isExtern = false;
3003 SymbolRef Symbol;
3004 for (const RelocationRef &Reloc : info->O->external_relocations()) {
3005 uint64_t RelocOffset = Reloc.getOffset();
3006 if (RelocOffset == seg_offset) {
3007 Rel = Reloc.getRawDataRefImpl();
3008 RE = info->O->getRelocation(Rel);
3009 // external relocation entries should always be external.
3010 isExtern = info->O->getPlainRelocationExternal(RE);
3011 if (isExtern) {
3012 symbol_iterator RelocSym = Reloc.getSymbol();
3013 Symbol = *RelocSym;
3014 }
3015 reloc_found = true;
3016 break;
3017 }
3018 }
3019 if (reloc_found && isExtern) {
3020 // The Value passed in will be adjusted by the Pc if the instruction
3021 // adds the Pc. But for x86_64 external relocation entries the Value
3022 // is the offset from the external symbol.
3023 if (info->O->getAnyRelocationPCRel(RE))
3024 op_info->Value -= Pc + InstSize;
3025 const char *name =
3026 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3027 op_info->AddSymbol.Present = 1;
3028 op_info->AddSymbol.Name = name;
3029 return 1;
3030 }
3031 return 0;
3032 }
3033 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3034 // for an entry for this section offset.
3035 uint64_t sect_addr = info->S.getAddress();
3036 uint64_t sect_offset = (Pc + Offset) - sect_addr;
3037 bool reloc_found = false;
3038 DataRefImpl Rel;
3039 MachO::any_relocation_info RE;
3040 bool isExtern = false;
3041 SymbolRef Symbol;
3042 for (const RelocationRef &Reloc : info->S.relocations()) {
3043 uint64_t RelocOffset = Reloc.getOffset();
3044 if (RelocOffset == sect_offset) {
3045 Rel = Reloc.getRawDataRefImpl();
3046 RE = info->O->getRelocation(Rel);
3047 // NOTE: Scattered relocations don't exist on x86_64.
3048 isExtern = info->O->getPlainRelocationExternal(RE);
3049 if (isExtern) {
3050 symbol_iterator RelocSym = Reloc.getSymbol();
3051 Symbol = *RelocSym;
3052 }
3053 reloc_found = true;
3054 break;
3055 }
3056 }
3057 if (reloc_found && isExtern) {
3058 // The Value passed in will be adjusted by the Pc if the instruction
3059 // adds the Pc. But for x86_64 external relocation entries the Value
3060 // is the offset from the external symbol.
3061 if (info->O->getAnyRelocationPCRel(RE))
3062 op_info->Value -= Pc + InstSize;
3063 const char *name =
3064 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3065 unsigned Type = info->O->getAnyRelocationType(RE);
3066 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
3067 DataRefImpl RelNext = Rel;
3068 info->O->moveRelocationNext(Rel&: RelNext);
3069 MachO::any_relocation_info RENext = info->O->getRelocation(Rel: RelNext);
3070 unsigned TypeNext = info->O->getAnyRelocationType(RE: RENext);
3071 bool isExternNext = info->O->getPlainRelocationExternal(RE: RENext);
3072 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RE: RENext);
3073 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
3074 op_info->SubtractSymbol.Present = 1;
3075 op_info->SubtractSymbol.Name = name;
3076 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(Index: SymbolNum);
3077 Symbol = *RelocSymNext;
3078 name = unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3079 }
3080 }
3081 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
3082 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
3083 op_info->AddSymbol.Present = 1;
3084 op_info->AddSymbol.Name = name;
3085 return 1;
3086 }
3087 return 0;
3088 }
3089 if (Arch == Triple::arm) {
3090 if (Offset != 0 || (InstSize != 4 && InstSize != 2))
3091 return 0;
3092 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3093 // TODO:
3094 // Search the external relocation entries of a fully linked image
3095 // (if any) for an entry that matches this segment offset.
3096 // uint32_t seg_offset = (Pc + Offset);
3097 return 0;
3098 }
3099 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3100 // for an entry for this section offset.
3101 uint32_t sect_addr = info->S.getAddress();
3102 uint32_t sect_offset = (Pc + Offset) - sect_addr;
3103 DataRefImpl Rel;
3104 MachO::any_relocation_info RE;
3105 bool isExtern = false;
3106 SymbolRef Symbol;
3107 bool r_scattered = false;
3108 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
3109 auto Reloc =
3110 find_if(Range: info->S.relocations(), P: [&](const RelocationRef &Reloc) {
3111 uint64_t RelocOffset = Reloc.getOffset();
3112 return RelocOffset == sect_offset;
3113 });
3114
3115 if (Reloc == info->S.relocations().end())
3116 return 0;
3117
3118 Rel = Reloc->getRawDataRefImpl();
3119 RE = info->O->getRelocation(Rel);
3120 r_length = info->O->getAnyRelocationLength(RE);
3121 r_scattered = info->O->isRelocationScattered(RE);
3122 if (r_scattered) {
3123 r_value = info->O->getScatteredRelocationValue(RE);
3124 r_type = info->O->getScatteredRelocationType(RE);
3125 } else {
3126 r_type = info->O->getAnyRelocationType(RE);
3127 isExtern = info->O->getPlainRelocationExternal(RE);
3128 if (isExtern) {
3129 symbol_iterator RelocSym = Reloc->getSymbol();
3130 Symbol = *RelocSym;
3131 }
3132 }
3133 if (r_type == MachO::ARM_RELOC_HALF ||
3134 r_type == MachO::ARM_RELOC_SECTDIFF ||
3135 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
3136 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3137 DataRefImpl RelNext = Rel;
3138 info->O->moveRelocationNext(Rel&: RelNext);
3139 MachO::any_relocation_info RENext;
3140 RENext = info->O->getRelocation(Rel: RelNext);
3141 other_half = info->O->getAnyRelocationAddress(RE: RENext) & 0xffff;
3142 if (info->O->isRelocationScattered(RE: RENext))
3143 pair_r_value = info->O->getScatteredRelocationValue(RE: RENext);
3144 }
3145
3146 if (isExtern) {
3147 const char *name =
3148 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3149 op_info->AddSymbol.Present = 1;
3150 op_info->AddSymbol.Name = name;
3151 switch (r_type) {
3152 case MachO::ARM_RELOC_HALF:
3153 if ((r_length & 0x1) == 1) {
3154 op_info->Value = value << 16 | other_half;
3155 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3156 } else {
3157 op_info->Value = other_half << 16 | value;
3158 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3159 }
3160 break;
3161 default:
3162 break;
3163 }
3164 return 1;
3165 }
3166 // If we have a branch that is not an external relocation entry then
3167 // return 0 so the code in tryAddingSymbolicOperand() can use the
3168 // SymbolLookUp call back with the branch target address to look up the
3169 // symbol and possibility add an annotation for a symbol stub.
3170 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
3171 r_type == MachO::ARM_THUMB_RELOC_BR22))
3172 return 0;
3173
3174 uint32_t offset = 0;
3175 if (r_type == MachO::ARM_RELOC_HALF ||
3176 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3177 if ((r_length & 0x1) == 1)
3178 value = value << 16 | other_half;
3179 else
3180 value = other_half << 16 | value;
3181 }
3182 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
3183 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
3184 offset = value - r_value;
3185 value = r_value;
3186 }
3187
3188 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3189 if ((r_length & 0x1) == 1)
3190 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3191 else
3192 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3193 const char *add = GuessSymbolName(value: r_value, AddrMap: info->AddrMap);
3194 const char *sub = GuessSymbolName(value: pair_r_value, AddrMap: info->AddrMap);
3195 int32_t offset = value - (r_value - pair_r_value);
3196 op_info->AddSymbol.Present = 1;
3197 if (add != nullptr)
3198 op_info->AddSymbol.Name = add;
3199 else
3200 op_info->AddSymbol.Value = r_value;
3201 op_info->SubtractSymbol.Present = 1;
3202 if (sub != nullptr)
3203 op_info->SubtractSymbol.Name = sub;
3204 else
3205 op_info->SubtractSymbol.Value = pair_r_value;
3206 op_info->Value = offset;
3207 return 1;
3208 }
3209
3210 op_info->AddSymbol.Present = 1;
3211 op_info->Value = offset;
3212 if (r_type == MachO::ARM_RELOC_HALF) {
3213 if ((r_length & 0x1) == 1)
3214 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3215 else
3216 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3217 }
3218 const char *add = GuessSymbolName(value, AddrMap: info->AddrMap);
3219 if (add != nullptr) {
3220 op_info->AddSymbol.Name = add;
3221 return 1;
3222 }
3223 op_info->AddSymbol.Value = value;
3224 return 1;
3225 }
3226 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32) {
3227 if (Offset != 0 || InstSize != 4)
3228 return 0;
3229 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3230 // TODO:
3231 // Search the external relocation entries of a fully linked image
3232 // (if any) for an entry that matches this segment offset.
3233 // uint64_t seg_offset = (Pc + Offset);
3234 return 0;
3235 }
3236 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3237 // for an entry for this section offset.
3238 uint64_t sect_addr = info->S.getAddress();
3239 uint64_t sect_offset = (Pc + Offset) - sect_addr;
3240 auto Reloc =
3241 find_if(Range: info->S.relocations(), P: [&](const RelocationRef &Reloc) {
3242 uint64_t RelocOffset = Reloc.getOffset();
3243 return RelocOffset == sect_offset;
3244 });
3245
3246 if (Reloc == info->S.relocations().end())
3247 return 0;
3248
3249 DataRefImpl Rel = Reloc->getRawDataRefImpl();
3250 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
3251 uint32_t r_type = info->O->getAnyRelocationType(RE);
3252 if (r_type == MachO::ARM64_RELOC_ADDEND) {
3253 DataRefImpl RelNext = Rel;
3254 info->O->moveRelocationNext(Rel&: RelNext);
3255 MachO::any_relocation_info RENext = info->O->getRelocation(Rel: RelNext);
3256 if (value == 0) {
3257 value = info->O->getPlainRelocationSymbolNum(RE: RENext);
3258 op_info->Value = value;
3259 }
3260 }
3261 // NOTE: Scattered relocations don't exist on arm64.
3262 if (!info->O->getPlainRelocationExternal(RE))
3263 return 0;
3264 const char *name =
3265 unwrapOrError(EO: Reloc->getSymbol()->getName(), Args: info->O->getFileName())
3266 .data();
3267 op_info->AddSymbol.Present = 1;
3268 op_info->AddSymbol.Name = name;
3269
3270 switch (r_type) {
3271 case MachO::ARM64_RELOC_PAGE21:
3272 /* @page */
3273 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
3274 break;
3275 case MachO::ARM64_RELOC_PAGEOFF12:
3276 /* @pageoff */
3277 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
3278 break;
3279 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
3280 /* @gotpage */
3281 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
3282 break;
3283 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
3284 /* @gotpageoff */
3285 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
3286 break;
3287 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
3288 /* @tvlppage is not implemented in llvm-mc */
3289 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
3290 break;
3291 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
3292 /* @tvlppageoff is not implemented in llvm-mc */
3293 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3294 break;
3295 default:
3296 case MachO::ARM64_RELOC_BRANCH26:
3297 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3298 break;
3299 }
3300 return 1;
3301 }
3302 return 0;
3303}
3304
3305// GuessCstringPointer is passed the address of what might be a pointer to a
3306// literal string in a cstring section. If that address is in a cstring section
3307// it returns a pointer to that string. Else it returns nullptr.
3308static const char *GuessCstringPointer(uint64_t ReferenceValue,
3309 struct DisassembleInfo *info) {
3310 for (const auto &Load : info->O->load_commands()) {
3311 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3312 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3313 for (unsigned J = 0; J < Seg.nsects; ++J) {
3314 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3315 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3316 if (section_type == MachO::S_CSTRING_LITERALS &&
3317 ReferenceValue >= Sec.addr &&
3318 ReferenceValue < Sec.addr + Sec.size) {
3319 uint64_t sect_offset = ReferenceValue - Sec.addr;
3320 uint64_t object_offset = Sec.offset + sect_offset;
3321 StringRef MachOContents = info->O->getData();
3322 uint64_t object_size = MachOContents.size();
3323 const char *object_addr = MachOContents.data();
3324 if (object_offset < object_size) {
3325 const char *name = object_addr + object_offset;
3326 return name;
3327 } else {
3328 return nullptr;
3329 }
3330 }
3331 }
3332 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3333 MachO::segment_command Seg = info->O->getSegmentLoadCommand(L: Load);
3334 for (unsigned J = 0; J < Seg.nsects; ++J) {
3335 MachO::section Sec = info->O->getSection(L: Load, Index: J);
3336 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3337 if (section_type == MachO::S_CSTRING_LITERALS &&
3338 ReferenceValue >= Sec.addr &&
3339 ReferenceValue < Sec.addr + Sec.size) {
3340 uint64_t sect_offset = ReferenceValue - Sec.addr;
3341 uint64_t object_offset = Sec.offset + sect_offset;
3342 StringRef MachOContents = info->O->getData();
3343 uint64_t object_size = MachOContents.size();
3344 const char *object_addr = MachOContents.data();
3345 if (object_offset < object_size) {
3346 const char *name = object_addr + object_offset;
3347 return name;
3348 } else {
3349 return nullptr;
3350 }
3351 }
3352 }
3353 }
3354 }
3355 return nullptr;
3356}
3357
3358// GuessIndirectSymbol returns the name of the indirect symbol for the
3359// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
3360// an address of a symbol stub or a lazy or non-lazy pointer to associate the
3361// symbol name being referenced by the stub or pointer.
3362static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3363 struct DisassembleInfo *info) {
3364 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3365 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3366 for (const auto &Load : info->O->load_commands()) {
3367 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3368 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3369 for (unsigned J = 0; J < Seg.nsects; ++J) {
3370 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3371 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3372 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3373 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3374 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3375 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3376 section_type == MachO::S_SYMBOL_STUBS) &&
3377 ReferenceValue >= Sec.addr &&
3378 ReferenceValue < Sec.addr + Sec.size) {
3379 uint32_t stride;
3380 if (section_type == MachO::S_SYMBOL_STUBS)
3381 stride = Sec.reserved2;
3382 else
3383 stride = 8;
3384 if (stride == 0)
3385 return nullptr;
3386 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3387 if (index < Dysymtab.nindirectsyms) {
3388 uint32_t indirect_symbol =
3389 info->O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: index);
3390 if (indirect_symbol < Symtab.nsyms) {
3391 symbol_iterator Sym = info->O->getSymbolByIndex(Index: indirect_symbol);
3392 return unwrapOrError(EO: Sym->getName(), Args: info->O->getFileName())
3393 .data();
3394 }
3395 }
3396 }
3397 }
3398 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3399 MachO::segment_command Seg = info->O->getSegmentLoadCommand(L: Load);
3400 for (unsigned J = 0; J < Seg.nsects; ++J) {
3401 MachO::section Sec = info->O->getSection(L: Load, Index: J);
3402 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3403 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3404 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3405 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3406 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3407 section_type == MachO::S_SYMBOL_STUBS) &&
3408 ReferenceValue >= Sec.addr &&
3409 ReferenceValue < Sec.addr + Sec.size) {
3410 uint32_t stride;
3411 if (section_type == MachO::S_SYMBOL_STUBS)
3412 stride = Sec.reserved2;
3413 else
3414 stride = 4;
3415 if (stride == 0)
3416 return nullptr;
3417 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3418 if (index < Dysymtab.nindirectsyms) {
3419 uint32_t indirect_symbol =
3420 info->O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: index);
3421 if (indirect_symbol < Symtab.nsyms) {
3422 symbol_iterator Sym = info->O->getSymbolByIndex(Index: indirect_symbol);
3423 return unwrapOrError(EO: Sym->getName(), Args: info->O->getFileName())
3424 .data();
3425 }
3426 }
3427 }
3428 }
3429 }
3430 }
3431 return nullptr;
3432}
3433
3434// method_reference() is called passing it the ReferenceName that might be
3435// a reference it to an Objective-C method call. If so then it allocates and
3436// assembles a method call string with the values last seen and saved in
3437// the DisassembleInfo's class_name and selector_name fields. This is saved
3438// into the method field of the info and any previous string is free'ed.
3439// Then the class_name field in the info is set to nullptr. The method call
3440// string is set into ReferenceName and ReferenceType is set to
3441// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3442// then both ReferenceType and ReferenceName are left unchanged.
3443static void method_reference(struct DisassembleInfo *info,
3444 uint64_t *ReferenceType,
3445 const char **ReferenceName) {
3446 unsigned int Arch = info->O->getArch();
3447 if (*ReferenceName != nullptr) {
3448 if (strcmp(s1: *ReferenceName, s2: "_objc_msgSend") == 0) {
3449 if (info->selector_name != nullptr) {
3450 if (info->class_name != nullptr) {
3451 info->method = std::make_unique<char[]>(
3452 num: 5 + strlen(s: info->class_name) + strlen(s: info->selector_name));
3453 char *method = info->method.get();
3454 if (method != nullptr) {
3455 strcpy(dest: method, src: "+[");
3456 strcat(dest: method, src: info->class_name);
3457 strcat(dest: method, src: " ");
3458 strcat(dest: method, src: info->selector_name);
3459 strcat(dest: method, src: "]");
3460 *ReferenceName = method;
3461 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3462 }
3463 } else {
3464 info->method =
3465 std::make_unique<char[]>(num: 9 + strlen(s: info->selector_name));
3466 char *method = info->method.get();
3467 if (method != nullptr) {
3468 if (Arch == Triple::x86_64)
3469 strcpy(dest: method, src: "-[%rdi ");
3470 else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32)
3471 strcpy(dest: method, src: "-[x0 ");
3472 else
3473 strcpy(dest: method, src: "-[r? ");
3474 strcat(dest: method, src: info->selector_name);
3475 strcat(dest: method, src: "]");
3476 *ReferenceName = method;
3477 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3478 }
3479 }
3480 info->class_name = nullptr;
3481 }
3482 } else if (strcmp(s1: *ReferenceName, s2: "_objc_msgSendSuper2") == 0) {
3483 if (info->selector_name != nullptr) {
3484 info->method =
3485 std::make_unique<char[]>(num: 17 + strlen(s: info->selector_name));
3486 char *method = info->method.get();
3487 if (method != nullptr) {
3488 if (Arch == Triple::x86_64)
3489 strcpy(dest: method, src: "-[[%rdi super] ");
3490 else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32)
3491 strcpy(dest: method, src: "-[[x0 super] ");
3492 else
3493 strcpy(dest: method, src: "-[[r? super] ");
3494 strcat(dest: method, src: info->selector_name);
3495 strcat(dest: method, src: "]");
3496 *ReferenceName = method;
3497 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3498 }
3499 info->class_name = nullptr;
3500 }
3501 }
3502 }
3503}
3504
3505// GuessPointerPointer() is passed the address of what might be a pointer to
3506// a reference to an Objective-C class, selector, message ref or cfstring.
3507// If so the value of the pointer is returned and one of the booleans are set
3508// to true. If not zero is returned and all the booleans are set to false.
3509static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3510 struct DisassembleInfo *info,
3511 bool &classref, bool &selref, bool &msgref,
3512 bool &cfstring) {
3513 classref = false;
3514 selref = false;
3515 msgref = false;
3516 cfstring = false;
3517 for (const auto &Load : info->O->load_commands()) {
3518 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3519 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3520 for (unsigned J = 0; J < Seg.nsects; ++J) {
3521 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3522 if ((strncmp(s1: Sec.sectname, s2: "__objc_selrefs", n: 16) == 0 ||
3523 strncmp(s1: Sec.sectname, s2: "__objc_classrefs", n: 16) == 0 ||
3524 strncmp(s1: Sec.sectname, s2: "__objc_superrefs", n: 16) == 0 ||
3525 strncmp(s1: Sec.sectname, s2: "__objc_msgrefs", n: 16) == 0 ||
3526 strncmp(s1: Sec.sectname, s2: "__cfstring", n: 16) == 0) &&
3527 ReferenceValue >= Sec.addr &&
3528 ReferenceValue < Sec.addr + Sec.size) {
3529 uint64_t sect_offset = ReferenceValue - Sec.addr;
3530 uint64_t object_offset = Sec.offset + sect_offset;
3531 StringRef MachOContents = info->O->getData();
3532 uint64_t object_size = MachOContents.size();
3533 const char *object_addr = MachOContents.data();
3534 if (object_offset < object_size) {
3535 uint64_t pointer_value;
3536 memcpy(dest: &pointer_value, src: object_addr + object_offset,
3537 n: sizeof(uint64_t));
3538 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3539 sys::swapByteOrder(Value&: pointer_value);
3540 if (strncmp(s1: Sec.sectname, s2: "__objc_selrefs", n: 16) == 0)
3541 selref = true;
3542 else if (strncmp(s1: Sec.sectname, s2: "__objc_classrefs", n: 16) == 0 ||
3543 strncmp(s1: Sec.sectname, s2: "__objc_superrefs", n: 16) == 0)
3544 classref = true;
3545 else if (strncmp(s1: Sec.sectname, s2: "__objc_msgrefs", n: 16) == 0 &&
3546 ReferenceValue + 8 < Sec.addr + Sec.size) {
3547 msgref = true;
3548 memcpy(dest: &pointer_value, src: object_addr + object_offset + 8,
3549 n: sizeof(uint64_t));
3550 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3551 sys::swapByteOrder(Value&: pointer_value);
3552 } else if (strncmp(s1: Sec.sectname, s2: "__cfstring", n: 16) == 0)
3553 cfstring = true;
3554 return pointer_value;
3555 } else {
3556 return 0;
3557 }
3558 }
3559 }
3560 }
3561 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3562 }
3563 return 0;
3564}
3565
3566// get_pointer_64 returns a pointer to the bytes in the object file at the
3567// Address from a section in the Mach-O file. And indirectly returns the
3568// offset into the section, number of bytes left in the section past the offset
3569// and which section is was being referenced. If the Address is not in a
3570// section nullptr is returned.
3571static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3572 uint32_t &left, SectionRef &S,
3573 DisassembleInfo *info,
3574 bool objc_only = false) {
3575 offset = 0;
3576 left = 0;
3577 S = SectionRef();
3578 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3579 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3580 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3581 if (SectSize == 0)
3582 continue;
3583 if (objc_only) {
3584 StringRef SectName;
3585 Expected<StringRef> SecNameOrErr =
3586 ((*(info->Sections))[SectIdx]).getName();
3587 if (SecNameOrErr)
3588 SectName = *SecNameOrErr;
3589 else
3590 consumeError(Err: SecNameOrErr.takeError());
3591
3592 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3593 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
3594 if (SegName != "__OBJC" && SectName != "__cstring")
3595 continue;
3596 }
3597 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3598 S = (*(info->Sections))[SectIdx];
3599 offset = Address - SectAddress;
3600 left = SectSize - offset;
3601 StringRef SectContents = unwrapOrError(
3602 EO: ((*(info->Sections))[SectIdx]).getContents(), Args: info->O->getFileName());
3603 return SectContents.data() + offset;
3604 }
3605 }
3606 return nullptr;
3607}
3608
3609static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3610 uint32_t &left, SectionRef &S,
3611 DisassembleInfo *info,
3612 bool objc_only = false) {
3613 return get_pointer_64(Address, offset, left, S, info, objc_only);
3614}
3615
3616// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3617// the symbol indirectly through n_value. Based on the relocation information
3618// for the specified section offset in the specified section reference.
3619// If no relocation information is found and a non-zero ReferenceValue for the
3620// symbol is passed, look up that address in the info's AddrMap.
3621static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3622 DisassembleInfo *info, uint64_t &n_value,
3623 uint64_t ReferenceValue = 0) {
3624 n_value = 0;
3625 if (!info->verbose)
3626 return nullptr;
3627
3628 // See if there is an external relocation entry at the sect_offset.
3629 bool reloc_found = false;
3630 DataRefImpl Rel;
3631 MachO::any_relocation_info RE;
3632 bool isExtern = false;
3633 SymbolRef Symbol;
3634 for (const RelocationRef &Reloc : S.relocations()) {
3635 uint64_t RelocOffset = Reloc.getOffset();
3636 if (RelocOffset == sect_offset) {
3637 Rel = Reloc.getRawDataRefImpl();
3638 RE = info->O->getRelocation(Rel);
3639 if (info->O->isRelocationScattered(RE))
3640 continue;
3641 isExtern = info->O->getPlainRelocationExternal(RE);
3642 if (isExtern) {
3643 symbol_iterator RelocSym = Reloc.getSymbol();
3644 Symbol = *RelocSym;
3645 }
3646 reloc_found = true;
3647 break;
3648 }
3649 }
3650 // If there is an external relocation entry for a symbol in this section
3651 // at this section_offset then use that symbol's value for the n_value
3652 // and return its name.
3653 const char *SymbolName = nullptr;
3654 if (reloc_found && isExtern) {
3655 n_value = cantFail(ValOrErr: Symbol.getValue());
3656 StringRef Name = unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName());
3657 if (!Name.empty()) {
3658 SymbolName = Name.data();
3659 return SymbolName;
3660 }
3661 }
3662
3663 // TODO: For fully linked images, look through the external relocation
3664 // entries off the dynamic symtab command. For these the r_offset is from the
3665 // start of the first writeable segment in the Mach-O file. So the offset
3666 // to this section from that segment is passed to this routine by the caller,
3667 // as the database_offset. Which is the difference of the section's starting
3668 // address and the first writable segment.
3669 //
3670 // NOTE: need add passing the database_offset to this routine.
3671
3672 // We did not find an external relocation entry so look up the ReferenceValue
3673 // as an address of a symbol and if found return that symbol's name.
3674 SymbolName = GuessSymbolName(value: ReferenceValue, AddrMap: info->AddrMap);
3675
3676 return SymbolName;
3677}
3678
3679static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3680 DisassembleInfo *info,
3681 uint32_t ReferenceValue) {
3682 uint64_t n_value64;
3683 return get_symbol_64(sect_offset, S, info, n_value&: n_value64, ReferenceValue);
3684}
3685
3686namespace {
3687
3688// These are structs in the Objective-C meta data and read to produce the
3689// comments for disassembly. While these are part of the ABI they are no
3690// public definitions. So the are here not in include/llvm/BinaryFormat/MachO.h
3691// .
3692
3693// The cfstring object in a 64-bit Mach-O file.
3694struct cfstring64_t {
3695 uint64_t isa; // class64_t * (64-bit pointer)
3696 uint64_t flags; // flag bits
3697 uint64_t characters; // char * (64-bit pointer)
3698 uint64_t length; // number of non-NULL characters in above
3699};
3700
3701// The class object in a 64-bit Mach-O file.
3702struct class64_t {
3703 uint64_t isa; // class64_t * (64-bit pointer)
3704 uint64_t superclass; // class64_t * (64-bit pointer)
3705 uint64_t cache; // Cache (64-bit pointer)
3706 uint64_t vtable; // IMP * (64-bit pointer)
3707 uint64_t data; // class_ro64_t * (64-bit pointer)
3708};
3709
3710struct class32_t {
3711 uint32_t isa; /* class32_t * (32-bit pointer) */
3712 uint32_t superclass; /* class32_t * (32-bit pointer) */
3713 uint32_t cache; /* Cache (32-bit pointer) */
3714 uint32_t vtable; /* IMP * (32-bit pointer) */
3715 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3716};
3717
3718struct class_ro64_t {
3719 uint32_t flags;
3720 uint32_t instanceStart;
3721 uint32_t instanceSize;
3722 uint32_t reserved;
3723 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3724 uint64_t name; // const char * (64-bit pointer)
3725 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3726 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3727 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3728 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3729 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3730};
3731
3732struct class_ro32_t {
3733 uint32_t flags;
3734 uint32_t instanceStart;
3735 uint32_t instanceSize;
3736 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3737 uint32_t name; /* const char * (32-bit pointer) */
3738 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3739 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3740 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3741 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3742 uint32_t baseProperties; /* const struct objc_property_list *
3743 (32-bit pointer) */
3744};
3745
3746/* Values for class_ro{64,32}_t->flags */
3747#define RO_META (1 << 0)
3748#define RO_ROOT (1 << 1)
3749#define RO_HAS_CXX_STRUCTORS (1 << 2)
3750
3751/* Values for method_list{64,32}_t->entsize */
3752#define ML_HAS_RELATIVE_PTRS (1 << 31)
3753#define ML_ENTSIZE_MASK 0xFFFF
3754
3755struct method_list64_t {
3756 uint32_t entsize;
3757 uint32_t count;
3758 /* struct method64_t first; These structures follow inline */
3759};
3760
3761struct method_list32_t {
3762 uint32_t entsize;
3763 uint32_t count;
3764 /* struct method32_t first; These structures follow inline */
3765};
3766
3767struct method64_t {
3768 uint64_t name; /* SEL (64-bit pointer) */
3769 uint64_t types; /* const char * (64-bit pointer) */
3770 uint64_t imp; /* IMP (64-bit pointer) */
3771};
3772
3773struct method32_t {
3774 uint32_t name; /* SEL (32-bit pointer) */
3775 uint32_t types; /* const char * (32-bit pointer) */
3776 uint32_t imp; /* IMP (32-bit pointer) */
3777};
3778
3779struct method_relative_t {
3780 int32_t name; /* SEL (32-bit relative) */
3781 int32_t types; /* const char * (32-bit relative) */
3782 int32_t imp; /* IMP (32-bit relative) */
3783};
3784
3785struct protocol_list64_t {
3786 uint64_t count; /* uintptr_t (a 64-bit value) */
3787 /* struct protocol64_t * list[0]; These pointers follow inline */
3788};
3789
3790struct protocol_list32_t {
3791 uint32_t count; /* uintptr_t (a 32-bit value) */
3792 /* struct protocol32_t * list[0]; These pointers follow inline */
3793};
3794
3795struct protocol64_t {
3796 uint64_t isa; /* id * (64-bit pointer) */
3797 uint64_t name; /* const char * (64-bit pointer) */
3798 uint64_t protocols; /* struct protocol_list64_t *
3799 (64-bit pointer) */
3800 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3801 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3802 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3803 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3804 uint64_t instanceProperties; /* struct objc_property_list *
3805 (64-bit pointer) */
3806};
3807
3808struct protocol32_t {
3809 uint32_t isa; /* id * (32-bit pointer) */
3810 uint32_t name; /* const char * (32-bit pointer) */
3811 uint32_t protocols; /* struct protocol_list_t *
3812 (32-bit pointer) */
3813 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3814 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3815 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3816 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3817 uint32_t instanceProperties; /* struct objc_property_list *
3818 (32-bit pointer) */
3819};
3820
3821struct ivar_list64_t {
3822 uint32_t entsize;
3823 uint32_t count;
3824 /* struct ivar64_t first; These structures follow inline */
3825};
3826
3827struct ivar_list32_t {
3828 uint32_t entsize;
3829 uint32_t count;
3830 /* struct ivar32_t first; These structures follow inline */
3831};
3832
3833struct ivar64_t {
3834 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3835 uint64_t name; /* const char * (64-bit pointer) */
3836 uint64_t type; /* const char * (64-bit pointer) */
3837 uint32_t alignment;
3838 uint32_t size;
3839};
3840
3841struct ivar32_t {
3842 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3843 uint32_t name; /* const char * (32-bit pointer) */
3844 uint32_t type; /* const char * (32-bit pointer) */
3845 uint32_t alignment;
3846 uint32_t size;
3847};
3848
3849struct objc_property_list64 {
3850 uint32_t entsize;
3851 uint32_t count;
3852 /* struct objc_property64 first; These structures follow inline */
3853};
3854
3855struct objc_property_list32 {
3856 uint32_t entsize;
3857 uint32_t count;
3858 /* struct objc_property32 first; These structures follow inline */
3859};
3860
3861struct objc_property64 {
3862 uint64_t name; /* const char * (64-bit pointer) */
3863 uint64_t attributes; /* const char * (64-bit pointer) */
3864};
3865
3866struct objc_property32 {
3867 uint32_t name; /* const char * (32-bit pointer) */
3868 uint32_t attributes; /* const char * (32-bit pointer) */
3869};
3870
3871struct category64_t {
3872 uint64_t name; /* const char * (64-bit pointer) */
3873 uint64_t cls; /* struct class_t * (64-bit pointer) */
3874 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3875 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3876 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3877 uint64_t instanceProperties; /* struct objc_property_list *
3878 (64-bit pointer) */
3879};
3880
3881struct category32_t {
3882 uint32_t name; /* const char * (32-bit pointer) */
3883 uint32_t cls; /* struct class_t * (32-bit pointer) */
3884 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3885 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3886 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3887 uint32_t instanceProperties; /* struct objc_property_list *
3888 (32-bit pointer) */
3889};
3890
3891struct objc_image_info64 {
3892 uint32_t version;
3893 uint32_t flags;
3894};
3895struct objc_image_info32 {
3896 uint32_t version;
3897 uint32_t flags;
3898};
3899struct imageInfo_t {
3900 uint32_t version;
3901 uint32_t flags;
3902};
3903/* masks for objc_image_info.flags */
3904#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3905#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3906#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3907#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3908
3909struct message_ref64 {
3910 uint64_t imp; /* IMP (64-bit pointer) */
3911 uint64_t sel; /* SEL (64-bit pointer) */
3912};
3913
3914struct message_ref32 {
3915 uint32_t imp; /* IMP (32-bit pointer) */
3916 uint32_t sel; /* SEL (32-bit pointer) */
3917};
3918
3919// Objective-C 1 (32-bit only) meta data structs.
3920
3921struct objc_module_t {
3922 uint32_t version;
3923 uint32_t size;
3924 uint32_t name; /* char * (32-bit pointer) */
3925 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3926};
3927
3928struct objc_symtab_t {
3929 uint32_t sel_ref_cnt;
3930 uint32_t refs; /* SEL * (32-bit pointer) */
3931 uint16_t cls_def_cnt;
3932 uint16_t cat_def_cnt;
3933 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3934};
3935
3936struct objc_class_t {
3937 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3938 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3939 uint32_t name; /* const char * (32-bit pointer) */
3940 int32_t version;
3941 int32_t info;
3942 int32_t instance_size;
3943 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3944 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3945 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3946 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3947};
3948
3949#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3950// class is not a metaclass
3951#define CLS_CLASS 0x1
3952// class is a metaclass
3953#define CLS_META 0x2
3954
3955struct objc_category_t {
3956 uint32_t category_name; /* char * (32-bit pointer) */
3957 uint32_t class_name; /* char * (32-bit pointer) */
3958 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3959 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3960 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3961};
3962
3963struct objc_ivar_t {
3964 uint32_t ivar_name; /* char * (32-bit pointer) */
3965 uint32_t ivar_type; /* char * (32-bit pointer) */
3966 int32_t ivar_offset;
3967};
3968
3969struct objc_ivar_list_t {
3970 int32_t ivar_count;
3971 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3972};
3973
3974struct objc_method_list_t {
3975 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3976 int32_t method_count;
3977 // struct objc_method_t method_list[1]; /* variable length structure */
3978};
3979
3980struct objc_method_t {
3981 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3982 uint32_t method_types; /* char * (32-bit pointer) */
3983 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3984 (32-bit pointer) */
3985};
3986
3987struct objc_protocol_list_t {
3988 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3989 int32_t count;
3990 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3991 // (32-bit pointer) */
3992};
3993
3994struct objc_protocol_t {
3995 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3996 uint32_t protocol_name; /* char * (32-bit pointer) */
3997 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3998 uint32_t instance_methods; /* struct objc_method_description_list *
3999 (32-bit pointer) */
4000 uint32_t class_methods; /* struct objc_method_description_list *
4001 (32-bit pointer) */
4002};
4003
4004struct objc_method_description_list_t {
4005 int32_t count;
4006 // struct objc_method_description_t list[1];
4007};
4008
4009struct objc_method_description_t {
4010 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
4011 uint32_t types; /* char * (32-bit pointer) */
4012};
4013
4014inline void swapStruct(struct cfstring64_t &cfs) {
4015 sys::swapByteOrder(Value&: cfs.isa);
4016 sys::swapByteOrder(Value&: cfs.flags);
4017 sys::swapByteOrder(Value&: cfs.characters);
4018 sys::swapByteOrder(Value&: cfs.length);
4019}
4020
4021inline void swapStruct(struct class64_t &c) {
4022 sys::swapByteOrder(Value&: c.isa);
4023 sys::swapByteOrder(Value&: c.superclass);
4024 sys::swapByteOrder(Value&: c.cache);
4025 sys::swapByteOrder(Value&: c.vtable);
4026 sys::swapByteOrder(Value&: c.data);
4027}
4028
4029inline void swapStruct(struct class32_t &c) {
4030 sys::swapByteOrder(Value&: c.isa);
4031 sys::swapByteOrder(Value&: c.superclass);
4032 sys::swapByteOrder(Value&: c.cache);
4033 sys::swapByteOrder(Value&: c.vtable);
4034 sys::swapByteOrder(Value&: c.data);
4035}
4036
4037inline void swapStruct(struct class_ro64_t &cro) {
4038 sys::swapByteOrder(Value&: cro.flags);
4039 sys::swapByteOrder(Value&: cro.instanceStart);
4040 sys::swapByteOrder(Value&: cro.instanceSize);
4041 sys::swapByteOrder(Value&: cro.reserved);
4042 sys::swapByteOrder(Value&: cro.ivarLayout);
4043 sys::swapByteOrder(Value&: cro.name);
4044 sys::swapByteOrder(Value&: cro.baseMethods);
4045 sys::swapByteOrder(Value&: cro.baseProtocols);
4046 sys::swapByteOrder(Value&: cro.ivars);
4047 sys::swapByteOrder(Value&: cro.weakIvarLayout);
4048 sys::swapByteOrder(Value&: cro.baseProperties);
4049}
4050
4051inline void swapStruct(struct class_ro32_t &cro) {
4052 sys::swapByteOrder(Value&: cro.flags);
4053 sys::swapByteOrder(Value&: cro.instanceStart);
4054 sys::swapByteOrder(Value&: cro.instanceSize);
4055 sys::swapByteOrder(Value&: cro.ivarLayout);
4056 sys::swapByteOrder(Value&: cro.name);
4057 sys::swapByteOrder(Value&: cro.baseMethods);
4058 sys::swapByteOrder(Value&: cro.baseProtocols);
4059 sys::swapByteOrder(Value&: cro.ivars);
4060 sys::swapByteOrder(Value&: cro.weakIvarLayout);
4061 sys::swapByteOrder(Value&: cro.baseProperties);
4062}
4063
4064inline void swapStruct(struct method_list64_t &ml) {
4065 sys::swapByteOrder(Value&: ml.entsize);
4066 sys::swapByteOrder(Value&: ml.count);
4067}
4068
4069inline void swapStruct(struct method_list32_t &ml) {
4070 sys::swapByteOrder(Value&: ml.entsize);
4071 sys::swapByteOrder(Value&: ml.count);
4072}
4073
4074inline void swapStruct(struct method64_t &m) {
4075 sys::swapByteOrder(Value&: m.name);
4076 sys::swapByteOrder(Value&: m.types);
4077 sys::swapByteOrder(Value&: m.imp);
4078}
4079
4080inline void swapStruct(struct method32_t &m) {
4081 sys::swapByteOrder(Value&: m.name);
4082 sys::swapByteOrder(Value&: m.types);
4083 sys::swapByteOrder(Value&: m.imp);
4084}
4085
4086inline void swapStruct(struct method_relative_t &m) {
4087 sys::swapByteOrder(Value&: m.name);
4088 sys::swapByteOrder(Value&: m.types);
4089 sys::swapByteOrder(Value&: m.imp);
4090}
4091
4092inline void swapStruct(struct protocol_list64_t &pl) {
4093 sys::swapByteOrder(Value&: pl.count);
4094}
4095
4096inline void swapStruct(struct protocol_list32_t &pl) {
4097 sys::swapByteOrder(Value&: pl.count);
4098}
4099
4100inline void swapStruct(struct protocol64_t &p) {
4101 sys::swapByteOrder(Value&: p.isa);
4102 sys::swapByteOrder(Value&: p.name);
4103 sys::swapByteOrder(Value&: p.protocols);
4104 sys::swapByteOrder(Value&: p.instanceMethods);
4105 sys::swapByteOrder(Value&: p.classMethods);
4106 sys::swapByteOrder(Value&: p.optionalInstanceMethods);
4107 sys::swapByteOrder(Value&: p.optionalClassMethods);
4108 sys::swapByteOrder(Value&: p.instanceProperties);
4109}
4110
4111inline void swapStruct(struct protocol32_t &p) {
4112 sys::swapByteOrder(Value&: p.isa);
4113 sys::swapByteOrder(Value&: p.name);
4114 sys::swapByteOrder(Value&: p.protocols);
4115 sys::swapByteOrder(Value&: p.instanceMethods);
4116 sys::swapByteOrder(Value&: p.classMethods);
4117 sys::swapByteOrder(Value&: p.optionalInstanceMethods);
4118 sys::swapByteOrder(Value&: p.optionalClassMethods);
4119 sys::swapByteOrder(Value&: p.instanceProperties);
4120}
4121
4122inline void swapStruct(struct ivar_list64_t &il) {
4123 sys::swapByteOrder(Value&: il.entsize);
4124 sys::swapByteOrder(Value&: il.count);
4125}
4126
4127inline void swapStruct(struct ivar_list32_t &il) {
4128 sys::swapByteOrder(Value&: il.entsize);
4129 sys::swapByteOrder(Value&: il.count);
4130}
4131
4132inline void swapStruct(struct ivar64_t &i) {
4133 sys::swapByteOrder(Value&: i.offset);
4134 sys::swapByteOrder(Value&: i.name);
4135 sys::swapByteOrder(Value&: i.type);
4136 sys::swapByteOrder(Value&: i.alignment);
4137 sys::swapByteOrder(Value&: i.size);
4138}
4139
4140inline void swapStruct(struct ivar32_t &i) {
4141 sys::swapByteOrder(Value&: i.offset);
4142 sys::swapByteOrder(Value&: i.name);
4143 sys::swapByteOrder(Value&: i.type);
4144 sys::swapByteOrder(Value&: i.alignment);
4145 sys::swapByteOrder(Value&: i.size);
4146}
4147
4148inline void swapStruct(struct objc_property_list64 &pl) {
4149 sys::swapByteOrder(Value&: pl.entsize);
4150 sys::swapByteOrder(Value&: pl.count);
4151}
4152
4153inline void swapStruct(struct objc_property_list32 &pl) {
4154 sys::swapByteOrder(Value&: pl.entsize);
4155 sys::swapByteOrder(Value&: pl.count);
4156}
4157
4158inline void swapStruct(struct objc_property64 &op) {
4159 sys::swapByteOrder(Value&: op.name);
4160 sys::swapByteOrder(Value&: op.attributes);
4161}
4162
4163inline void swapStruct(struct objc_property32 &op) {
4164 sys::swapByteOrder(Value&: op.name);
4165 sys::swapByteOrder(Value&: op.attributes);
4166}
4167
4168inline void swapStruct(struct category64_t &c) {
4169 sys::swapByteOrder(Value&: c.name);
4170 sys::swapByteOrder(Value&: c.cls);
4171 sys::swapByteOrder(Value&: c.instanceMethods);
4172 sys::swapByteOrder(Value&: c.classMethods);
4173 sys::swapByteOrder(Value&: c.protocols);
4174 sys::swapByteOrder(Value&: c.instanceProperties);
4175}
4176
4177inline void swapStruct(struct category32_t &c) {
4178 sys::swapByteOrder(Value&: c.name);
4179 sys::swapByteOrder(Value&: c.cls);
4180 sys::swapByteOrder(Value&: c.instanceMethods);
4181 sys::swapByteOrder(Value&: c.classMethods);
4182 sys::swapByteOrder(Value&: c.protocols);
4183 sys::swapByteOrder(Value&: c.instanceProperties);
4184}
4185
4186inline void swapStruct(struct objc_image_info64 &o) {
4187 sys::swapByteOrder(Value&: o.version);
4188 sys::swapByteOrder(Value&: o.flags);
4189}
4190
4191inline void swapStruct(struct objc_image_info32 &o) {
4192 sys::swapByteOrder(Value&: o.version);
4193 sys::swapByteOrder(Value&: o.flags);
4194}
4195
4196inline void swapStruct(struct imageInfo_t &o) {
4197 sys::swapByteOrder(Value&: o.version);
4198 sys::swapByteOrder(Value&: o.flags);
4199}
4200
4201inline void swapStruct(struct message_ref64 &mr) {
4202 sys::swapByteOrder(Value&: mr.imp);
4203 sys::swapByteOrder(Value&: mr.sel);
4204}
4205
4206inline void swapStruct(struct message_ref32 &mr) {
4207 sys::swapByteOrder(Value&: mr.imp);
4208 sys::swapByteOrder(Value&: mr.sel);
4209}
4210
4211inline void swapStruct(struct objc_module_t &module) {
4212 sys::swapByteOrder(Value&: module.version);
4213 sys::swapByteOrder(Value&: module.size);
4214 sys::swapByteOrder(Value&: module.name);
4215 sys::swapByteOrder(Value&: module.symtab);
4216}
4217
4218inline void swapStruct(struct objc_symtab_t &symtab) {
4219 sys::swapByteOrder(Value&: symtab.sel_ref_cnt);
4220 sys::swapByteOrder(Value&: symtab.refs);
4221 sys::swapByteOrder(Value&: symtab.cls_def_cnt);
4222 sys::swapByteOrder(Value&: symtab.cat_def_cnt);
4223}
4224
4225inline void swapStruct(struct objc_class_t &objc_class) {
4226 sys::swapByteOrder(Value&: objc_class.isa);
4227 sys::swapByteOrder(Value&: objc_class.super_class);
4228 sys::swapByteOrder(Value&: objc_class.name);
4229 sys::swapByteOrder(Value&: objc_class.version);
4230 sys::swapByteOrder(Value&: objc_class.info);
4231 sys::swapByteOrder(Value&: objc_class.instance_size);
4232 sys::swapByteOrder(Value&: objc_class.ivars);
4233 sys::swapByteOrder(Value&: objc_class.methodLists);
4234 sys::swapByteOrder(Value&: objc_class.cache);
4235 sys::swapByteOrder(Value&: objc_class.protocols);
4236}
4237
4238inline void swapStruct(struct objc_category_t &objc_category) {
4239 sys::swapByteOrder(Value&: objc_category.category_name);
4240 sys::swapByteOrder(Value&: objc_category.class_name);
4241 sys::swapByteOrder(Value&: objc_category.instance_methods);
4242 sys::swapByteOrder(Value&: objc_category.class_methods);
4243 sys::swapByteOrder(Value&: objc_category.protocols);
4244}
4245
4246inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
4247 sys::swapByteOrder(Value&: objc_ivar_list.ivar_count);
4248}
4249
4250inline void swapStruct(struct objc_ivar_t &objc_ivar) {
4251 sys::swapByteOrder(Value&: objc_ivar.ivar_name);
4252 sys::swapByteOrder(Value&: objc_ivar.ivar_type);
4253 sys::swapByteOrder(Value&: objc_ivar.ivar_offset);
4254}
4255
4256inline void swapStruct(struct objc_method_list_t &method_list) {
4257 sys::swapByteOrder(Value&: method_list.obsolete);
4258 sys::swapByteOrder(Value&: method_list.method_count);
4259}
4260
4261inline void swapStruct(struct objc_method_t &method) {
4262 sys::swapByteOrder(Value&: method.method_name);
4263 sys::swapByteOrder(Value&: method.method_types);
4264 sys::swapByteOrder(Value&: method.method_imp);
4265}
4266
4267inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
4268 sys::swapByteOrder(Value&: protocol_list.next);
4269 sys::swapByteOrder(Value&: protocol_list.count);
4270}
4271
4272inline void swapStruct(struct objc_protocol_t &protocol) {
4273 sys::swapByteOrder(Value&: protocol.isa);
4274 sys::swapByteOrder(Value&: protocol.protocol_name);
4275 sys::swapByteOrder(Value&: protocol.protocol_list);
4276 sys::swapByteOrder(Value&: protocol.instance_methods);
4277 sys::swapByteOrder(Value&: protocol.class_methods);
4278}
4279
4280inline void swapStruct(struct objc_method_description_list_t &mdl) {
4281 sys::swapByteOrder(Value&: mdl.count);
4282}
4283
4284inline void swapStruct(struct objc_method_description_t &md) {
4285 sys::swapByteOrder(Value&: md.name);
4286 sys::swapByteOrder(Value&: md.types);
4287}
4288
4289} // namespace
4290
4291static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4292 struct DisassembleInfo *info);
4293
4294// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
4295// to an Objective-C class and returns the class name. It is also passed the
4296// address of the pointer, so when the pointer is zero as it can be in an .o
4297// file, that is used to look for an external relocation entry with a symbol
4298// name.
4299static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
4300 uint64_t ReferenceValue,
4301 struct DisassembleInfo *info) {
4302 const char *r;
4303 uint32_t offset, left;
4304 SectionRef S;
4305
4306 // The pointer_value can be 0 in an object file and have a relocation
4307 // entry for the class symbol at the ReferenceValue (the address of the
4308 // pointer).
4309 if (pointer_value == 0) {
4310 r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4311 if (r == nullptr || left < sizeof(uint64_t))
4312 return nullptr;
4313 uint64_t n_value;
4314 const char *symbol_name = get_symbol_64(sect_offset: offset, S, info, n_value);
4315 if (symbol_name == nullptr)
4316 return nullptr;
4317 const char *class_name = strrchr(s: symbol_name, c: '$');
4318 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4319 return class_name + 2;
4320 else
4321 return nullptr;
4322 }
4323
4324 // The case were the pointer_value is non-zero and points to a class defined
4325 // in this Mach-O file.
4326 r = get_pointer_64(Address: pointer_value, offset, left, S, info);
4327 if (r == nullptr || left < sizeof(struct class64_t))
4328 return nullptr;
4329 struct class64_t c;
4330 memcpy(dest: &c, src: r, n: sizeof(struct class64_t));
4331 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4332 swapStruct(c);
4333 if (c.data == 0)
4334 return nullptr;
4335 r = get_pointer_64(Address: c.data, offset, left, S, info);
4336 if (r == nullptr || left < sizeof(struct class_ro64_t))
4337 return nullptr;
4338 struct class_ro64_t cro;
4339 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro64_t));
4340 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4341 swapStruct(cro);
4342 if (cro.name == 0)
4343 return nullptr;
4344 const char *name = get_pointer_64(Address: cro.name, offset, left, S, info);
4345 return name;
4346}
4347
4348// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4349// pointer to a cfstring and returns its name or nullptr.
4350static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4351 struct DisassembleInfo *info) {
4352 const char *r, *name;
4353 uint32_t offset, left;
4354 SectionRef S;
4355 struct cfstring64_t cfs;
4356 uint64_t cfs_characters;
4357
4358 r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4359 if (r == nullptr || left < sizeof(struct cfstring64_t))
4360 return nullptr;
4361 memcpy(dest: &cfs, src: r, n: sizeof(struct cfstring64_t));
4362 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4363 swapStruct(cfs);
4364 if (cfs.characters == 0) {
4365 uint64_t n_value;
4366 const char *symbol_name = get_symbol_64(
4367 sect_offset: offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4368 if (symbol_name == nullptr)
4369 return nullptr;
4370 cfs_characters = n_value;
4371 } else
4372 cfs_characters = cfs.characters;
4373 name = get_pointer_64(Address: cfs_characters, offset, left, S, info);
4374
4375 return name;
4376}
4377
4378// get_objc2_64bit_selref() is used for disassembly and is passed a the address
4379// of a pointer to an Objective-C selector reference when the pointer value is
4380// zero as in a .o file and is likely to have a external relocation entry with
4381// who's symbol's n_value is the real pointer to the selector name. If that is
4382// the case the real pointer to the selector name is returned else 0 is
4383// returned
4384static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4385 struct DisassembleInfo *info) {
4386 uint32_t offset, left;
4387 SectionRef S;
4388
4389 const char *r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4390 if (r == nullptr || left < sizeof(uint64_t))
4391 return 0;
4392 uint64_t n_value;
4393 const char *symbol_name = get_symbol_64(sect_offset: offset, S, info, n_value);
4394 if (symbol_name == nullptr)
4395 return 0;
4396 return n_value;
4397}
4398
4399static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4400 const char *sectname) {
4401 for (const SectionRef &Section : O->sections()) {
4402 StringRef SectName;
4403 Expected<StringRef> SecNameOrErr = Section.getName();
4404 if (SecNameOrErr)
4405 SectName = *SecNameOrErr;
4406 else
4407 consumeError(Err: SecNameOrErr.takeError());
4408
4409 DataRefImpl Ref = Section.getRawDataRefImpl();
4410 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4411 if (SegName == segname && SectName == sectname)
4412 return Section;
4413 }
4414 return SectionRef();
4415}
4416
4417static void
4418walk_pointer_list_64(const char *listname, const SectionRef S,
4419 MachOObjectFile *O, struct DisassembleInfo *info,
4420 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4421 if (S == SectionRef())
4422 return;
4423
4424 StringRef SectName;
4425 Expected<StringRef> SecNameOrErr = S.getName();
4426 if (SecNameOrErr)
4427 SectName = *SecNameOrErr;
4428 else
4429 consumeError(Err: SecNameOrErr.takeError());
4430
4431 DataRefImpl Ref = S.getRawDataRefImpl();
4432 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4433 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4434
4435 StringRef BytesStr = unwrapOrError(EO: S.getContents(), Args: O->getFileName());
4436 const char *Contents = BytesStr.data();
4437
4438 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4439 uint32_t left = S.getSize() - i;
4440 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4441 uint64_t p = 0;
4442 memcpy(dest: &p, src: Contents + i, n: size);
4443 if (i + sizeof(uint64_t) > S.getSize())
4444 outs() << listname << " list pointer extends past end of (" << SegName
4445 << "," << SectName << ") section\n";
4446 outs() << format(Fmt: "%016" PRIx64, Vals: S.getAddress() + i) << " ";
4447
4448 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4449 sys::swapByteOrder(Value&: p);
4450
4451 uint64_t n_value = 0;
4452 const char *name = get_symbol_64(sect_offset: i, S, info, n_value, ReferenceValue: p);
4453 if (name == nullptr)
4454 name = get_dyld_bind_info_symbolname(ReferenceValue: S.getAddress() + i, info);
4455
4456 if (n_value != 0) {
4457 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4458 if (p != 0)
4459 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: p);
4460 } else
4461 outs() << format(Fmt: "0x%" PRIx64, Vals: p);
4462 if (name != nullptr)
4463 outs() << " " << name;
4464 outs() << "\n";
4465
4466 p += n_value;
4467 if (func)
4468 func(p, info);
4469 }
4470}
4471
4472static void
4473walk_pointer_list_32(const char *listname, const SectionRef S,
4474 MachOObjectFile *O, struct DisassembleInfo *info,
4475 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4476 if (S == SectionRef())
4477 return;
4478
4479 StringRef SectName = unwrapOrError(EO: S.getName(), Args: O->getFileName());
4480 DataRefImpl Ref = S.getRawDataRefImpl();
4481 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4482 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4483
4484 StringRef BytesStr = unwrapOrError(EO: S.getContents(), Args: O->getFileName());
4485 const char *Contents = BytesStr.data();
4486
4487 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4488 uint32_t left = S.getSize() - i;
4489 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4490 uint32_t p = 0;
4491 memcpy(dest: &p, src: Contents + i, n: size);
4492 if (i + sizeof(uint32_t) > S.getSize())
4493 outs() << listname << " list pointer extends past end of (" << SegName
4494 << "," << SectName << ") section\n";
4495 uint32_t Address = S.getAddress() + i;
4496 outs() << format(Fmt: "%08" PRIx32, Vals: Address) << " ";
4497
4498 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4499 sys::swapByteOrder(Value&: p);
4500 outs() << format(Fmt: "0x%" PRIx32, Vals: p);
4501
4502 const char *name = get_symbol_32(sect_offset: i, S, info, ReferenceValue: p);
4503 if (name != nullptr)
4504 outs() << " " << name;
4505 outs() << "\n";
4506
4507 if (func)
4508 func(p, info);
4509 }
4510}
4511
4512static void print_layout_map(const char *layout_map, uint32_t left) {
4513 if (layout_map == nullptr)
4514 return;
4515 outs() << " layout map: ";
4516 do {
4517 outs() << format(Fmt: "0x%02" PRIx32, Vals: (*layout_map) & 0xff) << " ";
4518 left--;
4519 layout_map++;
4520 } while (*layout_map != '\0' && left != 0);
4521 outs() << "\n";
4522}
4523
4524static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4525 uint32_t offset, left;
4526 SectionRef S;
4527 const char *layout_map;
4528
4529 if (p == 0)
4530 return;
4531 layout_map = get_pointer_64(Address: p, offset, left, S, info);
4532 print_layout_map(layout_map, left);
4533}
4534
4535static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4536 uint32_t offset, left;
4537 SectionRef S;
4538 const char *layout_map;
4539
4540 if (p == 0)
4541 return;
4542 layout_map = get_pointer_32(Address: p, offset, left, S, info);
4543 print_layout_map(layout_map, left);
4544}
4545
4546static void print_relative_method_list(uint32_t structSizeAndFlags,
4547 uint32_t structCount, uint64_t p,
4548 struct DisassembleInfo *info,
4549 const char *indent,
4550 uint32_t pointerBits) {
4551 struct method_relative_t m;
4552 const char *r, *name;
4553 uint32_t offset, xoffset, left, i;
4554 SectionRef S, xS;
4555
4556 assert(((structSizeAndFlags & ML_HAS_RELATIVE_PTRS) != 0) &&
4557 "expected structSizeAndFlags to have ML_HAS_RELATIVE_PTRS flag");
4558
4559 outs() << indent << "\t\t entsize "
4560 << (structSizeAndFlags & ML_ENTSIZE_MASK) << " (relative) \n";
4561 outs() << indent << "\t\t count " << structCount << "\n";
4562
4563 for (i = 0; i < structCount; i++) {
4564 r = get_pointer_64(Address: p, offset, left, S, info);
4565 memset(s: &m, c: '\0', n: sizeof(struct method_relative_t));
4566 if (left < sizeof(struct method_relative_t)) {
4567 memcpy(dest: &m, src: r, n: left);
4568 outs() << indent << " (method_t extends past the end of the section)\n";
4569 } else
4570 memcpy(dest: &m, src: r, n: sizeof(struct method_relative_t));
4571 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4572 swapStruct(m);
4573
4574 outs() << indent << "\t\t name " << format(Fmt: "0x%" PRIx32, Vals: m.name);
4575 uint64_t relNameRefVA = p + offsetof(struct method_relative_t, name);
4576 uint64_t absNameRefVA = relNameRefVA + m.name;
4577 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absNameRefVA) << ")";
4578
4579 // since this is a relative list, absNameRefVA is the address of the
4580 // __objc_selrefs entry, so a pointer, not the actual name
4581 const char *nameRefPtr =
4582 get_pointer_64(Address: absNameRefVA, offset&: xoffset, left, S&: xS, info);
4583 if (nameRefPtr) {
4584 uint32_t pointerSize = pointerBits / CHAR_BIT;
4585 if (left < pointerSize)
4586 outs() << indent << " (nameRefPtr extends past the end of the section)";
4587 else {
4588 if (pointerSize == 64) {
4589 uint64_t nameOff_64 = *reinterpret_cast<const uint64_t *>(nameRefPtr);
4590 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4591 sys::swapByteOrder(Value&: nameOff_64);
4592 name = get_pointer_64(Address: nameOff_64, offset&: xoffset, left, S&: xS, info);
4593 } else {
4594 uint32_t nameOff_32 = *reinterpret_cast<const uint32_t *>(nameRefPtr);
4595 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4596 sys::swapByteOrder(Value&: nameOff_32);
4597 name = get_pointer_32(Address: nameOff_32, offset&: xoffset, left, S&: xS, info);
4598 }
4599 if (name != nullptr)
4600 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4601 }
4602 }
4603 outs() << "\n";
4604
4605 outs() << indent << "\t\t types " << format(Fmt: "0x%" PRIx32, Vals: m.types);
4606 uint64_t relTypesVA = p + offsetof(struct method_relative_t, types);
4607 uint64_t absTypesVA = relTypesVA + m.types;
4608 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absTypesVA) << ")";
4609 name = get_pointer_32(Address: absTypesVA, offset&: xoffset, left, S&: xS, info);
4610 if (name != nullptr)
4611 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4612 outs() << "\n";
4613
4614 outs() << indent << "\t\t imp " << format(Fmt: "0x%" PRIx32, Vals: m.imp);
4615 uint64_t relImpVA = p + offsetof(struct method_relative_t, imp);
4616 uint64_t absImpVA = relImpVA + m.imp;
4617 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absImpVA) << ")";
4618 name = GuessSymbolName(value: absImpVA, AddrMap: info->AddrMap);
4619 if (name != nullptr)
4620 outs() << " " << name;
4621 outs() << "\n";
4622
4623 p += sizeof(struct method_relative_t);
4624 offset += sizeof(struct method_relative_t);
4625 }
4626}
4627
4628static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4629 const char *indent) {
4630 struct method_list64_t ml;
4631 struct method64_t m;
4632 const char *r;
4633 uint32_t offset, xoffset, left, i;
4634 SectionRef S, xS;
4635 const char *name, *sym_name;
4636 uint64_t n_value;
4637
4638 r = get_pointer_64(Address: p, offset, left, S, info);
4639 if (r == nullptr)
4640 return;
4641 memset(s: &ml, c: '\0', n: sizeof(struct method_list64_t));
4642 if (left < sizeof(struct method_list64_t)) {
4643 memcpy(dest: &ml, src: r, n: left);
4644 outs() << " (method_list_t entends past the end of the section)\n";
4645 } else
4646 memcpy(dest: &ml, src: r, n: sizeof(struct method_list64_t));
4647 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4648 swapStruct(ml);
4649 p += sizeof(struct method_list64_t);
4650
4651 if ((ml.entsize & ML_HAS_RELATIVE_PTRS) != 0) {
4652 print_relative_method_list(structSizeAndFlags: ml.entsize, structCount: ml.count, p, info, indent,
4653 /*pointerBits=*/64);
4654 return;
4655 }
4656
4657 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4658 outs() << indent << "\t\t count " << ml.count << "\n";
4659
4660 offset += sizeof(struct method_list64_t);
4661 for (i = 0; i < ml.count; i++) {
4662 r = get_pointer_64(Address: p, offset, left, S, info);
4663 if (r == nullptr)
4664 return;
4665 memset(s: &m, c: '\0', n: sizeof(struct method64_t));
4666 if (left < sizeof(struct method64_t)) {
4667 memcpy(dest: &m, src: r, n: left);
4668 outs() << indent << " (method_t extends past the end of the section)\n";
4669 } else
4670 memcpy(dest: &m, src: r, n: sizeof(struct method64_t));
4671 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4672 swapStruct(m);
4673
4674 outs() << indent << "\t\t name ";
4675 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, name), S,
4676 info, n_value, ReferenceValue: m.name);
4677 if (n_value != 0) {
4678 if (info->verbose && sym_name != nullptr)
4679 outs() << sym_name;
4680 else
4681 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4682 if (m.name != 0)
4683 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: m.name);
4684 } else
4685 outs() << format(Fmt: "0x%" PRIx64, Vals: m.name);
4686 name = get_pointer_64(Address: m.name + n_value, offset&: xoffset, left, S&: xS, info);
4687 if (name != nullptr)
4688 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4689 outs() << "\n";
4690
4691 outs() << indent << "\t\t types ";
4692 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, types), S,
4693 info, n_value, ReferenceValue: m.types);
4694 if (n_value != 0) {
4695 if (info->verbose && sym_name != nullptr)
4696 outs() << sym_name;
4697 else
4698 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4699 if (m.types != 0)
4700 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: m.types);
4701 } else
4702 outs() << format(Fmt: "0x%" PRIx64, Vals: m.types);
4703 name = get_pointer_64(Address: m.types + n_value, offset&: xoffset, left, S&: xS, info);
4704 if (name != nullptr)
4705 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4706 outs() << "\n";
4707
4708 outs() << indent << "\t\t imp ";
4709 name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, imp), S, info,
4710 n_value, ReferenceValue: m.imp);
4711 if (info->verbose && name == nullptr) {
4712 if (n_value != 0) {
4713 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value) << " ";
4714 if (m.imp != 0)
4715 outs() << "+ " << format(Fmt: "0x%" PRIx64, Vals: m.imp) << " ";
4716 } else
4717 outs() << format(Fmt: "0x%" PRIx64, Vals: m.imp) << " ";
4718 }
4719 if (name != nullptr)
4720 outs() << name;
4721 outs() << "\n";
4722
4723 p += sizeof(struct method64_t);
4724 offset += sizeof(struct method64_t);
4725 }
4726}
4727
4728static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4729 const char *indent) {
4730 struct method_list32_t ml;
4731 struct method32_t m;
4732 const char *r, *name;
4733 uint32_t offset, xoffset, left, i;
4734 SectionRef S, xS;
4735
4736 r = get_pointer_32(Address: p, offset, left, S, info);
4737 if (r == nullptr)
4738 return;
4739 memset(s: &ml, c: '\0', n: sizeof(struct method_list32_t));
4740 if (left < sizeof(struct method_list32_t)) {
4741 memcpy(dest: &ml, src: r, n: left);
4742 outs() << " (method_list_t entends past the end of the section)\n";
4743 } else
4744 memcpy(dest: &ml, src: r, n: sizeof(struct method_list32_t));
4745 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4746 swapStruct(ml);
4747 p += sizeof(struct method_list32_t);
4748
4749 if ((ml.entsize & ML_HAS_RELATIVE_PTRS) != 0) {
4750 print_relative_method_list(structSizeAndFlags: ml.entsize, structCount: ml.count, p, info, indent,
4751 /*pointerBits=*/32);
4752 return;
4753 }
4754
4755 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4756 outs() << indent << "\t\t count " << ml.count << "\n";
4757
4758 offset += sizeof(struct method_list32_t);
4759 for (i = 0; i < ml.count; i++) {
4760 r = get_pointer_32(Address: p, offset, left, S, info);
4761 if (r == nullptr)
4762 return;
4763 memset(s: &m, c: '\0', n: sizeof(struct method32_t));
4764 if (left < sizeof(struct method32_t)) {
4765 memcpy(dest: &ml, src: r, n: left);
4766 outs() << indent << " (method_t entends past the end of the section)\n";
4767 } else
4768 memcpy(dest: &m, src: r, n: sizeof(struct method32_t));
4769 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4770 swapStruct(m);
4771
4772 outs() << indent << "\t\t name " << format(Fmt: "0x%" PRIx32, Vals: m.name);
4773 name = get_pointer_32(Address: m.name, offset&: xoffset, left, S&: xS, info);
4774 if (name != nullptr)
4775 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4776 outs() << "\n";
4777
4778 outs() << indent << "\t\t types " << format(Fmt: "0x%" PRIx32, Vals: m.types);
4779 name = get_pointer_32(Address: m.types, offset&: xoffset, left, S&: xS, info);
4780 if (name != nullptr)
4781 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4782 outs() << "\n";
4783
4784 outs() << indent << "\t\t imp " << format(Fmt: "0x%" PRIx32, Vals: m.imp);
4785 name = get_symbol_32(sect_offset: offset + offsetof(struct method32_t, imp), S, info,
4786 ReferenceValue: m.imp);
4787 if (name != nullptr)
4788 outs() << " " << name;
4789 outs() << "\n";
4790
4791 p += sizeof(struct method32_t);
4792 offset += sizeof(struct method32_t);
4793 }
4794}
4795
4796static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4797 uint32_t offset, left, xleft;
4798 SectionRef S;
4799 struct objc_method_list_t method_list;
4800 struct objc_method_t method;
4801 const char *r, *methods, *name, *SymbolName;
4802 int32_t i;
4803
4804 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
4805 if (r == nullptr)
4806 return true;
4807
4808 outs() << "\n";
4809 if (left > sizeof(struct objc_method_list_t)) {
4810 memcpy(dest: &method_list, src: r, n: sizeof(struct objc_method_list_t));
4811 } else {
4812 outs() << "\t\t objc_method_list extends past end of the section\n";
4813 memset(s: &method_list, c: '\0', n: sizeof(struct objc_method_list_t));
4814 memcpy(dest: &method_list, src: r, n: left);
4815 }
4816 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4817 swapStruct(method_list);
4818
4819 outs() << "\t\t obsolete "
4820 << format(Fmt: "0x%08" PRIx32, Vals: method_list.obsolete) << "\n";
4821 outs() << "\t\t method_count " << method_list.method_count << "\n";
4822
4823 methods = r + sizeof(struct objc_method_list_t);
4824 for (i = 0; i < method_list.method_count; i++) {
4825 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4826 outs() << "\t\t remaining method's extend past the of the section\n";
4827 break;
4828 }
4829 memcpy(dest: &method, src: methods + i * sizeof(struct objc_method_t),
4830 n: sizeof(struct objc_method_t));
4831 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4832 swapStruct(method);
4833
4834 outs() << "\t\t method_name "
4835 << format(Fmt: "0x%08" PRIx32, Vals: method.method_name);
4836 if (info->verbose) {
4837 name = get_pointer_32(Address: method.method_name, offset, left&: xleft, S, info, objc_only: true);
4838 if (name != nullptr)
4839 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
4840 else
4841 outs() << " (not in an __OBJC section)";
4842 }
4843 outs() << "\n";
4844
4845 outs() << "\t\t method_types "
4846 << format(Fmt: "0x%08" PRIx32, Vals: method.method_types);
4847 if (info->verbose) {
4848 name = get_pointer_32(Address: method.method_types, offset, left&: xleft, S, info, objc_only: true);
4849 if (name != nullptr)
4850 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
4851 else
4852 outs() << " (not in an __OBJC section)";
4853 }
4854 outs() << "\n";
4855
4856 outs() << "\t\t method_imp "
4857 << format(Fmt: "0x%08" PRIx32, Vals: method.method_imp) << " ";
4858 if (info->verbose) {
4859 SymbolName = GuessSymbolName(value: method.method_imp, AddrMap: info->AddrMap);
4860 if (SymbolName != nullptr)
4861 outs() << SymbolName;
4862 }
4863 outs() << "\n";
4864 }
4865 return false;
4866}
4867
4868static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4869 struct protocol_list64_t pl;
4870 uint64_t q, n_value;
4871 struct protocol64_t pc;
4872 const char *r;
4873 uint32_t offset, xoffset, left, i;
4874 SectionRef S, xS;
4875 const char *name, *sym_name;
4876
4877 r = get_pointer_64(Address: p, offset, left, S, info);
4878 if (r == nullptr)
4879 return;
4880 memset(s: &pl, c: '\0', n: sizeof(struct protocol_list64_t));
4881 if (left < sizeof(struct protocol_list64_t)) {
4882 memcpy(dest: &pl, src: r, n: left);
4883 outs() << " (protocol_list_t entends past the end of the section)\n";
4884 } else
4885 memcpy(dest: &pl, src: r, n: sizeof(struct protocol_list64_t));
4886 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4887 swapStruct(pl);
4888 outs() << " count " << pl.count << "\n";
4889
4890 p += sizeof(struct protocol_list64_t);
4891 offset += sizeof(struct protocol_list64_t);
4892 for (i = 0; i < pl.count; i++) {
4893 r = get_pointer_64(Address: p, offset, left, S, info);
4894 if (r == nullptr)
4895 return;
4896 q = 0;
4897 if (left < sizeof(uint64_t)) {
4898 memcpy(dest: &q, src: r, n: left);
4899 outs() << " (protocol_t * entends past the end of the section)\n";
4900 } else
4901 memcpy(dest: &q, src: r, n: sizeof(uint64_t));
4902 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4903 sys::swapByteOrder(Value&: q);
4904
4905 outs() << "\t\t list[" << i << "] ";
4906 sym_name = get_symbol_64(sect_offset: offset, S, info, n_value, ReferenceValue: q);
4907 if (n_value != 0) {
4908 if (info->verbose && sym_name != nullptr)
4909 outs() << sym_name;
4910 else
4911 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4912 if (q != 0)
4913 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: q);
4914 } else
4915 outs() << format(Fmt: "0x%" PRIx64, Vals: q);
4916 outs() << " (struct protocol_t *)\n";
4917
4918 r = get_pointer_64(Address: q + n_value, offset, left, S, info);
4919 if (r == nullptr)
4920 return;
4921 memset(s: &pc, c: '\0', n: sizeof(struct protocol64_t));
4922 if (left < sizeof(struct protocol64_t)) {
4923 memcpy(dest: &pc, src: r, n: left);
4924 outs() << " (protocol_t entends past the end of the section)\n";
4925 } else
4926 memcpy(dest: &pc, src: r, n: sizeof(struct protocol64_t));
4927 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4928 swapStruct(p&: pc);
4929
4930 outs() << "\t\t\t isa " << format(Fmt: "0x%" PRIx64, Vals: pc.isa) << "\n";
4931
4932 outs() << "\t\t\t name ";
4933 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, name), S,
4934 info, n_value, ReferenceValue: pc.name);
4935 if (n_value != 0) {
4936 if (info->verbose && sym_name != nullptr)
4937 outs() << sym_name;
4938 else
4939 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4940 if (pc.name != 0)
4941 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.name);
4942 } else
4943 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.name);
4944 name = get_pointer_64(Address: pc.name + n_value, offset&: xoffset, left, S&: xS, info);
4945 if (name != nullptr)
4946 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4947 outs() << "\n";
4948
4949 outs() << "\t\t\tprotocols " << format(Fmt: "0x%" PRIx64, Vals: pc.protocols) << "\n";
4950
4951 outs() << "\t\t instanceMethods ";
4952 sym_name =
4953 get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, instanceMethods),
4954 S, info, n_value, ReferenceValue: pc.instanceMethods);
4955 if (n_value != 0) {
4956 if (info->verbose && sym_name != nullptr)
4957 outs() << sym_name;
4958 else
4959 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4960 if (pc.instanceMethods != 0)
4961 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.instanceMethods);
4962 } else
4963 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.instanceMethods);
4964 outs() << " (struct method_list_t *)\n";
4965 if (pc.instanceMethods + n_value != 0)
4966 print_method_list64_t(p: pc.instanceMethods + n_value, info, indent: "\t");
4967
4968 outs() << "\t\t classMethods ";
4969 sym_name =
4970 get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, classMethods), S,
4971 info, n_value, ReferenceValue: pc.classMethods);
4972 if (n_value != 0) {
4973 if (info->verbose && sym_name != nullptr)
4974 outs() << sym_name;
4975 else
4976 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4977 if (pc.classMethods != 0)
4978 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.classMethods);
4979 } else
4980 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.classMethods);
4981 outs() << " (struct method_list_t *)\n";
4982 if (pc.classMethods + n_value != 0)
4983 print_method_list64_t(p: pc.classMethods + n_value, info, indent: "\t");
4984
4985 outs() << "\t optionalInstanceMethods "
4986 << format(Fmt: "0x%" PRIx64, Vals: pc.optionalInstanceMethods) << "\n";
4987 outs() << "\t optionalClassMethods "
4988 << format(Fmt: "0x%" PRIx64, Vals: pc.optionalClassMethods) << "\n";
4989 outs() << "\t instanceProperties "
4990 << format(Fmt: "0x%" PRIx64, Vals: pc.instanceProperties) << "\n";
4991
4992 p += sizeof(uint64_t);
4993 offset += sizeof(uint64_t);
4994 }
4995}
4996
4997static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4998 struct protocol_list32_t pl;
4999 uint32_t q;
5000 struct protocol32_t pc;
5001 const char *r;
5002 uint32_t offset, xoffset, left, i;
5003 SectionRef S, xS;
5004 const char *name;
5005
5006 r = get_pointer_32(Address: p, offset, left, S, info);
5007 if (r == nullptr)
5008 return;
5009 memset(s: &pl, c: '\0', n: sizeof(struct protocol_list32_t));
5010 if (left < sizeof(struct protocol_list32_t)) {
5011 memcpy(dest: &pl, src: r, n: left);
5012 outs() << " (protocol_list_t entends past the end of the section)\n";
5013 } else
5014 memcpy(dest: &pl, src: r, n: sizeof(struct protocol_list32_t));
5015 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5016 swapStruct(pl);
5017 outs() << " count " << pl.count << "\n";
5018
5019 p += sizeof(struct protocol_list32_t);
5020 offset += sizeof(struct protocol_list32_t);
5021 for (i = 0; i < pl.count; i++) {
5022 r = get_pointer_32(Address: p, offset, left, S, info);
5023 if (r == nullptr)
5024 return;
5025 q = 0;
5026 if (left < sizeof(uint32_t)) {
5027 memcpy(dest: &q, src: r, n: left);
5028 outs() << " (protocol_t * entends past the end of the section)\n";
5029 } else
5030 memcpy(dest: &q, src: r, n: sizeof(uint32_t));
5031 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5032 sys::swapByteOrder(Value&: q);
5033 outs() << "\t\t list[" << i << "] " << format(Fmt: "0x%" PRIx32, Vals: q)
5034 << " (struct protocol_t *)\n";
5035 r = get_pointer_32(Address: q, offset, left, S, info);
5036 if (r == nullptr)
5037 return;
5038 memset(s: &pc, c: '\0', n: sizeof(struct protocol32_t));
5039 if (left < sizeof(struct protocol32_t)) {
5040 memcpy(dest: &pc, src: r, n: left);
5041 outs() << " (protocol_t entends past the end of the section)\n";
5042 } else
5043 memcpy(dest: &pc, src: r, n: sizeof(struct protocol32_t));
5044 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5045 swapStruct(p&: pc);
5046 outs() << "\t\t\t isa " << format(Fmt: "0x%" PRIx32, Vals: pc.isa) << "\n";
5047 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: pc.name);
5048 name = get_pointer_32(Address: pc.name, offset&: xoffset, left, S&: xS, info);
5049 if (name != nullptr)
5050 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5051 outs() << "\n";
5052 outs() << "\t\t\tprotocols " << format(Fmt: "0x%" PRIx32, Vals: pc.protocols) << "\n";
5053 outs() << "\t\t instanceMethods "
5054 << format(Fmt: "0x%" PRIx32, Vals: pc.instanceMethods)
5055 << " (struct method_list_t *)\n";
5056 if (pc.instanceMethods != 0)
5057 print_method_list32_t(p: pc.instanceMethods, info, indent: "\t");
5058 outs() << "\t\t classMethods " << format(Fmt: "0x%" PRIx32, Vals: pc.classMethods)
5059 << " (struct method_list_t *)\n";
5060 if (pc.classMethods != 0)
5061 print_method_list32_t(p: pc.classMethods, info, indent: "\t");
5062 outs() << "\t optionalInstanceMethods "
5063 << format(Fmt: "0x%" PRIx32, Vals: pc.optionalInstanceMethods) << "\n";
5064 outs() << "\t optionalClassMethods "
5065 << format(Fmt: "0x%" PRIx32, Vals: pc.optionalClassMethods) << "\n";
5066 outs() << "\t instanceProperties "
5067 << format(Fmt: "0x%" PRIx32, Vals: pc.instanceProperties) << "\n";
5068 p += sizeof(uint32_t);
5069 offset += sizeof(uint32_t);
5070 }
5071}
5072
5073static void print_indent(uint32_t indent) {
5074 for (uint32_t i = 0; i < indent;) {
5075 if (indent - i >= 8) {
5076 outs() << "\t";
5077 i += 8;
5078 } else {
5079 for (uint32_t j = i; j < indent; j++)
5080 outs() << " ";
5081 return;
5082 }
5083 }
5084}
5085
5086static bool print_method_description_list(uint32_t p, uint32_t indent,
5087 struct DisassembleInfo *info) {
5088 uint32_t offset, left, xleft;
5089 SectionRef S;
5090 struct objc_method_description_list_t mdl;
5091 struct objc_method_description_t md;
5092 const char *r, *list, *name;
5093 int32_t i;
5094
5095 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5096 if (r == nullptr)
5097 return true;
5098
5099 outs() << "\n";
5100 if (left > sizeof(struct objc_method_description_list_t)) {
5101 memcpy(dest: &mdl, src: r, n: sizeof(struct objc_method_description_list_t));
5102 } else {
5103 print_indent(indent);
5104 outs() << " objc_method_description_list extends past end of the section\n";
5105 memset(s: &mdl, c: '\0', n: sizeof(struct objc_method_description_list_t));
5106 memcpy(dest: &mdl, src: r, n: left);
5107 }
5108 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5109 swapStruct(mdl);
5110
5111 print_indent(indent);
5112 outs() << " count " << mdl.count << "\n";
5113
5114 list = r + sizeof(struct objc_method_description_list_t);
5115 for (i = 0; i < mdl.count; i++) {
5116 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
5117 print_indent(indent);
5118 outs() << " remaining list entries extend past the of the section\n";
5119 break;
5120 }
5121 print_indent(indent);
5122 outs() << " list[" << i << "]\n";
5123 memcpy(dest: &md, src: list + i * sizeof(struct objc_method_description_t),
5124 n: sizeof(struct objc_method_description_t));
5125 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5126 swapStruct(md);
5127
5128 print_indent(indent);
5129 outs() << " name " << format(Fmt: "0x%08" PRIx32, Vals: md.name);
5130 if (info->verbose) {
5131 name = get_pointer_32(Address: md.name, offset, left&: xleft, S, info, objc_only: true);
5132 if (name != nullptr)
5133 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5134 else
5135 outs() << " (not in an __OBJC section)";
5136 }
5137 outs() << "\n";
5138
5139 print_indent(indent);
5140 outs() << " types " << format(Fmt: "0x%08" PRIx32, Vals: md.types);
5141 if (info->verbose) {
5142 name = get_pointer_32(Address: md.types, offset, left&: xleft, S, info, objc_only: true);
5143 if (name != nullptr)
5144 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5145 else
5146 outs() << " (not in an __OBJC section)";
5147 }
5148 outs() << "\n";
5149 }
5150 return false;
5151}
5152
5153static bool print_protocol_list(uint32_t p, uint32_t indent,
5154 struct DisassembleInfo *info);
5155
5156static bool print_protocol(uint32_t p, uint32_t indent,
5157 struct DisassembleInfo *info) {
5158 uint32_t offset, left;
5159 SectionRef S;
5160 struct objc_protocol_t protocol;
5161 const char *r, *name;
5162
5163 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5164 if (r == nullptr)
5165 return true;
5166
5167 outs() << "\n";
5168 if (left >= sizeof(struct objc_protocol_t)) {
5169 memcpy(dest: &protocol, src: r, n: sizeof(struct objc_protocol_t));
5170 } else {
5171 print_indent(indent);
5172 outs() << " Protocol extends past end of the section\n";
5173 memset(s: &protocol, c: '\0', n: sizeof(struct objc_protocol_t));
5174 memcpy(dest: &protocol, src: r, n: left);
5175 }
5176 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5177 swapStruct(protocol);
5178
5179 print_indent(indent);
5180 outs() << " isa " << format(Fmt: "0x%08" PRIx32, Vals: protocol.isa)
5181 << "\n";
5182
5183 print_indent(indent);
5184 outs() << " protocol_name "
5185 << format(Fmt: "0x%08" PRIx32, Vals: protocol.protocol_name);
5186 if (info->verbose) {
5187 name = get_pointer_32(Address: protocol.protocol_name, offset, left, S, info, objc_only: true);
5188 if (name != nullptr)
5189 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5190 else
5191 outs() << " (not in an __OBJC section)";
5192 }
5193 outs() << "\n";
5194
5195 print_indent(indent);
5196 outs() << " protocol_list "
5197 << format(Fmt: "0x%08" PRIx32, Vals: protocol.protocol_list);
5198 if (print_protocol_list(p: protocol.protocol_list, indent: indent + 4, info))
5199 outs() << " (not in an __OBJC section)\n";
5200
5201 print_indent(indent);
5202 outs() << " instance_methods "
5203 << format(Fmt: "0x%08" PRIx32, Vals: protocol.instance_methods);
5204 if (print_method_description_list(p: protocol.instance_methods, indent, info))
5205 outs() << " (not in an __OBJC section)\n";
5206
5207 print_indent(indent);
5208 outs() << " class_methods "
5209 << format(Fmt: "0x%08" PRIx32, Vals: protocol.class_methods);
5210 if (print_method_description_list(p: protocol.class_methods, indent, info))
5211 outs() << " (not in an __OBJC section)\n";
5212
5213 return false;
5214}
5215
5216static bool print_protocol_list(uint32_t p, uint32_t indent,
5217 struct DisassembleInfo *info) {
5218 uint32_t offset, left, l;
5219 SectionRef S;
5220 struct objc_protocol_list_t protocol_list;
5221 const char *r, *list;
5222 int32_t i;
5223
5224 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5225 if (r == nullptr)
5226 return true;
5227
5228 outs() << "\n";
5229 if (left > sizeof(struct objc_protocol_list_t)) {
5230 memcpy(dest: &protocol_list, src: r, n: sizeof(struct objc_protocol_list_t));
5231 } else {
5232 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
5233 memset(s: &protocol_list, c: '\0', n: sizeof(struct objc_protocol_list_t));
5234 memcpy(dest: &protocol_list, src: r, n: left);
5235 }
5236 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5237 swapStruct(protocol_list);
5238
5239 print_indent(indent);
5240 outs() << " next " << format(Fmt: "0x%08" PRIx32, Vals: protocol_list.next)
5241 << "\n";
5242 print_indent(indent);
5243 outs() << " count " << protocol_list.count << "\n";
5244
5245 list = r + sizeof(struct objc_protocol_list_t);
5246 for (i = 0; i < protocol_list.count; i++) {
5247 if ((i + 1) * sizeof(uint32_t) > left) {
5248 outs() << "\t\t remaining list entries extend past the of the section\n";
5249 break;
5250 }
5251 memcpy(dest: &l, src: list + i * sizeof(uint32_t), n: sizeof(uint32_t));
5252 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5253 sys::swapByteOrder(Value&: l);
5254
5255 print_indent(indent);
5256 outs() << " list[" << i << "] " << format(Fmt: "0x%08" PRIx32, Vals: l);
5257 if (print_protocol(p: l, indent, info))
5258 outs() << "(not in an __OBJC section)\n";
5259 }
5260 return false;
5261}
5262
5263static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
5264 struct ivar_list64_t il;
5265 struct ivar64_t i;
5266 const char *r;
5267 uint32_t offset, xoffset, left, j;
5268 SectionRef S, xS;
5269 const char *name, *sym_name, *ivar_offset_p;
5270 uint64_t ivar_offset, n_value;
5271
5272 r = get_pointer_64(Address: p, offset, left, S, info);
5273 if (r == nullptr)
5274 return;
5275 memset(s: &il, c: '\0', n: sizeof(struct ivar_list64_t));
5276 if (left < sizeof(struct ivar_list64_t)) {
5277 memcpy(dest: &il, src: r, n: left);
5278 outs() << " (ivar_list_t entends past the end of the section)\n";
5279 } else
5280 memcpy(dest: &il, src: r, n: sizeof(struct ivar_list64_t));
5281 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5282 swapStruct(il);
5283 outs() << " entsize " << il.entsize << "\n";
5284 outs() << " count " << il.count << "\n";
5285
5286 p += sizeof(struct ivar_list64_t);
5287 offset += sizeof(struct ivar_list64_t);
5288 for (j = 0; j < il.count; j++) {
5289 r = get_pointer_64(Address: p, offset, left, S, info);
5290 if (r == nullptr)
5291 return;
5292 memset(s: &i, c: '\0', n: sizeof(struct ivar64_t));
5293 if (left < sizeof(struct ivar64_t)) {
5294 memcpy(dest: &i, src: r, n: left);
5295 outs() << " (ivar_t entends past the end of the section)\n";
5296 } else
5297 memcpy(dest: &i, src: r, n: sizeof(struct ivar64_t));
5298 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5299 swapStruct(i);
5300
5301 outs() << "\t\t\t offset ";
5302 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, offset), S,
5303 info, n_value, ReferenceValue: i.offset);
5304 if (n_value != 0) {
5305 if (info->verbose && sym_name != nullptr)
5306 outs() << sym_name;
5307 else
5308 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5309 if (i.offset != 0)
5310 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.offset);
5311 } else
5312 outs() << format(Fmt: "0x%" PRIx64, Vals: i.offset);
5313 ivar_offset_p = get_pointer_64(Address: i.offset + n_value, offset&: xoffset, left, S&: xS, info);
5314 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5315 memcpy(dest: &ivar_offset, src: ivar_offset_p, n: sizeof(ivar_offset));
5316 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5317 sys::swapByteOrder(Value&: ivar_offset);
5318 outs() << " " << ivar_offset << "\n";
5319 } else
5320 outs() << "\n";
5321
5322 outs() << "\t\t\t name ";
5323 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, name), S, info,
5324 n_value, ReferenceValue: i.name);
5325 if (n_value != 0) {
5326 if (info->verbose && sym_name != nullptr)
5327 outs() << sym_name;
5328 else
5329 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5330 if (i.name != 0)
5331 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.name);
5332 } else
5333 outs() << format(Fmt: "0x%" PRIx64, Vals: i.name);
5334 name = get_pointer_64(Address: i.name + n_value, offset&: xoffset, left, S&: xS, info);
5335 if (name != nullptr)
5336 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5337 outs() << "\n";
5338
5339 outs() << "\t\t\t type ";
5340 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, type), S, info,
5341 n_value, ReferenceValue: i.name);
5342 name = get_pointer_64(Address: i.type + n_value, offset&: xoffset, left, S&: xS, info);
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.type != 0)
5349 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.type);
5350 } else
5351 outs() << format(Fmt: "0x%" PRIx64, Vals: i.type);
5352 if (name != nullptr)
5353 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5354 outs() << "\n";
5355
5356 outs() << "\t\t\talignment " << i.alignment << "\n";
5357 outs() << "\t\t\t size " << i.size << "\n";
5358
5359 p += sizeof(struct ivar64_t);
5360 offset += sizeof(struct ivar64_t);
5361 }
5362}
5363
5364static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
5365 struct ivar_list32_t il;
5366 struct ivar32_t i;
5367 const char *r;
5368 uint32_t offset, xoffset, left, j;
5369 SectionRef S, xS;
5370 const char *name, *ivar_offset_p;
5371 uint32_t ivar_offset;
5372
5373 r = get_pointer_32(Address: p, offset, left, S, info);
5374 if (r == nullptr)
5375 return;
5376 memset(s: &il, c: '\0', n: sizeof(struct ivar_list32_t));
5377 if (left < sizeof(struct ivar_list32_t)) {
5378 memcpy(dest: &il, src: r, n: left);
5379 outs() << " (ivar_list_t entends past the end of the section)\n";
5380 } else
5381 memcpy(dest: &il, src: r, n: sizeof(struct ivar_list32_t));
5382 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5383 swapStruct(il);
5384 outs() << " entsize " << il.entsize << "\n";
5385 outs() << " count " << il.count << "\n";
5386
5387 p += sizeof(struct ivar_list32_t);
5388 offset += sizeof(struct ivar_list32_t);
5389 for (j = 0; j < il.count; j++) {
5390 r = get_pointer_32(Address: p, offset, left, S, info);
5391 if (r == nullptr)
5392 return;
5393 memset(s: &i, c: '\0', n: sizeof(struct ivar32_t));
5394 if (left < sizeof(struct ivar32_t)) {
5395 memcpy(dest: &i, src: r, n: left);
5396 outs() << " (ivar_t entends past the end of the section)\n";
5397 } else
5398 memcpy(dest: &i, src: r, n: sizeof(struct ivar32_t));
5399 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5400 swapStruct(i);
5401
5402 outs() << "\t\t\t offset " << format(Fmt: "0x%" PRIx32, Vals: i.offset);
5403 ivar_offset_p = get_pointer_32(Address: i.offset, offset&: xoffset, left, S&: xS, info);
5404 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5405 memcpy(dest: &ivar_offset, src: ivar_offset_p, n: sizeof(ivar_offset));
5406 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5407 sys::swapByteOrder(Value&: ivar_offset);
5408 outs() << " " << ivar_offset << "\n";
5409 } else
5410 outs() << "\n";
5411
5412 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: i.name);
5413 name = get_pointer_32(Address: i.name, offset&: xoffset, left, S&: xS, info);
5414 if (name != nullptr)
5415 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5416 outs() << "\n";
5417
5418 outs() << "\t\t\t type " << format(Fmt: "0x%" PRIx32, Vals: i.type);
5419 name = get_pointer_32(Address: i.type, offset&: xoffset, left, S&: xS, info);
5420 if (name != nullptr)
5421 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5422 outs() << "\n";
5423
5424 outs() << "\t\t\talignment " << i.alignment << "\n";
5425 outs() << "\t\t\t size " << i.size << "\n";
5426
5427 p += sizeof(struct ivar32_t);
5428 offset += sizeof(struct ivar32_t);
5429 }
5430}
5431
5432static void print_objc_property_list64(uint64_t p,
5433 struct DisassembleInfo *info) {
5434 struct objc_property_list64 opl;
5435 struct objc_property64 op;
5436 const char *r;
5437 uint32_t offset, xoffset, left, j;
5438 SectionRef S, xS;
5439 const char *name, *sym_name;
5440 uint64_t n_value;
5441
5442 r = get_pointer_64(Address: p, offset, left, S, info);
5443 if (r == nullptr)
5444 return;
5445 memset(s: &opl, c: '\0', n: sizeof(struct objc_property_list64));
5446 if (left < sizeof(struct objc_property_list64)) {
5447 memcpy(dest: &opl, src: r, n: left);
5448 outs() << " (objc_property_list entends past the end of the section)\n";
5449 } else
5450 memcpy(dest: &opl, src: r, n: sizeof(struct objc_property_list64));
5451 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5452 swapStruct(pl&: opl);
5453 outs() << " entsize " << opl.entsize << "\n";
5454 outs() << " count " << opl.count << "\n";
5455
5456 p += sizeof(struct objc_property_list64);
5457 offset += sizeof(struct objc_property_list64);
5458 for (j = 0; j < opl.count; j++) {
5459 r = get_pointer_64(Address: p, offset, left, S, info);
5460 if (r == nullptr)
5461 return;
5462 memset(s: &op, c: '\0', n: sizeof(struct objc_property64));
5463 if (left < sizeof(struct objc_property64)) {
5464 memcpy(dest: &op, src: r, n: left);
5465 outs() << " (objc_property entends past the end of the section)\n";
5466 } else
5467 memcpy(dest: &op, src: r, n: sizeof(struct objc_property64));
5468 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5469 swapStruct(op);
5470
5471 outs() << "\t\t\t name ";
5472 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct objc_property64, name), S,
5473 info, n_value, ReferenceValue: op.name);
5474 if (n_value != 0) {
5475 if (info->verbose && sym_name != nullptr)
5476 outs() << sym_name;
5477 else
5478 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5479 if (op.name != 0)
5480 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: op.name);
5481 } else
5482 outs() << format(Fmt: "0x%" PRIx64, Vals: op.name);
5483 name = get_pointer_64(Address: op.name + n_value, offset&: xoffset, left, S&: xS, info);
5484 if (name != nullptr)
5485 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5486 outs() << "\n";
5487
5488 outs() << "\t\t\tattributes ";
5489 sym_name =
5490 get_symbol_64(sect_offset: offset + offsetof(struct objc_property64, attributes), S,
5491 info, n_value, ReferenceValue: op.attributes);
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.attributes != 0)
5498 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: op.attributes);
5499 } else
5500 outs() << format(Fmt: "0x%" PRIx64, Vals: op.attributes);
5501 name = get_pointer_64(Address: op.attributes + 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 p += sizeof(struct objc_property64);
5507 offset += sizeof(struct objc_property64);
5508 }
5509}
5510
5511static void print_objc_property_list32(uint32_t p,
5512 struct DisassembleInfo *info) {
5513 struct objc_property_list32 opl;
5514 struct objc_property32 op;
5515 const char *r;
5516 uint32_t offset, xoffset, left, j;
5517 SectionRef S, xS;
5518 const char *name;
5519
5520 r = get_pointer_32(Address: p, offset, left, S, info);
5521 if (r == nullptr)
5522 return;
5523 memset(s: &opl, c: '\0', n: sizeof(struct objc_property_list32));
5524 if (left < sizeof(struct objc_property_list32)) {
5525 memcpy(dest: &opl, src: r, n: left);
5526 outs() << " (objc_property_list entends past the end of the section)\n";
5527 } else
5528 memcpy(dest: &opl, src: r, n: sizeof(struct objc_property_list32));
5529 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5530 swapStruct(pl&: opl);
5531 outs() << " entsize " << opl.entsize << "\n";
5532 outs() << " count " << opl.count << "\n";
5533
5534 p += sizeof(struct objc_property_list32);
5535 offset += sizeof(struct objc_property_list32);
5536 for (j = 0; j < opl.count; j++) {
5537 r = get_pointer_32(Address: p, offset, left, S, info);
5538 if (r == nullptr)
5539 return;
5540 memset(s: &op, c: '\0', n: sizeof(struct objc_property32));
5541 if (left < sizeof(struct objc_property32)) {
5542 memcpy(dest: &op, src: r, n: left);
5543 outs() << " (objc_property entends past the end of the section)\n";
5544 } else
5545 memcpy(dest: &op, src: r, n: sizeof(struct objc_property32));
5546 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5547 swapStruct(op);
5548
5549 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: op.name);
5550 name = get_pointer_32(Address: op.name, offset&: xoffset, left, S&: xS, info);
5551 if (name != nullptr)
5552 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5553 outs() << "\n";
5554
5555 outs() << "\t\t\tattributes " << format(Fmt: "0x%" PRIx32, Vals: op.attributes);
5556 name = get_pointer_32(Address: op.attributes, offset&: xoffset, left, S&: xS, info);
5557 if (name != nullptr)
5558 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5559 outs() << "\n";
5560
5561 p += sizeof(struct objc_property32);
5562 offset += sizeof(struct objc_property32);
5563 }
5564}
5565
5566static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5567 bool &is_meta_class) {
5568 struct class_ro64_t cro;
5569 const char *r;
5570 uint32_t offset, xoffset, left;
5571 SectionRef S, xS;
5572 const char *name, *sym_name;
5573 uint64_t n_value;
5574
5575 r = get_pointer_64(Address: p, offset, left, S, info);
5576 if (r == nullptr || left < sizeof(struct class_ro64_t))
5577 return false;
5578 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro64_t));
5579 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5580 swapStruct(cro);
5581 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: cro.flags);
5582 if (cro.flags & RO_META)
5583 outs() << " RO_META";
5584 if (cro.flags & RO_ROOT)
5585 outs() << " RO_ROOT";
5586 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5587 outs() << " RO_HAS_CXX_STRUCTORS";
5588 outs() << "\n";
5589 outs() << " instanceStart " << cro.instanceStart << "\n";
5590 outs() << " instanceSize " << cro.instanceSize << "\n";
5591 outs() << " reserved " << format(Fmt: "0x%" PRIx32, Vals: cro.reserved)
5592 << "\n";
5593 outs() << " ivarLayout " << format(Fmt: "0x%" PRIx64, Vals: cro.ivarLayout)
5594 << "\n";
5595 print_layout_map64(p: cro.ivarLayout, info);
5596
5597 outs() << " name ";
5598 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, name), S,
5599 info, n_value, ReferenceValue: cro.name);
5600 if (n_value != 0) {
5601 if (info->verbose && sym_name != nullptr)
5602 outs() << sym_name;
5603 else
5604 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5605 if (cro.name != 0)
5606 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.name);
5607 } else
5608 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.name);
5609 name = get_pointer_64(Address: cro.name + n_value, offset&: xoffset, left, S&: xS, info);
5610 if (name != nullptr)
5611 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5612 outs() << "\n";
5613
5614 outs() << " baseMethods ";
5615 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseMethods),
5616 S, info, n_value, ReferenceValue: cro.baseMethods);
5617 if (n_value != 0) {
5618 if (info->verbose && sym_name != nullptr)
5619 outs() << sym_name;
5620 else
5621 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5622 if (cro.baseMethods != 0)
5623 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseMethods);
5624 } else
5625 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseMethods);
5626 outs() << " (struct method_list_t *)\n";
5627 if (cro.baseMethods + n_value != 0)
5628 print_method_list64_t(p: cro.baseMethods + n_value, info, indent: "");
5629
5630 outs() << " baseProtocols ";
5631 sym_name =
5632 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseProtocols), S,
5633 info, n_value, ReferenceValue: cro.baseProtocols);
5634 if (n_value != 0) {
5635 if (info->verbose && sym_name != nullptr)
5636 outs() << sym_name;
5637 else
5638 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5639 if (cro.baseProtocols != 0)
5640 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseProtocols);
5641 } else
5642 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseProtocols);
5643 outs() << "\n";
5644 if (cro.baseProtocols + n_value != 0)
5645 print_protocol_list64_t(p: cro.baseProtocols + n_value, info);
5646
5647 outs() << " ivars ";
5648 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, ivars), S,
5649 info, n_value, ReferenceValue: cro.ivars);
5650 if (n_value != 0) {
5651 if (info->verbose && sym_name != nullptr)
5652 outs() << sym_name;
5653 else
5654 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5655 if (cro.ivars != 0)
5656 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.ivars);
5657 } else
5658 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.ivars);
5659 outs() << "\n";
5660 if (cro.ivars + n_value != 0)
5661 print_ivar_list64_t(p: cro.ivars + n_value, info);
5662
5663 outs() << " weakIvarLayout ";
5664 sym_name =
5665 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5666 info, n_value, ReferenceValue: cro.weakIvarLayout);
5667 if (n_value != 0) {
5668 if (info->verbose && sym_name != nullptr)
5669 outs() << sym_name;
5670 else
5671 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5672 if (cro.weakIvarLayout != 0)
5673 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.weakIvarLayout);
5674 } else
5675 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.weakIvarLayout);
5676 outs() << "\n";
5677 print_layout_map64(p: cro.weakIvarLayout + n_value, info);
5678
5679 outs() << " baseProperties ";
5680 sym_name =
5681 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseProperties), S,
5682 info, n_value, ReferenceValue: cro.baseProperties);
5683 if (n_value != 0) {
5684 if (info->verbose && sym_name != nullptr)
5685 outs() << sym_name;
5686 else
5687 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5688 if (cro.baseProperties != 0)
5689 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseProperties);
5690 } else
5691 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseProperties);
5692 outs() << "\n";
5693 if (cro.baseProperties + n_value != 0)
5694 print_objc_property_list64(p: cro.baseProperties + n_value, info);
5695
5696 is_meta_class = (cro.flags & RO_META) != 0;
5697 return true;
5698}
5699
5700static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5701 bool &is_meta_class) {
5702 struct class_ro32_t cro;
5703 const char *r;
5704 uint32_t offset, xoffset, left;
5705 SectionRef S, xS;
5706 const char *name;
5707
5708 r = get_pointer_32(Address: p, offset, left, S, info);
5709 if (r == nullptr)
5710 return false;
5711 memset(s: &cro, c: '\0', n: sizeof(struct class_ro32_t));
5712 if (left < sizeof(struct class_ro32_t)) {
5713 memcpy(dest: &cro, src: r, n: left);
5714 outs() << " (class_ro_t entends past the end of the section)\n";
5715 } else
5716 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro32_t));
5717 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5718 swapStruct(cro);
5719 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: cro.flags);
5720 if (cro.flags & RO_META)
5721 outs() << " RO_META";
5722 if (cro.flags & RO_ROOT)
5723 outs() << " RO_ROOT";
5724 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5725 outs() << " RO_HAS_CXX_STRUCTORS";
5726 outs() << "\n";
5727 outs() << " instanceStart " << cro.instanceStart << "\n";
5728 outs() << " instanceSize " << cro.instanceSize << "\n";
5729 outs() << " ivarLayout " << format(Fmt: "0x%" PRIx32, Vals: cro.ivarLayout)
5730 << "\n";
5731 print_layout_map32(p: cro.ivarLayout, info);
5732
5733 outs() << " name " << format(Fmt: "0x%" PRIx32, Vals: cro.name);
5734 name = get_pointer_32(Address: cro.name, offset&: xoffset, left, S&: xS, info);
5735 if (name != nullptr)
5736 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5737 outs() << "\n";
5738
5739 outs() << " baseMethods "
5740 << format(Fmt: "0x%" PRIx32, Vals: cro.baseMethods)
5741 << " (struct method_list_t *)\n";
5742 if (cro.baseMethods != 0)
5743 print_method_list32_t(p: cro.baseMethods, info, indent: "");
5744
5745 outs() << " baseProtocols "
5746 << format(Fmt: "0x%" PRIx32, Vals: cro.baseProtocols) << "\n";
5747 if (cro.baseProtocols != 0)
5748 print_protocol_list32_t(p: cro.baseProtocols, info);
5749 outs() << " ivars " << format(Fmt: "0x%" PRIx32, Vals: cro.ivars)
5750 << "\n";
5751 if (cro.ivars != 0)
5752 print_ivar_list32_t(p: cro.ivars, info);
5753 outs() << " weakIvarLayout "
5754 << format(Fmt: "0x%" PRIx32, Vals: cro.weakIvarLayout) << "\n";
5755 print_layout_map32(p: cro.weakIvarLayout, info);
5756 outs() << " baseProperties "
5757 << format(Fmt: "0x%" PRIx32, Vals: cro.baseProperties) << "\n";
5758 if (cro.baseProperties != 0)
5759 print_objc_property_list32(p: cro.baseProperties, info);
5760 is_meta_class = (cro.flags & RO_META) != 0;
5761 return true;
5762}
5763
5764static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5765 struct class64_t c;
5766 const char *r;
5767 uint32_t offset, left;
5768 SectionRef S;
5769 const char *name;
5770 uint64_t isa_n_value, n_value;
5771
5772 r = get_pointer_64(Address: p, offset, left, S, info);
5773 if (r == nullptr || left < sizeof(struct class64_t))
5774 return;
5775 memcpy(dest: &c, src: r, n: sizeof(struct class64_t));
5776 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5777 swapStruct(c);
5778
5779 outs() << " isa " << format(Fmt: "0x%" PRIx64, Vals: c.isa);
5780 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, isa), S, info,
5781 n_value&: isa_n_value, ReferenceValue: c.isa);
5782 if (name != nullptr)
5783 outs() << " " << name;
5784 outs() << "\n";
5785
5786 outs() << " superclass " << format(Fmt: "0x%" PRIx64, Vals: c.superclass);
5787 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, superclass), S, info,
5788 n_value, ReferenceValue: c.superclass);
5789 if (name != nullptr)
5790 outs() << " " << name;
5791 else {
5792 name = get_dyld_bind_info_symbolname(ReferenceValue: S.getAddress() +
5793 offset + offsetof(struct class64_t, superclass), info);
5794 if (name != nullptr)
5795 outs() << " " << name;
5796 }
5797 outs() << "\n";
5798
5799 outs() << " cache " << format(Fmt: "0x%" PRIx64, Vals: c.cache);
5800 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, cache), S, info,
5801 n_value, ReferenceValue: c.cache);
5802 if (name != nullptr)
5803 outs() << " " << name;
5804 outs() << "\n";
5805
5806 outs() << " vtable " << format(Fmt: "0x%" PRIx64, Vals: c.vtable);
5807 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, vtable), S, info,
5808 n_value, ReferenceValue: c.vtable);
5809 if (name != nullptr)
5810 outs() << " " << name;
5811 outs() << "\n";
5812
5813 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, data), S, info,
5814 n_value, ReferenceValue: c.data);
5815 outs() << " data ";
5816 if (n_value != 0) {
5817 if (info->verbose && name != nullptr)
5818 outs() << name;
5819 else
5820 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5821 if (c.data != 0)
5822 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.data);
5823 } else
5824 outs() << format(Fmt: "0x%" PRIx64, Vals: c.data);
5825 outs() << " (struct class_ro_t *)";
5826
5827 // This is a Swift class if some of the low bits of the pointer are set.
5828 if ((c.data + n_value) & 0x7)
5829 outs() << " Swift class";
5830 outs() << "\n";
5831 bool is_meta_class;
5832 if (!print_class_ro64_t(p: (c.data + n_value) & ~0x7, info, is_meta_class))
5833 return;
5834
5835 if (!is_meta_class &&
5836 c.isa + isa_n_value != p &&
5837 c.isa + isa_n_value != 0 &&
5838 info->depth < 100) {
5839 info->depth++;
5840 outs() << "Meta Class\n";
5841 print_class64_t(p: c.isa + isa_n_value, info);
5842 }
5843}
5844
5845static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5846 struct class32_t c;
5847 const char *r;
5848 uint32_t offset, left;
5849 SectionRef S;
5850 const char *name;
5851
5852 r = get_pointer_32(Address: p, offset, left, S, info);
5853 if (r == nullptr)
5854 return;
5855 memset(s: &c, c: '\0', n: sizeof(struct class32_t));
5856 if (left < sizeof(struct class32_t)) {
5857 memcpy(dest: &c, src: r, n: left);
5858 outs() << " (class_t entends past the end of the section)\n";
5859 } else
5860 memcpy(dest: &c, src: r, n: sizeof(struct class32_t));
5861 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5862 swapStruct(c);
5863
5864 outs() << " isa " << format(Fmt: "0x%" PRIx32, Vals: c.isa);
5865 name =
5866 get_symbol_32(sect_offset: offset + offsetof(struct class32_t, isa), S, info, ReferenceValue: c.isa);
5867 if (name != nullptr)
5868 outs() << " " << name;
5869 outs() << "\n";
5870
5871 outs() << " superclass " << format(Fmt: "0x%" PRIx32, Vals: c.superclass);
5872 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, superclass), S, info,
5873 ReferenceValue: c.superclass);
5874 if (name != nullptr)
5875 outs() << " " << name;
5876 outs() << "\n";
5877
5878 outs() << " cache " << format(Fmt: "0x%" PRIx32, Vals: c.cache);
5879 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, cache), S, info,
5880 ReferenceValue: c.cache);
5881 if (name != nullptr)
5882 outs() << " " << name;
5883 outs() << "\n";
5884
5885 outs() << " vtable " << format(Fmt: "0x%" PRIx32, Vals: c.vtable);
5886 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, vtable), S, info,
5887 ReferenceValue: c.vtable);
5888 if (name != nullptr)
5889 outs() << " " << name;
5890 outs() << "\n";
5891
5892 name =
5893 get_symbol_32(sect_offset: offset + offsetof(struct class32_t, data), S, info, ReferenceValue: c.data);
5894 outs() << " data " << format(Fmt: "0x%" PRIx32, Vals: c.data)
5895 << " (struct class_ro_t *)";
5896
5897 // This is a Swift class if some of the low bits of the pointer are set.
5898 if (c.data & 0x3)
5899 outs() << " Swift class";
5900 outs() << "\n";
5901 bool is_meta_class;
5902 if (!print_class_ro32_t(p: c.data & ~0x3, info, is_meta_class))
5903 return;
5904
5905 if (!is_meta_class) {
5906 outs() << "Meta Class\n";
5907 print_class32_t(p: c.isa, info);
5908 }
5909}
5910
5911static void print_objc_class_t(struct objc_class_t *objc_class,
5912 struct DisassembleInfo *info) {
5913 uint32_t offset, left, xleft;
5914 const char *name, *p, *ivar_list;
5915 SectionRef S;
5916 int32_t i;
5917 struct objc_ivar_list_t objc_ivar_list;
5918 struct objc_ivar_t ivar;
5919
5920 outs() << "\t\t isa " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->isa);
5921 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5922 name = get_pointer_32(Address: objc_class->isa, offset, left, S, info, objc_only: true);
5923 if (name != nullptr)
5924 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5925 else
5926 outs() << " (not in an __OBJC section)";
5927 }
5928 outs() << "\n";
5929
5930 outs() << "\t super_class "
5931 << format(Fmt: "0x%08" PRIx32, Vals: objc_class->super_class);
5932 if (info->verbose) {
5933 name = get_pointer_32(Address: objc_class->super_class, offset, left, S, info, objc_only: true);
5934 if (name != nullptr)
5935 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5936 else
5937 outs() << " (not in an __OBJC section)";
5938 }
5939 outs() << "\n";
5940
5941 outs() << "\t\t name " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->name);
5942 if (info->verbose) {
5943 name = get_pointer_32(Address: objc_class->name, offset, left, S, info, objc_only: true);
5944 if (name != nullptr)
5945 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5946 else
5947 outs() << " (not in an __OBJC section)";
5948 }
5949 outs() << "\n";
5950
5951 outs() << "\t\t version " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->version)
5952 << "\n";
5953
5954 outs() << "\t\t info " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->info);
5955 if (info->verbose) {
5956 if (CLS_GETINFO(objc_class, CLS_CLASS))
5957 outs() << " CLS_CLASS";
5958 else if (CLS_GETINFO(objc_class, CLS_META))
5959 outs() << " CLS_META";
5960 }
5961 outs() << "\n";
5962
5963 outs() << "\t instance_size "
5964 << format(Fmt: "0x%08" PRIx32, Vals: objc_class->instance_size) << "\n";
5965
5966 p = get_pointer_32(Address: objc_class->ivars, offset, left, S, info, objc_only: true);
5967 outs() << "\t\t ivars " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->ivars);
5968 if (p != nullptr) {
5969 if (left > sizeof(struct objc_ivar_list_t)) {
5970 outs() << "\n";
5971 memcpy(dest: &objc_ivar_list, src: p, n: sizeof(struct objc_ivar_list_t));
5972 } else {
5973 outs() << " (entends past the end of the section)\n";
5974 memset(s: &objc_ivar_list, c: '\0', n: sizeof(struct objc_ivar_list_t));
5975 memcpy(dest: &objc_ivar_list, src: p, n: left);
5976 }
5977 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5978 swapStruct(objc_ivar_list);
5979 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5980 ivar_list = p + sizeof(struct objc_ivar_list_t);
5981 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5982 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5983 outs() << "\t\t remaining ivar's extend past the of the section\n";
5984 break;
5985 }
5986 memcpy(dest: &ivar, src: ivar_list + i * sizeof(struct objc_ivar_t),
5987 n: sizeof(struct objc_ivar_t));
5988 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5989 swapStruct(objc_ivar&: ivar);
5990
5991 outs() << "\t\t\tivar_name " << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_name);
5992 if (info->verbose) {
5993 name = get_pointer_32(Address: ivar.ivar_name, offset, left&: xleft, S, info, objc_only: true);
5994 if (name != nullptr)
5995 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5996 else
5997 outs() << " (not in an __OBJC section)";
5998 }
5999 outs() << "\n";
6000
6001 outs() << "\t\t\tivar_type " << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_type);
6002 if (info->verbose) {
6003 name = get_pointer_32(Address: ivar.ivar_type, offset, left&: xleft, S, info, objc_only: true);
6004 if (name != nullptr)
6005 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
6006 else
6007 outs() << " (not in an __OBJC section)";
6008 }
6009 outs() << "\n";
6010
6011 outs() << "\t\t ivar_offset "
6012 << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_offset) << "\n";
6013 }
6014 } else {
6015 outs() << " (not in an __OBJC section)\n";
6016 }
6017
6018 outs() << "\t\t methods " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->methodLists);
6019 if (print_method_list(p: objc_class->methodLists, info))
6020 outs() << " (not in an __OBJC section)\n";
6021
6022 outs() << "\t\t cache " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->cache)
6023 << "\n";
6024
6025 outs() << "\t\tprotocols " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->protocols);
6026 if (print_protocol_list(p: objc_class->protocols, indent: 16, info))
6027 outs() << " (not in an __OBJC section)\n";
6028}
6029
6030static void print_objc_objc_category_t(struct objc_category_t *objc_category,
6031 struct DisassembleInfo *info) {
6032 uint32_t offset, left;
6033 const char *name;
6034 SectionRef S;
6035
6036 outs() << "\t category name "
6037 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->category_name);
6038 if (info->verbose) {
6039 name = get_pointer_32(Address: objc_category->category_name, offset, left, S, info,
6040 objc_only: true);
6041 if (name != nullptr)
6042 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6043 else
6044 outs() << " (not in an __OBJC section)";
6045 }
6046 outs() << "\n";
6047
6048 outs() << "\t\t class name "
6049 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->class_name);
6050 if (info->verbose) {
6051 name =
6052 get_pointer_32(Address: objc_category->class_name, offset, left, S, info, objc_only: true);
6053 if (name != nullptr)
6054 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6055 else
6056 outs() << " (not in an __OBJC section)";
6057 }
6058 outs() << "\n";
6059
6060 outs() << "\t instance methods "
6061 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->instance_methods);
6062 if (print_method_list(p: objc_category->instance_methods, info))
6063 outs() << " (not in an __OBJC section)\n";
6064
6065 outs() << "\t class methods "
6066 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->class_methods);
6067 if (print_method_list(p: objc_category->class_methods, info))
6068 outs() << " (not in an __OBJC section)\n";
6069}
6070
6071static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
6072 struct category64_t c;
6073 const char *r;
6074 uint32_t offset, xoffset, left;
6075 SectionRef S, xS;
6076 const char *name, *sym_name;
6077 uint64_t n_value;
6078
6079 r = get_pointer_64(Address: p, offset, left, S, info);
6080 if (r == nullptr)
6081 return;
6082 memset(s: &c, c: '\0', n: sizeof(struct category64_t));
6083 if (left < sizeof(struct category64_t)) {
6084 memcpy(dest: &c, src: r, n: left);
6085 outs() << " (category_t entends past the end of the section)\n";
6086 } else
6087 memcpy(dest: &c, src: r, n: sizeof(struct category64_t));
6088 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6089 swapStruct(c);
6090
6091 outs() << " name ";
6092 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, name), S,
6093 info, n_value, ReferenceValue: c.name);
6094 if (n_value != 0) {
6095 if (info->verbose && sym_name != nullptr)
6096 outs() << sym_name;
6097 else
6098 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6099 if (c.name != 0)
6100 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.name);
6101 } else
6102 outs() << format(Fmt: "0x%" PRIx64, Vals: c.name);
6103 name = get_pointer_64(Address: c.name + n_value, offset&: xoffset, left, S&: xS, info);
6104 if (name != nullptr)
6105 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6106 outs() << "\n";
6107
6108 outs() << " cls ";
6109 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, cls), S, info,
6110 n_value, ReferenceValue: c.cls);
6111 if (n_value != 0) {
6112 if (info->verbose && sym_name != nullptr)
6113 outs() << sym_name;
6114 else
6115 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6116 if (c.cls != 0)
6117 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.cls);
6118 } else
6119 outs() << format(Fmt: "0x%" PRIx64, Vals: c.cls);
6120 outs() << "\n";
6121 if (c.cls + n_value != 0)
6122 print_class64_t(p: c.cls + n_value, info);
6123
6124 outs() << " instanceMethods ";
6125 sym_name =
6126 get_symbol_64(sect_offset: offset + offsetof(struct category64_t, instanceMethods), S,
6127 info, n_value, ReferenceValue: c.instanceMethods);
6128 if (n_value != 0) {
6129 if (info->verbose && sym_name != nullptr)
6130 outs() << sym_name;
6131 else
6132 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6133 if (c.instanceMethods != 0)
6134 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.instanceMethods);
6135 } else
6136 outs() << format(Fmt: "0x%" PRIx64, Vals: c.instanceMethods);
6137 outs() << "\n";
6138 if (c.instanceMethods + n_value != 0)
6139 print_method_list64_t(p: c.instanceMethods + n_value, info, indent: "");
6140
6141 outs() << " classMethods ";
6142 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, classMethods),
6143 S, info, n_value, ReferenceValue: c.classMethods);
6144 if (n_value != 0) {
6145 if (info->verbose && sym_name != nullptr)
6146 outs() << sym_name;
6147 else
6148 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6149 if (c.classMethods != 0)
6150 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.classMethods);
6151 } else
6152 outs() << format(Fmt: "0x%" PRIx64, Vals: c.classMethods);
6153 outs() << "\n";
6154 if (c.classMethods + n_value != 0)
6155 print_method_list64_t(p: c.classMethods + n_value, info, indent: "");
6156
6157 outs() << " protocols ";
6158 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, protocols), S,
6159 info, n_value, ReferenceValue: c.protocols);
6160 if (n_value != 0) {
6161 if (info->verbose && sym_name != nullptr)
6162 outs() << sym_name;
6163 else
6164 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6165 if (c.protocols != 0)
6166 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.protocols);
6167 } else
6168 outs() << format(Fmt: "0x%" PRIx64, Vals: c.protocols);
6169 outs() << "\n";
6170 if (c.protocols + n_value != 0)
6171 print_protocol_list64_t(p: c.protocols + n_value, info);
6172
6173 outs() << "instanceProperties ";
6174 sym_name =
6175 get_symbol_64(sect_offset: offset + offsetof(struct category64_t, instanceProperties),
6176 S, info, n_value, ReferenceValue: c.instanceProperties);
6177 if (n_value != 0) {
6178 if (info->verbose && sym_name != nullptr)
6179 outs() << sym_name;
6180 else
6181 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6182 if (c.instanceProperties != 0)
6183 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.instanceProperties);
6184 } else
6185 outs() << format(Fmt: "0x%" PRIx64, Vals: c.instanceProperties);
6186 outs() << "\n";
6187 if (c.instanceProperties + n_value != 0)
6188 print_objc_property_list64(p: c.instanceProperties + n_value, info);
6189}
6190
6191static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
6192 struct category32_t c;
6193 const char *r;
6194 uint32_t offset, left;
6195 SectionRef S, xS;
6196 const char *name;
6197
6198 r = get_pointer_32(Address: p, offset, left, S, info);
6199 if (r == nullptr)
6200 return;
6201 memset(s: &c, c: '\0', n: sizeof(struct category32_t));
6202 if (left < sizeof(struct category32_t)) {
6203 memcpy(dest: &c, src: r, n: left);
6204 outs() << " (category_t entends past the end of the section)\n";
6205 } else
6206 memcpy(dest: &c, src: r, n: sizeof(struct category32_t));
6207 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6208 swapStruct(c);
6209
6210 outs() << " name " << format(Fmt: "0x%" PRIx32, Vals: c.name);
6211 name = get_symbol_32(sect_offset: offset + offsetof(struct category32_t, name), S, info,
6212 ReferenceValue: c.name);
6213 if (name)
6214 outs() << " " << name;
6215 outs() << "\n";
6216
6217 outs() << " cls " << format(Fmt: "0x%" PRIx32, Vals: c.cls) << "\n";
6218 if (c.cls != 0)
6219 print_class32_t(p: c.cls, info);
6220 outs() << " instanceMethods " << format(Fmt: "0x%" PRIx32, Vals: c.instanceMethods)
6221 << "\n";
6222 if (c.instanceMethods != 0)
6223 print_method_list32_t(p: c.instanceMethods, info, indent: "");
6224 outs() << " classMethods " << format(Fmt: "0x%" PRIx32, Vals: c.classMethods)
6225 << "\n";
6226 if (c.classMethods != 0)
6227 print_method_list32_t(p: c.classMethods, info, indent: "");
6228 outs() << " protocols " << format(Fmt: "0x%" PRIx32, Vals: c.protocols) << "\n";
6229 if (c.protocols != 0)
6230 print_protocol_list32_t(p: c.protocols, info);
6231 outs() << "instanceProperties " << format(Fmt: "0x%" PRIx32, Vals: c.instanceProperties)
6232 << "\n";
6233 if (c.instanceProperties != 0)
6234 print_objc_property_list32(p: c.instanceProperties, info);
6235}
6236
6237static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
6238 uint32_t i, left, offset, xoffset;
6239 uint64_t p, n_value;
6240 struct message_ref64 mr;
6241 const char *name, *sym_name;
6242 const char *r;
6243 SectionRef xS;
6244
6245 if (S == SectionRef())
6246 return;
6247
6248 StringRef SectName;
6249 Expected<StringRef> SecNameOrErr = S.getName();
6250 if (SecNameOrErr)
6251 SectName = *SecNameOrErr;
6252 else
6253 consumeError(Err: SecNameOrErr.takeError());
6254
6255 DataRefImpl Ref = S.getRawDataRefImpl();
6256 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6257 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6258 offset = 0;
6259 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6260 p = S.getAddress() + i;
6261 r = get_pointer_64(Address: p, offset, left, S, info);
6262 if (r == nullptr)
6263 return;
6264 memset(s: &mr, c: '\0', n: sizeof(struct message_ref64));
6265 if (left < sizeof(struct message_ref64)) {
6266 memcpy(dest: &mr, src: r, n: left);
6267 outs() << " (message_ref entends past the end of the section)\n";
6268 } else
6269 memcpy(dest: &mr, src: r, n: sizeof(struct message_ref64));
6270 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6271 swapStruct(mr);
6272
6273 outs() << " imp ";
6274 name = get_symbol_64(sect_offset: offset + offsetof(struct message_ref64, imp), S, info,
6275 n_value, ReferenceValue: mr.imp);
6276 if (n_value != 0) {
6277 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value) << " ";
6278 if (mr.imp != 0)
6279 outs() << "+ " << format(Fmt: "0x%" PRIx64, Vals: mr.imp) << " ";
6280 } else
6281 outs() << format(Fmt: "0x%" PRIx64, Vals: mr.imp) << " ";
6282 if (name != nullptr)
6283 outs() << " " << name;
6284 outs() << "\n";
6285
6286 outs() << " sel ";
6287 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct message_ref64, sel), S,
6288 info, n_value, ReferenceValue: mr.sel);
6289 if (n_value != 0) {
6290 if (info->verbose && sym_name != nullptr)
6291 outs() << sym_name;
6292 else
6293 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6294 if (mr.sel != 0)
6295 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: mr.sel);
6296 } else
6297 outs() << format(Fmt: "0x%" PRIx64, Vals: mr.sel);
6298 name = get_pointer_64(Address: mr.sel + n_value, offset&: xoffset, left, S&: xS, info);
6299 if (name != nullptr)
6300 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6301 outs() << "\n";
6302
6303 offset += sizeof(struct message_ref64);
6304 }
6305}
6306
6307static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
6308 uint32_t i, left, offset, xoffset, p;
6309 struct message_ref32 mr;
6310 const char *name, *r;
6311 SectionRef xS;
6312
6313 if (S == SectionRef())
6314 return;
6315
6316 StringRef SectName;
6317 Expected<StringRef> SecNameOrErr = S.getName();
6318 if (SecNameOrErr)
6319 SectName = *SecNameOrErr;
6320 else
6321 consumeError(Err: SecNameOrErr.takeError());
6322
6323 DataRefImpl Ref = S.getRawDataRefImpl();
6324 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6325 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6326 offset = 0;
6327 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6328 p = S.getAddress() + i;
6329 r = get_pointer_32(Address: p, offset, left, S, info);
6330 if (r == nullptr)
6331 return;
6332 memset(s: &mr, c: '\0', n: sizeof(struct message_ref32));
6333 if (left < sizeof(struct message_ref32)) {
6334 memcpy(dest: &mr, src: r, n: left);
6335 outs() << " (message_ref entends past the end of the section)\n";
6336 } else
6337 memcpy(dest: &mr, src: r, n: sizeof(struct message_ref32));
6338 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6339 swapStruct(mr);
6340
6341 outs() << " imp " << format(Fmt: "0x%" PRIx32, Vals: mr.imp);
6342 name = get_symbol_32(sect_offset: offset + offsetof(struct message_ref32, imp), S, info,
6343 ReferenceValue: mr.imp);
6344 if (name != nullptr)
6345 outs() << " " << name;
6346 outs() << "\n";
6347
6348 outs() << " sel " << format(Fmt: "0x%" PRIx32, Vals: mr.sel);
6349 name = get_pointer_32(Address: mr.sel, offset&: xoffset, left, S&: xS, info);
6350 if (name != nullptr)
6351 outs() << " " << name;
6352 outs() << "\n";
6353
6354 offset += sizeof(struct message_ref32);
6355 }
6356}
6357
6358static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
6359 uint32_t left, offset, swift_version;
6360 uint64_t p;
6361 struct objc_image_info64 o;
6362 const char *r;
6363
6364 if (S == SectionRef())
6365 return;
6366
6367 StringRef SectName;
6368 Expected<StringRef> SecNameOrErr = S.getName();
6369 if (SecNameOrErr)
6370 SectName = *SecNameOrErr;
6371 else
6372 consumeError(Err: SecNameOrErr.takeError());
6373
6374 DataRefImpl Ref = S.getRawDataRefImpl();
6375 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6376 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6377 p = S.getAddress();
6378 r = get_pointer_64(Address: p, offset, left, S, info);
6379 if (r == nullptr)
6380 return;
6381 memset(s: &o, c: '\0', n: sizeof(struct objc_image_info64));
6382 if (left < sizeof(struct objc_image_info64)) {
6383 memcpy(dest: &o, src: r, n: left);
6384 outs() << " (objc_image_info entends past the end of the section)\n";
6385 } else
6386 memcpy(dest: &o, src: r, n: sizeof(struct objc_image_info64));
6387 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6388 swapStruct(o);
6389 outs() << " version " << o.version << "\n";
6390 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6391 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6392 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6393 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6394 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6395 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
6396 outs() << " OBJC_IMAGE_IS_SIMULATED";
6397 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
6398 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
6399 swift_version = (o.flags >> 8) & 0xff;
6400 if (swift_version != 0) {
6401 if (swift_version == 1)
6402 outs() << " Swift 1.0";
6403 else if (swift_version == 2)
6404 outs() << " Swift 1.1";
6405 else if(swift_version == 3)
6406 outs() << " Swift 2.0";
6407 else if(swift_version == 4)
6408 outs() << " Swift 3.0";
6409 else if(swift_version == 5)
6410 outs() << " Swift 4.0";
6411 else if(swift_version == 6)
6412 outs() << " Swift 4.1/Swift 4.2";
6413 else if(swift_version == 7)
6414 outs() << " Swift 5 or later";
6415 else
6416 outs() << " unknown future Swift version (" << swift_version << ")";
6417 }
6418 outs() << "\n";
6419}
6420
6421static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6422 uint32_t left, offset, swift_version, p;
6423 struct objc_image_info32 o;
6424 const char *r;
6425
6426 if (S == SectionRef())
6427 return;
6428
6429 StringRef SectName;
6430 Expected<StringRef> SecNameOrErr = S.getName();
6431 if (SecNameOrErr)
6432 SectName = *SecNameOrErr;
6433 else
6434 consumeError(Err: SecNameOrErr.takeError());
6435
6436 DataRefImpl Ref = S.getRawDataRefImpl();
6437 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6438 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6439 p = S.getAddress();
6440 r = get_pointer_32(Address: p, offset, left, S, info);
6441 if (r == nullptr)
6442 return;
6443 memset(s: &o, c: '\0', n: sizeof(struct objc_image_info32));
6444 if (left < sizeof(struct objc_image_info32)) {
6445 memcpy(dest: &o, src: r, n: left);
6446 outs() << " (objc_image_info entends past the end of the section)\n";
6447 } else
6448 memcpy(dest: &o, src: r, n: sizeof(struct objc_image_info32));
6449 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6450 swapStruct(o);
6451 outs() << " version " << o.version << "\n";
6452 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6453 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6454 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6455 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6456 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6457 swift_version = (o.flags >> 8) & 0xff;
6458 if (swift_version != 0) {
6459 if (swift_version == 1)
6460 outs() << " Swift 1.0";
6461 else if (swift_version == 2)
6462 outs() << " Swift 1.1";
6463 else if(swift_version == 3)
6464 outs() << " Swift 2.0";
6465 else if(swift_version == 4)
6466 outs() << " Swift 3.0";
6467 else if(swift_version == 5)
6468 outs() << " Swift 4.0";
6469 else if(swift_version == 6)
6470 outs() << " Swift 4.1/Swift 4.2";
6471 else if(swift_version == 7)
6472 outs() << " Swift 5 or later";
6473 else
6474 outs() << " unknown future Swift version (" << swift_version << ")";
6475 }
6476 outs() << "\n";
6477}
6478
6479static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6480 uint32_t left, offset, p;
6481 struct imageInfo_t o;
6482 const char *r;
6483
6484 StringRef SectName;
6485 Expected<StringRef> SecNameOrErr = S.getName();
6486 if (SecNameOrErr)
6487 SectName = *SecNameOrErr;
6488 else
6489 consumeError(Err: SecNameOrErr.takeError());
6490
6491 DataRefImpl Ref = S.getRawDataRefImpl();
6492 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6493 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6494 p = S.getAddress();
6495 r = get_pointer_32(Address: p, offset, left, S, info);
6496 if (r == nullptr)
6497 return;
6498 memset(s: &o, c: '\0', n: sizeof(struct imageInfo_t));
6499 if (left < sizeof(struct imageInfo_t)) {
6500 memcpy(dest: &o, src: r, n: left);
6501 outs() << " (imageInfo entends past the end of the section)\n";
6502 } else
6503 memcpy(dest: &o, src: r, n: sizeof(struct imageInfo_t));
6504 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6505 swapStruct(o);
6506 outs() << " version " << o.version << "\n";
6507 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6508 if (o.flags & 0x1)
6509 outs() << " F&C";
6510 if (o.flags & 0x2)
6511 outs() << " GC";
6512 if (o.flags & 0x4)
6513 outs() << " GC-only";
6514 else
6515 outs() << " RR";
6516 outs() << "\n";
6517}
6518
6519static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6520 SymbolAddressMap AddrMap;
6521 if (verbose)
6522 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6523
6524 std::vector<SectionRef> Sections;
6525 append_range(C&: Sections, R: O->sections());
6526
6527 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6528
6529 SectionRef CL = get_section(O, segname: "__OBJC2", sectname: "__class_list");
6530 if (CL == SectionRef())
6531 CL = get_section(O, segname: "__DATA", sectname: "__objc_classlist");
6532 if (CL == SectionRef())
6533 CL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classlist");
6534 if (CL == SectionRef())
6535 CL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classlist");
6536 info.S = CL;
6537 walk_pointer_list_64(listname: "class", S: CL, O, info: &info, func: print_class64_t);
6538
6539 SectionRef CR = get_section(O, segname: "__OBJC2", sectname: "__class_refs");
6540 if (CR == SectionRef())
6541 CR = get_section(O, segname: "__DATA", sectname: "__objc_classrefs");
6542 if (CR == SectionRef())
6543 CR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classrefs");
6544 if (CR == SectionRef())
6545 CR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classrefs");
6546 info.S = CR;
6547 walk_pointer_list_64(listname: "class refs", S: CR, O, info: &info, func: nullptr);
6548
6549 SectionRef SR = get_section(O, segname: "__OBJC2", sectname: "__super_refs");
6550 if (SR == SectionRef())
6551 SR = get_section(O, segname: "__DATA", sectname: "__objc_superrefs");
6552 if (SR == SectionRef())
6553 SR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_superrefs");
6554 if (SR == SectionRef())
6555 SR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_superrefs");
6556 info.S = SR;
6557 walk_pointer_list_64(listname: "super refs", S: SR, O, info: &info, func: nullptr);
6558
6559 SectionRef CA = get_section(O, segname: "__OBJC2", sectname: "__category_list");
6560 if (CA == SectionRef())
6561 CA = get_section(O, segname: "__DATA", sectname: "__objc_catlist");
6562 if (CA == SectionRef())
6563 CA = get_section(O, segname: "__DATA_CONST", sectname: "__objc_catlist");
6564 if (CA == SectionRef())
6565 CA = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_catlist");
6566 info.S = CA;
6567 walk_pointer_list_64(listname: "category", S: CA, O, info: &info, func: print_category64_t);
6568
6569 SectionRef PL = get_section(O, segname: "__OBJC2", sectname: "__protocol_list");
6570 if (PL == SectionRef())
6571 PL = get_section(O, segname: "__DATA", sectname: "__objc_protolist");
6572 if (PL == SectionRef())
6573 PL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_protolist");
6574 if (PL == SectionRef())
6575 PL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_protolist");
6576 info.S = PL;
6577 walk_pointer_list_64(listname: "protocol", S: PL, O, info: &info, func: nullptr);
6578
6579 SectionRef MR = get_section(O, segname: "__OBJC2", sectname: "__message_refs");
6580 if (MR == SectionRef())
6581 MR = get_section(O, segname: "__DATA", sectname: "__objc_msgrefs");
6582 if (MR == SectionRef())
6583 MR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_msgrefs");
6584 if (MR == SectionRef())
6585 MR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_msgrefs");
6586 info.S = MR;
6587 print_message_refs64(S: MR, info: &info);
6588
6589 SectionRef II = get_section(O, segname: "__OBJC2", sectname: "__image_info");
6590 if (II == SectionRef())
6591 II = get_section(O, segname: "__DATA", sectname: "__objc_imageinfo");
6592 if (II == SectionRef())
6593 II = get_section(O, segname: "__DATA_CONST", sectname: "__objc_imageinfo");
6594 if (II == SectionRef())
6595 II = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_imageinfo");
6596 info.S = II;
6597 print_image_info64(S: II, info: &info);
6598}
6599
6600static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6601 SymbolAddressMap AddrMap;
6602 if (verbose)
6603 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6604
6605 std::vector<SectionRef> Sections;
6606 append_range(C&: Sections, R: O->sections());
6607
6608 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6609
6610 SectionRef CL = get_section(O, segname: "__OBJC2", sectname: "__class_list");
6611 if (CL == SectionRef())
6612 CL = get_section(O, segname: "__DATA", sectname: "__objc_classlist");
6613 if (CL == SectionRef())
6614 CL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classlist");
6615 if (CL == SectionRef())
6616 CL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classlist");
6617 info.S = CL;
6618 walk_pointer_list_32(listname: "class", S: CL, O, info: &info, func: print_class32_t);
6619
6620 SectionRef CR = get_section(O, segname: "__OBJC2", sectname: "__class_refs");
6621 if (CR == SectionRef())
6622 CR = get_section(O, segname: "__DATA", sectname: "__objc_classrefs");
6623 if (CR == SectionRef())
6624 CR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classrefs");
6625 if (CR == SectionRef())
6626 CR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classrefs");
6627 info.S = CR;
6628 walk_pointer_list_32(listname: "class refs", S: CR, O, info: &info, func: nullptr);
6629
6630 SectionRef SR = get_section(O, segname: "__OBJC2", sectname: "__super_refs");
6631 if (SR == SectionRef())
6632 SR = get_section(O, segname: "__DATA", sectname: "__objc_superrefs");
6633 if (SR == SectionRef())
6634 SR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_superrefs");
6635 if (SR == SectionRef())
6636 SR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_superrefs");
6637 info.S = SR;
6638 walk_pointer_list_32(listname: "super refs", S: SR, O, info: &info, func: nullptr);
6639
6640 SectionRef CA = get_section(O, segname: "__OBJC2", sectname: "__category_list");
6641 if (CA == SectionRef())
6642 CA = get_section(O, segname: "__DATA", sectname: "__objc_catlist");
6643 if (CA == SectionRef())
6644 CA = get_section(O, segname: "__DATA_CONST", sectname: "__objc_catlist");
6645 if (CA == SectionRef())
6646 CA = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_catlist");
6647 info.S = CA;
6648 walk_pointer_list_32(listname: "category", S: CA, O, info: &info, func: print_category32_t);
6649
6650 SectionRef PL = get_section(O, segname: "__OBJC2", sectname: "__protocol_list");
6651 if (PL == SectionRef())
6652 PL = get_section(O, segname: "__DATA", sectname: "__objc_protolist");
6653 if (PL == SectionRef())
6654 PL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_protolist");
6655 if (PL == SectionRef())
6656 PL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_protolist");
6657 info.S = PL;
6658 walk_pointer_list_32(listname: "protocol", S: PL, O, info: &info, func: nullptr);
6659
6660 SectionRef MR = get_section(O, segname: "__OBJC2", sectname: "__message_refs");
6661 if (MR == SectionRef())
6662 MR = get_section(O, segname: "__DATA", sectname: "__objc_msgrefs");
6663 if (MR == SectionRef())
6664 MR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_msgrefs");
6665 if (MR == SectionRef())
6666 MR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_msgrefs");
6667 info.S = MR;
6668 print_message_refs32(S: MR, info: &info);
6669
6670 SectionRef II = get_section(O, segname: "__OBJC2", sectname: "__image_info");
6671 if (II == SectionRef())
6672 II = get_section(O, segname: "__DATA", sectname: "__objc_imageinfo");
6673 if (II == SectionRef())
6674 II = get_section(O, segname: "__DATA_CONST", sectname: "__objc_imageinfo");
6675 if (II == SectionRef())
6676 II = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_imageinfo");
6677 info.S = II;
6678 print_image_info32(S: II, info: &info);
6679}
6680
6681static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6682 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6683 const char *r, *name, *defs;
6684 struct objc_module_t module;
6685 SectionRef S, xS;
6686 struct objc_symtab_t symtab;
6687 struct objc_class_t objc_class;
6688 struct objc_category_t objc_category;
6689
6690 outs() << "Objective-C segment\n";
6691 S = get_section(O, segname: "__OBJC", sectname: "__module_info");
6692 if (S == SectionRef())
6693 return false;
6694
6695 SymbolAddressMap AddrMap;
6696 if (verbose)
6697 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6698
6699 std::vector<SectionRef> Sections;
6700 append_range(C&: Sections, R: O->sections());
6701
6702 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6703
6704 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6705 p = S.getAddress() + i;
6706 r = get_pointer_32(Address: p, offset, left, S, info: &info, objc_only: true);
6707 if (r == nullptr)
6708 return true;
6709 memset(s: &module, c: '\0', n: sizeof(struct objc_module_t));
6710 if (left < sizeof(struct objc_module_t)) {
6711 memcpy(dest: &module, src: r, n: left);
6712 outs() << " (module extends past end of __module_info section)\n";
6713 } else
6714 memcpy(dest: &module, src: r, n: sizeof(struct objc_module_t));
6715 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6716 swapStruct(module);
6717
6718 outs() << "Module " << format(Fmt: "0x%" PRIx32, Vals: p) << "\n";
6719 outs() << " version " << module.version << "\n";
6720 outs() << " size " << module.size << "\n";
6721 outs() << " name ";
6722 name = get_pointer_32(Address: module.name, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6723 if (name != nullptr)
6724 outs() << format(Fmt: "%.*s", Vals: left, Vals: name);
6725 else
6726 outs() << format(Fmt: "0x%08" PRIx32, Vals: module.name)
6727 << "(not in an __OBJC section)";
6728 outs() << "\n";
6729
6730 r = get_pointer_32(Address: module.symtab, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6731 if (module.symtab == 0 || r == nullptr) {
6732 outs() << " symtab " << format(Fmt: "0x%08" PRIx32, Vals: module.symtab)
6733 << " (not in an __OBJC section)\n";
6734 continue;
6735 }
6736 outs() << " symtab " << format(Fmt: "0x%08" PRIx32, Vals: module.symtab) << "\n";
6737 memset(s: &symtab, c: '\0', n: sizeof(struct objc_symtab_t));
6738 defs_left = 0;
6739 defs = nullptr;
6740 if (left < sizeof(struct objc_symtab_t)) {
6741 memcpy(dest: &symtab, src: r, n: left);
6742 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6743 } else {
6744 memcpy(dest: &symtab, src: r, n: sizeof(struct objc_symtab_t));
6745 if (left > sizeof(struct objc_symtab_t)) {
6746 defs_left = left - sizeof(struct objc_symtab_t);
6747 defs = r + sizeof(struct objc_symtab_t);
6748 }
6749 }
6750 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6751 swapStruct(symtab);
6752
6753 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6754 r = get_pointer_32(Address: symtab.refs, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6755 outs() << "\trefs " << format(Fmt: "0x%08" PRIx32, Vals: symtab.refs);
6756 if (r == nullptr)
6757 outs() << " (not in an __OBJC section)";
6758 outs() << "\n";
6759 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6760 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6761 if (symtab.cls_def_cnt > 0)
6762 outs() << "\tClass Definitions\n";
6763 for (j = 0; j < symtab.cls_def_cnt; j++) {
6764 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6765 outs() << "\t(remaining class defs entries entends past the end of the "
6766 << "section)\n";
6767 break;
6768 }
6769 memcpy(dest: &def, src: defs + j * sizeof(uint32_t), n: sizeof(uint32_t));
6770 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6771 sys::swapByteOrder(Value&: def);
6772
6773 r = get_pointer_32(Address: def, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6774 outs() << "\tdefs[" << j << "] " << format(Fmt: "0x%08" PRIx32, Vals: def);
6775 if (r != nullptr) {
6776 if (left > sizeof(struct objc_class_t)) {
6777 outs() << "\n";
6778 memcpy(dest: &objc_class, src: r, n: sizeof(struct objc_class_t));
6779 } else {
6780 outs() << " (entends past the end of the section)\n";
6781 memset(s: &objc_class, c: '\0', n: sizeof(struct objc_class_t));
6782 memcpy(dest: &objc_class, src: r, n: left);
6783 }
6784 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6785 swapStruct(objc_class);
6786 print_objc_class_t(objc_class: &objc_class, info: &info);
6787 } else {
6788 outs() << "(not in an __OBJC section)\n";
6789 }
6790
6791 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6792 outs() << "\tMeta Class";
6793 r = get_pointer_32(Address: objc_class.isa, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6794 if (r != nullptr) {
6795 if (left > sizeof(struct objc_class_t)) {
6796 outs() << "\n";
6797 memcpy(dest: &objc_class, src: r, n: sizeof(struct objc_class_t));
6798 } else {
6799 outs() << " (entends past the end of the section)\n";
6800 memset(s: &objc_class, c: '\0', n: sizeof(struct objc_class_t));
6801 memcpy(dest: &objc_class, src: r, n: left);
6802 }
6803 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6804 swapStruct(objc_class);
6805 print_objc_class_t(objc_class: &objc_class, info: &info);
6806 } else {
6807 outs() << "(not in an __OBJC section)\n";
6808 }
6809 }
6810 }
6811 if (symtab.cat_def_cnt > 0)
6812 outs() << "\tCategory Definitions\n";
6813 for (j = 0; j < symtab.cat_def_cnt; j++) {
6814 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6815 outs() << "\t(remaining category defs entries entends past the end of "
6816 << "the section)\n";
6817 break;
6818 }
6819 memcpy(dest: &def, src: defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6820 n: sizeof(uint32_t));
6821 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6822 sys::swapByteOrder(Value&: def);
6823
6824 r = get_pointer_32(Address: def, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6825 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6826 << format(Fmt: "0x%08" PRIx32, Vals: def);
6827 if (r != nullptr) {
6828 if (left > sizeof(struct objc_category_t)) {
6829 outs() << "\n";
6830 memcpy(dest: &objc_category, src: r, n: sizeof(struct objc_category_t));
6831 } else {
6832 outs() << " (entends past the end of the section)\n";
6833 memset(s: &objc_category, c: '\0', n: sizeof(struct objc_category_t));
6834 memcpy(dest: &objc_category, src: r, n: left);
6835 }
6836 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6837 swapStruct(objc_category);
6838 print_objc_objc_category_t(objc_category: &objc_category, info: &info);
6839 } else {
6840 outs() << "(not in an __OBJC section)\n";
6841 }
6842 }
6843 }
6844 const SectionRef II = get_section(O, segname: "__OBJC", sectname: "__image_info");
6845 if (II != SectionRef())
6846 print_image_info(S: II, info: &info);
6847
6848 return true;
6849}
6850
6851static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6852 uint32_t size, uint32_t addr) {
6853 SymbolAddressMap AddrMap;
6854 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6855
6856 std::vector<SectionRef> Sections;
6857 append_range(C&: Sections, R: O->sections());
6858
6859 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6860
6861 const char *p;
6862 struct objc_protocol_t protocol;
6863 uint32_t left, paddr;
6864 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6865 memset(s: &protocol, c: '\0', n: sizeof(struct objc_protocol_t));
6866 left = size - (p - sect);
6867 if (left < sizeof(struct objc_protocol_t)) {
6868 outs() << "Protocol extends past end of __protocol section\n";
6869 memcpy(dest: &protocol, src: p, n: left);
6870 } else
6871 memcpy(dest: &protocol, src: p, n: sizeof(struct objc_protocol_t));
6872 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6873 swapStruct(protocol);
6874 paddr = addr + (p - sect);
6875 outs() << "Protocol " << format(Fmt: "0x%" PRIx32, Vals: paddr);
6876 if (print_protocol(p: paddr, indent: 0, info: &info))
6877 outs() << "(not in an __OBJC section)\n";
6878 }
6879}
6880
6881static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6882 if (O->is64Bit())
6883 printObjc2_64bit_MetaData(O, verbose);
6884 else {
6885 MachO::mach_header H;
6886 H = O->getHeader();
6887 if (H.cputype == MachO::CPU_TYPE_ARM)
6888 printObjc2_32bit_MetaData(O, verbose);
6889 else {
6890 // This is the 32-bit non-arm cputype case. Which is normally
6891 // the first Objective-C ABI. But it may be the case of a
6892 // binary for the iOS simulator which is the second Objective-C
6893 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6894 // and return false.
6895 if (!printObjc1_32bit_MetaData(O, verbose))
6896 printObjc2_32bit_MetaData(O, verbose);
6897 }
6898 }
6899}
6900
6901// GuessLiteralPointer returns a string which for the item in the Mach-O file
6902// for the address passed in as ReferenceValue for printing as a comment with
6903// the instruction and also returns the corresponding type of that item
6904// indirectly through ReferenceType.
6905//
6906// If ReferenceValue is an address of literal cstring then a pointer to the
6907// cstring is returned and ReferenceType is set to
6908// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6909//
6910// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6911// Class ref that name is returned and the ReferenceType is set accordingly.
6912//
6913// Lastly, literals which are Symbol address in a literal pool are looked for
6914// and if found the symbol name is returned and ReferenceType is set to
6915// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6916//
6917// If there is no item in the Mach-O file for the address passed in as
6918// ReferenceValue nullptr is returned and ReferenceType is unchanged.
6919static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6920 uint64_t ReferencePC,
6921 uint64_t *ReferenceType,
6922 struct DisassembleInfo *info) {
6923 // First see if there is an external relocation entry at the ReferencePC.
6924 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6925 uint64_t sect_addr = info->S.getAddress();
6926 uint64_t sect_offset = ReferencePC - sect_addr;
6927 bool reloc_found = false;
6928 DataRefImpl Rel;
6929 MachO::any_relocation_info RE;
6930 bool isExtern = false;
6931 SymbolRef Symbol;
6932 for (const RelocationRef &Reloc : info->S.relocations()) {
6933 uint64_t RelocOffset = Reloc.getOffset();
6934 if (RelocOffset == sect_offset) {
6935 Rel = Reloc.getRawDataRefImpl();
6936 RE = info->O->getRelocation(Rel);
6937 if (info->O->isRelocationScattered(RE))
6938 continue;
6939 isExtern = info->O->getPlainRelocationExternal(RE);
6940 if (isExtern) {
6941 symbol_iterator RelocSym = Reloc.getSymbol();
6942 Symbol = *RelocSym;
6943 }
6944 reloc_found = true;
6945 break;
6946 }
6947 }
6948 // If there is an external relocation entry for a symbol in a section
6949 // then used that symbol's value for the value of the reference.
6950 if (reloc_found && isExtern) {
6951 if (info->O->getAnyRelocationPCRel(RE)) {
6952 unsigned Type = info->O->getAnyRelocationType(RE);
6953 if (Type == MachO::X86_64_RELOC_SIGNED) {
6954 ReferenceValue = cantFail(ValOrErr: Symbol.getValue());
6955 }
6956 }
6957 }
6958 }
6959
6960 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6961 // Message refs and Class refs.
6962 bool classref, selref, msgref, cfstring;
6963 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6964 selref, msgref, cfstring);
6965 if (classref && pointer_value == 0) {
6966 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6967 // And the pointer_value in that section is typically zero as it will be
6968 // set by dyld as part of the "bind information".
6969 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6970 if (name != nullptr) {
6971 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6972 const char *class_name = strrchr(s: name, c: '$');
6973 if (class_name != nullptr && class_name[1] == '_' &&
6974 class_name[2] != '\0') {
6975 info->class_name = class_name + 2;
6976 return name;
6977 }
6978 }
6979 }
6980
6981 if (classref) {
6982 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6983 const char *name =
6984 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6985 if (name != nullptr)
6986 info->class_name = name;
6987 else
6988 name = "bad class ref";
6989 return name;
6990 }
6991
6992 if (cfstring) {
6993 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6994 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6995 return name;
6996 }
6997
6998 if (selref && pointer_value == 0)
6999 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
7000
7001 if (pointer_value != 0)
7002 ReferenceValue = pointer_value;
7003
7004 const char *name = GuessCstringPointer(ReferenceValue, info);
7005 if (name) {
7006 if (pointer_value != 0 && selref) {
7007 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
7008 info->selector_name = name;
7009 } else if (pointer_value != 0 && msgref) {
7010 info->class_name = nullptr;
7011 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
7012 info->selector_name = name;
7013 } else
7014 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
7015 return name;
7016 }
7017
7018 // Lastly look for an indirect symbol with this ReferenceValue which is in
7019 // a literal pool. If found return that symbol name.
7020 name = GuessIndirectSymbol(ReferenceValue, info);
7021 if (name) {
7022 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
7023 return name;
7024 }
7025
7026 return nullptr;
7027}
7028
7029// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
7030// the Symbolizer. It looks up the ReferenceValue using the info passed via the
7031// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
7032// is created and returns the symbol name that matches the ReferenceValue or
7033// nullptr if none. The ReferenceType is passed in for the IN type of
7034// reference the instruction is making from the values in defined in the header
7035// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
7036// Out type and the ReferenceName will also be set which is added as a comment
7037// to the disassembled instruction.
7038//
7039// If the symbol name is a C++ mangled name then the demangled name is
7040// returned through ReferenceName and ReferenceType is set to
7041// LLVMDisassembler_ReferenceType_DeMangled_Name .
7042//
7043// When this is called to get a symbol name for a branch target then the
7044// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
7045// SymbolValue will be looked for in the indirect symbol table to determine if
7046// it is an address for a symbol stub. If so then the symbol name for that
7047// stub is returned indirectly through ReferenceName and then ReferenceType is
7048// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
7049//
7050// When this is called with an value loaded via a PC relative load then
7051// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
7052// SymbolValue is checked to be an address of literal pointer, symbol pointer,
7053// or an Objective-C meta data reference. If so the output ReferenceType is
7054// set to correspond to that as well as setting the ReferenceName.
7055static const char *SymbolizerSymbolLookUp(void *DisInfo,
7056 uint64_t ReferenceValue,
7057 uint64_t *ReferenceType,
7058 uint64_t ReferencePC,
7059 const char **ReferenceName) {
7060 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
7061 // If no verbose symbolic information is wanted then just return nullptr.
7062 if (!info->verbose) {
7063 *ReferenceName = nullptr;
7064 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7065 return nullptr;
7066 }
7067
7068 const char *SymbolName = GuessSymbolName(value: ReferenceValue, AddrMap: info->AddrMap);
7069
7070 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
7071 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
7072 if (*ReferenceName != nullptr) {
7073 method_reference(info, ReferenceType, ReferenceName);
7074 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7075 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7076 } else if (SymbolName != nullptr && strncmp(s1: SymbolName, s2: "__Z", n: 3) == 0) {
7077 if (info->demangled_name != nullptr)
7078 free(ptr: info->demangled_name);
7079 info->demangled_name = itaniumDemangle(mangled_name: SymbolName + 1);
7080 if (info->demangled_name != nullptr) {
7081 *ReferenceName = info->demangled_name;
7082 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7083 } else
7084 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7085 } else
7086 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7087 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7088 *ReferenceName =
7089 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7090 if (*ReferenceName)
7091 method_reference(info, ReferenceType, ReferenceName);
7092 else
7093 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7094 // If this is arm64 and the reference is an adrp instruction save the
7095 // instruction, passed in ReferenceValue and the address of the instruction
7096 // for use later if we see and add immediate instruction.
7097 } else if ((info->O->getArch() == Triple::aarch64 ||
7098 info->O->getArch() == Triple::aarch64_32) &&
7099 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7100 info->adrp_inst = ReferenceValue;
7101 info->adrp_addr = ReferencePC;
7102 SymbolName = nullptr;
7103 *ReferenceName = nullptr;
7104 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7105 // If this is arm64 and reference is an add immediate instruction and we
7106 // have
7107 // seen an adrp instruction just before it and the adrp's Xd register
7108 // matches
7109 // this add's Xn register reconstruct the value being referenced and look to
7110 // see if it is a literal pointer. Note the add immediate instruction is
7111 // passed in ReferenceValue.
7112 } else if ((info->O->getArch() == Triple::aarch64 ||
7113 info->O->getArch() == Triple::aarch64_32) &&
7114 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7115 ReferencePC - 4 == info->adrp_addr &&
7116 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7117 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7118 uint32_t addxri_inst;
7119 uint64_t adrp_imm, addxri_imm;
7120
7121 adrp_imm =
7122 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7123 if (info->adrp_inst & 0x0200000)
7124 adrp_imm |= 0xfffffffffc000000LL;
7125
7126 addxri_inst = ReferenceValue;
7127 addxri_imm = (addxri_inst >> 10) & 0xfff;
7128 if (((addxri_inst >> 22) & 0x3) == 1)
7129 addxri_imm <<= 12;
7130
7131 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7132 (adrp_imm << 12) + addxri_imm;
7133
7134 *ReferenceName =
7135 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7136 if (*ReferenceName == nullptr)
7137 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7138 // If this is arm64 and the reference is a load register instruction and we
7139 // have seen an adrp instruction just before it and the adrp's Xd register
7140 // matches this add's Xn register reconstruct the value being referenced and
7141 // look to see if it is a literal pointer. Note the load register
7142 // instruction is passed in ReferenceValue.
7143 } else if ((info->O->getArch() == Triple::aarch64 ||
7144 info->O->getArch() == Triple::aarch64_32) &&
7145 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7146 ReferencePC - 4 == info->adrp_addr &&
7147 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7148 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7149 uint32_t ldrxui_inst;
7150 uint64_t adrp_imm, ldrxui_imm;
7151
7152 adrp_imm =
7153 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7154 if (info->adrp_inst & 0x0200000)
7155 adrp_imm |= 0xfffffffffc000000LL;
7156
7157 ldrxui_inst = ReferenceValue;
7158 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7159
7160 // The size field (bits [31:30]) determines the scaling.
7161 unsigned Scale = (ldrxui_inst >> 30) & 0x3;
7162 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7163 (adrp_imm << 12) + (ldrxui_imm << Scale);
7164
7165 *ReferenceName =
7166 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7167 if (*ReferenceName == nullptr)
7168 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7169 }
7170 // If this arm64 and is an load register (PC-relative) instruction the
7171 // ReferenceValue is the PC plus the immediate value.
7172 else if ((info->O->getArch() == Triple::aarch64 ||
7173 info->O->getArch() == Triple::aarch64_32) &&
7174 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7175 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7176 *ReferenceName =
7177 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7178 if (*ReferenceName == nullptr)
7179 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7180 } else if (SymbolName != nullptr && strncmp(s1: SymbolName, s2: "__Z", n: 3) == 0) {
7181 if (info->demangled_name != nullptr)
7182 free(ptr: info->demangled_name);
7183 info->demangled_name = itaniumDemangle(mangled_name: SymbolName + 1);
7184 if (info->demangled_name != nullptr) {
7185 *ReferenceName = info->demangled_name;
7186 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7187 }
7188 } else {
7189 *ReferenceName = nullptr;
7190 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7191 }
7192
7193 return SymbolName;
7194}
7195
7196/// Emits the comments that are stored in the CommentStream.
7197/// Each comment in the CommentStream must end with a newline.
7198static void emitComments(raw_svector_ostream &CommentStream,
7199 SmallString<128> &CommentsToEmit,
7200 formatted_raw_ostream &FormattedOS,
7201 const MCAsmInfo &MAI) {
7202 // Flush the stream before taking its content.
7203 StringRef Comments = CommentsToEmit.str();
7204 // Get the default information for printing a comment.
7205 StringRef CommentBegin = MAI.getCommentString();
7206 unsigned CommentColumn = MAI.getCommentColumn();
7207 ListSeparator LS("\n");
7208 while (!Comments.empty()) {
7209 FormattedOS << LS;
7210 // Emit a line of comments.
7211 FormattedOS.PadToColumn(NewCol: CommentColumn);
7212 size_t Position = Comments.find(C: '\n');
7213 FormattedOS << CommentBegin << ' ' << Comments.substr(Start: 0, N: Position);
7214 // Move after the newline character.
7215 Comments = Comments.substr(Start: Position + 1);
7216 }
7217 FormattedOS.flush();
7218
7219 // Tell the comment stream that the vector changed underneath it.
7220 CommentsToEmit.clear();
7221}
7222
7223const MachOObjectFile *
7224objdump::getMachODSymObject(const MachOObjectFile *MachOOF, StringRef Filename,
7225 std::unique_ptr<Binary> &DSYMBinary,
7226 std::unique_ptr<MemoryBuffer> &DSYMBuf) {
7227 const MachOObjectFile *DbgObj = MachOOF;
7228 std::string DSYMPath;
7229
7230 // Auto-detect w/o --dsym.
7231 if (DSYMFile.empty()) {
7232 sys::fs::file_status DSYMStatus;
7233 Twine FilenameDSYM = Filename + ".dSYM";
7234 if (!status(path: FilenameDSYM, result&: DSYMStatus)) {
7235 if (sys::fs::is_directory(status: DSYMStatus)) {
7236 SmallString<1024> Path;
7237 FilenameDSYM.toVector(Out&: Path);
7238 sys::path::append(path&: Path, a: "Contents", b: "Resources", c: "DWARF",
7239 d: sys::path::filename(path: Filename));
7240 DSYMPath = std::string(Path);
7241 } else if (sys::fs::is_regular_file(status: DSYMStatus)) {
7242 DSYMPath = FilenameDSYM.str();
7243 }
7244 }
7245 }
7246
7247 if (DSYMPath.empty() && !DSYMFile.empty()) {
7248 // If DSYMPath is a .dSYM directory, append the Mach-O file.
7249 if (sys::fs::is_directory(Path: DSYMFile) &&
7250 sys::path::extension(path: DSYMFile) == ".dSYM") {
7251 SmallString<128> ShortName(sys::path::filename(path: DSYMFile));
7252 sys::path::replace_extension(path&: ShortName, extension: "");
7253 SmallString<1024> FullPath(DSYMFile);
7254 sys::path::append(path&: FullPath, a: "Contents", b: "Resources", c: "DWARF", d: ShortName);
7255 DSYMPath = FullPath.str();
7256 } else {
7257 DSYMPath = DSYMFile;
7258 }
7259 }
7260
7261 if (!DSYMPath.empty()) {
7262 // Load the file.
7263 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7264 MemoryBuffer::getFileOrSTDIN(Filename: DSYMPath);
7265 if (std::error_code EC = BufOrErr.getError()) {
7266 reportError(E: errorCodeToError(EC), FileName: DSYMPath);
7267 return nullptr;
7268 }
7269
7270 // We need to keep the file alive, because we're replacing DbgObj with it.
7271 DSYMBuf = std::move(BufOrErr.get());
7272
7273 Expected<std::unique_ptr<Binary>> BinaryOrErr =
7274 createBinary(Source: DSYMBuf->getMemBufferRef());
7275 if (!BinaryOrErr) {
7276 reportError(E: BinaryOrErr.takeError(), FileName: DSYMPath);
7277 return nullptr;
7278 }
7279
7280 // We need to keep the Binary alive with the buffer
7281 DSYMBinary = std::move(BinaryOrErr.get());
7282 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: DSYMBinary.get())) {
7283 // this is a Mach-O object file, use it
7284 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(Val: &*O)) {
7285 DbgObj = MachDSYM;
7286 } else {
7287 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
7288 << DSYMPath << " is not a Mach-O file type.\n";
7289 return nullptr;
7290 }
7291 } else if (auto *UB = dyn_cast<MachOUniversalBinary>(Val: DSYMBinary.get())) {
7292 // this is a Universal Binary, find a Mach-O for this architecture
7293 uint32_t CPUType, CPUSubType;
7294 const char *ArchFlag;
7295 if (MachOOF->is64Bit()) {
7296 const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7297 CPUType = H_64.cputype;
7298 CPUSubType = H_64.cpusubtype;
7299 } else {
7300 const MachO::mach_header H = MachOOF->getHeader();
7301 CPUType = H.cputype;
7302 CPUSubType = H.cpusubtype;
7303 }
7304 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, McpuDefault: nullptr,
7305 ArchFlag: &ArchFlag);
7306 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7307 UB->getMachOObjectForArch(ArchName: ArchFlag);
7308 if (!MachDSYM) {
7309 reportError(E: MachDSYM.takeError(), FileName: DSYMPath);
7310 return nullptr;
7311 }
7312
7313 // We need to keep the Binary alive with the buffer
7314 DbgObj = &*MachDSYM.get();
7315 DSYMBinary = std::move(*MachDSYM);
7316 } else {
7317 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
7318 << DSYMPath << " is not a Mach-O or Universal file type.\n";
7319 return nullptr;
7320 }
7321 }
7322 return DbgObj;
7323}
7324
7325static bool shouldInstPrinterUseColor() {
7326 switch (DisassemblyColor) {
7327 case ColorOutput::Enable:
7328 return true;
7329 case ColorOutput::Auto:
7330 return outs().has_colors();
7331 case ColorOutput::Disable:
7332 case ColorOutput::Invalid:
7333 return false;
7334 }
7335 return false;
7336}
7337
7338static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7339 StringRef DisSegName, StringRef DisSectName) {
7340 const char *McpuDefault = nullptr;
7341 const Target *ThumbTarget = nullptr;
7342 Triple ThumbTriple;
7343 const Target *TheTarget =
7344 GetTarget(MachOObj: MachOOF, McpuDefault: &McpuDefault, ThumbTarget: &ThumbTarget, ThumbTriple);
7345 if (!TheTarget) {
7346 // GetTarget prints out stuff.
7347 return;
7348 }
7349 std::string MachOMCPU;
7350 if (MCPU.empty() && McpuDefault)
7351 MachOMCPU = McpuDefault;
7352 else
7353 MachOMCPU = MCPU;
7354
7355#define CHECK_TARGET_INFO_CREATION(NAME) \
7356 do { \
7357 if (!NAME) { \
7358 WithColor::error(errs(), "llvm-objdump") \
7359 << "couldn't initialize disassembler for target " << TripleName \
7360 << '\n'; \
7361 return; \
7362 } \
7363 } while (false)
7364#define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \
7365 do { \
7366 if (!NAME) { \
7367 WithColor::error(errs(), "llvm-objdump") \
7368 << "couldn't initialize disassembler for target " << ThumbTripleName \
7369 << '\n'; \
7370 return; \
7371 } \
7372 } while (false)
7373
7374 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7375 CHECK_TARGET_INFO_CREATION(InstrInfo);
7376 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7377 if (ThumbTarget) {
7378 ThumbInstrInfo.reset(p: ThumbTarget->createMCInstrInfo());
7379 CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7380 }
7381
7382 // Package up features to be passed to target/subtarget
7383 std::string FeaturesStr;
7384 if (!MAttrs.empty()) {
7385 SubtargetFeatures Features;
7386 for (unsigned i = 0; i != MAttrs.size(); ++i)
7387 Features.AddFeature(String: MAttrs[i]);
7388 FeaturesStr = Features.getString();
7389 }
7390
7391 Triple TheTriple(TripleName);
7392
7393 MCTargetOptions MCOptions;
7394 // Set up disassembler.
7395 std::unique_ptr<const MCRegisterInfo> MRI(
7396 TheTarget->createMCRegInfo(TT: TheTriple));
7397 CHECK_TARGET_INFO_CREATION(MRI);
7398 std::unique_ptr<const MCAsmInfo> AsmInfo(
7399 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
7400 CHECK_TARGET_INFO_CREATION(AsmInfo);
7401 std::unique_ptr<const MCSubtargetInfo> STI(
7402 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MachOMCPU, Features: FeaturesStr));
7403 CHECK_TARGET_INFO_CREATION(STI);
7404 MCContext Ctx(TheTriple, *AsmInfo, *MRI, *STI);
7405 std::unique_ptr<MCDisassembler> DisAsm(
7406 TheTarget->createMCDisassembler(STI: *STI, Ctx));
7407 CHECK_TARGET_INFO_CREATION(DisAsm);
7408 std::unique_ptr<MCSymbolizer> Symbolizer;
7409 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7410 std::unique_ptr<MCRelocationInfo> RelInfo(
7411 TheTarget->createMCRelocationInfo(TT: TheTriple, Ctx));
7412 if (RelInfo) {
7413 Symbolizer.reset(p: TheTarget->createMCSymbolizer(
7414 TT: TheTriple, GetOpInfo: SymbolizerGetOpInfo, SymbolLookUp: SymbolizerSymbolLookUp, DisInfo: &SymbolizerInfo,
7415 Ctx: &Ctx, RelInfo: std::move(RelInfo)));
7416 DisAsm->setSymbolizer(std::move(Symbolizer));
7417 }
7418 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7419 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7420 T: TheTriple, SyntaxVariant: AsmPrinterVariant, MAI: *AsmInfo, MII: *InstrInfo, MRI: *MRI));
7421 CHECK_TARGET_INFO_CREATION(IP);
7422 IP->setPrintImmHex(PrintImmHex);
7423 IP->setUseColor(shouldInstPrinterUseColor());
7424
7425 // Comment stream and backing vector.
7426 SmallString<128> CommentsToEmit;
7427 raw_svector_ostream CommentStream(CommentsToEmit);
7428 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7429 // if it is done then arm64 comments for string literals don't get printed
7430 // and some constant get printed instead and not setting it causes intel
7431 // (32-bit and 64-bit) comments printed with different spacing before the
7432 // comment causing different diffs with the 'C' disassembler library API.
7433 // IP->setCommentStream(CommentStream);
7434
7435 for (StringRef Opt : DisassemblerOptions)
7436 if (!IP->applyTargetSpecificCLOption(Opt))
7437 reportError(File: Filename, Message: "unrecognized disassembler option: " + Opt);
7438
7439 // Set up separate thumb disassembler if needed.
7440 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7441 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7442 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7443 std::unique_ptr<MCDisassembler> ThumbDisAsm;
7444 std::unique_ptr<MCInstPrinter> ThumbIP;
7445 std::unique_ptr<MCContext> ThumbCtx;
7446 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7447 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7448 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7449 if (ThumbTarget) {
7450 ThumbMRI.reset(p: ThumbTarget->createMCRegInfo(TT: ThumbTriple));
7451 CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7452 ThumbAsmInfo.reset(
7453 p: ThumbTarget->createMCAsmInfo(MRI: *ThumbMRI, TheTriple: ThumbTriple, Options: MCOptions));
7454 CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7455 ThumbSTI.reset(p: ThumbTarget->createMCSubtargetInfo(TheTriple: ThumbTriple, CPU: MachOMCPU,
7456 Features: FeaturesStr));
7457 CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7458 ThumbCtx.reset(
7459 p: new MCContext(ThumbTriple, *ThumbAsmInfo, *ThumbMRI, *ThumbSTI));
7460 ThumbDisAsm.reset(p: ThumbTarget->createMCDisassembler(STI: *ThumbSTI, Ctx&: *ThumbCtx));
7461 CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7462 MCContext *PtrThumbCtx = ThumbCtx.get();
7463 ThumbRelInfo.reset(
7464 p: ThumbTarget->createMCRelocationInfo(TT: ThumbTriple, Ctx&: *PtrThumbCtx));
7465 if (ThumbRelInfo) {
7466 ThumbSymbolizer.reset(p: ThumbTarget->createMCSymbolizer(
7467 TT: ThumbTriple, GetOpInfo: SymbolizerGetOpInfo, SymbolLookUp: SymbolizerSymbolLookUp,
7468 DisInfo: &ThumbSymbolizerInfo, Ctx: PtrThumbCtx, RelInfo: std::move(ThumbRelInfo)));
7469 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7470 }
7471 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7472 ThumbIP.reset(p: ThumbTarget->createMCInstPrinter(
7473 T: ThumbTriple, SyntaxVariant: ThumbAsmPrinterVariant, MAI: *ThumbAsmInfo, MII: *ThumbInstrInfo,
7474 MRI: *ThumbMRI));
7475 CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7476 ThumbIP->setPrintImmHex(PrintImmHex);
7477 ThumbIP->setUseColor(shouldInstPrinterUseColor());
7478 }
7479
7480#undef CHECK_TARGET_INFO_CREATION
7481#undef CHECK_THUMB_TARGET_INFO_CREATION
7482
7483 MachO::mach_header Header = MachOOF->getHeader();
7484
7485 // FIXME: Using the -cfg command line option, this code used to be able to
7486 // annotate relocations with the referenced symbol's name, and if this was
7487 // inside a __[cf]string section, the data it points to. This is now replaced
7488 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7489 std::vector<SectionRef> Sections;
7490 std::vector<SymbolRef> Symbols;
7491 SmallVector<uint64_t, 8> FoundFns;
7492 uint64_t BaseSegmentAddress = 0;
7493
7494 getSectionsAndSymbols(MachOObj: MachOOF, Sections, Symbols, FoundFns,
7495 BaseSegmentAddress);
7496
7497 // Sort the symbols by address, just in case they didn't come in that way.
7498 llvm::stable_sort(Range&: Symbols, C: SymbolSorter());
7499
7500 // Build a data in code table that is sorted on by the address of each entry.
7501 uint64_t BaseAddress = 0;
7502 if (Header.filetype == MachO::MH_OBJECT)
7503 BaseAddress = Sections[0].getAddress();
7504 else
7505 BaseAddress = BaseSegmentAddress;
7506 DiceTable Dices;
7507 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7508 DI != DE; ++DI) {
7509 uint32_t Offset;
7510 DI->getOffset(Result&: Offset);
7511 Dices.push_back(x: std::make_pair(x: BaseAddress + Offset, y: *DI));
7512 }
7513 array_pod_sort(Start: Dices.begin(), End: Dices.end());
7514
7515 // Try to find debug info and set up the DIContext for it.
7516 std::unique_ptr<DIContext> diContext;
7517 std::unique_ptr<Binary> DSYMBinary;
7518 std::unique_ptr<MemoryBuffer> DSYMBuf;
7519 const ObjectFile *DbgObj = MachOOF;
7520 if (UseDbg || PrintSource || PrintLines) {
7521 // Look for debug info in external dSYM file or embedded in the object.
7522 // getMachODSymObject returns MachOOF by default if no external dSYM found.
7523 const ObjectFile *DSym =
7524 getMachODSymObject(MachOOF, Filename, DSYMBinary, DSYMBuf);
7525 if (!DSym)
7526 return;
7527 DbgObj = DSym;
7528 if (UseDbg || PrintLines) {
7529 // Setup the DIContext
7530 diContext = DWARFContext::create(Obj: *DbgObj);
7531 }
7532 }
7533
7534 std::optional<SourcePrinter> SP;
7535 std::optional<LiveElementPrinter> LEP;
7536 if (PrintSource || PrintLines) {
7537 SP.emplace(args&: DbgObj, args: TheTarget->getName());
7538 LEP.emplace(args: *MRI, args: *STI);
7539 }
7540
7541 if (FilterSections.empty())
7542 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7543
7544 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7545 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7546 if (!SecNameOrErr) {
7547 consumeError(Err: SecNameOrErr.takeError());
7548 continue;
7549 }
7550 if (*SecNameOrErr != DisSectName)
7551 continue;
7552
7553 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7554
7555 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(Sec: DR);
7556 if (SegmentName != DisSegName)
7557 continue;
7558
7559 StringRef BytesStr =
7560 unwrapOrError(EO: Sections[SectIdx].getContents(), Args&: Filename);
7561 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(Input: BytesStr);
7562 uint64_t SectAddress = Sections[SectIdx].getAddress();
7563
7564 bool symbolTableWorked = false;
7565
7566 // Create a map of symbol addresses to symbol names for use by
7567 // the SymbolizerSymbolLookUp() routine.
7568 SymbolAddressMap AddrMap;
7569 bool DisSymNameFound = false;
7570 for (const SymbolRef &Symbol : MachOOF->symbols()) {
7571 SymbolRef::Type ST =
7572 unwrapOrError(EO: Symbol.getType(), Args: MachOOF->getFileName());
7573 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7574 ST == SymbolRef::ST_Other) {
7575 uint64_t Address = cantFail(ValOrErr: Symbol.getValue());
7576 StringRef SymName =
7577 unwrapOrError(EO: Symbol.getName(), Args: MachOOF->getFileName());
7578 AddrMap[Address] = SymName;
7579 if (!DisSymName.empty() && DisSymName == SymName)
7580 DisSymNameFound = true;
7581 }
7582 }
7583 if (!DisSymName.empty() && !DisSymNameFound) {
7584 outs() << "Can't find " << (IsOtool ? "-p symbol" : "--dis-symname")
7585 << ": " << DisSymName << "\n";
7586 return;
7587 }
7588 // Set up the block of info used by the Symbolizer call backs.
7589 SymbolizerInfo.verbose = SymbolicOperands;
7590 SymbolizerInfo.O = MachOOF;
7591 SymbolizerInfo.S = Sections[SectIdx];
7592 SymbolizerInfo.AddrMap = &AddrMap;
7593 SymbolizerInfo.Sections = &Sections;
7594 // Same for the ThumbSymbolizer
7595 ThumbSymbolizerInfo.verbose = SymbolicOperands;
7596 ThumbSymbolizerInfo.O = MachOOF;
7597 ThumbSymbolizerInfo.S = Sections[SectIdx];
7598 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7599 ThumbSymbolizerInfo.Sections = &Sections;
7600
7601 unsigned int Arch = MachOOF->getArch();
7602
7603 // Skip all symbols if this is a stubs file.
7604 if (Bytes.empty())
7605 return;
7606
7607 // If the section has symbols but no symbol at the start of the section
7608 // these are used to make sure the bytes before the first symbol are
7609 // disassembled.
7610 bool FirstSymbol = true;
7611 bool FirstSymbolAtSectionStart = true;
7612
7613 // Disassemble symbol by symbol.
7614 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7615 StringRef SymName =
7616 unwrapOrError(EO: Symbols[SymIdx].getName(), Args: MachOOF->getFileName());
7617 SymbolRef::Type ST =
7618 unwrapOrError(EO: Symbols[SymIdx].getType(), Args: MachOOF->getFileName());
7619 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7620 continue;
7621
7622 // Make sure the symbol is defined in this section.
7623 bool containsSym = Sections[SectIdx].containsSymbol(S: Symbols[SymIdx]);
7624 if (!containsSym) {
7625 if (!DisSymName.empty() && DisSymName == SymName) {
7626 outs() << (IsOtool ? "-p symbol" : "--dis-symname") << ": "
7627 << DisSymName << " not in the section\n";
7628 return;
7629 }
7630 continue;
7631 }
7632 // The __mh_execute_header is special and we need to deal with that fact
7633 // this symbol is before the start of the (__TEXT,__text) section and at the
7634 // address of the start of the __TEXT segment. This is because this symbol
7635 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7636 // start of the section in a standard MH_EXECUTE filetype.
7637 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7638 outs() << (IsOtool ? "-p symbol" : "--dis-symname")
7639 << ": __mh_execute_header not in any section\n";
7640 return;
7641 }
7642 // When this code is trying to disassemble a symbol at a time and in the
7643 // case there is only the __mh_execute_header symbol left as in a stripped
7644 // executable, we need to deal with this by ignoring this symbol so the
7645 // whole section is disassembled and this symbol is then not displayed.
7646 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7647 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7648 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7649 continue;
7650
7651 // If we are only disassembling one symbol see if this is that symbol.
7652 if (!DisSymName.empty() && DisSymName != SymName)
7653 continue;
7654
7655 // Start at the address of the symbol relative to the section's address.
7656 uint64_t SectSize = Sections[SectIdx].getSize();
7657 uint64_t Start = cantFail(ValOrErr: Symbols[SymIdx].getValue());
7658 uint64_t SectionAddress = Sections[SectIdx].getAddress();
7659 Start -= SectionAddress;
7660
7661 if (Start > SectSize) {
7662 outs() << "section data ends, " << SymName
7663 << " lies outside valid range\n";
7664 return;
7665 }
7666
7667 // Stop disassembling either at the beginning of the next symbol or at
7668 // the end of the section.
7669 bool containsNextSym = false;
7670 uint64_t NextSym = 0;
7671 uint64_t NextSymIdx = SymIdx + 1;
7672 while (Symbols.size() > NextSymIdx) {
7673 SymbolRef::Type NextSymType = unwrapOrError(
7674 EO: Symbols[NextSymIdx].getType(), Args: MachOOF->getFileName());
7675 if (NextSymType == SymbolRef::ST_Function) {
7676 containsNextSym =
7677 Sections[SectIdx].containsSymbol(S: Symbols[NextSymIdx]);
7678 NextSym = cantFail(ValOrErr: Symbols[NextSymIdx].getValue());
7679 NextSym -= SectionAddress;
7680 break;
7681 }
7682 ++NextSymIdx;
7683 }
7684
7685 uint64_t End = containsNextSym ? std::min(a: NextSym, b: SectSize) : SectSize;
7686 uint64_t Size;
7687
7688 symbolTableWorked = true;
7689
7690 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7691 uint32_t SymbolFlags = cantFail(ValOrErr: MachOOF->getSymbolFlags(Symb));
7692 bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7693
7694 // We only need the dedicated Thumb target if there's a real choice
7695 // (i.e. we're not targeting M-class) and the function is Thumb.
7696 bool UseThumbTarget = IsThumb && ThumbTarget;
7697
7698 // If we are not specifying a symbol to start disassembly with and this
7699 // is the first symbol in the section but not at the start of the section
7700 // then move the disassembly index to the start of the section and
7701 // don't print the symbol name just yet. This is so the bytes before the
7702 // first symbol are disassembled.
7703 uint64_t SymbolStart = Start;
7704 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7705 FirstSymbolAtSectionStart = false;
7706 Start = 0;
7707 }
7708 else
7709 outs() << SymName << ":\n";
7710
7711 DILineInfo lastLine;
7712 for (uint64_t Index = Start; Index < End; Index += Size) {
7713 MCInst Inst;
7714
7715 // If this is the first symbol in the section and it was not at the
7716 // start of the section, see if we are at its Index now and if so print
7717 // the symbol name.
7718 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7719 outs() << SymName << ":\n";
7720
7721 uint64_t PC = SectAddress + Index;
7722
7723 if (PrintSource || PrintLines) {
7724 formatted_raw_ostream FOS(outs());
7725 SP->printSourceLine(OS&: FOS, Address: {.Address: PC, .SectionIndex: SectIdx}, ObjectFilename: Filename, LEP&: *LEP);
7726 }
7727
7728 if (LeadingAddr) {
7729 if (FullLeadingAddr) {
7730 if (MachOOF->is64Bit())
7731 outs() << format(Fmt: "%016" PRIx64, Vals: PC);
7732 else
7733 outs() << format(Fmt: "%08" PRIx64, Vals: PC);
7734 } else {
7735 outs() << format(Fmt: "%8" PRIx64 ":", Vals: PC);
7736 }
7737 }
7738 if (ShowRawInsn || Arch == Triple::arm)
7739 outs() << "\t";
7740
7741 if (DumpAndSkipDataInCode(PC, bytes: Bytes.data() + Index, Dices, InstSize&: Size))
7742 continue;
7743
7744 SmallVector<char, 64> AnnotationsBytes;
7745 raw_svector_ostream Annotations(AnnotationsBytes);
7746
7747 bool gotInst;
7748 if (UseThumbTarget)
7749 gotInst = ThumbDisAsm->getInstruction(Instr&: Inst, Size, Bytes: Bytes.slice(N: Index),
7750 Address: PC, CStream&: Annotations);
7751 else
7752 gotInst = DisAsm->getInstruction(Instr&: Inst, Size, Bytes: Bytes.slice(N: Index), Address: PC,
7753 CStream&: Annotations);
7754 if (gotInst) {
7755 if (ShowRawInsn || Arch == Triple::arm) {
7756 dumpBytes(Bytes: ArrayRef(Bytes.data() + Index, Size), OS&: outs());
7757 }
7758 formatted_raw_ostream FormattedOS(outs());
7759 StringRef AnnotationsStr = Annotations.str();
7760 if (UseThumbTarget)
7761 ThumbIP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *ThumbSTI,
7762 OS&: FormattedOS);
7763 else
7764 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *STI, OS&: FormattedOS);
7765 emitComments(CommentStream, CommentsToEmit, FormattedOS, MAI: *AsmInfo);
7766
7767 // Print debug info.
7768 if (diContext) {
7769 DILineInfo dli = diContext->getLineInfoForAddress(Address: {.Address: PC, .SectionIndex: SectIdx})
7770 .value_or(u: DILineInfo());
7771 // Print valid line info if it changed.
7772 if (dli != lastLine && dli.Line != 0)
7773 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7774 << dli.Column;
7775 lastLine = dli;
7776 }
7777 outs() << "\n";
7778 } else {
7779 if (MachOOF->getArchTriple().isX86()) {
7780 outs() << format(Fmt: "\t.byte 0x%02x #bad opcode\n",
7781 Vals: *(Bytes.data() + Index) & 0xff);
7782 Size = 1; // skip exactly one illegible byte and move on.
7783 } else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32 ||
7784 (Arch == Triple::arm && !IsThumb)) {
7785 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7786 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7787 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7788 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7789 outs() << format(Fmt: "\t.long\t0x%08x\n", Vals: opcode);
7790 Size = 4;
7791 } else if (Arch == Triple::arm) {
7792 assert(IsThumb && "ARM mode should have been dealt with above");
7793 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7794 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7795 outs() << format(Fmt: "\t.short\t0x%04x\n", Vals: opcode);
7796 Size = 2;
7797 } else {
7798 WithColor::warning(OS&: errs(), Prefix: "llvm-objdump")
7799 << "invalid instruction encoding\n";
7800 if (Size == 0)
7801 Size = 1; // skip illegible bytes
7802 }
7803 }
7804 }
7805 // Now that we are done disassembled the first symbol set the bool that
7806 // were doing this to false.
7807 FirstSymbol = false;
7808 }
7809 if (!symbolTableWorked) {
7810 // Reading the symbol table didn't work, disassemble the whole section.
7811 uint64_t SectAddress = Sections[SectIdx].getAddress();
7812 uint64_t SectSize = Sections[SectIdx].getSize();
7813 uint64_t InstSize;
7814 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7815 MCInst Inst;
7816
7817 uint64_t PC = SectAddress + Index;
7818
7819 if (PrintSource || PrintLines) {
7820 formatted_raw_ostream FOS(outs());
7821 SP->printSourceLine(OS&: FOS, Address: {.Address: PC, .SectionIndex: SectIdx}, ObjectFilename: Filename, LEP&: *LEP);
7822 }
7823
7824 if (DumpAndSkipDataInCode(PC, bytes: Bytes.data() + Index, Dices, InstSize))
7825 continue;
7826
7827 SmallVector<char, 64> AnnotationsBytes;
7828 raw_svector_ostream Annotations(AnnotationsBytes);
7829 if (DisAsm->getInstruction(Instr&: Inst, Size&: InstSize, Bytes: Bytes.slice(N: Index), Address: PC,
7830 CStream&: Annotations)) {
7831 if (LeadingAddr) {
7832 if (FullLeadingAddr) {
7833 if (MachOOF->is64Bit())
7834 outs() << format(Fmt: "%016" PRIx64, Vals: PC);
7835 else
7836 outs() << format(Fmt: "%08" PRIx64, Vals: PC);
7837 } else {
7838 outs() << format(Fmt: "%8" PRIx64 ":", Vals: PC);
7839 }
7840 }
7841 if (ShowRawInsn || Arch == Triple::arm) {
7842 outs() << "\t";
7843 dumpBytes(Bytes: ArrayRef(Bytes.data() + Index, InstSize), OS&: outs());
7844 }
7845 StringRef AnnotationsStr = Annotations.str();
7846 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *STI, OS&: outs());
7847 outs() << "\n";
7848 } else {
7849 if (MachOOF->getArchTriple().isX86()) {
7850 outs() << format(Fmt: "\t.byte 0x%02x #bad opcode\n",
7851 Vals: *(Bytes.data() + Index) & 0xff);
7852 InstSize = 1; // skip exactly one illegible byte and move on.
7853 } else {
7854 WithColor::warning(OS&: errs(), Prefix: "llvm-objdump")
7855 << "invalid instruction encoding\n";
7856 if (InstSize == 0)
7857 InstSize = 1; // skip illegible bytes
7858 }
7859 }
7860 }
7861 }
7862 // The TripleName's need to be reset if we are called again for a different
7863 // architecture.
7864 TripleName = "";
7865 ThumbTripleName = "";
7866
7867 if (SymbolizerInfo.demangled_name != nullptr)
7868 free(ptr: SymbolizerInfo.demangled_name);
7869 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7870 free(ptr: ThumbSymbolizerInfo.demangled_name);
7871 }
7872}
7873
7874//===----------------------------------------------------------------------===//
7875// __compact_unwind section dumping
7876//===----------------------------------------------------------------------===//
7877
7878namespace {
7879
7880template <typename T>
7881static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7882 if (Offset + sizeof(T) > Contents.size()) {
7883 outs() << "warning: attempt to read past end of buffer\n";
7884 return T();
7885 }
7886
7887 uint64_t Val = support::endian::read<T, llvm::endianness::little>(
7888 Contents.data() + Offset);
7889 return Val;
7890}
7891
7892template <typename T>
7893static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7894 T Val = read<T>(Contents, Offset);
7895 Offset += sizeof(T);
7896 return Val;
7897}
7898
7899struct CompactUnwindEntry {
7900 uint32_t OffsetInSection;
7901
7902 uint64_t FunctionAddr;
7903 uint32_t Length;
7904 uint32_t CompactEncoding;
7905 uint64_t PersonalityAddr;
7906 uint64_t LSDAAddr;
7907
7908 RelocationRef FunctionReloc;
7909 RelocationRef PersonalityReloc;
7910 RelocationRef LSDAReloc;
7911
7912 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7913 : OffsetInSection(Offset) {
7914 if (Is64)
7915 read<uint64_t>(Contents, Offset);
7916 else
7917 read<uint32_t>(Contents, Offset);
7918 }
7919
7920private:
7921 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7922 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7923 Length = readNext<uint32_t>(Contents, Offset);
7924 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7925 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7926 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7927 }
7928};
7929}
7930
7931/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7932/// and data being relocated, determine the best base Name and Addend to use for
7933/// display purposes.
7934///
7935/// 1. An Extern relocation will directly reference a symbol (and the data is
7936/// then already an addend), so use that.
7937/// 2. Otherwise the data is an offset in the object file's layout; try to find
7938// a symbol before it in the same section, and use the offset from there.
7939/// 3. Finally, if all that fails, fall back to an offset from the start of the
7940/// referenced section.
7941static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7942 std::map<uint64_t, SymbolRef> &Symbols,
7943 const RelocationRef &Reloc, uint64_t Addr,
7944 StringRef &Name, uint64_t &Addend) {
7945 if (Reloc.getSymbol() != Obj->symbol_end()) {
7946 Name = unwrapOrError(EO: Reloc.getSymbol()->getName(), Args: Obj->getFileName());
7947 Addend = Addr;
7948 return;
7949 }
7950
7951 auto RE = Obj->getRelocation(Rel: Reloc.getRawDataRefImpl());
7952 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7953
7954 uint64_t SectionAddr = RelocSection.getAddress();
7955
7956 auto Sym = Symbols.upper_bound(x: Addr);
7957 if (Sym == Symbols.begin()) {
7958 // The first symbol in the object is after this reference, the best we can
7959 // do is section-relative notation.
7960 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7961 Name = *NameOrErr;
7962 else
7963 consumeError(Err: NameOrErr.takeError());
7964
7965 Addend = Addr - SectionAddr;
7966 return;
7967 }
7968
7969 // Go back one so that SymbolAddress <= Addr.
7970 --Sym;
7971
7972 section_iterator SymSection =
7973 unwrapOrError(EO: Sym->second.getSection(), Args: Obj->getFileName());
7974 if (RelocSection == *SymSection) {
7975 // There's a valid symbol in the same section before this reference.
7976 Name = unwrapOrError(EO: Sym->second.getName(), Args: Obj->getFileName());
7977 Addend = Addr - Sym->first;
7978 return;
7979 }
7980
7981 // There is a symbol before this reference, but it's in a different
7982 // section. Probably not helpful to mention it, so use the section name.
7983 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7984 Name = *NameOrErr;
7985 else
7986 consumeError(Err: NameOrErr.takeError());
7987
7988 Addend = Addr - SectionAddr;
7989}
7990
7991static void printUnwindRelocDest(const MachOObjectFile *Obj,
7992 std::map<uint64_t, SymbolRef> &Symbols,
7993 const RelocationRef &Reloc, uint64_t Addr) {
7994 StringRef Name;
7995 uint64_t Addend;
7996
7997 if (!Reloc.getObject())
7998 return;
7999
8000 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
8001
8002 outs() << Name;
8003 if (Addend)
8004 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: Addend);
8005}
8006
8007static void
8008printMachOCompactUnwindSection(const MachOObjectFile *Obj,
8009 std::map<uint64_t, SymbolRef> &Symbols,
8010 const SectionRef &CompactUnwind) {
8011
8012 if (!Obj->isLittleEndian()) {
8013 outs() << "Skipping big-endian __compact_unwind section\n";
8014 return;
8015 }
8016
8017 bool Is64 = Obj->is64Bit();
8018 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
8019 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
8020
8021 StringRef Contents =
8022 unwrapOrError(EO: CompactUnwind.getContents(), Args: Obj->getFileName());
8023 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
8024
8025 // First populate the initial raw offsets, encodings and so on from the entry.
8026 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
8027 CompactUnwindEntry Entry(Contents, Offset, Is64);
8028 CompactUnwinds.push_back(Elt: Entry);
8029 }
8030
8031 // Next we need to look at the relocations to find out what objects are
8032 // actually being referred to.
8033 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
8034 uint64_t RelocAddress = Reloc.getOffset();
8035
8036 uint32_t EntryIdx = RelocAddress / EntrySize;
8037 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
8038 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
8039
8040 if (OffsetInEntry == 0)
8041 Entry.FunctionReloc = Reloc;
8042 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
8043 Entry.PersonalityReloc = Reloc;
8044 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
8045 Entry.LSDAReloc = Reloc;
8046 else {
8047 outs() << "Invalid relocation in __compact_unwind section\n";
8048 return;
8049 }
8050 }
8051
8052 // Finally, we're ready to print the data we've gathered.
8053 outs() << "Contents of __compact_unwind section:\n";
8054 for (auto &Entry : CompactUnwinds) {
8055 outs() << " Entry at offset "
8056 << format(Fmt: "0x%" PRIx32, Vals: Entry.OffsetInSection) << ":\n";
8057
8058 // 1. Start of the region this entry applies to.
8059 outs() << " start: " << format(Fmt: "0x%" PRIx64,
8060 Vals: Entry.FunctionAddr) << ' ';
8061 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.FunctionReloc, Addr: Entry.FunctionAddr);
8062 outs() << '\n';
8063
8064 // 2. Length of the region this entry applies to.
8065 outs() << " length: " << format(Fmt: "0x%" PRIx32, Vals: Entry.Length)
8066 << '\n';
8067 // 3. The 32-bit compact encoding.
8068 outs() << " compact encoding: "
8069 << format(Fmt: "0x%08" PRIx32, Vals: Entry.CompactEncoding) << '\n';
8070
8071 // 4. The personality function, if present.
8072 if (Entry.PersonalityReloc.getObject()) {
8073 outs() << " personality function: "
8074 << format(Fmt: "0x%" PRIx64, Vals: Entry.PersonalityAddr) << ' ';
8075 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.PersonalityReloc,
8076 Addr: Entry.PersonalityAddr);
8077 outs() << '\n';
8078 }
8079
8080 // 5. This entry's language-specific data area.
8081 if (Entry.LSDAReloc.getObject()) {
8082 outs() << " LSDA: " << format(Fmt: "0x%" PRIx64,
8083 Vals: Entry.LSDAAddr) << ' ';
8084 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.LSDAReloc, Addr: Entry.LSDAAddr);
8085 outs() << '\n';
8086 }
8087 }
8088}
8089
8090//===----------------------------------------------------------------------===//
8091// __unwind_info section dumping
8092//===----------------------------------------------------------------------===//
8093
8094static void printRegularSecondLevelUnwindPage(StringRef PageData) {
8095 ptrdiff_t Pos = 0;
8096 uint32_t Kind = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8097 (void)Kind;
8098 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
8099
8100 uint16_t EntriesStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8101 uint16_t NumEntries = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8102
8103 Pos = EntriesStart;
8104 for (unsigned i = 0; i < NumEntries; ++i) {
8105 uint32_t FunctionOffset = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8106 uint32_t Encoding = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8107
8108 outs() << " [" << i << "]: "
8109 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8110 << ", "
8111 << "encoding=" << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8112 }
8113}
8114
8115static void printCompressedSecondLevelUnwindPage(
8116 StringRef PageData, uint32_t FunctionBase,
8117 const SmallVectorImpl<uint32_t> &CommonEncodings) {
8118 ptrdiff_t Pos = 0;
8119 uint32_t Kind = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8120 (void)Kind;
8121 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8122
8123 uint32_t NumCommonEncodings = CommonEncodings.size();
8124 uint16_t EntriesStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8125 uint16_t NumEntries = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8126
8127 uint16_t PageEncodingsStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8128 uint16_t NumPageEncodings = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8129 SmallVector<uint32_t, 64> PageEncodings;
8130 if (NumPageEncodings) {
8131 outs() << " Page encodings: (count = " << NumPageEncodings << ")\n";
8132 Pos = PageEncodingsStart;
8133 for (unsigned i = 0; i < NumPageEncodings; ++i) {
8134 uint32_t Encoding = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8135 PageEncodings.push_back(Elt: Encoding);
8136 outs() << " encoding[" << (i + NumCommonEncodings)
8137 << "]: " << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8138 }
8139 }
8140
8141 Pos = EntriesStart;
8142 for (unsigned i = 0; i < NumEntries; ++i) {
8143 uint32_t Entry = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8144 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8145 uint32_t EncodingIdx = Entry >> 24;
8146
8147 uint32_t Encoding;
8148 if (EncodingIdx < NumCommonEncodings)
8149 Encoding = CommonEncodings[EncodingIdx];
8150 else
8151 Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
8152
8153 outs() << " [" << i << "]: "
8154 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8155 << ", "
8156 << "encoding[" << EncodingIdx
8157 << "]=" << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8158 }
8159}
8160
8161static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8162 std::map<uint64_t, SymbolRef> &Symbols,
8163 const SectionRef &UnwindInfo) {
8164
8165 if (!Obj->isLittleEndian()) {
8166 outs() << "Skipping big-endian __unwind_info section\n";
8167 return;
8168 }
8169
8170 outs() << "Contents of __unwind_info section:\n";
8171
8172 StringRef Contents =
8173 unwrapOrError(EO: UnwindInfo.getContents(), Args: Obj->getFileName());
8174 ptrdiff_t Pos = 0;
8175
8176 //===----------------------------------
8177 // Section header
8178 //===----------------------------------
8179
8180 uint32_t Version = readNext<uint32_t>(Contents, Offset&: Pos);
8181 outs() << " Version: "
8182 << format(Fmt: "0x%" PRIx32, Vals: Version) << '\n';
8183 if (Version != 1) {
8184 outs() << " Skipping section with unknown version\n";
8185 return;
8186 }
8187
8188 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Offset&: Pos);
8189 outs() << " Common encodings array section offset: "
8190 << format(Fmt: "0x%" PRIx32, Vals: CommonEncodingsStart) << '\n';
8191 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Offset&: Pos);
8192 outs() << " Number of common encodings in array: "
8193 << format(Fmt: "0x%" PRIx32, Vals: NumCommonEncodings) << '\n';
8194
8195 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Offset&: Pos);
8196 outs() << " Personality function array section offset: "
8197 << format(Fmt: "0x%" PRIx32, Vals: PersonalitiesStart) << '\n';
8198 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Offset&: Pos);
8199 outs() << " Number of personality functions in array: "
8200 << format(Fmt: "0x%" PRIx32, Vals: NumPersonalities) << '\n';
8201
8202 uint32_t IndicesStart = readNext<uint32_t>(Contents, Offset&: Pos);
8203 outs() << " Index array section offset: "
8204 << format(Fmt: "0x%" PRIx32, Vals: IndicesStart) << '\n';
8205 uint32_t NumIndices = readNext<uint32_t>(Contents, Offset&: Pos);
8206 outs() << " Number of indices in array: "
8207 << format(Fmt: "0x%" PRIx32, Vals: NumIndices) << '\n';
8208
8209 //===----------------------------------
8210 // A shared list of common encodings
8211 //===----------------------------------
8212
8213 // These occupy indices in the range [0, N] whenever an encoding is referenced
8214 // from a compressed 2nd level index table. In practice the linker only
8215 // creates ~128 of these, so that indices are available to embed encodings in
8216 // the 2nd level index.
8217
8218 SmallVector<uint32_t, 64> CommonEncodings;
8219 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
8220 Pos = CommonEncodingsStart;
8221 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8222 uint32_t Encoding = readNext<uint32_t>(Contents, Offset&: Pos);
8223 CommonEncodings.push_back(Elt: Encoding);
8224
8225 outs() << " encoding[" << i << "]: " << format(Fmt: "0x%08" PRIx32, Vals: Encoding)
8226 << '\n';
8227 }
8228
8229 //===----------------------------------
8230 // Personality functions used in this executable
8231 //===----------------------------------
8232
8233 // There should be only a handful of these (one per source language,
8234 // roughly). Particularly since they only get 2 bits in the compact encoding.
8235
8236 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
8237 Pos = PersonalitiesStart;
8238 for (unsigned i = 0; i < NumPersonalities; ++i) {
8239 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Offset&: Pos);
8240 outs() << " personality[" << i + 1
8241 << "]: " << format(Fmt: "0x%08" PRIx32, Vals: PersonalityFn) << '\n';
8242 }
8243
8244 //===----------------------------------
8245 // The level 1 index entries
8246 //===----------------------------------
8247
8248 // These specify an approximate place to start searching for the more detailed
8249 // information, sorted by PC.
8250
8251 struct IndexEntry {
8252 uint32_t FunctionOffset;
8253 uint32_t SecondLevelPageStart;
8254 uint32_t LSDAStart;
8255 };
8256
8257 SmallVector<IndexEntry, 4> IndexEntries;
8258
8259 outs() << " Top level indices: (count = " << NumIndices << ")\n";
8260 Pos = IndicesStart;
8261 for (unsigned i = 0; i < NumIndices; ++i) {
8262 IndexEntry Entry;
8263
8264 Entry.FunctionOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8265 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Offset&: Pos);
8266 Entry.LSDAStart = readNext<uint32_t>(Contents, Offset&: Pos);
8267 IndexEntries.push_back(Elt: Entry);
8268
8269 outs() << " [" << i << "]: "
8270 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: Entry.FunctionOffset)
8271 << ", "
8272 << "2nd level page offset="
8273 << format(Fmt: "0x%08" PRIx32, Vals: Entry.SecondLevelPageStart) << ", "
8274 << "LSDA offset=" << format(Fmt: "0x%08" PRIx32, Vals: Entry.LSDAStart) << '\n';
8275 }
8276
8277 //===----------------------------------
8278 // Next come the LSDA tables
8279 //===----------------------------------
8280
8281 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8282 // the first top-level index's LSDAOffset to the last (sentinel).
8283
8284 outs() << " LSDA descriptors:\n";
8285 Pos = IndexEntries[0].LSDAStart;
8286 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8287 int NumLSDAs =
8288 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8289
8290 for (int i = 0; i < NumLSDAs; ++i) {
8291 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8292 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8293 outs() << " [" << i << "]: "
8294 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8295 << ", "
8296 << "LSDA offset=" << format(Fmt: "0x%08" PRIx32, Vals: LSDAOffset) << '\n';
8297 }
8298
8299 //===----------------------------------
8300 // Finally, the 2nd level indices
8301 //===----------------------------------
8302
8303 // Generally these are 4K in size, and have 2 possible forms:
8304 // + Regular stores up to 511 entries with disparate encodings
8305 // + Compressed stores up to 1021 entries if few enough compact encoding
8306 // values are used.
8307 outs() << " Second level indices:\n";
8308 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8309 // The final sentinel top-level index has no associated 2nd level page
8310 if (IndexEntries[i].SecondLevelPageStart == 0)
8311 break;
8312
8313 outs() << " Second level index[" << i << "]: "
8314 << "offset in section="
8315 << format(Fmt: "0x%08" PRIx32, Vals: IndexEntries[i].SecondLevelPageStart)
8316 << ", "
8317 << "base function offset="
8318 << format(Fmt: "0x%08" PRIx32, Vals: IndexEntries[i].FunctionOffset) << '\n';
8319
8320 Pos = IndexEntries[i].SecondLevelPageStart;
8321 if (Pos + sizeof(uint32_t) > Contents.size()) {
8322 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8323 continue;
8324 }
8325
8326 uint32_t Kind =
8327 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8328 if (Kind == 2)
8329 printRegularSecondLevelUnwindPage(PageData: Contents.substr(Start: Pos, N: 4096));
8330 else if (Kind == 3)
8331 printCompressedSecondLevelUnwindPage(PageData: Contents.substr(Start: Pos, N: 4096),
8332 FunctionBase: IndexEntries[i].FunctionOffset,
8333 CommonEncodings);
8334 else
8335 outs() << " Skipping 2nd level page with unknown kind " << Kind
8336 << '\n';
8337 }
8338}
8339
8340void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8341 std::map<uint64_t, SymbolRef> Symbols;
8342 for (const SymbolRef &SymRef : Obj->symbols()) {
8343 // Discard any undefined or absolute symbols. They're not going to take part
8344 // in the convenience lookup for unwind info and just take up resources.
8345 auto SectOrErr = SymRef.getSection();
8346 if (!SectOrErr) {
8347 // TODO: Actually report errors helpfully.
8348 consumeError(Err: SectOrErr.takeError());
8349 continue;
8350 }
8351 section_iterator Section = *SectOrErr;
8352 if (Section == Obj->section_end())
8353 continue;
8354
8355 uint64_t Addr = cantFail(ValOrErr: SymRef.getValue());
8356 Symbols.insert(x: std::make_pair(x&: Addr, y: SymRef));
8357 }
8358
8359 for (const SectionRef &Section : Obj->sections()) {
8360 StringRef SectName;
8361 if (Expected<StringRef> NameOrErr = Section.getName())
8362 SectName = *NameOrErr;
8363 else
8364 consumeError(Err: NameOrErr.takeError());
8365
8366 if (SectName == "__compact_unwind")
8367 printMachOCompactUnwindSection(Obj, Symbols, CompactUnwind: Section);
8368 else if (SectName == "__unwind_info")
8369 printMachOUnwindInfoSection(Obj, Symbols, UnwindInfo: Section);
8370 }
8371}
8372
8373static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8374 uint32_t cpusubtype, uint32_t filetype,
8375 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8376 bool verbose) {
8377 outs() << "Mach header\n";
8378 outs() << " magic cputype cpusubtype caps filetype ncmds "
8379 "sizeofcmds flags\n";
8380 if (verbose) {
8381 if (magic == MachO::MH_MAGIC)
8382 outs() << " MH_MAGIC";
8383 else if (magic == MachO::MH_MAGIC_64)
8384 outs() << "MH_MAGIC_64";
8385 else
8386 outs() << format(Fmt: " 0x%08" PRIx32, Vals: magic);
8387 switch (cputype) {
8388 case MachO::CPU_TYPE_I386:
8389 outs() << " I386";
8390 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8391 case MachO::CPU_SUBTYPE_I386_ALL:
8392 outs() << " ALL";
8393 break;
8394 default:
8395 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8396 break;
8397 }
8398 break;
8399 case MachO::CPU_TYPE_X86_64:
8400 outs() << " X86_64";
8401 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8402 case MachO::CPU_SUBTYPE_X86_64_ALL:
8403 outs() << " ALL";
8404 break;
8405 case MachO::CPU_SUBTYPE_X86_64_H:
8406 outs() << " Haswell";
8407 break;
8408 default:
8409 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8410 break;
8411 }
8412 break;
8413 case MachO::CPU_TYPE_ARM:
8414 outs() << " ARM";
8415 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8416 case MachO::CPU_SUBTYPE_ARM_ALL:
8417 outs() << " ALL";
8418 break;
8419 case MachO::CPU_SUBTYPE_ARM_V4T:
8420 outs() << " V4T";
8421 break;
8422 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8423 outs() << " V5TEJ";
8424 break;
8425 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8426 outs() << " XSCALE";
8427 break;
8428 case MachO::CPU_SUBTYPE_ARM_V6:
8429 outs() << " V6";
8430 break;
8431 case MachO::CPU_SUBTYPE_ARM_V6M:
8432 outs() << " V6M";
8433 break;
8434 case MachO::CPU_SUBTYPE_ARM_V7:
8435 outs() << " V7";
8436 break;
8437 case MachO::CPU_SUBTYPE_ARM_V7EM:
8438 outs() << " V7EM";
8439 break;
8440 case MachO::CPU_SUBTYPE_ARM_V7K:
8441 outs() << " V7K";
8442 break;
8443 case MachO::CPU_SUBTYPE_ARM_V7M:
8444 outs() << " V7M";
8445 break;
8446 case MachO::CPU_SUBTYPE_ARM_V7S:
8447 outs() << " V7S";
8448 break;
8449 case MachO::CPU_SUBTYPE_ARM_V8M_MAIN:
8450 outs() << " V8M_MAIN";
8451 break;
8452 case MachO::CPU_SUBTYPE_ARM_V8M_BASE:
8453 outs() << " V8M_BASE";
8454 break;
8455 case MachO::CPU_SUBTYPE_ARM_V8_1M_MAIN:
8456 outs() << " V8_1M_MAIN";
8457 break;
8458 default:
8459 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8460 break;
8461 }
8462 break;
8463 case MachO::CPU_TYPE_ARM64:
8464 outs() << " ARM64";
8465 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8466 case MachO::CPU_SUBTYPE_ARM64_ALL:
8467 outs() << " ALL";
8468 break;
8469 case MachO::CPU_SUBTYPE_ARM64_V8:
8470 outs() << " V8";
8471 break;
8472 case MachO::CPU_SUBTYPE_ARM64E:
8473 outs() << " E";
8474 break;
8475 default:
8476 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8477 break;
8478 }
8479 break;
8480 case MachO::CPU_TYPE_ARM64_32:
8481 outs() << " ARM64_32";
8482 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8483 case MachO::CPU_SUBTYPE_ARM64_32_V8:
8484 outs() << " V8";
8485 break;
8486 default:
8487 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8488 break;
8489 }
8490 break;
8491 case MachO::CPU_TYPE_POWERPC:
8492 outs() << " PPC";
8493 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8494 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8495 outs() << " ALL";
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_POWERPC64:
8503 outs() << " PPC64";
8504 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8505 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8506 outs() << " ALL";
8507 break;
8508 default:
8509 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8510 break;
8511 }
8512 break;
8513 default:
8514 outs() << format(Fmt: " %7d", Vals: cputype);
8515 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8516 break;
8517 }
8518
8519 if (cputype == MachO::CPU_TYPE_ARM64 &&
8520 MachO::CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(ST: cpusubtype)) {
8521 const char *Format =
8522 MachO::CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(ST: cpusubtype)
8523 ? " PAK%02d"
8524 : " PAC%02d";
8525 outs() << format(Fmt: Format,
8526 Vals: MachO::CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(ST: cpusubtype));
8527 } else if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) ==
8528 MachO::CPU_SUBTYPE_LIB64) {
8529 outs() << " LIB64";
8530 } else {
8531 outs() << format(Fmt: " 0x%02" PRIx32,
8532 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8533 }
8534 switch (filetype) {
8535 case MachO::MH_OBJECT:
8536 outs() << " OBJECT";
8537 break;
8538 case MachO::MH_EXECUTE:
8539 outs() << " EXECUTE";
8540 break;
8541 case MachO::MH_FVMLIB:
8542 outs() << " FVMLIB";
8543 break;
8544 case MachO::MH_CORE:
8545 outs() << " CORE";
8546 break;
8547 case MachO::MH_PRELOAD:
8548 outs() << " PRELOAD";
8549 break;
8550 case MachO::MH_DYLIB:
8551 outs() << " DYLIB";
8552 break;
8553 case MachO::MH_DYLIB_STUB:
8554 outs() << " DYLIB_STUB";
8555 break;
8556 case MachO::MH_DYLINKER:
8557 outs() << " DYLINKER";
8558 break;
8559 case MachO::MH_BUNDLE:
8560 outs() << " BUNDLE";
8561 break;
8562 case MachO::MH_DSYM:
8563 outs() << " DSYM";
8564 break;
8565 case MachO::MH_KEXT_BUNDLE:
8566 outs() << " KEXTBUNDLE";
8567 break;
8568 case MachO::MH_FILESET:
8569 outs() << " FILESET";
8570 break;
8571 default:
8572 outs() << format(Fmt: " %10u", Vals: filetype);
8573 break;
8574 }
8575 outs() << format(Fmt: " %5u", Vals: ncmds);
8576 outs() << format(Fmt: " %10u", Vals: sizeofcmds);
8577 uint32_t f = flags;
8578 if (f & MachO::MH_NOUNDEFS) {
8579 outs() << " NOUNDEFS";
8580 f &= ~MachO::MH_NOUNDEFS;
8581 }
8582 if (f & MachO::MH_INCRLINK) {
8583 outs() << " INCRLINK";
8584 f &= ~MachO::MH_INCRLINK;
8585 }
8586 if (f & MachO::MH_DYLDLINK) {
8587 outs() << " DYLDLINK";
8588 f &= ~MachO::MH_DYLDLINK;
8589 }
8590 if (f & MachO::MH_BINDATLOAD) {
8591 outs() << " BINDATLOAD";
8592 f &= ~MachO::MH_BINDATLOAD;
8593 }
8594 if (f & MachO::MH_PREBOUND) {
8595 outs() << " PREBOUND";
8596 f &= ~MachO::MH_PREBOUND;
8597 }
8598 if (f & MachO::MH_SPLIT_SEGS) {
8599 outs() << " SPLIT_SEGS";
8600 f &= ~MachO::MH_SPLIT_SEGS;
8601 }
8602 if (f & MachO::MH_LAZY_INIT) {
8603 outs() << " LAZY_INIT";
8604 f &= ~MachO::MH_LAZY_INIT;
8605 }
8606 if (f & MachO::MH_TWOLEVEL) {
8607 outs() << " TWOLEVEL";
8608 f &= ~MachO::MH_TWOLEVEL;
8609 }
8610 if (f & MachO::MH_FORCE_FLAT) {
8611 outs() << " FORCE_FLAT";
8612 f &= ~MachO::MH_FORCE_FLAT;
8613 }
8614 if (f & MachO::MH_NOMULTIDEFS) {
8615 outs() << " NOMULTIDEFS";
8616 f &= ~MachO::MH_NOMULTIDEFS;
8617 }
8618 if (f & MachO::MH_NOFIXPREBINDING) {
8619 outs() << " NOFIXPREBINDING";
8620 f &= ~MachO::MH_NOFIXPREBINDING;
8621 }
8622 if (f & MachO::MH_PREBINDABLE) {
8623 outs() << " PREBINDABLE";
8624 f &= ~MachO::MH_PREBINDABLE;
8625 }
8626 if (f & MachO::MH_ALLMODSBOUND) {
8627 outs() << " ALLMODSBOUND";
8628 f &= ~MachO::MH_ALLMODSBOUND;
8629 }
8630 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8631 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8632 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8633 }
8634 if (f & MachO::MH_CANONICAL) {
8635 outs() << " CANONICAL";
8636 f &= ~MachO::MH_CANONICAL;
8637 }
8638 if (f & MachO::MH_WEAK_DEFINES) {
8639 outs() << " WEAK_DEFINES";
8640 f &= ~MachO::MH_WEAK_DEFINES;
8641 }
8642 if (f & MachO::MH_BINDS_TO_WEAK) {
8643 outs() << " BINDS_TO_WEAK";
8644 f &= ~MachO::MH_BINDS_TO_WEAK;
8645 }
8646 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8647 outs() << " ALLOW_STACK_EXECUTION";
8648 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8649 }
8650 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8651 outs() << " DEAD_STRIPPABLE_DYLIB";
8652 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8653 }
8654 if (f & MachO::MH_PIE) {
8655 outs() << " PIE";
8656 f &= ~MachO::MH_PIE;
8657 }
8658 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8659 outs() << " NO_REEXPORTED_DYLIBS";
8660 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8661 }
8662 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8663 outs() << " MH_HAS_TLV_DESCRIPTORS";
8664 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8665 }
8666 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8667 outs() << " MH_NO_HEAP_EXECUTION";
8668 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8669 }
8670 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8671 outs() << " APP_EXTENSION_SAFE";
8672 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8673 }
8674 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8675 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8676 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8677 }
8678 if (f != 0 || flags == 0)
8679 outs() << format(Fmt: " 0x%08" PRIx32, Vals: f);
8680 } else {
8681 outs() << format(Fmt: " 0x%08" PRIx32, Vals: magic);
8682 outs() << format(Fmt: " %7d", Vals: cputype);
8683 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8684 outs() << format(Fmt: " 0x%02" PRIx32,
8685 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8686 outs() << format(Fmt: " %10u", Vals: filetype);
8687 outs() << format(Fmt: " %5u", Vals: ncmds);
8688 outs() << format(Fmt: " %10u", Vals: sizeofcmds);
8689 outs() << format(Fmt: " 0x%08" PRIx32, Vals: flags);
8690 }
8691 outs() << "\n";
8692}
8693
8694static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8695 StringRef SegName, uint64_t vmaddr,
8696 uint64_t vmsize, uint64_t fileoff,
8697 uint64_t filesize, uint32_t maxprot,
8698 uint32_t initprot, uint32_t nsects,
8699 uint32_t flags, uint32_t object_size,
8700 bool verbose) {
8701 uint64_t expected_cmdsize;
8702 if (cmd == MachO::LC_SEGMENT) {
8703 outs() << " cmd LC_SEGMENT\n";
8704 expected_cmdsize = nsects;
8705 expected_cmdsize *= sizeof(struct MachO::section);
8706 expected_cmdsize += sizeof(struct MachO::segment_command);
8707 } else {
8708 outs() << " cmd LC_SEGMENT_64\n";
8709 expected_cmdsize = nsects;
8710 expected_cmdsize *= sizeof(struct MachO::section_64);
8711 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8712 }
8713 outs() << " cmdsize " << cmdsize;
8714 if (cmdsize != expected_cmdsize)
8715 outs() << " Inconsistent size\n";
8716 else
8717 outs() << "\n";
8718 outs() << " segname " << SegName << "\n";
8719 if (cmd == MachO::LC_SEGMENT_64) {
8720 outs() << " vmaddr " << format(Fmt: "0x%016" PRIx64, Vals: vmaddr) << "\n";
8721 outs() << " vmsize " << format(Fmt: "0x%016" PRIx64, Vals: vmsize) << "\n";
8722 } else {
8723 outs() << " vmaddr " << format(Fmt: "0x%08" PRIx64, Vals: vmaddr) << "\n";
8724 outs() << " vmsize " << format(Fmt: "0x%08" PRIx64, Vals: vmsize) << "\n";
8725 }
8726 outs() << " fileoff " << fileoff;
8727 if (fileoff > object_size)
8728 outs() << " (past end of file)\n";
8729 else
8730 outs() << "\n";
8731 outs() << " filesize " << filesize;
8732 if (fileoff + filesize > object_size)
8733 outs() << " (past end of file)\n";
8734 else
8735 outs() << "\n";
8736 if (verbose) {
8737 if ((maxprot &
8738 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8739 MachO::VM_PROT_EXECUTE)) != 0)
8740 outs() << " maxprot ?" << format(Fmt: "0x%08" PRIx32, Vals: maxprot) << "\n";
8741 else {
8742 outs() << " maxprot ";
8743 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8744 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8745 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8746 }
8747 if ((initprot &
8748 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8749 MachO::VM_PROT_EXECUTE)) != 0)
8750 outs() << " initprot ?" << format(Fmt: "0x%08" PRIx32, Vals: initprot) << "\n";
8751 else {
8752 outs() << " initprot ";
8753 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8754 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8755 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8756 }
8757 } else {
8758 outs() << " maxprot " << format(Fmt: "0x%08" PRIx32, Vals: maxprot) << "\n";
8759 outs() << " initprot " << format(Fmt: "0x%08" PRIx32, Vals: initprot) << "\n";
8760 }
8761 outs() << " nsects " << nsects << "\n";
8762 if (verbose) {
8763 outs() << " flags";
8764 if (flags == 0)
8765 outs() << " (none)\n";
8766 else {
8767 if (flags & MachO::SG_HIGHVM) {
8768 outs() << " HIGHVM";
8769 flags &= ~MachO::SG_HIGHVM;
8770 }
8771 if (flags & MachO::SG_FVMLIB) {
8772 outs() << " FVMLIB";
8773 flags &= ~MachO::SG_FVMLIB;
8774 }
8775 if (flags & MachO::SG_NORELOC) {
8776 outs() << " NORELOC";
8777 flags &= ~MachO::SG_NORELOC;
8778 }
8779 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8780 outs() << " PROTECTED_VERSION_1";
8781 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8782 }
8783 if (flags & MachO::SG_READ_ONLY) {
8784 // Apple's otool prints the SG_ prefix for this flag, but not for the
8785 // others.
8786 outs() << " SG_READ_ONLY";
8787 flags &= ~MachO::SG_READ_ONLY;
8788 }
8789 if (flags)
8790 outs() << format(Fmt: " 0x%08" PRIx32, Vals: flags) << " (unknown flags)\n";
8791 else
8792 outs() << "\n";
8793 }
8794 } else {
8795 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: flags) << "\n";
8796 }
8797}
8798
8799static void PrintSection(const char *sectname, const char *segname,
8800 uint64_t addr, uint64_t size, uint32_t offset,
8801 uint32_t align, uint32_t reloff, uint32_t nreloc,
8802 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8803 uint32_t cmd, const char *sg_segname,
8804 uint32_t filetype, uint32_t object_size,
8805 bool verbose) {
8806 outs() << "Section\n";
8807 outs() << " sectname " << format(Fmt: "%.16s\n", Vals: sectname);
8808 outs() << " segname " << format(Fmt: "%.16s", Vals: segname);
8809 if (filetype != MachO::MH_OBJECT && strncmp(s1: sg_segname, s2: segname, n: 16) != 0)
8810 outs() << " (does not match segment)\n";
8811 else
8812 outs() << "\n";
8813 if (cmd == MachO::LC_SEGMENT_64) {
8814 outs() << " addr " << format(Fmt: "0x%016" PRIx64, Vals: addr) << "\n";
8815 outs() << " size " << format(Fmt: "0x%016" PRIx64, Vals: size);
8816 } else {
8817 outs() << " addr " << format(Fmt: "0x%08" PRIx64, Vals: addr) << "\n";
8818 outs() << " size " << format(Fmt: "0x%08" PRIx64, Vals: size);
8819 }
8820 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8821 outs() << " (past end of file)\n";
8822 else
8823 outs() << "\n";
8824 outs() << " offset " << offset;
8825 if (offset > object_size)
8826 outs() << " (past end of file)\n";
8827 else
8828 outs() << "\n";
8829 uint32_t align_shifted = 1 << align;
8830 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8831 outs() << " reloff " << reloff;
8832 if (reloff > object_size)
8833 outs() << " (past end of file)\n";
8834 else
8835 outs() << "\n";
8836 outs() << " nreloc " << nreloc;
8837 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8838 outs() << " (past end of file)\n";
8839 else
8840 outs() << "\n";
8841 uint32_t section_type = flags & MachO::SECTION_TYPE;
8842 if (verbose) {
8843 outs() << " type";
8844 if (section_type == MachO::S_REGULAR)
8845 outs() << " S_REGULAR\n";
8846 else if (section_type == MachO::S_ZEROFILL)
8847 outs() << " S_ZEROFILL\n";
8848 else if (section_type == MachO::S_CSTRING_LITERALS)
8849 outs() << " S_CSTRING_LITERALS\n";
8850 else if (section_type == MachO::S_4BYTE_LITERALS)
8851 outs() << " S_4BYTE_LITERALS\n";
8852 else if (section_type == MachO::S_8BYTE_LITERALS)
8853 outs() << " S_8BYTE_LITERALS\n";
8854 else if (section_type == MachO::S_16BYTE_LITERALS)
8855 outs() << " S_16BYTE_LITERALS\n";
8856 else if (section_type == MachO::S_LITERAL_POINTERS)
8857 outs() << " S_LITERAL_POINTERS\n";
8858 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8859 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8860 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8861 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8862 else if (section_type == MachO::S_SYMBOL_STUBS)
8863 outs() << " S_SYMBOL_STUBS\n";
8864 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8865 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8866 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8867 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8868 else if (section_type == MachO::S_COALESCED)
8869 outs() << " S_COALESCED\n";
8870 else if (section_type == MachO::S_INTERPOSING)
8871 outs() << " S_INTERPOSING\n";
8872 else if (section_type == MachO::S_DTRACE_DOF)
8873 outs() << " S_DTRACE_DOF\n";
8874 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8875 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8876 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8877 outs() << " S_THREAD_LOCAL_REGULAR\n";
8878 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8879 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8880 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8881 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8882 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8883 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8884 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8885 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8886 else if (section_type == MachO::S_INIT_FUNC_OFFSETS)
8887 outs() << " S_INIT_FUNC_OFFSETS\n";
8888 else
8889 outs() << format(Fmt: "0x%08" PRIx32, Vals: section_type) << "\n";
8890 outs() << "attributes";
8891 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8892 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8893 outs() << " PURE_INSTRUCTIONS";
8894 if (section_attributes & MachO::S_ATTR_NO_TOC)
8895 outs() << " NO_TOC";
8896 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8897 outs() << " STRIP_STATIC_SYMS";
8898 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8899 outs() << " NO_DEAD_STRIP";
8900 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8901 outs() << " LIVE_SUPPORT";
8902 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8903 outs() << " SELF_MODIFYING_CODE";
8904 if (section_attributes & MachO::S_ATTR_DEBUG)
8905 outs() << " DEBUG";
8906 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8907 outs() << " SOME_INSTRUCTIONS";
8908 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8909 outs() << " EXT_RELOC";
8910 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8911 outs() << " LOC_RELOC";
8912 if (section_attributes == 0)
8913 outs() << " (none)";
8914 outs() << "\n";
8915 } else
8916 outs() << " flags " << format(Fmt: "0x%08" PRIx32, Vals: flags) << "\n";
8917 outs() << " reserved1 " << reserved1;
8918 if (section_type == MachO::S_SYMBOL_STUBS ||
8919 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8920 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8921 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8922 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8923 outs() << " (index into indirect symbol table)\n";
8924 else
8925 outs() << "\n";
8926 outs() << " reserved2 " << reserved2;
8927 if (section_type == MachO::S_SYMBOL_STUBS)
8928 outs() << " (size of stubs)\n";
8929 else
8930 outs() << "\n";
8931}
8932
8933static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8934 uint32_t object_size) {
8935 outs() << " cmd LC_SYMTAB\n";
8936 outs() << " cmdsize " << st.cmdsize;
8937 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8938 outs() << " Incorrect size\n";
8939 else
8940 outs() << "\n";
8941 outs() << " symoff " << st.symoff;
8942 if (st.symoff > object_size)
8943 outs() << " (past end of file)\n";
8944 else
8945 outs() << "\n";
8946 outs() << " nsyms " << st.nsyms;
8947 uint64_t big_size;
8948 if (Is64Bit) {
8949 big_size = st.nsyms;
8950 big_size *= sizeof(struct MachO::nlist_64);
8951 big_size += st.symoff;
8952 if (big_size > object_size)
8953 outs() << " (past end of file)\n";
8954 else
8955 outs() << "\n";
8956 } else {
8957 big_size = st.nsyms;
8958 big_size *= sizeof(struct MachO::nlist);
8959 big_size += st.symoff;
8960 if (big_size > object_size)
8961 outs() << " (past end of file)\n";
8962 else
8963 outs() << "\n";
8964 }
8965 outs() << " stroff " << st.stroff;
8966 if (st.stroff > object_size)
8967 outs() << " (past end of file)\n";
8968 else
8969 outs() << "\n";
8970 outs() << " strsize " << st.strsize;
8971 big_size = st.stroff;
8972 big_size += st.strsize;
8973 if (big_size > object_size)
8974 outs() << " (past end of file)\n";
8975 else
8976 outs() << "\n";
8977}
8978
8979static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8980 uint32_t nsyms, uint32_t object_size,
8981 bool Is64Bit) {
8982 outs() << " cmd LC_DYSYMTAB\n";
8983 outs() << " cmdsize " << dyst.cmdsize;
8984 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8985 outs() << " Incorrect size\n";
8986 else
8987 outs() << "\n";
8988 outs() << " ilocalsym " << dyst.ilocalsym;
8989 if (dyst.ilocalsym > nsyms)
8990 outs() << " (greater than the number of symbols)\n";
8991 else
8992 outs() << "\n";
8993 outs() << " nlocalsym " << dyst.nlocalsym;
8994 uint64_t big_size;
8995 big_size = dyst.ilocalsym;
8996 big_size += dyst.nlocalsym;
8997 if (big_size > nsyms)
8998 outs() << " (past the end of the symbol table)\n";
8999 else
9000 outs() << "\n";
9001 outs() << " iextdefsym " << dyst.iextdefsym;
9002 if (dyst.iextdefsym > nsyms)
9003 outs() << " (greater than the number of symbols)\n";
9004 else
9005 outs() << "\n";
9006 outs() << " nextdefsym " << dyst.nextdefsym;
9007 big_size = dyst.iextdefsym;
9008 big_size += dyst.nextdefsym;
9009 if (big_size > nsyms)
9010 outs() << " (past the end of the symbol table)\n";
9011 else
9012 outs() << "\n";
9013 outs() << " iundefsym " << dyst.iundefsym;
9014 if (dyst.iundefsym > nsyms)
9015 outs() << " (greater than the number of symbols)\n";
9016 else
9017 outs() << "\n";
9018 outs() << " nundefsym " << dyst.nundefsym;
9019 big_size = dyst.iundefsym;
9020 big_size += dyst.nundefsym;
9021 if (big_size > nsyms)
9022 outs() << " (past the end of the symbol table)\n";
9023 else
9024 outs() << "\n";
9025 outs() << " tocoff " << dyst.tocoff;
9026 if (dyst.tocoff > object_size)
9027 outs() << " (past end of file)\n";
9028 else
9029 outs() << "\n";
9030 outs() << " ntoc " << dyst.ntoc;
9031 big_size = dyst.ntoc;
9032 big_size *= sizeof(struct MachO::dylib_table_of_contents);
9033 big_size += dyst.tocoff;
9034 if (big_size > object_size)
9035 outs() << " (past end of file)\n";
9036 else
9037 outs() << "\n";
9038 outs() << " modtaboff " << dyst.modtaboff;
9039 if (dyst.modtaboff > object_size)
9040 outs() << " (past end of file)\n";
9041 else
9042 outs() << "\n";
9043 outs() << " nmodtab " << dyst.nmodtab;
9044 uint64_t modtabend;
9045 if (Is64Bit) {
9046 modtabend = dyst.nmodtab;
9047 modtabend *= sizeof(struct MachO::dylib_module_64);
9048 modtabend += dyst.modtaboff;
9049 } else {
9050 modtabend = dyst.nmodtab;
9051 modtabend *= sizeof(struct MachO::dylib_module);
9052 modtabend += dyst.modtaboff;
9053 }
9054 if (modtabend > object_size)
9055 outs() << " (past end of file)\n";
9056 else
9057 outs() << "\n";
9058 outs() << " extrefsymoff " << dyst.extrefsymoff;
9059 if (dyst.extrefsymoff > object_size)
9060 outs() << " (past end of file)\n";
9061 else
9062 outs() << "\n";
9063 outs() << " nextrefsyms " << dyst.nextrefsyms;
9064 big_size = dyst.nextrefsyms;
9065 big_size *= sizeof(struct MachO::dylib_reference);
9066 big_size += dyst.extrefsymoff;
9067 if (big_size > object_size)
9068 outs() << " (past end of file)\n";
9069 else
9070 outs() << "\n";
9071 outs() << " indirectsymoff " << dyst.indirectsymoff;
9072 if (dyst.indirectsymoff > object_size)
9073 outs() << " (past end of file)\n";
9074 else
9075 outs() << "\n";
9076 outs() << " nindirectsyms " << dyst.nindirectsyms;
9077 big_size = dyst.nindirectsyms;
9078 big_size *= sizeof(uint32_t);
9079 big_size += dyst.indirectsymoff;
9080 if (big_size > object_size)
9081 outs() << " (past end of file)\n";
9082 else
9083 outs() << "\n";
9084 outs() << " extreloff " << dyst.extreloff;
9085 if (dyst.extreloff > object_size)
9086 outs() << " (past end of file)\n";
9087 else
9088 outs() << "\n";
9089 outs() << " nextrel " << dyst.nextrel;
9090 big_size = dyst.nextrel;
9091 big_size *= sizeof(struct MachO::relocation_info);
9092 big_size += dyst.extreloff;
9093 if (big_size > object_size)
9094 outs() << " (past end of file)\n";
9095 else
9096 outs() << "\n";
9097 outs() << " locreloff " << dyst.locreloff;
9098 if (dyst.locreloff > object_size)
9099 outs() << " (past end of file)\n";
9100 else
9101 outs() << "\n";
9102 outs() << " nlocrel " << dyst.nlocrel;
9103 big_size = dyst.nlocrel;
9104 big_size *= sizeof(struct MachO::relocation_info);
9105 big_size += dyst.locreloff;
9106 if (big_size > object_size)
9107 outs() << " (past end of file)\n";
9108 else
9109 outs() << "\n";
9110}
9111
9112static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
9113 uint32_t object_size) {
9114 if (dc.cmd == MachO::LC_DYLD_INFO)
9115 outs() << " cmd LC_DYLD_INFO\n";
9116 else
9117 outs() << " cmd LC_DYLD_INFO_ONLY\n";
9118 outs() << " cmdsize " << dc.cmdsize;
9119 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
9120 outs() << " Incorrect size\n";
9121 else
9122 outs() << "\n";
9123 outs() << " rebase_off " << dc.rebase_off;
9124 if (dc.rebase_off > object_size)
9125 outs() << " (past end of file)\n";
9126 else
9127 outs() << "\n";
9128 outs() << " rebase_size " << dc.rebase_size;
9129 uint64_t big_size;
9130 big_size = dc.rebase_off;
9131 big_size += dc.rebase_size;
9132 if (big_size > object_size)
9133 outs() << " (past end of file)\n";
9134 else
9135 outs() << "\n";
9136 outs() << " bind_off " << dc.bind_off;
9137 if (dc.bind_off > object_size)
9138 outs() << " (past end of file)\n";
9139 else
9140 outs() << "\n";
9141 outs() << " bind_size " << dc.bind_size;
9142 big_size = dc.bind_off;
9143 big_size += dc.bind_size;
9144 if (big_size > object_size)
9145 outs() << " (past end of file)\n";
9146 else
9147 outs() << "\n";
9148 outs() << " weak_bind_off " << dc.weak_bind_off;
9149 if (dc.weak_bind_off > object_size)
9150 outs() << " (past end of file)\n";
9151 else
9152 outs() << "\n";
9153 outs() << " weak_bind_size " << dc.weak_bind_size;
9154 big_size = dc.weak_bind_off;
9155 big_size += dc.weak_bind_size;
9156 if (big_size > object_size)
9157 outs() << " (past end of file)\n";
9158 else
9159 outs() << "\n";
9160 outs() << " lazy_bind_off " << dc.lazy_bind_off;
9161 if (dc.lazy_bind_off > object_size)
9162 outs() << " (past end of file)\n";
9163 else
9164 outs() << "\n";
9165 outs() << " lazy_bind_size " << dc.lazy_bind_size;
9166 big_size = dc.lazy_bind_off;
9167 big_size += dc.lazy_bind_size;
9168 if (big_size > object_size)
9169 outs() << " (past end of file)\n";
9170 else
9171 outs() << "\n";
9172 outs() << " export_off " << dc.export_off;
9173 if (dc.export_off > object_size)
9174 outs() << " (past end of file)\n";
9175 else
9176 outs() << "\n";
9177 outs() << " export_size " << dc.export_size;
9178 big_size = dc.export_off;
9179 big_size += dc.export_size;
9180 if (big_size > object_size)
9181 outs() << " (past end of file)\n";
9182 else
9183 outs() << "\n";
9184}
9185
9186static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9187 const char *Ptr) {
9188 if (dyld.cmd == MachO::LC_ID_DYLINKER)
9189 outs() << " cmd LC_ID_DYLINKER\n";
9190 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9191 outs() << " cmd LC_LOAD_DYLINKER\n";
9192 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9193 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
9194 else
9195 outs() << " cmd ?(" << dyld.cmd << ")\n";
9196 outs() << " cmdsize " << dyld.cmdsize;
9197 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9198 outs() << " Incorrect size\n";
9199 else
9200 outs() << "\n";
9201 if (dyld.name >= dyld.cmdsize)
9202 outs() << " name ?(bad offset " << dyld.name << ")\n";
9203 else {
9204 const char *P = Ptr + dyld.name;
9205 outs() << " name " << P << " (offset " << dyld.name << ")\n";
9206 }
9207}
9208
9209static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9210 outs() << " cmd LC_UUID\n";
9211 outs() << " cmdsize " << uuid.cmdsize;
9212 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9213 outs() << " Incorrect size\n";
9214 else
9215 outs() << "\n";
9216 outs() << " uuid ";
9217 for (int i = 0; i < 16; ++i) {
9218 outs() << format(Fmt: "%02" PRIX32, Vals: uuid.uuid[i]);
9219 if (i == 3 || i == 5 || i == 7 || i == 9)
9220 outs() << "-";
9221 }
9222 outs() << "\n";
9223}
9224
9225static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9226 outs() << " cmd LC_RPATH\n";
9227 outs() << " cmdsize " << rpath.cmdsize;
9228 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9229 outs() << " Incorrect size\n";
9230 else
9231 outs() << "\n";
9232 if (rpath.path >= rpath.cmdsize)
9233 outs() << " path ?(bad offset " << rpath.path << ")\n";
9234 else {
9235 const char *P = Ptr + rpath.path;
9236 outs() << " path " << P << " (offset " << rpath.path << ")\n";
9237 }
9238}
9239
9240static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9241 StringRef LoadCmdName;
9242 switch (vd.cmd) {
9243 case MachO::LC_VERSION_MIN_MACOSX:
9244 LoadCmdName = "LC_VERSION_MIN_MACOSX";
9245 break;
9246 case MachO::LC_VERSION_MIN_IPHONEOS:
9247 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9248 break;
9249 case MachO::LC_VERSION_MIN_TVOS:
9250 LoadCmdName = "LC_VERSION_MIN_TVOS";
9251 break;
9252 case MachO::LC_VERSION_MIN_WATCHOS:
9253 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9254 break;
9255 default:
9256 llvm_unreachable("Unknown version min load command");
9257 }
9258
9259 outs() << " cmd " << LoadCmdName << '\n';
9260 outs() << " cmdsize " << vd.cmdsize;
9261 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9262 outs() << " Incorrect size\n";
9263 else
9264 outs() << "\n";
9265 outs() << " version "
9266 << MachOObjectFile::getVersionMinMajor(C&: vd, SDK: false) << "."
9267 << MachOObjectFile::getVersionMinMinor(C&: vd, SDK: false);
9268 uint32_t Update = MachOObjectFile::getVersionMinUpdate(C&: vd, SDK: false);
9269 if (Update != 0)
9270 outs() << "." << Update;
9271 outs() << "\n";
9272 if (vd.sdk == 0)
9273 outs() << " sdk n/a";
9274 else {
9275 outs() << " sdk "
9276 << MachOObjectFile::getVersionMinMajor(C&: vd, SDK: true) << "."
9277 << MachOObjectFile::getVersionMinMinor(C&: vd, SDK: true);
9278 }
9279 Update = MachOObjectFile::getVersionMinUpdate(C&: vd, SDK: true);
9280 if (Update != 0)
9281 outs() << "." << Update;
9282 outs() << "\n";
9283}
9284
9285static void PrintNoteLoadCommand(MachO::note_command Nt) {
9286 outs() << " cmd LC_NOTE\n";
9287 outs() << " cmdsize " << Nt.cmdsize;
9288 if (Nt.cmdsize != sizeof(struct MachO::note_command))
9289 outs() << " Incorrect size\n";
9290 else
9291 outs() << "\n";
9292 const char *d = Nt.data_owner;
9293 outs() << "data_owner " << format(Fmt: "%.16s\n", Vals: d);
9294 outs() << " offset " << Nt.offset << "\n";
9295 outs() << " size " << Nt.size << "\n";
9296}
9297
9298static void PrintBuildToolVersion(MachO::build_tool_version bv, bool verbose) {
9299 outs() << " tool ";
9300 if (verbose)
9301 outs() << MachOObjectFile::getBuildTool(tools: bv.tool);
9302 else
9303 outs() << bv.tool;
9304 outs() << "\n";
9305 outs() << " version " << MachOObjectFile::getVersionString(version: bv.version)
9306 << "\n";
9307}
9308
9309static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9310 MachO::build_version_command bd,
9311 bool verbose) {
9312 outs() << " cmd LC_BUILD_VERSION\n";
9313 outs() << " cmdsize " << bd.cmdsize;
9314 if (bd.cmdsize !=
9315 sizeof(struct MachO::build_version_command) +
9316 bd.ntools * sizeof(struct MachO::build_tool_version))
9317 outs() << " Incorrect size\n";
9318 else
9319 outs() << "\n";
9320 outs() << " platform ";
9321 if (verbose)
9322 outs() << MachOObjectFile::getBuildPlatform(platform: bd.platform);
9323 else
9324 outs() << bd.platform;
9325 outs() << "\n";
9326 if (bd.sdk)
9327 outs() << " sdk " << MachOObjectFile::getVersionString(version: bd.sdk)
9328 << "\n";
9329 else
9330 outs() << " sdk n/a\n";
9331 outs() << " minos " << MachOObjectFile::getVersionString(version: bd.minos)
9332 << "\n";
9333 outs() << " ntools " << bd.ntools << "\n";
9334 for (unsigned i = 0; i < bd.ntools; ++i) {
9335 MachO::build_tool_version bv = obj->getBuildToolVersion(index: i);
9336 PrintBuildToolVersion(bv, verbose);
9337 }
9338}
9339
9340static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9341 outs() << " cmd LC_SOURCE_VERSION\n";
9342 outs() << " cmdsize " << sd.cmdsize;
9343 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9344 outs() << " Incorrect size\n";
9345 else
9346 outs() << "\n";
9347 uint64_t a = (sd.version >> 40) & 0xffffff;
9348 uint64_t b = (sd.version >> 30) & 0x3ff;
9349 uint64_t c = (sd.version >> 20) & 0x3ff;
9350 uint64_t d = (sd.version >> 10) & 0x3ff;
9351 uint64_t e = sd.version & 0x3ff;
9352 outs() << " version " << a << "." << b;
9353 if (e != 0)
9354 outs() << "." << c << "." << d << "." << e;
9355 else if (d != 0)
9356 outs() << "." << c << "." << d;
9357 else if (c != 0)
9358 outs() << "." << c;
9359 outs() << "\n";
9360}
9361
9362static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9363 outs() << " cmd LC_MAIN\n";
9364 outs() << " cmdsize " << ep.cmdsize;
9365 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9366 outs() << " Incorrect size\n";
9367 else
9368 outs() << "\n";
9369 outs() << " entryoff " << ep.entryoff << "\n";
9370 outs() << " stacksize " << ep.stacksize << "\n";
9371}
9372
9373static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9374 uint32_t object_size) {
9375 outs() << " cmd LC_ENCRYPTION_INFO\n";
9376 outs() << " cmdsize " << ec.cmdsize;
9377 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9378 outs() << " Incorrect size\n";
9379 else
9380 outs() << "\n";
9381 outs() << " cryptoff " << ec.cryptoff;
9382 if (ec.cryptoff > object_size)
9383 outs() << " (past end of file)\n";
9384 else
9385 outs() << "\n";
9386 outs() << " cryptsize " << ec.cryptsize;
9387 if (ec.cryptsize > object_size)
9388 outs() << " (past end of file)\n";
9389 else
9390 outs() << "\n";
9391 outs() << " cryptid " << ec.cryptid << "\n";
9392}
9393
9394static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9395 uint32_t object_size) {
9396 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9397 outs() << " cmdsize " << ec.cmdsize;
9398 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9399 outs() << " Incorrect size\n";
9400 else
9401 outs() << "\n";
9402 outs() << " cryptoff " << ec.cryptoff;
9403 if (ec.cryptoff > object_size)
9404 outs() << " (past end of file)\n";
9405 else
9406 outs() << "\n";
9407 outs() << " cryptsize " << ec.cryptsize;
9408 if (ec.cryptsize > object_size)
9409 outs() << " (past end of file)\n";
9410 else
9411 outs() << "\n";
9412 outs() << " cryptid " << ec.cryptid << "\n";
9413 outs() << " pad " << ec.pad << "\n";
9414}
9415
9416static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9417 const char *Ptr) {
9418 outs() << " cmd LC_LINKER_OPTION\n";
9419 outs() << " cmdsize " << lo.cmdsize;
9420 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9421 outs() << " Incorrect size\n";
9422 else
9423 outs() << "\n";
9424 outs() << " count " << lo.count << "\n";
9425 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9426 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9427 uint32_t i = 0;
9428 while (left > 0) {
9429 while (*string == '\0' && left > 0) {
9430 string++;
9431 left--;
9432 }
9433 if (left > 0) {
9434 i++;
9435 outs() << " string #" << i << " " << format(Fmt: "%.*s\n", Vals: left, Vals: string);
9436 uint32_t NullPos = StringRef(string, left).find(C: '\0');
9437 uint32_t len = std::min(a: NullPos, b: left) + 1;
9438 string += len;
9439 left -= len;
9440 }
9441 }
9442 if (lo.count != i)
9443 outs() << " count " << lo.count << " does not match number of strings "
9444 << i << "\n";
9445}
9446
9447static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9448 const char *Ptr) {
9449 outs() << " cmd LC_SUB_FRAMEWORK\n";
9450 outs() << " cmdsize " << sub.cmdsize;
9451 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9452 outs() << " Incorrect size\n";
9453 else
9454 outs() << "\n";
9455 if (sub.umbrella < sub.cmdsize) {
9456 const char *P = Ptr + sub.umbrella;
9457 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9458 } else {
9459 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9460 }
9461}
9462
9463static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9464 const char *Ptr) {
9465 outs() << " cmd LC_SUB_UMBRELLA\n";
9466 outs() << " cmdsize " << sub.cmdsize;
9467 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9468 outs() << " Incorrect size\n";
9469 else
9470 outs() << "\n";
9471 if (sub.sub_umbrella < sub.cmdsize) {
9472 const char *P = Ptr + sub.sub_umbrella;
9473 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9474 } else {
9475 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9476 }
9477}
9478
9479static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9480 const char *Ptr) {
9481 outs() << " cmd LC_SUB_LIBRARY\n";
9482 outs() << " cmdsize " << sub.cmdsize;
9483 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9484 outs() << " Incorrect size\n";
9485 else
9486 outs() << "\n";
9487 if (sub.sub_library < sub.cmdsize) {
9488 const char *P = Ptr + sub.sub_library;
9489 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9490 } else {
9491 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9492 }
9493}
9494
9495static void PrintSubClientCommand(MachO::sub_client_command sub,
9496 const char *Ptr) {
9497 outs() << " cmd LC_SUB_CLIENT\n";
9498 outs() << " cmdsize " << sub.cmdsize;
9499 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9500 outs() << " Incorrect size\n";
9501 else
9502 outs() << "\n";
9503 if (sub.client < sub.cmdsize) {
9504 const char *P = Ptr + sub.client;
9505 outs() << " client " << P << " (offset " << sub.client << ")\n";
9506 } else {
9507 outs() << " client ?(bad offset " << sub.client << ")\n";
9508 }
9509}
9510
9511static void PrintRoutinesCommand(MachO::routines_command r) {
9512 outs() << " cmd LC_ROUTINES\n";
9513 outs() << " cmdsize " << r.cmdsize;
9514 if (r.cmdsize != sizeof(struct MachO::routines_command))
9515 outs() << " Incorrect size\n";
9516 else
9517 outs() << "\n";
9518 outs() << " init_address " << format(Fmt: "0x%08" PRIx32, Vals: r.init_address) << "\n";
9519 outs() << " init_module " << r.init_module << "\n";
9520 outs() << " reserved1 " << r.reserved1 << "\n";
9521 outs() << " reserved2 " << r.reserved2 << "\n";
9522 outs() << " reserved3 " << r.reserved3 << "\n";
9523 outs() << " reserved4 " << r.reserved4 << "\n";
9524 outs() << " reserved5 " << r.reserved5 << "\n";
9525 outs() << " reserved6 " << r.reserved6 << "\n";
9526}
9527
9528static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9529 outs() << " cmd LC_ROUTINES_64\n";
9530 outs() << " cmdsize " << r.cmdsize;
9531 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9532 outs() << " Incorrect size\n";
9533 else
9534 outs() << "\n";
9535 outs() << " init_address " << format(Fmt: "0x%016" PRIx64, Vals: r.init_address) << "\n";
9536 outs() << " init_module " << r.init_module << "\n";
9537 outs() << " reserved1 " << r.reserved1 << "\n";
9538 outs() << " reserved2 " << r.reserved2 << "\n";
9539 outs() << " reserved3 " << r.reserved3 << "\n";
9540 outs() << " reserved4 " << r.reserved4 << "\n";
9541 outs() << " reserved5 " << r.reserved5 << "\n";
9542 outs() << " reserved6 " << r.reserved6 << "\n";
9543}
9544
9545static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9546 outs() << "\t eax " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eax);
9547 outs() << " ebx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ebx);
9548 outs() << " ecx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ecx);
9549 outs() << " edx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.edx) << "\n";
9550 outs() << "\t edi " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.edi);
9551 outs() << " esi " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.esi);
9552 outs() << " ebp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ebp);
9553 outs() << " esp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.esp) << "\n";
9554 outs() << "\t ss " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ss);
9555 outs() << " eflags " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eflags);
9556 outs() << " eip " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eip);
9557 outs() << " cs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.cs) << "\n";
9558 outs() << "\t ds " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ds);
9559 outs() << " es " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.es);
9560 outs() << " fs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.fs);
9561 outs() << " gs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.gs) << "\n";
9562}
9563
9564static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9565 outs() << " rax " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rax);
9566 outs() << " rbx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rbx);
9567 outs() << " rcx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rcx) << "\n";
9568 outs() << " rdx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rdx);
9569 outs() << " rdi " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rdi);
9570 outs() << " rsi " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rsi) << "\n";
9571 outs() << " rbp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rbp);
9572 outs() << " rsp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rsp);
9573 outs() << " r8 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r8) << "\n";
9574 outs() << " r9 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r9);
9575 outs() << " r10 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r10);
9576 outs() << " r11 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r11) << "\n";
9577 outs() << " r12 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r12);
9578 outs() << " r13 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r13);
9579 outs() << " r14 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r14) << "\n";
9580 outs() << " r15 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r15);
9581 outs() << " rip " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rip) << "\n";
9582 outs() << "rflags " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rflags);
9583 outs() << " cs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.cs);
9584 outs() << " fs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.fs) << "\n";
9585 outs() << " gs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.gs) << "\n";
9586}
9587
9588static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9589 uint32_t f;
9590 outs() << "\t mmst_reg ";
9591 for (f = 0; f < 10; f++)
9592 outs() << format(Fmt: "%02" PRIx32, Vals: (r.mmst_reg[f] & 0xff)) << " ";
9593 outs() << "\n";
9594 outs() << "\t mmst_rsrv ";
9595 for (f = 0; f < 6; f++)
9596 outs() << format(Fmt: "%02" PRIx32, Vals: (r.mmst_rsrv[f] & 0xff)) << " ";
9597 outs() << "\n";
9598}
9599
9600static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9601 uint32_t f;
9602 outs() << "\t xmm_reg ";
9603 for (f = 0; f < 16; f++)
9604 outs() << format(Fmt: "%02" PRIx32, Vals: (r.xmm_reg[f] & 0xff)) << " ";
9605 outs() << "\n";
9606}
9607
9608static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9609 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9610 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9611 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9612 outs() << " denorm " << fpu.fpu_fcw.denorm;
9613 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9614 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9615 outs() << " undfl " << fpu.fpu_fcw.undfl;
9616 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9617 outs() << "\t\t pc ";
9618 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9619 outs() << "FP_PREC_24B ";
9620 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9621 outs() << "FP_PREC_53B ";
9622 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9623 outs() << "FP_PREC_64B ";
9624 else
9625 outs() << fpu.fpu_fcw.pc << " ";
9626 outs() << "rc ";
9627 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9628 outs() << "FP_RND_NEAR ";
9629 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9630 outs() << "FP_RND_DOWN ";
9631 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9632 outs() << "FP_RND_UP ";
9633 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9634 outs() << "FP_CHOP ";
9635 outs() << "\n";
9636 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9637 outs() << " denorm " << fpu.fpu_fsw.denorm;
9638 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9639 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9640 outs() << " undfl " << fpu.fpu_fsw.undfl;
9641 outs() << " precis " << fpu.fpu_fsw.precis;
9642 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9643 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9644 outs() << " c0 " << fpu.fpu_fsw.c0;
9645 outs() << " c1 " << fpu.fpu_fsw.c1;
9646 outs() << " c2 " << fpu.fpu_fsw.c2;
9647 outs() << " tos " << fpu.fpu_fsw.tos;
9648 outs() << " c3 " << fpu.fpu_fsw.c3;
9649 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9650 outs() << "\t fpu_ftw " << format(Fmt: "0x%02" PRIx32, Vals: fpu.fpu_ftw);
9651 outs() << " fpu_rsrv1 " << format(Fmt: "0x%02" PRIx32, Vals: fpu.fpu_rsrv1);
9652 outs() << " fpu_fop " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_fop);
9653 outs() << " fpu_ip " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_ip) << "\n";
9654 outs() << "\t fpu_cs " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_cs);
9655 outs() << " fpu_rsrv2 " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_rsrv2);
9656 outs() << " fpu_dp " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_dp);
9657 outs() << " fpu_ds " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_ds) << "\n";
9658 outs() << "\t fpu_rsrv3 " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_rsrv3);
9659 outs() << " fpu_mxcsr " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_mxcsr);
9660 outs() << " fpu_mxcsrmask " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_mxcsrmask);
9661 outs() << "\n";
9662 outs() << "\t fpu_stmm0:\n";
9663 Print_mmst_reg(r&: fpu.fpu_stmm0);
9664 outs() << "\t fpu_stmm1:\n";
9665 Print_mmst_reg(r&: fpu.fpu_stmm1);
9666 outs() << "\t fpu_stmm2:\n";
9667 Print_mmst_reg(r&: fpu.fpu_stmm2);
9668 outs() << "\t fpu_stmm3:\n";
9669 Print_mmst_reg(r&: fpu.fpu_stmm3);
9670 outs() << "\t fpu_stmm4:\n";
9671 Print_mmst_reg(r&: fpu.fpu_stmm4);
9672 outs() << "\t fpu_stmm5:\n";
9673 Print_mmst_reg(r&: fpu.fpu_stmm5);
9674 outs() << "\t fpu_stmm6:\n";
9675 Print_mmst_reg(r&: fpu.fpu_stmm6);
9676 outs() << "\t fpu_stmm7:\n";
9677 Print_mmst_reg(r&: fpu.fpu_stmm7);
9678 outs() << "\t fpu_xmm0:\n";
9679 Print_xmm_reg(r&: fpu.fpu_xmm0);
9680 outs() << "\t fpu_xmm1:\n";
9681 Print_xmm_reg(r&: fpu.fpu_xmm1);
9682 outs() << "\t fpu_xmm2:\n";
9683 Print_xmm_reg(r&: fpu.fpu_xmm2);
9684 outs() << "\t fpu_xmm3:\n";
9685 Print_xmm_reg(r&: fpu.fpu_xmm3);
9686 outs() << "\t fpu_xmm4:\n";
9687 Print_xmm_reg(r&: fpu.fpu_xmm4);
9688 outs() << "\t fpu_xmm5:\n";
9689 Print_xmm_reg(r&: fpu.fpu_xmm5);
9690 outs() << "\t fpu_xmm6:\n";
9691 Print_xmm_reg(r&: fpu.fpu_xmm6);
9692 outs() << "\t fpu_xmm7:\n";
9693 Print_xmm_reg(r&: fpu.fpu_xmm7);
9694 outs() << "\t fpu_xmm8:\n";
9695 Print_xmm_reg(r&: fpu.fpu_xmm8);
9696 outs() << "\t fpu_xmm9:\n";
9697 Print_xmm_reg(r&: fpu.fpu_xmm9);
9698 outs() << "\t fpu_xmm10:\n";
9699 Print_xmm_reg(r&: fpu.fpu_xmm10);
9700 outs() << "\t fpu_xmm11:\n";
9701 Print_xmm_reg(r&: fpu.fpu_xmm11);
9702 outs() << "\t fpu_xmm12:\n";
9703 Print_xmm_reg(r&: fpu.fpu_xmm12);
9704 outs() << "\t fpu_xmm13:\n";
9705 Print_xmm_reg(r&: fpu.fpu_xmm13);
9706 outs() << "\t fpu_xmm14:\n";
9707 Print_xmm_reg(r&: fpu.fpu_xmm14);
9708 outs() << "\t fpu_xmm15:\n";
9709 Print_xmm_reg(r&: fpu.fpu_xmm15);
9710 outs() << "\t fpu_rsrv4:\n";
9711 for (uint32_t f = 0; f < 6; f++) {
9712 outs() << "\t ";
9713 for (uint32_t g = 0; g < 16; g++)
9714 outs() << format(Fmt: "%02" PRIx32, Vals: fpu.fpu_rsrv4[f * g]) << " ";
9715 outs() << "\n";
9716 }
9717 outs() << "\t fpu_reserved1 " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_reserved1);
9718 outs() << "\n";
9719}
9720
9721static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9722 outs() << "\t trapno " << format(Fmt: "0x%08" PRIx32, Vals: exc64.trapno);
9723 outs() << " err " << format(Fmt: "0x%08" PRIx32, Vals: exc64.err);
9724 outs() << " faultvaddr " << format(Fmt: "0x%016" PRIx64, Vals: exc64.faultvaddr) << "\n";
9725}
9726
9727static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9728 outs() << "\t r0 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[0]);
9729 outs() << " r1 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[1]);
9730 outs() << " r2 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[2]);
9731 outs() << " r3 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[3]) << "\n";
9732 outs() << "\t r4 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[4]);
9733 outs() << " r5 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[5]);
9734 outs() << " r6 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[6]);
9735 outs() << " r7 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[7]) << "\n";
9736 outs() << "\t r8 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[8]);
9737 outs() << " r9 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[9]);
9738 outs() << " r10 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[10]);
9739 outs() << " r11 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[11]) << "\n";
9740 outs() << "\t r12 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[12]);
9741 outs() << " sp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.sp);
9742 outs() << " lr " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.lr);
9743 outs() << " pc " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.pc) << "\n";
9744 outs() << "\t cpsr " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.cpsr) << "\n";
9745}
9746
9747static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9748 outs() << "\t x0 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[0]);
9749 outs() << " x1 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[1]);
9750 outs() << " x2 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[2]) << "\n";
9751 outs() << "\t x3 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[3]);
9752 outs() << " x4 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[4]);
9753 outs() << " x5 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[5]) << "\n";
9754 outs() << "\t x6 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[6]);
9755 outs() << " x7 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[7]);
9756 outs() << " x8 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[8]) << "\n";
9757 outs() << "\t x9 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[9]);
9758 outs() << " x10 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[10]);
9759 outs() << " x11 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[11]) << "\n";
9760 outs() << "\t x12 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[12]);
9761 outs() << " x13 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[13]);
9762 outs() << " x14 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[14]) << "\n";
9763 outs() << "\t x15 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[15]);
9764 outs() << " x16 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[16]);
9765 outs() << " x17 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[17]) << "\n";
9766 outs() << "\t x18 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[18]);
9767 outs() << " x19 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[19]);
9768 outs() << " x20 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[20]) << "\n";
9769 outs() << "\t x21 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[21]);
9770 outs() << " x22 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[22]);
9771 outs() << " x23 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[23]) << "\n";
9772 outs() << "\t x24 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[24]);
9773 outs() << " x25 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[25]);
9774 outs() << " x26 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[26]) << "\n";
9775 outs() << "\t x27 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[27]);
9776 outs() << " x28 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[28]);
9777 outs() << " fp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.fp) << "\n";
9778 outs() << "\t lr " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.lr);
9779 outs() << " sp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.sp);
9780 outs() << " pc " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.pc) << "\n";
9781 outs() << "\t cpsr " << format(Fmt: "0x%08" PRIx32, Vals: cpu64.cpsr) << "\n";
9782}
9783
9784static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9785 bool isLittleEndian, uint32_t cputype) {
9786 if (t.cmd == MachO::LC_THREAD)
9787 outs() << " cmd LC_THREAD\n";
9788 else if (t.cmd == MachO::LC_UNIXTHREAD)
9789 outs() << " cmd LC_UNIXTHREAD\n";
9790 else
9791 outs() << " cmd " << t.cmd << " (unknown)\n";
9792 outs() << " cmdsize " << t.cmdsize;
9793 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9794 outs() << " Incorrect size\n";
9795 else
9796 outs() << "\n";
9797
9798 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9799 const char *end = Ptr + t.cmdsize;
9800 uint32_t flavor, count, left;
9801 if (cputype == MachO::CPU_TYPE_I386) {
9802 while (begin < end) {
9803 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9804 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9805 begin += sizeof(uint32_t);
9806 } else {
9807 flavor = 0;
9808 begin = end;
9809 }
9810 if (isLittleEndian != sys::IsLittleEndianHost)
9811 sys::swapByteOrder(Value&: flavor);
9812 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9813 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9814 begin += sizeof(uint32_t);
9815 } else {
9816 count = 0;
9817 begin = end;
9818 }
9819 if (isLittleEndian != sys::IsLittleEndianHost)
9820 sys::swapByteOrder(Value&: count);
9821 if (flavor == MachO::x86_THREAD_STATE32) {
9822 outs() << " flavor i386_THREAD_STATE\n";
9823 if (count == MachO::x86_THREAD_STATE32_COUNT)
9824 outs() << " count i386_THREAD_STATE_COUNT\n";
9825 else
9826 outs() << " count " << count
9827 << " (not x86_THREAD_STATE32_COUNT)\n";
9828 MachO::x86_thread_state32_t cpu32;
9829 left = end - begin;
9830 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9831 memcpy(dest: &cpu32, src: begin, n: sizeof(MachO::x86_thread_state32_t));
9832 begin += sizeof(MachO::x86_thread_state32_t);
9833 } else {
9834 memset(s: &cpu32, c: '\0', n: sizeof(MachO::x86_thread_state32_t));
9835 memcpy(dest: &cpu32, src: begin, n: left);
9836 begin += left;
9837 }
9838 if (isLittleEndian != sys::IsLittleEndianHost)
9839 swapStruct(x&: cpu32);
9840 Print_x86_thread_state32_t(cpu32);
9841 } else if (flavor == MachO::x86_THREAD_STATE) {
9842 outs() << " flavor x86_THREAD_STATE\n";
9843 if (count == MachO::x86_THREAD_STATE_COUNT)
9844 outs() << " count x86_THREAD_STATE_COUNT\n";
9845 else
9846 outs() << " count " << count
9847 << " (not x86_THREAD_STATE_COUNT)\n";
9848 struct MachO::x86_thread_state_t ts;
9849 left = end - begin;
9850 if (left >= sizeof(MachO::x86_thread_state_t)) {
9851 memcpy(dest: &ts, src: begin, n: sizeof(MachO::x86_thread_state_t));
9852 begin += sizeof(MachO::x86_thread_state_t);
9853 } else {
9854 memset(s: &ts, c: '\0', n: sizeof(MachO::x86_thread_state_t));
9855 memcpy(dest: &ts, src: begin, n: left);
9856 begin += left;
9857 }
9858 if (isLittleEndian != sys::IsLittleEndianHost)
9859 swapStruct(x&: ts);
9860 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9861 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9862 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9863 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9864 else
9865 outs() << "tsh.count " << ts.tsh.count
9866 << " (not x86_THREAD_STATE32_COUNT\n";
9867 Print_x86_thread_state32_t(cpu32&: ts.uts.ts32);
9868 } else {
9869 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9870 << ts.tsh.count << "\n";
9871 }
9872 } else {
9873 outs() << " flavor " << flavor << " (unknown)\n";
9874 outs() << " count " << count << "\n";
9875 outs() << " state (unknown)\n";
9876 begin += count * sizeof(uint32_t);
9877 }
9878 }
9879 } else if (cputype == MachO::CPU_TYPE_X86_64) {
9880 while (begin < end) {
9881 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9882 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9883 begin += sizeof(uint32_t);
9884 } else {
9885 flavor = 0;
9886 begin = end;
9887 }
9888 if (isLittleEndian != sys::IsLittleEndianHost)
9889 sys::swapByteOrder(Value&: flavor);
9890 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9891 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9892 begin += sizeof(uint32_t);
9893 } else {
9894 count = 0;
9895 begin = end;
9896 }
9897 if (isLittleEndian != sys::IsLittleEndianHost)
9898 sys::swapByteOrder(Value&: count);
9899 if (flavor == MachO::x86_THREAD_STATE64) {
9900 outs() << " flavor x86_THREAD_STATE64\n";
9901 if (count == MachO::x86_THREAD_STATE64_COUNT)
9902 outs() << " count x86_THREAD_STATE64_COUNT\n";
9903 else
9904 outs() << " count " << count
9905 << " (not x86_THREAD_STATE64_COUNT)\n";
9906 MachO::x86_thread_state64_t cpu64;
9907 left = end - begin;
9908 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9909 memcpy(dest: &cpu64, src: begin, n: sizeof(MachO::x86_thread_state64_t));
9910 begin += sizeof(MachO::x86_thread_state64_t);
9911 } else {
9912 memset(s: &cpu64, c: '\0', n: sizeof(MachO::x86_thread_state64_t));
9913 memcpy(dest: &cpu64, src: begin, n: left);
9914 begin += left;
9915 }
9916 if (isLittleEndian != sys::IsLittleEndianHost)
9917 swapStruct(x&: cpu64);
9918 Print_x86_thread_state64_t(cpu64);
9919 } else if (flavor == MachO::x86_THREAD_STATE) {
9920 outs() << " flavor x86_THREAD_STATE\n";
9921 if (count == MachO::x86_THREAD_STATE_COUNT)
9922 outs() << " count x86_THREAD_STATE_COUNT\n";
9923 else
9924 outs() << " count " << count
9925 << " (not x86_THREAD_STATE_COUNT)\n";
9926 struct MachO::x86_thread_state_t ts;
9927 left = end - begin;
9928 if (left >= sizeof(MachO::x86_thread_state_t)) {
9929 memcpy(dest: &ts, src: begin, n: sizeof(MachO::x86_thread_state_t));
9930 begin += sizeof(MachO::x86_thread_state_t);
9931 } else {
9932 memset(s: &ts, c: '\0', n: sizeof(MachO::x86_thread_state_t));
9933 memcpy(dest: &ts, src: begin, n: left);
9934 begin += left;
9935 }
9936 if (isLittleEndian != sys::IsLittleEndianHost)
9937 swapStruct(x&: ts);
9938 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9939 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9940 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9941 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9942 else
9943 outs() << "tsh.count " << ts.tsh.count
9944 << " (not x86_THREAD_STATE64_COUNT\n";
9945 Print_x86_thread_state64_t(cpu64&: ts.uts.ts64);
9946 } else {
9947 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9948 << ts.tsh.count << "\n";
9949 }
9950 } else if (flavor == MachO::x86_FLOAT_STATE) {
9951 outs() << " flavor x86_FLOAT_STATE\n";
9952 if (count == MachO::x86_FLOAT_STATE_COUNT)
9953 outs() << " count x86_FLOAT_STATE_COUNT\n";
9954 else
9955 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9956 struct MachO::x86_float_state_t fs;
9957 left = end - begin;
9958 if (left >= sizeof(MachO::x86_float_state_t)) {
9959 memcpy(dest: &fs, src: begin, n: sizeof(MachO::x86_float_state_t));
9960 begin += sizeof(MachO::x86_float_state_t);
9961 } else {
9962 memset(s: &fs, c: '\0', n: sizeof(MachO::x86_float_state_t));
9963 memcpy(dest: &fs, src: begin, n: left);
9964 begin += left;
9965 }
9966 if (isLittleEndian != sys::IsLittleEndianHost)
9967 swapStruct(x&: fs);
9968 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9969 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
9970 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9971 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9972 else
9973 outs() << "fsh.count " << fs.fsh.count
9974 << " (not x86_FLOAT_STATE64_COUNT\n";
9975 Print_x86_float_state_t(fpu&: fs.ufs.fs64);
9976 } else {
9977 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9978 << fs.fsh.count << "\n";
9979 }
9980 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9981 outs() << " flavor x86_EXCEPTION_STATE\n";
9982 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9983 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9984 else
9985 outs() << " count " << count
9986 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9987 struct MachO::x86_exception_state_t es;
9988 left = end - begin;
9989 if (left >= sizeof(MachO::x86_exception_state_t)) {
9990 memcpy(dest: &es, src: begin, n: sizeof(MachO::x86_exception_state_t));
9991 begin += sizeof(MachO::x86_exception_state_t);
9992 } else {
9993 memset(s: &es, c: '\0', n: sizeof(MachO::x86_exception_state_t));
9994 memcpy(dest: &es, src: begin, n: left);
9995 begin += left;
9996 }
9997 if (isLittleEndian != sys::IsLittleEndianHost)
9998 swapStruct(x&: es);
9999 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
10000 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
10001 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
10002 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
10003 else
10004 outs() << "\t esh.count " << es.esh.count
10005 << " (not x86_EXCEPTION_STATE64_COUNT\n";
10006 Print_x86_exception_state_t(exc64&: es.ues.es64);
10007 } else {
10008 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
10009 << es.esh.count << "\n";
10010 }
10011 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
10012 outs() << " flavor x86_EXCEPTION_STATE64\n";
10013 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
10014 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
10015 else
10016 outs() << " count " << count
10017 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
10018 struct MachO::x86_exception_state64_t es64;
10019 left = end - begin;
10020 if (left >= sizeof(MachO::x86_exception_state64_t)) {
10021 memcpy(dest: &es64, src: begin, n: sizeof(MachO::x86_exception_state64_t));
10022 begin += sizeof(MachO::x86_exception_state64_t);
10023 } else {
10024 memset(s: &es64, c: '\0', n: sizeof(MachO::x86_exception_state64_t));
10025 memcpy(dest: &es64, src: begin, n: left);
10026 begin += left;
10027 }
10028 if (isLittleEndian != sys::IsLittleEndianHost)
10029 swapStruct(x&: es64);
10030 Print_x86_exception_state_t(exc64&: es64);
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_ARM) {
10039 while (begin < end) {
10040 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10041 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
10042 begin += sizeof(uint32_t);
10043 } else {
10044 flavor = 0;
10045 begin = end;
10046 }
10047 if (isLittleEndian != sys::IsLittleEndianHost)
10048 sys::swapByteOrder(Value&: flavor);
10049 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10050 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10051 begin += sizeof(uint32_t);
10052 } else {
10053 count = 0;
10054 begin = end;
10055 }
10056 if (isLittleEndian != sys::IsLittleEndianHost)
10057 sys::swapByteOrder(Value&: count);
10058 if (flavor == MachO::ARM_THREAD_STATE) {
10059 outs() << " flavor ARM_THREAD_STATE\n";
10060 if (count == MachO::ARM_THREAD_STATE_COUNT)
10061 outs() << " count ARM_THREAD_STATE_COUNT\n";
10062 else
10063 outs() << " count " << count
10064 << " (not ARM_THREAD_STATE_COUNT)\n";
10065 MachO::arm_thread_state32_t cpu32;
10066 left = end - begin;
10067 if (left >= sizeof(MachO::arm_thread_state32_t)) {
10068 memcpy(dest: &cpu32, src: begin, n: sizeof(MachO::arm_thread_state32_t));
10069 begin += sizeof(MachO::arm_thread_state32_t);
10070 } else {
10071 memset(s: &cpu32, c: '\0', n: sizeof(MachO::arm_thread_state32_t));
10072 memcpy(dest: &cpu32, src: begin, n: left);
10073 begin += left;
10074 }
10075 if (isLittleEndian != sys::IsLittleEndianHost)
10076 swapStruct(x&: cpu32);
10077 Print_arm_thread_state32_t(cpu32);
10078 } else {
10079 outs() << " flavor " << flavor << " (unknown)\n";
10080 outs() << " count " << count << "\n";
10081 outs() << " state (unknown)\n";
10082 begin += count * sizeof(uint32_t);
10083 }
10084 }
10085 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
10086 cputype == MachO::CPU_TYPE_ARM64_32) {
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 if (flavor == MachO::ARM_THREAD_STATE64) {
10107 outs() << " flavor ARM_THREAD_STATE64\n";
10108 if (count == MachO::ARM_THREAD_STATE64_COUNT)
10109 outs() << " count ARM_THREAD_STATE64_COUNT\n";
10110 else
10111 outs() << " count " << count
10112 << " (not ARM_THREAD_STATE64_COUNT)\n";
10113 MachO::arm_thread_state64_t cpu64;
10114 left = end - begin;
10115 if (left >= sizeof(MachO::arm_thread_state64_t)) {
10116 memcpy(dest: &cpu64, src: begin, n: sizeof(MachO::arm_thread_state64_t));
10117 begin += sizeof(MachO::arm_thread_state64_t);
10118 } else {
10119 memset(s: &cpu64, c: '\0', n: sizeof(MachO::arm_thread_state64_t));
10120 memcpy(dest: &cpu64, src: begin, n: left);
10121 begin += left;
10122 }
10123 if (isLittleEndian != sys::IsLittleEndianHost)
10124 swapStruct(x&: cpu64);
10125 Print_arm_thread_state64_t(cpu64);
10126 } else {
10127 outs() << " flavor " << flavor << " (unknown)\n";
10128 outs() << " count " << count << "\n";
10129 outs() << " state (unknown)\n";
10130 begin += count * sizeof(uint32_t);
10131 }
10132 }
10133 } else {
10134 while (begin < end) {
10135 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10136 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
10137 begin += sizeof(uint32_t);
10138 } else {
10139 flavor = 0;
10140 begin = end;
10141 }
10142 if (isLittleEndian != sys::IsLittleEndianHost)
10143 sys::swapByteOrder(Value&: flavor);
10144 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10145 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10146 begin += sizeof(uint32_t);
10147 } else {
10148 count = 0;
10149 begin = end;
10150 }
10151 if (isLittleEndian != sys::IsLittleEndianHost)
10152 sys::swapByteOrder(Value&: count);
10153 outs() << " flavor " << flavor << "\n";
10154 outs() << " count " << count << "\n";
10155 outs() << " state (Unknown cputype/cpusubtype)\n";
10156 begin += count * sizeof(uint32_t);
10157 }
10158 }
10159}
10160
10161static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10162 if (dl.cmd == MachO::LC_ID_DYLIB)
10163 outs() << " cmd LC_ID_DYLIB\n";
10164 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
10165 outs() << " cmd LC_LOAD_DYLIB\n";
10166 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
10167 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
10168 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
10169 outs() << " cmd LC_REEXPORT_DYLIB\n";
10170 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
10171 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
10172 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
10173 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
10174 else
10175 outs() << " cmd " << dl.cmd << " (unknown)\n";
10176 outs() << " cmdsize " << dl.cmdsize;
10177 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
10178 outs() << " Incorrect size\n";
10179 else
10180 outs() << "\n";
10181 if (dl.dylib.name < dl.cmdsize) {
10182 const char *P = Ptr + dl.dylib.name;
10183 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
10184 } else {
10185 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
10186 }
10187 outs() << " time stamp " << dl.dylib.timestamp << " ";
10188 time_t t = dl.dylib.timestamp;
10189 outs() << ctime(timer: &t);
10190 outs() << " current version ";
10191 if (dl.dylib.current_version == 0xffffffff)
10192 outs() << "n/a\n";
10193 else
10194 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10195 << ((dl.dylib.current_version >> 8) & 0xff) << "."
10196 << (dl.dylib.current_version & 0xff) << "\n";
10197 outs() << "compatibility version ";
10198 if (dl.dylib.compatibility_version == 0xffffffff)
10199 outs() << "n/a\n";
10200 else
10201 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10202 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10203 << (dl.dylib.compatibility_version & 0xff) << "\n";
10204}
10205
10206static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10207 uint32_t object_size) {
10208 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10209 outs() << " cmd LC_CODE_SIGNATURE\n";
10210 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10211 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
10212 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10213 outs() << " cmd LC_FUNCTION_STARTS\n";
10214 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10215 outs() << " cmd LC_DATA_IN_CODE\n";
10216 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10217 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
10218 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10219 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
10220 else if (ld.cmd == MachO::LC_DYLD_EXPORTS_TRIE)
10221 outs() << " cmd LC_DYLD_EXPORTS_TRIE\n";
10222 else if (ld.cmd == MachO::LC_DYLD_CHAINED_FIXUPS)
10223 outs() << " cmd LC_DYLD_CHAINED_FIXUPS\n";
10224 else if (ld.cmd == MachO::LC_ATOM_INFO)
10225 outs() << " cmd LC_ATOM_INFO\n";
10226 else
10227 outs() << " cmd " << ld.cmd << " (?)\n";
10228 outs() << " cmdsize " << ld.cmdsize;
10229 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10230 outs() << " Incorrect size\n";
10231 else
10232 outs() << "\n";
10233 outs() << " dataoff " << ld.dataoff;
10234 if (ld.dataoff > object_size)
10235 outs() << " (past end of file)\n";
10236 else
10237 outs() << "\n";
10238 outs() << " datasize " << ld.datasize;
10239 uint64_t big_size = ld.dataoff;
10240 big_size += ld.datasize;
10241 if (big_size > object_size)
10242 outs() << " (past end of file)\n";
10243 else
10244 outs() << "\n";
10245}
10246
10247static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10248 uint32_t cputype, bool verbose) {
10249 StringRef Buf = Obj->getData();
10250 unsigned Index = 0;
10251 for (const auto &Command : Obj->load_commands()) {
10252 outs() << "Load command " << Index++ << "\n";
10253 if (Command.C.cmd == MachO::LC_SEGMENT) {
10254 MachO::segment_command SLC = Obj->getSegmentLoadCommand(L: Command);
10255 const char *sg_segname = SLC.segname;
10256 PrintSegmentCommand(cmd: SLC.cmd, cmdsize: SLC.cmdsize, SegName: SLC.segname, vmaddr: SLC.vmaddr,
10257 vmsize: SLC.vmsize, fileoff: SLC.fileoff, filesize: SLC.filesize, maxprot: SLC.maxprot,
10258 initprot: SLC.initprot, nsects: SLC.nsects, flags: SLC.flags, object_size: Buf.size(),
10259 verbose);
10260 for (unsigned j = 0; j < SLC.nsects; j++) {
10261 MachO::section S = Obj->getSection(L: Command, Index: j);
10262 PrintSection(sectname: S.sectname, segname: S.segname, addr: S.addr, size: S.size, offset: S.offset, align: S.align,
10263 reloff: S.reloff, nreloc: S.nreloc, flags: S.flags, reserved1: S.reserved1, reserved2: S.reserved2,
10264 cmd: SLC.cmd, sg_segname, filetype, object_size: Buf.size(), verbose);
10265 }
10266 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10267 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(L: Command);
10268 const char *sg_segname = SLC_64.segname;
10269 PrintSegmentCommand(cmd: SLC_64.cmd, cmdsize: SLC_64.cmdsize, SegName: SLC_64.segname,
10270 vmaddr: SLC_64.vmaddr, vmsize: SLC_64.vmsize, fileoff: SLC_64.fileoff,
10271 filesize: SLC_64.filesize, maxprot: SLC_64.maxprot, initprot: SLC_64.initprot,
10272 nsects: SLC_64.nsects, flags: SLC_64.flags, object_size: Buf.size(), verbose);
10273 for (unsigned j = 0; j < SLC_64.nsects; j++) {
10274 MachO::section_64 S_64 = Obj->getSection64(L: Command, Index: j);
10275 PrintSection(sectname: S_64.sectname, segname: S_64.segname, addr: S_64.addr, size: S_64.size,
10276 offset: S_64.offset, align: S_64.align, reloff: S_64.reloff, nreloc: S_64.nreloc,
10277 flags: S_64.flags, reserved1: S_64.reserved1, reserved2: S_64.reserved2, cmd: SLC_64.cmd,
10278 sg_segname, filetype, object_size: Buf.size(), verbose);
10279 }
10280 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10281 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10282 PrintSymtabLoadCommand(st: Symtab, Is64Bit: Obj->is64Bit(), object_size: Buf.size());
10283 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10284 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10285 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10286 PrintDysymtabLoadCommand(dyst: Dysymtab, nsyms: Symtab.nsyms, object_size: Buf.size(),
10287 Is64Bit: Obj->is64Bit());
10288 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10289 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10290 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(L: Command);
10291 PrintDyldInfoLoadCommand(dc: DyldInfo, object_size: Buf.size());
10292 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10293 Command.C.cmd == MachO::LC_ID_DYLINKER ||
10294 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10295 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(L: Command);
10296 PrintDyldLoadCommand(dyld: Dyld, Ptr: Command.Ptr);
10297 } else if (Command.C.cmd == MachO::LC_UUID) {
10298 MachO::uuid_command Uuid = Obj->getUuidCommand(L: Command);
10299 PrintUuidLoadCommand(uuid: Uuid);
10300 } else if (Command.C.cmd == MachO::LC_RPATH) {
10301 MachO::rpath_command Rpath = Obj->getRpathCommand(L: Command);
10302 PrintRpathLoadCommand(rpath: Rpath, Ptr: Command.Ptr);
10303 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10304 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10305 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10306 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10307 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(L: Command);
10308 PrintVersionMinLoadCommand(vd: Vd);
10309 } else if (Command.C.cmd == MachO::LC_NOTE) {
10310 MachO::note_command Nt = Obj->getNoteLoadCommand(L: Command);
10311 PrintNoteLoadCommand(Nt);
10312 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10313 MachO::build_version_command Bv =
10314 Obj->getBuildVersionLoadCommand(L: Command);
10315 PrintBuildVersionLoadCommand(obj: Obj, bd: Bv, verbose);
10316 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10317 MachO::source_version_command Sd = Obj->getSourceVersionCommand(L: Command);
10318 PrintSourceVersionCommand(sd: Sd);
10319 } else if (Command.C.cmd == MachO::LC_MAIN) {
10320 MachO::entry_point_command Ep = Obj->getEntryPointCommand(L: Command);
10321 PrintEntryPointCommand(ep: Ep);
10322 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10323 MachO::encryption_info_command Ei =
10324 Obj->getEncryptionInfoCommand(L: Command);
10325 PrintEncryptionInfoCommand(ec: Ei, object_size: Buf.size());
10326 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10327 MachO::encryption_info_command_64 Ei =
10328 Obj->getEncryptionInfoCommand64(L: Command);
10329 PrintEncryptionInfoCommand64(ec: Ei, object_size: Buf.size());
10330 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10331 MachO::linker_option_command Lo =
10332 Obj->getLinkerOptionLoadCommand(L: Command);
10333 PrintLinkerOptionCommand(lo: Lo, Ptr: Command.Ptr);
10334 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10335 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(L: Command);
10336 PrintSubFrameworkCommand(sub: Sf, Ptr: Command.Ptr);
10337 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10338 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(L: Command);
10339 PrintSubUmbrellaCommand(sub: Sf, Ptr: Command.Ptr);
10340 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10341 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(L: Command);
10342 PrintSubLibraryCommand(sub: Sl, Ptr: Command.Ptr);
10343 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10344 MachO::sub_client_command Sc = Obj->getSubClientCommand(L: Command);
10345 PrintSubClientCommand(sub: Sc, Ptr: Command.Ptr);
10346 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10347 MachO::routines_command Rc = Obj->getRoutinesCommand(L: Command);
10348 PrintRoutinesCommand(r: Rc);
10349 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10350 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(L: Command);
10351 PrintRoutinesCommand64(r: Rc);
10352 } else if (Command.C.cmd == MachO::LC_THREAD ||
10353 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10354 MachO::thread_command Tc = Obj->getThreadCommand(L: Command);
10355 PrintThreadCommand(t: Tc, Ptr: Command.Ptr, isLittleEndian: Obj->isLittleEndian(), cputype);
10356 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10357 Command.C.cmd == MachO::LC_ID_DYLIB ||
10358 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10359 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10360 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10361 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10362 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(L: Command);
10363 PrintDylibCommand(dl: Dl, Ptr: Command.Ptr);
10364 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10365 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10366 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10367 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10368 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10369 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT ||
10370 Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE ||
10371 Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS ||
10372 Command.C.cmd == MachO::LC_ATOM_INFO) {
10373 MachO::linkedit_data_command Ld =
10374 Obj->getLinkeditDataLoadCommand(L: Command);
10375 PrintLinkEditDataCommand(ld: Ld, object_size: Buf.size());
10376 } else {
10377 outs() << " cmd ?(" << format(Fmt: "0x%08" PRIx32, Vals: Command.C.cmd)
10378 << ")\n";
10379 outs() << " cmdsize " << Command.C.cmdsize << "\n";
10380 // TODO: get and print the raw bytes of the load command.
10381 }
10382 // TODO: print all the other kinds of load commands.
10383 }
10384}
10385
10386static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10387 if (Obj->is64Bit()) {
10388 MachO::mach_header_64 H_64;
10389 H_64 = Obj->getHeader64();
10390 PrintMachHeader(magic: H_64.magic, cputype: H_64.cputype, cpusubtype: H_64.cpusubtype, filetype: H_64.filetype,
10391 ncmds: H_64.ncmds, sizeofcmds: H_64.sizeofcmds, flags: H_64.flags, verbose);
10392 } else {
10393 MachO::mach_header H;
10394 H = Obj->getHeader();
10395 PrintMachHeader(magic: H.magic, cputype: H.cputype, cpusubtype: H.cpusubtype, filetype: H.filetype, ncmds: H.ncmds,
10396 sizeofcmds: H.sizeofcmds, flags: H.flags, verbose);
10397 }
10398}
10399
10400void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10401 const MachOObjectFile *file = cast<const MachOObjectFile>(Val: Obj);
10402 PrintMachHeader(Obj: file, verbose: Verbose);
10403}
10404
10405void MachODumper::printPrivateHeaders() {
10406 printMachOFileHeader(Obj: &Obj);
10407 if (!FirstPrivateHeader)
10408 printMachOLoadCommands(O: &Obj);
10409}
10410
10411void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10412 const MachOObjectFile *file = cast<const MachOObjectFile>(Val: Obj);
10413 uint32_t filetype = 0;
10414 uint32_t cputype = 0;
10415 if (file->is64Bit()) {
10416 MachO::mach_header_64 H_64;
10417 H_64 = file->getHeader64();
10418 filetype = H_64.filetype;
10419 cputype = H_64.cputype;
10420 } else {
10421 MachO::mach_header H;
10422 H = file->getHeader();
10423 filetype = H.filetype;
10424 cputype = H.cputype;
10425 }
10426 PrintLoadCommands(Obj: file, filetype, cputype, verbose: Verbose);
10427}
10428
10429//===----------------------------------------------------------------------===//
10430// export trie dumping
10431//===----------------------------------------------------------------------===//
10432
10433static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10434 uint64_t BaseSegmentAddress = 0;
10435 for (const auto &Command : Obj->load_commands()) {
10436 if (Command.C.cmd == MachO::LC_SEGMENT) {
10437 MachO::segment_command Seg = Obj->getSegmentLoadCommand(L: Command);
10438 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10439 BaseSegmentAddress = Seg.vmaddr;
10440 break;
10441 }
10442 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10443 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(L: Command);
10444 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10445 BaseSegmentAddress = Seg.vmaddr;
10446 break;
10447 }
10448 }
10449 }
10450 Error Err = Error::success();
10451 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10452 uint64_t Flags = Entry.flags();
10453 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10454 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10455 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10456 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10457 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10458 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10459 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10460 if (ReExport)
10461 outs() << "[re-export] ";
10462 else
10463 outs() << format(Fmt: "0x%08llX ",
10464 Vals: Entry.address() + BaseSegmentAddress);
10465 outs() << Entry.name();
10466 if (WeakDef || ThreadLocal || Resolver || Abs) {
10467 ListSeparator LS;
10468 outs() << " [";
10469 if (WeakDef)
10470 outs() << LS << "weak_def";
10471 if (ThreadLocal)
10472 outs() << LS << "per-thread";
10473 if (Abs)
10474 outs() << LS << "absolute";
10475 if (Resolver)
10476 outs() << LS << format(Fmt: "resolver=0x%08llX", Vals: Entry.other());
10477 outs() << "]";
10478 }
10479 if (ReExport) {
10480 StringRef DylibName = "unknown";
10481 int Ordinal = Entry.other() - 1;
10482 Obj->getLibraryShortNameByIndex(Index: Ordinal, DylibName);
10483 if (Entry.otherName().empty())
10484 outs() << " (from " << DylibName << ")";
10485 else
10486 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10487 }
10488 outs() << "\n";
10489 }
10490 if (Err)
10491 reportError(E: std::move(Err), FileName: Obj->getFileName());
10492}
10493
10494//===----------------------------------------------------------------------===//
10495// rebase table dumping
10496//===----------------------------------------------------------------------===//
10497
10498static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10499 outs() << "segment section address type\n";
10500 Error Err = Error::success();
10501 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10502 StringRef SegmentName = Entry.segmentName();
10503 StringRef SectionName = Entry.sectionName();
10504 uint64_t Address = Entry.address();
10505
10506 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
10507 outs() << format(Fmt: "%-8s %-18s 0x%08" PRIX64 " %s\n",
10508 Vals: SegmentName.str().c_str(), Vals: SectionName.str().c_str(),
10509 Vals: Address, Vals: Entry.typeName().str().c_str());
10510 }
10511 if (Err)
10512 reportError(E: std::move(Err), FileName: Obj->getFileName());
10513}
10514
10515static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10516 StringRef DylibName;
10517 switch (Ordinal) {
10518 case MachO::BIND_SPECIAL_DYLIB_SELF:
10519 return "this-image";
10520 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10521 return "main-executable";
10522 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10523 return "flat-namespace";
10524 case MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP:
10525 return "weak";
10526 default:
10527 if (Ordinal > 0) {
10528 std::error_code EC =
10529 Obj->getLibraryShortNameByIndex(Index: Ordinal - 1, DylibName);
10530 if (EC)
10531 return "<<bad library ordinal>>";
10532 return DylibName;
10533 }
10534 }
10535 return "<<unknown special ordinal>>";
10536}
10537
10538//===----------------------------------------------------------------------===//
10539// bind table dumping
10540//===----------------------------------------------------------------------===//
10541
10542static void printMachOBindTable(object::MachOObjectFile *Obj) {
10543 // Build table of sections so names can used in final output.
10544 outs() << "segment section address type "
10545 "addend dylib symbol\n";
10546 Error Err = Error::success();
10547 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10548 StringRef SegmentName = Entry.segmentName();
10549 StringRef SectionName = Entry.sectionName();
10550 uint64_t Address = Entry.address();
10551
10552 // Table lines look like:
10553 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
10554 StringRef Attr;
10555 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10556 Attr = " (weak_import)";
10557 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10558 << left_justify(Str: SectionName, Width: 18) << " "
10559 << format_hex(N: Address, Width: 10, Upper: true) << " "
10560 << left_justify(Str: Entry.typeName(), Width: 8) << " "
10561 << format_decimal(N: Entry.addend(), Width: 8) << " "
10562 << left_justify(Str: ordinalName(Obj, Ordinal: Entry.ordinal()), Width: 16) << " "
10563 << Entry.symbolName() << Attr << "\n";
10564 }
10565 if (Err)
10566 reportError(E: std::move(Err), FileName: Obj->getFileName());
10567}
10568
10569//===----------------------------------------------------------------------===//
10570// lazy bind table dumping
10571//===----------------------------------------------------------------------===//
10572
10573static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10574 outs() << "segment section address "
10575 "dylib symbol\n";
10576 Error Err = Error::success();
10577 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10578 StringRef SegmentName = Entry.segmentName();
10579 StringRef SectionName = Entry.sectionName();
10580 uint64_t Address = Entry.address();
10581
10582 // Table lines look like:
10583 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
10584 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10585 << left_justify(Str: SectionName, Width: 18) << " "
10586 << format_hex(N: Address, Width: 10, Upper: true) << " "
10587 << left_justify(Str: ordinalName(Obj, Ordinal: Entry.ordinal()), Width: 16) << " "
10588 << Entry.symbolName() << "\n";
10589 }
10590 if (Err)
10591 reportError(E: std::move(Err), FileName: Obj->getFileName());
10592}
10593
10594//===----------------------------------------------------------------------===//
10595// weak bind table dumping
10596//===----------------------------------------------------------------------===//
10597
10598static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10599 outs() << "segment section address "
10600 "type addend symbol\n";
10601 Error Err = Error::success();
10602 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10603 // Strong symbols don't have a location to update.
10604 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10605 outs() << " strong "
10606 << Entry.symbolName() << "\n";
10607 continue;
10608 }
10609 StringRef SegmentName = Entry.segmentName();
10610 StringRef SectionName = Entry.sectionName();
10611 uint64_t Address = Entry.address();
10612
10613 // Table lines look like:
10614 // __DATA __data 0x00001000 pointer 0 _foo
10615 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10616 << left_justify(Str: SectionName, Width: 18) << " "
10617 << format_hex(N: Address, Width: 10, Upper: true) << " "
10618 << left_justify(Str: Entry.typeName(), Width: 8) << " "
10619 << format_decimal(N: Entry.addend(), Width: 8) << " " << Entry.symbolName()
10620 << "\n";
10621 }
10622 if (Err)
10623 reportError(E: std::move(Err), FileName: Obj->getFileName());
10624}
10625
10626// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10627// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10628// information for that address. If the address is found its binding symbol
10629// name is returned. If not nullptr is returned.
10630static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10631 struct DisassembleInfo *info) {
10632 if (info->bindtable == nullptr) {
10633 info->bindtable = std::make_unique<SymbolAddressMap>();
10634 Error Err = Error::success();
10635 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10636 uint64_t Address = Entry.address();
10637 StringRef name = Entry.symbolName();
10638 if (!name.empty())
10639 (*info->bindtable)[Address] = name;
10640 }
10641 if (Err)
10642 reportError(E: std::move(Err), FileName: info->O->getFileName());
10643 }
10644 auto name = info->bindtable->lookup(Val: ReferenceValue);
10645 return !name.empty() ? name.data() : nullptr;
10646}
10647
10648void objdump::printLazyBindTable(ObjectFile *o) {
10649 outs() << "\nLazy bind table:\n";
10650 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10651 printMachOLazyBindTable(Obj: MachO);
10652 else
10653 WithColor::error()
10654 << "This operation is only currently supported "
10655 "for Mach-O executable files.\n";
10656}
10657
10658void objdump::printWeakBindTable(ObjectFile *o) {
10659 outs() << "\nWeak bind table:\n";
10660 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10661 printMachOWeakBindTable(Obj: MachO);
10662 else
10663 WithColor::error()
10664 << "This operation is only currently supported "
10665 "for Mach-O executable files.\n";
10666}
10667
10668void objdump::printExportsTrie(const ObjectFile *o) {
10669 outs() << "\nExports trie:\n";
10670 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10671 printMachOExportsTrie(Obj: MachO);
10672 else
10673 WithColor::error()
10674 << "This operation is only currently supported "
10675 "for Mach-O executable files.\n";
10676}
10677
10678void objdump::printRebaseTable(ObjectFile *o) {
10679 outs() << "\nRebase table:\n";
10680 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10681 printMachORebaseTable(Obj: MachO);
10682 else
10683 WithColor::error()
10684 << "This operation is only currently supported "
10685 "for Mach-O executable files.\n";
10686}
10687
10688void objdump::printBindTable(ObjectFile *o) {
10689 outs() << "\nBind table:\n";
10690 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10691 printMachOBindTable(Obj: MachO);
10692 else
10693 WithColor::error()
10694 << "This operation is only currently supported "
10695 "for Mach-O executable files.\n";
10696}
10697