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::SymbolicOperands;
84static std::vector<std::string> ArchFlags;
85
86static bool ArchAll = false;
87static std::string ThumbTripleName;
88
89static StringRef ordinalName(const object::MachOObjectFile *, int);
90
91void objdump::parseMachOOptions(const llvm::opt::InputArgList &InputArgs) {
92 FirstPrivateHeader = InputArgs.hasArg(Ids: OBJDUMP_private_header);
93 ExportsTrie = InputArgs.hasArg(Ids: OBJDUMP_exports_trie);
94 Rebase = InputArgs.hasArg(Ids: OBJDUMP_rebase);
95 Rpaths = InputArgs.hasArg(Ids: OBJDUMP_rpaths);
96 Bind = InputArgs.hasArg(Ids: OBJDUMP_bind);
97 LazyBind = InputArgs.hasArg(Ids: OBJDUMP_lazy_bind);
98 WeakBind = InputArgs.hasArg(Ids: OBJDUMP_weak_bind);
99 UseDbg = InputArgs.hasArg(Ids: OBJDUMP_g);
100 DSYMFile = InputArgs.getLastArgValue(Id: OBJDUMP_dsym_EQ).str();
101 FullLeadingAddr = InputArgs.hasArg(Ids: OBJDUMP_full_leading_addr);
102 LeadingHeaders = !InputArgs.hasArg(Ids: OBJDUMP_no_leading_headers);
103 UniversalHeaders = InputArgs.hasArg(Ids: OBJDUMP_universal_headers);
104 ArchiveMemberOffsets = InputArgs.hasArg(Ids: OBJDUMP_archive_member_offsets);
105 IndirectSymbols = InputArgs.hasArg(Ids: OBJDUMP_indirect_symbols);
106 DataInCode = InputArgs.hasArg(Ids: OBJDUMP_data_in_code);
107 if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_function_starts_EQ)) {
108 FunctionStartsType = StringSwitch<FunctionStartsMode>(A->getValue())
109 .Case(S: "addrs", Value: FunctionStartsMode::Addrs)
110 .Case(S: "names", Value: FunctionStartsMode::Names)
111 .Case(S: "both", Value: FunctionStartsMode::Both)
112 .Default(Value: FunctionStartsMode::None);
113 if (FunctionStartsType == FunctionStartsMode::None)
114 invalidArgValue(A);
115 }
116 LinkOptHints = InputArgs.hasArg(Ids: OBJDUMP_link_opt_hints);
117 InfoPlist = InputArgs.hasArg(Ids: OBJDUMP_info_plist);
118 ChainedFixups = InputArgs.hasArg(Ids: OBJDUMP_chained_fixups);
119 DyldInfo = InputArgs.hasArg(Ids: OBJDUMP_dyld_info);
120 DylibsUsed = InputArgs.hasArg(Ids: OBJDUMP_dylibs_used);
121 DylibId = InputArgs.hasArg(Ids: OBJDUMP_dylib_id);
122 Verbose = !InputArgs.hasArg(Ids: OBJDUMP_non_verbose);
123 ObjcMetaData = InputArgs.hasArg(Ids: OBJDUMP_objc_meta_data);
124 DisSymName = InputArgs.getLastArgValue(Id: OBJDUMP_dis_symname).str();
125 SymbolicOperands = !InputArgs.hasArg(Ids: OBJDUMP_no_symbolic_operands);
126 ArchFlags = InputArgs.getAllArgValues(Id: OBJDUMP_arch_EQ);
127}
128
129static const Target *GetTarget(const MachOObjectFile *MachOObj,
130 const char **McpuDefault,
131 const Target **ThumbTarget,
132 Triple &ThumbTriple) {
133 // Figure out the target triple.
134 Triple TT(TripleName);
135 if (TripleName.empty()) {
136 TT = MachOObj->getArchTriple(McpuDefault);
137 TripleName = TT.str();
138 }
139
140 if (TT.getArch() == Triple::arm) {
141 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
142 // that support ARM are also capable of Thumb mode.
143 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(Start: 3)).str();
144 ThumbTriple = TT;
145 ThumbTriple.setArchName(ThumbName);
146 ThumbTripleName = ThumbTriple.str();
147 }
148
149 // Get the target specific parser.
150 std::string Error;
151 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple: TT, Error);
152 if (TheTarget && ThumbTripleName.empty())
153 return TheTarget;
154
155 *ThumbTarget = TargetRegistry::lookupTarget(TheTriple: ThumbTriple, Error);
156 if (*ThumbTarget)
157 return TheTarget;
158
159 WithColor::error(OS&: errs(), Prefix: "llvm-objdump") << "unable to get target for '";
160 if (!TheTarget)
161 errs() << TripleName;
162 else
163 errs() << ThumbTripleName;
164 errs() << "', see --version and --triple.\n";
165 return nullptr;
166}
167
168namespace {
169struct SymbolSorter {
170 bool operator()(const SymbolRef &A, const SymbolRef &B) {
171 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
172 if (!ATypeOrErr)
173 reportError(E: ATypeOrErr.takeError(), FileName: A.getObject()->getFileName());
174 SymbolRef::Type AType = *ATypeOrErr;
175 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
176 if (!BTypeOrErr)
177 reportError(E: BTypeOrErr.takeError(), FileName: B.getObject()->getFileName());
178 SymbolRef::Type BType = *BTypeOrErr;
179 uint64_t AAddr =
180 (AType != SymbolRef::ST_Function) ? 0 : cantFail(ValOrErr: A.getValue());
181 uint64_t BAddr =
182 (BType != SymbolRef::ST_Function) ? 0 : cantFail(ValOrErr: B.getValue());
183 return AAddr < BAddr;
184 }
185};
186
187class MachODumper : public Dumper {
188 const object::MachOObjectFile &Obj;
189
190public:
191 MachODumper(const object::MachOObjectFile &O) : Dumper(O), Obj(O) {}
192 void printPrivateHeaders() override;
193};
194} // namespace
195
196std::unique_ptr<Dumper>
197objdump::createMachODumper(const object::MachOObjectFile &Obj) {
198 return std::make_unique<MachODumper>(args: Obj);
199}
200
201// Types for the storted data in code table that is built before disassembly
202// and the predicate function to sort them.
203typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
204typedef std::vector<DiceTableEntry> DiceTable;
205typedef DiceTable::iterator dice_table_iterator;
206
207// This is used to search for a data in code table entry for the PC being
208// disassembled. The j parameter has the PC in j.first. A single data in code
209// table entry can cover many bytes for each of its Kind's. So if the offset,
210// aka the i.first value, of the data in code table entry plus its Length
211// covers the PC being searched for this will return true. If not it will
212// return false.
213static bool compareDiceTableEntries(const DiceTableEntry &i,
214 const DiceTableEntry &j) {
215 uint16_t Length;
216 i.second.getLength(Result&: Length);
217
218 return j.first >= i.first && j.first < i.first + Length;
219}
220
221static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
222 unsigned short Kind) {
223 uint32_t Value, Size = 1;
224
225 switch (Kind) {
226 default:
227 case MachO::DICE_KIND_DATA:
228 if (Length >= 4) {
229 if (ShowRawInsn)
230 dumpBytes(Bytes: ArrayRef(bytes, 4), OS&: outs());
231 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
232 outs() << "\t.long " << Value;
233 Size = 4;
234 } else if (Length >= 2) {
235 if (ShowRawInsn)
236 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
237 Value = bytes[1] << 8 | bytes[0];
238 outs() << "\t.short " << Value;
239 Size = 2;
240 } else {
241 if (ShowRawInsn)
242 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
243 Value = bytes[0];
244 outs() << "\t.byte " << Value;
245 Size = 1;
246 }
247 if (Kind == MachO::DICE_KIND_DATA)
248 outs() << "\t@ KIND_DATA\n";
249 else
250 outs() << "\t@ data in code kind = " << Kind << "\n";
251 break;
252 case MachO::DICE_KIND_JUMP_TABLE8:
253 if (ShowRawInsn)
254 dumpBytes(Bytes: ArrayRef(bytes, 1), OS&: outs());
255 Value = bytes[0];
256 outs() << "\t.byte " << format(Fmt: "%3u", Vals: Value) << "\t@ KIND_JUMP_TABLE8\n";
257 Size = 1;
258 break;
259 case MachO::DICE_KIND_JUMP_TABLE16:
260 if (ShowRawInsn)
261 dumpBytes(Bytes: ArrayRef(bytes, 2), OS&: outs());
262 Value = bytes[1] << 8 | bytes[0];
263 outs() << "\t.short " << format(Fmt: "%5u", Vals: Value & 0xffff)
264 << "\t@ KIND_JUMP_TABLE16\n";
265 Size = 2;
266 break;
267 case MachO::DICE_KIND_JUMP_TABLE32:
268 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
269 if (ShowRawInsn)
270 dumpBytes(Bytes: ArrayRef(bytes, 4), OS&: outs());
271 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
272 outs() << "\t.long " << Value;
273 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
274 outs() << "\t@ KIND_JUMP_TABLE32\n";
275 else
276 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
277 Size = 4;
278 break;
279 }
280 return Size;
281}
282
283static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
284 std::vector<SectionRef> &Sections,
285 std::vector<SymbolRef> &Symbols,
286 SmallVectorImpl<uint64_t> &FoundFns,
287 uint64_t &BaseSegmentAddress) {
288 const StringRef FileName = MachOObj->getFileName();
289 for (const SymbolRef &Symbol : MachOObj->symbols()) {
290 StringRef SymName = unwrapOrError(EO: Symbol.getName(), Args: FileName);
291 if (!SymName.starts_with(Prefix: "ltmp"))
292 Symbols.push_back(x: Symbol);
293 }
294
295 append_range(C&: Sections, R: MachOObj->sections());
296
297 bool BaseSegmentAddressSet = false;
298 for (const auto &Command : MachOObj->load_commands()) {
299 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
300 // We found a function starts segment, parse the addresses for later
301 // consumption.
302 MachO::linkedit_data_command LLC =
303 MachOObj->getLinkeditDataLoadCommand(L: Command);
304
305 MachOObj->ReadULEB128s(Index: LLC.dataoff, Out&: FoundFns);
306 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
307 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(L: Command);
308 StringRef SegName = SLC.segname;
309 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
310 BaseSegmentAddressSet = true;
311 BaseSegmentAddress = SLC.vmaddr;
312 }
313 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
314 MachO::segment_command_64 SLC = MachOObj->getSegment64LoadCommand(L: Command);
315 StringRef SegName = SLC.segname;
316 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
317 BaseSegmentAddressSet = true;
318 BaseSegmentAddress = SLC.vmaddr;
319 }
320 }
321 }
322}
323
324static bool DumpAndSkipDataInCode(uint64_t PC, const uint8_t *bytes,
325 DiceTable &Dices, uint64_t &InstSize) {
326 // Check the data in code table here to see if this is data not an
327 // instruction to be disassembled.
328 DiceTable Dice;
329 Dice.push_back(x: std::make_pair(x&: PC, y: DiceRef()));
330 dice_table_iterator DTI =
331 std::search(first1: Dices.begin(), last1: Dices.end(), first2: Dice.begin(), last2: Dice.end(),
332 predicate: compareDiceTableEntries);
333 if (DTI != Dices.end()) {
334 uint16_t Length;
335 DTI->second.getLength(Result&: Length);
336 uint16_t Kind;
337 DTI->second.getKind(Result&: Kind);
338 InstSize = DumpDataInCode(bytes, Length, Kind);
339 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
340 (PC == (DTI->first + Length - 1)) && (Length & 1))
341 InstSize++;
342 return true;
343 }
344 return false;
345}
346
347static void printRelocationTargetName(const MachOObjectFile *O,
348 const MachO::any_relocation_info &RE,
349 raw_string_ostream &Fmt) {
350 // Target of a scattered relocation is an address. In the interest of
351 // generating pretty output, scan through the symbol table looking for a
352 // symbol that aligns with that address. If we find one, print it.
353 // Otherwise, we just print the hex address of the target.
354 const StringRef FileName = O->getFileName();
355 if (O->isRelocationScattered(RE)) {
356 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
357
358 for (const SymbolRef &Symbol : O->symbols()) {
359 uint64_t Addr = unwrapOrError(EO: Symbol.getAddress(), Args: FileName);
360 if (Addr != Val)
361 continue;
362 Fmt << unwrapOrError(EO: Symbol.getName(), Args: FileName);
363 return;
364 }
365
366 // If we couldn't find a symbol that this relocation refers to, try
367 // to find a section beginning instead.
368 for (const SectionRef &Section : ToolSectionFilter(O: *O)) {
369 uint64_t Addr = Section.getAddress();
370 if (Addr != Val)
371 continue;
372 StringRef NameOrErr = unwrapOrError(EO: Section.getName(), Args: O->getFileName());
373 Fmt << NameOrErr;
374 return;
375 }
376
377 Fmt << format(Fmt: "0x%x", Vals: Val);
378 return;
379 }
380
381 StringRef S;
382 bool isExtern = O->getPlainRelocationExternal(RE);
383 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
384
385 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND &&
386 Triple(O->getArchTriple()).isAArch64()) {
387 Fmt << format(Fmt: "0x%0" PRIx64, Vals: Val);
388 return;
389 }
390
391 if (O->getAnyRelocationType(RE) == MachO::RISCV_RELOC_ADDEND &&
392 O->getArch() == Triple::riscv32) {
393 Fmt << format(Fmt: "0x%0" PRIx64, Vals: Val);
394 return;
395 }
396
397 if (isExtern) {
398 symbol_iterator SI = O->symbol_begin();
399 std::advance(i&: SI, n: Val);
400 S = unwrapOrError(EO: SI->getName(), Args: FileName);
401 } else {
402 section_iterator SI = O->section_begin();
403 // Adjust for the fact that sections are 1-indexed.
404 if (Val == 0) {
405 Fmt << "0 (?,?)";
406 return;
407 }
408 uint32_t I = Val - 1;
409 while (I != 0 && SI != O->section_end()) {
410 --I;
411 std::advance(i&: SI, n: 1);
412 }
413 if (SI == O->section_end()) {
414 Fmt << Val << " (?,?)";
415 } else {
416 if (Expected<StringRef> NameOrErr = SI->getName())
417 S = *NameOrErr;
418 else
419 consumeError(Err: NameOrErr.takeError());
420 }
421 }
422
423 Fmt << S;
424}
425
426Error objdump::getMachORelocationValueString(const MachOObjectFile *Obj,
427 const RelocationRef &RelRef,
428 SmallVectorImpl<char> &Result) {
429 DataRefImpl Rel = RelRef.getRawDataRefImpl();
430 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
431
432 unsigned Arch = Obj->getArch();
433
434 std::string FmtBuf;
435 raw_string_ostream Fmt(FmtBuf);
436 unsigned Type = Obj->getAnyRelocationType(RE);
437 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
438
439 // Determine any addends that should be displayed with the relocation.
440 // These require decoding the relocation type, which is triple-specific.
441
442 // X86_64 has entirely custom relocation types.
443 if (Arch == Triple::x86_64) {
444 switch (Type) {
445 case MachO::X86_64_RELOC_GOT_LOAD:
446 case MachO::X86_64_RELOC_GOT: {
447 printRelocationTargetName(O: Obj, RE, Fmt);
448 Fmt << "@GOT";
449 if (IsPCRel)
450 Fmt << "PCREL";
451 break;
452 }
453 case MachO::X86_64_RELOC_SUBTRACTOR: {
454 DataRefImpl RelNext = Rel;
455 Obj->moveRelocationNext(Rel&: RelNext);
456 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
457
458 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
459 // X86_64_RELOC_UNSIGNED.
460 // NOTE: Scattered relocations don't exist on x86_64.
461 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
462 if (RType != MachO::X86_64_RELOC_UNSIGNED)
463 reportError(File: Obj->getFileName(), Message: "Expected X86_64_RELOC_UNSIGNED after "
464 "X86_64_RELOC_SUBTRACTOR.");
465
466 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
467 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
468 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
469 Fmt << "-";
470 printRelocationTargetName(O: Obj, RE, Fmt);
471 break;
472 }
473 case MachO::X86_64_RELOC_TLV:
474 printRelocationTargetName(O: Obj, RE, Fmt);
475 Fmt << "@TLV";
476 if (IsPCRel)
477 Fmt << "P";
478 break;
479 case MachO::X86_64_RELOC_SIGNED_1:
480 printRelocationTargetName(O: Obj, RE, Fmt);
481 Fmt << "-1";
482 break;
483 case MachO::X86_64_RELOC_SIGNED_2:
484 printRelocationTargetName(O: Obj, RE, Fmt);
485 Fmt << "-2";
486 break;
487 case MachO::X86_64_RELOC_SIGNED_4:
488 printRelocationTargetName(O: Obj, RE, Fmt);
489 Fmt << "-4";
490 break;
491 default:
492 printRelocationTargetName(O: Obj, RE, Fmt);
493 break;
494 }
495 // X86 and ARM share some relocation types in common.
496 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
497 Arch == Triple::ppc) {
498 // Generic relocation types...
499 switch (Type) {
500 case MachO::GENERIC_RELOC_PAIR: // prints no info
501 return Error::success();
502 case MachO::GENERIC_RELOC_SECTDIFF: {
503 DataRefImpl RelNext = Rel;
504 Obj->moveRelocationNext(Rel&: RelNext);
505 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
506
507 // X86 sect diff's must be followed by a relocation of type
508 // GENERIC_RELOC_PAIR.
509 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
510
511 if (RType != MachO::GENERIC_RELOC_PAIR)
512 reportError(File: Obj->getFileName(), Message: "Expected GENERIC_RELOC_PAIR after "
513 "GENERIC_RELOC_SECTDIFF.");
514
515 printRelocationTargetName(O: Obj, RE, Fmt);
516 Fmt << "-";
517 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
518 break;
519 }
520 }
521
522 if (Arch == Triple::x86 || Arch == Triple::ppc) {
523 switch (Type) {
524 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
525 DataRefImpl RelNext = Rel;
526 Obj->moveRelocationNext(Rel&: RelNext);
527 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
528
529 // X86 sect diff's must be followed by a relocation of type
530 // GENERIC_RELOC_PAIR.
531 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
532 if (RType != MachO::GENERIC_RELOC_PAIR)
533 reportError(File: Obj->getFileName(), Message: "Expected GENERIC_RELOC_PAIR after "
534 "GENERIC_RELOC_LOCAL_SECTDIFF.");
535
536 printRelocationTargetName(O: Obj, RE, Fmt);
537 Fmt << "-";
538 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
539 break;
540 }
541 case MachO::GENERIC_RELOC_TLV: {
542 printRelocationTargetName(O: Obj, RE, Fmt);
543 Fmt << "@TLV";
544 if (IsPCRel)
545 Fmt << "P";
546 break;
547 }
548 default:
549 printRelocationTargetName(O: Obj, RE, Fmt);
550 }
551 } else { // ARM-specific relocations
552 switch (Type) {
553 case MachO::ARM_RELOC_HALF:
554 case MachO::ARM_RELOC_HALF_SECTDIFF: {
555 // Half relocations steal a bit from the length field to encode
556 // whether this is an upper16 or a lower16 relocation.
557 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
558
559 if (isUpper)
560 Fmt << ":upper16:(";
561 else
562 Fmt << ":lower16:(";
563 printRelocationTargetName(O: Obj, RE, Fmt);
564
565 DataRefImpl RelNext = Rel;
566 Obj->moveRelocationNext(Rel&: RelNext);
567 MachO::any_relocation_info RENext = Obj->getRelocation(Rel: RelNext);
568
569 // ARM half relocs must be followed by a relocation of type
570 // ARM_RELOC_PAIR.
571 unsigned RType = Obj->getAnyRelocationType(RE: RENext);
572 if (RType != MachO::ARM_RELOC_PAIR)
573 reportError(File: Obj->getFileName(), Message: "Expected ARM_RELOC_PAIR after "
574 "ARM_RELOC_HALF");
575
576 // NOTE: The half of the target virtual address is stashed in the
577 // address field of the secondary relocation, but we can't reverse
578 // engineer the constant offset from it without decoding the movw/movt
579 // instruction to find the other half in its immediate field.
580
581 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
582 // symbol/section pointer of the follow-on relocation.
583 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
584 Fmt << "-";
585 printRelocationTargetName(O: Obj, RE: RENext, Fmt);
586 }
587
588 Fmt << ")";
589 break;
590 }
591 default: {
592 printRelocationTargetName(O: Obj, RE, Fmt);
593 }
594 }
595 }
596 } else
597 printRelocationTargetName(O: Obj, RE, Fmt);
598
599 Result.append(in_start: FmtBuf.begin(), in_end: FmtBuf.end());
600 return Error::success();
601}
602
603static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
604 uint32_t n, uint32_t count,
605 uint32_t stride, uint64_t addr) {
606 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
607 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
608 if (n > nindirectsyms)
609 outs() << " (entries start past the end of the indirect symbol "
610 "table) (reserved1 field greater than the table size)";
611 else if (n + count > nindirectsyms)
612 outs() << " (entries extends past the end of the indirect symbol "
613 "table)";
614 outs() << "\n";
615 uint32_t cputype = O->getHeader().cputype;
616 if (cputype & MachO::CPU_ARCH_ABI64)
617 outs() << "address index";
618 else
619 outs() << "address index";
620 if (verbose)
621 outs() << " name\n";
622 else
623 outs() << "\n";
624 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
625 if (cputype & MachO::CPU_ARCH_ABI64)
626 outs() << format(Fmt: "0x%016" PRIx64, Vals: addr + j * stride) << " ";
627 else
628 outs() << format(Fmt: "0x%08" PRIx32, Vals: (uint32_t)addr + j * stride) << " ";
629 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
630 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: n + j);
631 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
632 outs() << "LOCAL\n";
633 continue;
634 }
635 if (indirect_symbol ==
636 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
637 outs() << "LOCAL ABSOLUTE\n";
638 continue;
639 }
640 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
641 outs() << "ABSOLUTE\n";
642 continue;
643 }
644 outs() << format(Fmt: "%5u ", Vals: indirect_symbol);
645 if (verbose) {
646 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
647 if (indirect_symbol < Symtab.nsyms) {
648 symbol_iterator Sym = O->getSymbolByIndex(Index: indirect_symbol);
649 SymbolRef Symbol = *Sym;
650 outs() << unwrapOrError(EO: Symbol.getName(), Args: O->getFileName());
651 } else {
652 outs() << "?";
653 }
654 }
655 outs() << "\n";
656 }
657}
658
659static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
660 for (const auto &Load : O->load_commands()) {
661 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
662 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(L: Load);
663 for (unsigned J = 0; J < Seg.nsects; ++J) {
664 MachO::section_64 Sec = O->getSection64(L: Load, Index: J);
665 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
666 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
667 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
668 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
669 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
670 section_type == MachO::S_SYMBOL_STUBS) {
671 uint32_t stride;
672 if (section_type == MachO::S_SYMBOL_STUBS)
673 stride = Sec.reserved2;
674 else
675 stride = 8;
676 if (stride == 0) {
677 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
678 << Sec.sectname << ") "
679 << "(size of stubs in reserved2 field is zero)\n";
680 continue;
681 }
682 uint32_t count = Sec.size / stride;
683 outs() << "Indirect symbols for (" << Sec.segname << ","
684 << Sec.sectname << ") " << count << " entries";
685 uint32_t n = Sec.reserved1;
686 PrintIndirectSymbolTable(O, verbose, n, count, stride, addr: Sec.addr);
687 }
688 }
689 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
690 MachO::segment_command Seg = O->getSegmentLoadCommand(L: Load);
691 for (unsigned J = 0; J < Seg.nsects; ++J) {
692 MachO::section Sec = O->getSection(L: Load, Index: J);
693 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
694 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
695 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
696 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
697 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
698 section_type == MachO::S_SYMBOL_STUBS) {
699 uint32_t stride;
700 if (section_type == MachO::S_SYMBOL_STUBS)
701 stride = Sec.reserved2;
702 else
703 stride = 4;
704 if (stride == 0) {
705 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
706 << Sec.sectname << ") "
707 << "(size of stubs in reserved2 field is zero)\n";
708 continue;
709 }
710 uint32_t count = Sec.size / stride;
711 outs() << "Indirect symbols for (" << Sec.segname << ","
712 << Sec.sectname << ") " << count << " entries";
713 uint32_t n = Sec.reserved1;
714 PrintIndirectSymbolTable(O, verbose, n, count, stride, addr: Sec.addr);
715 }
716 }
717 }
718 }
719}
720
721static void PrintRType(const uint64_t cputype, const unsigned r_type) {
722 static char const *generic_r_types[] = {
723 "VANILLA ", "PAIR ", "SECTDIF ", "PBLAPTR ", "LOCSDIF ", "TLV ",
724 " 6 (?) ", " 7 (?) ", " 8 (?) ", " 9 (?) ", " 10 (?) ", " 11 (?) ",
725 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
726 };
727 static char const *x86_64_r_types[] = {
728 "UNSIGND ", "SIGNED ", "BRANCH ", "GOT_LD ", "GOT ", "SUB ",
729 "SIGNED1 ", "SIGNED2 ", "SIGNED4 ", "TLV ", " 10 (?) ", " 11 (?) ",
730 " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
731 };
732 static char const *arm_r_types[] = {
733 "VANILLA ", "PAIR ", "SECTDIFF", "LOCSDIF ", "PBLAPTR ",
734 "BR24 ", "T_BR22 ", "T_BR32 ", "HALF ", "HALFDIF ",
735 " 10 (?) ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
736 };
737 static char const *arm64_r_types[] = {
738 "UNSIGND ", "SUB ", "BR26 ", "PAGE21 ", "PAGOF12 ",
739 "GOTLDP ", "GOTLDPOF", "PTRTGOT ", "TLVLDP ", "TLVLDPOF",
740 "ADDEND ", " 11 (?) ", " 12 (?) ", " 13 (?) ", " 14 (?) ", " 15 (?) "
741 };
742
743 if (r_type > 0xf){
744 outs() << format(Fmt: "%-7u", Vals: r_type) << " ";
745 return;
746 }
747 switch (cputype) {
748 case MachO::CPU_TYPE_I386:
749 outs() << generic_r_types[r_type];
750 break;
751 case MachO::CPU_TYPE_X86_64:
752 outs() << x86_64_r_types[r_type];
753 break;
754 case MachO::CPU_TYPE_ARM:
755 outs() << arm_r_types[r_type];
756 break;
757 case MachO::CPU_TYPE_ARM64:
758 case MachO::CPU_TYPE_ARM64_32:
759 outs() << arm64_r_types[r_type];
760 break;
761 default:
762 outs() << format(Fmt: "%-7u ", Vals: r_type);
763 }
764}
765
766static void PrintRLength(const uint64_t cputype, const unsigned r_type,
767 const unsigned r_length, const bool previous_arm_half){
768 if (cputype == MachO::CPU_TYPE_ARM &&
769 (r_type == MachO::ARM_RELOC_HALF ||
770 r_type == MachO::ARM_RELOC_HALF_SECTDIFF || previous_arm_half == true)) {
771 if ((r_length & 0x1) == 0)
772 outs() << "lo/";
773 else
774 outs() << "hi/";
775 if ((r_length & 0x1) == 0)
776 outs() << "arm ";
777 else
778 outs() << "thm ";
779 } else {
780 switch (r_length) {
781 case 0:
782 outs() << "byte ";
783 break;
784 case 1:
785 outs() << "word ";
786 break;
787 case 2:
788 outs() << "long ";
789 break;
790 case 3:
791 if (cputype == MachO::CPU_TYPE_X86_64)
792 outs() << "quad ";
793 else
794 outs() << format(Fmt: "?(%2d) ", Vals: r_length);
795 break;
796 default:
797 outs() << format(Fmt: "?(%2d) ", Vals: r_length);
798 }
799 }
800}
801
802static void PrintRelocationEntries(const MachOObjectFile *O,
803 const relocation_iterator Begin,
804 const relocation_iterator End,
805 const uint64_t cputype,
806 const bool verbose) {
807 const MachO::symtab_command Symtab = O->getSymtabLoadCommand();
808 bool previous_arm_half = false;
809 bool previous_sectdiff = false;
810 uint32_t sectdiff_r_type = 0;
811
812 for (relocation_iterator Reloc = Begin; Reloc != End; ++Reloc) {
813 const DataRefImpl Rel = Reloc->getRawDataRefImpl();
814 const MachO::any_relocation_info RE = O->getRelocation(Rel);
815 const unsigned r_type = O->getAnyRelocationType(RE);
816 const bool r_scattered = O->isRelocationScattered(RE);
817 const unsigned r_pcrel = O->getAnyRelocationPCRel(RE);
818 const unsigned r_length = O->getAnyRelocationLength(RE);
819 const unsigned r_address = O->getAnyRelocationAddress(RE);
820 const bool r_extern = (r_scattered ? false :
821 O->getPlainRelocationExternal(RE));
822 const uint32_t r_value = (r_scattered ?
823 O->getScatteredRelocationValue(RE) : 0);
824 const unsigned r_symbolnum = (r_scattered ? 0 :
825 O->getPlainRelocationSymbolNum(RE));
826
827 if (r_scattered && cputype != MachO::CPU_TYPE_X86_64) {
828 if (verbose) {
829 // scattered: address
830 if ((cputype == MachO::CPU_TYPE_I386 &&
831 r_type == MachO::GENERIC_RELOC_PAIR) ||
832 (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR))
833 outs() << " ";
834 else
835 outs() << format(Fmt: "%08x ", Vals: (unsigned int)r_address);
836
837 // scattered: pcrel
838 if (r_pcrel)
839 outs() << "True ";
840 else
841 outs() << "False ";
842
843 // scattered: length
844 PrintRLength(cputype, r_type, r_length, previous_arm_half);
845
846 // scattered: extern & type
847 outs() << "n/a ";
848 PrintRType(cputype, r_type);
849
850 // scattered: scattered & value
851 outs() << format(Fmt: "True 0x%08x", Vals: (unsigned int)r_value);
852 if (previous_sectdiff == false) {
853 if ((cputype == MachO::CPU_TYPE_ARM &&
854 r_type == MachO::ARM_RELOC_PAIR))
855 outs() << format(Fmt: " half = 0x%04x ", Vals: (unsigned int)r_address);
856 } else if (cputype == MachO::CPU_TYPE_ARM &&
857 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF)
858 outs() << format(Fmt: " other_half = 0x%04x ", Vals: (unsigned int)r_address);
859 if ((cputype == MachO::CPU_TYPE_I386 &&
860 (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
861 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) ||
862 (cputype == MachO::CPU_TYPE_ARM &&
863 (sectdiff_r_type == MachO::ARM_RELOC_SECTDIFF ||
864 sectdiff_r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
865 sectdiff_r_type == MachO::ARM_RELOC_HALF_SECTDIFF))) {
866 previous_sectdiff = true;
867 sectdiff_r_type = r_type;
868 } else {
869 previous_sectdiff = false;
870 sectdiff_r_type = 0;
871 }
872 if (cputype == MachO::CPU_TYPE_ARM &&
873 (r_type == MachO::ARM_RELOC_HALF ||
874 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
875 previous_arm_half = true;
876 else
877 previous_arm_half = false;
878 outs() << "\n";
879 }
880 else {
881 // scattered: address pcrel length extern type scattered value
882 outs() << format(Fmt: "%08x %1d %-2d n/a %-7d 1 0x%08x\n",
883 Vals: (unsigned int)r_address, Vals: r_pcrel, Vals: r_length, Vals: r_type,
884 Vals: (unsigned int)r_value);
885 }
886 }
887 else {
888 if (verbose) {
889 // plain: address
890 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
891 outs() << " ";
892 else
893 outs() << format(Fmt: "%08x ", Vals: (unsigned int)r_address);
894
895 // plain: pcrel
896 if (r_pcrel)
897 outs() << "True ";
898 else
899 outs() << "False ";
900
901 // plain: length
902 PrintRLength(cputype, r_type, r_length, previous_arm_half);
903
904 if (r_extern) {
905 // plain: extern & type & scattered
906 outs() << "True ";
907 PrintRType(cputype, r_type);
908 outs() << "False ";
909
910 // plain: symbolnum/value
911 if (r_symbolnum > Symtab.nsyms)
912 outs() << format(Fmt: "?(%d)\n", Vals: r_symbolnum);
913 else {
914 SymbolRef Symbol = *O->getSymbolByIndex(Index: r_symbolnum);
915 Expected<StringRef> SymNameNext = Symbol.getName();
916 const char *name = nullptr;
917 if (SymNameNext)
918 name = SymNameNext->data();
919 if (name == nullptr)
920 outs() << format(Fmt: "?(%d)\n", Vals: r_symbolnum);
921 else
922 outs() << name << "\n";
923 }
924 }
925 else {
926 // plain: extern & type & scattered
927 outs() << "False ";
928 PrintRType(cputype, r_type);
929 outs() << "False ";
930
931 // plain: symbolnum/value
932 if (cputype == MachO::CPU_TYPE_ARM && r_type == MachO::ARM_RELOC_PAIR)
933 outs() << format(Fmt: "other_half = 0x%04x\n", Vals: (unsigned int)r_address);
934 else if ((cputype == MachO::CPU_TYPE_ARM64 ||
935 cputype == MachO::CPU_TYPE_ARM64_32) &&
936 r_type == MachO::ARM64_RELOC_ADDEND)
937 outs() << format(Fmt: "addend = 0x%06x\n", Vals: (unsigned int)r_symbolnum);
938 else if (cputype == MachO::CPU_TYPE_RISCV &&
939 r_type == MachO::RISCV_RELOC_ADDEND)
940 outs() << format(Fmt: "addend = 0x%06x\n", Vals: (unsigned int)r_symbolnum);
941 else {
942 outs() << format(Fmt: "%d ", Vals: r_symbolnum);
943 if (r_symbolnum == MachO::R_ABS)
944 outs() << "R_ABS\n";
945 else {
946 // in this case, r_symbolnum is actually a 1-based section number
947 uint32_t nsects = O->section_end()->getRawDataRefImpl().d.a;
948 if (r_symbolnum > 0 && r_symbolnum <= nsects) {
949 object::DataRefImpl DRI;
950 DRI.d.a = r_symbolnum-1;
951 StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
952 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
953 outs() << "(" << SegName << "," << *NameOrErr << ")\n";
954 else
955 outs() << "(?,?)\n";
956 }
957 else {
958 outs() << "(?,?)\n";
959 }
960 }
961 }
962 }
963 if (cputype == MachO::CPU_TYPE_ARM &&
964 (r_type == MachO::ARM_RELOC_HALF ||
965 r_type == MachO::ARM_RELOC_HALF_SECTDIFF))
966 previous_arm_half = true;
967 else
968 previous_arm_half = false;
969 }
970 else {
971 // plain: address pcrel length extern type scattered symbolnum/section
972 outs() << format(Fmt: "%08x %1d %-2d %1d %-7d 0 %d\n",
973 Vals: (unsigned int)r_address, Vals: r_pcrel, Vals: r_length, Vals: r_extern,
974 Vals: r_type, Vals: r_symbolnum);
975 }
976 }
977 }
978}
979
980static void PrintRelocations(const MachOObjectFile *O, const bool verbose) {
981 const uint64_t cputype = O->getHeader().cputype;
982 const MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
983 if (Dysymtab.nextrel != 0) {
984 outs() << "External relocation information " << Dysymtab.nextrel
985 << " entries";
986 outs() << "\naddress pcrel length extern type scattered "
987 "symbolnum/value\n";
988 PrintRelocationEntries(O, Begin: O->extrel_begin(), End: O->extrel_end(), cputype,
989 verbose);
990 }
991 if (Dysymtab.nlocrel != 0) {
992 outs() << format(Fmt: "Local relocation information %u entries",
993 Vals: Dysymtab.nlocrel);
994 outs() << "\naddress pcrel length extern type scattered "
995 "symbolnum/value\n";
996 PrintRelocationEntries(O, Begin: O->locrel_begin(), End: O->locrel_end(), cputype,
997 verbose);
998 }
999 for (const auto &Load : O->load_commands()) {
1000 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
1001 const MachO::segment_command_64 Seg = O->getSegment64LoadCommand(L: Load);
1002 for (unsigned J = 0; J < Seg.nsects; ++J) {
1003 const MachO::section_64 Sec = O->getSection64(L: Load, Index: J);
1004 if (Sec.nreloc != 0) {
1005 DataRefImpl DRI;
1006 DRI.d.a = J;
1007 const StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
1008 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
1009 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1010 << format(Fmt: ") %u entries", Vals: Sec.nreloc);
1011 else
1012 outs() << "Relocation information (" << SegName << ",?) "
1013 << format(Fmt: "%u entries", Vals: Sec.nreloc);
1014 outs() << "\naddress pcrel length extern type scattered "
1015 "symbolnum/value\n";
1016 PrintRelocationEntries(O, Begin: O->section_rel_begin(Sec: DRI),
1017 End: O->section_rel_end(Sec: DRI), cputype, verbose);
1018 }
1019 }
1020 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
1021 const MachO::segment_command Seg = O->getSegmentLoadCommand(L: Load);
1022 for (unsigned J = 0; J < Seg.nsects; ++J) {
1023 const MachO::section Sec = O->getSection(L: Load, Index: J);
1024 if (Sec.nreloc != 0) {
1025 DataRefImpl DRI;
1026 DRI.d.a = J;
1027 const StringRef SegName = O->getSectionFinalSegmentName(Sec: DRI);
1028 if (Expected<StringRef> NameOrErr = O->getSectionName(Sec: DRI))
1029 outs() << "Relocation information (" << SegName << "," << *NameOrErr
1030 << format(Fmt: ") %u entries", Vals: Sec.nreloc);
1031 else
1032 outs() << "Relocation information (" << SegName << ",?) "
1033 << format(Fmt: "%u entries", Vals: Sec.nreloc);
1034 outs() << "\naddress pcrel length extern type scattered "
1035 "symbolnum/value\n";
1036 PrintRelocationEntries(O, Begin: O->section_rel_begin(Sec: DRI),
1037 End: O->section_rel_end(Sec: DRI), cputype, verbose);
1038 }
1039 }
1040 }
1041 }
1042}
1043
1044static void PrintFunctionStarts(MachOObjectFile *O) {
1045 uint64_t BaseSegmentAddress = 0;
1046 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1047 if (Command.C.cmd == MachO::LC_SEGMENT) {
1048 MachO::segment_command SLC = O->getSegmentLoadCommand(L: Command);
1049 if (StringRef(SLC.segname) == "__TEXT") {
1050 BaseSegmentAddress = SLC.vmaddr;
1051 break;
1052 }
1053 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1054 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(L: Command);
1055 if (StringRef(SLC.segname) == "__TEXT") {
1056 BaseSegmentAddress = SLC.vmaddr;
1057 break;
1058 }
1059 }
1060 }
1061
1062 SmallVector<uint64_t, 8> FunctionStarts;
1063 for (const MachOObjectFile::LoadCommandInfo &LC : O->load_commands()) {
1064 if (LC.C.cmd == MachO::LC_FUNCTION_STARTS) {
1065 MachO::linkedit_data_command FunctionStartsLC =
1066 O->getLinkeditDataLoadCommand(L: LC);
1067 O->ReadULEB128s(Index: FunctionStartsLC.dataoff, Out&: FunctionStarts);
1068 break;
1069 }
1070 }
1071
1072 DenseMap<uint64_t, StringRef> SymbolNames;
1073 if (FunctionStartsType == FunctionStartsMode::Names ||
1074 FunctionStartsType == FunctionStartsMode::Both) {
1075 for (SymbolRef Sym : O->symbols()) {
1076 if (Expected<uint64_t> Addr = Sym.getAddress()) {
1077 if (Expected<StringRef> Name = Sym.getName()) {
1078 SymbolNames[*Addr] = *Name;
1079 }
1080 }
1081 }
1082 }
1083
1084 for (uint64_t S : FunctionStarts) {
1085 uint64_t Addr = BaseSegmentAddress + S;
1086 if (FunctionStartsType == FunctionStartsMode::Names) {
1087 auto It = SymbolNames.find(Val: Addr);
1088 if (It != SymbolNames.end())
1089 outs() << It->second << "\n";
1090 } else {
1091 if (O->is64Bit())
1092 outs() << format(Fmt: "%016" PRIx64, Vals: Addr);
1093 else
1094 outs() << format(Fmt: "%08" PRIx32, Vals: static_cast<uint32_t>(Addr));
1095
1096 if (FunctionStartsType == FunctionStartsMode::Both) {
1097 auto It = SymbolNames.find(Val: Addr);
1098 if (It != SymbolNames.end())
1099 outs() << " " << It->second;
1100 else
1101 outs() << " ?";
1102 }
1103 outs() << "\n";
1104 }
1105 }
1106}
1107
1108static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
1109 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
1110 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
1111 outs() << "Data in code table (" << nentries << " entries)\n";
1112 outs() << "offset length kind\n";
1113 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
1114 ++DI) {
1115 uint32_t Offset;
1116 DI->getOffset(Result&: Offset);
1117 outs() << format(Fmt: "0x%08" PRIx32, Vals: Offset) << " ";
1118 uint16_t Length;
1119 DI->getLength(Result&: Length);
1120 outs() << format(Fmt: "%6u", Vals: Length) << " ";
1121 uint16_t Kind;
1122 DI->getKind(Result&: Kind);
1123 if (verbose) {
1124 switch (Kind) {
1125 case MachO::DICE_KIND_DATA:
1126 outs() << "DATA";
1127 break;
1128 case MachO::DICE_KIND_JUMP_TABLE8:
1129 outs() << "JUMP_TABLE8";
1130 break;
1131 case MachO::DICE_KIND_JUMP_TABLE16:
1132 outs() << "JUMP_TABLE16";
1133 break;
1134 case MachO::DICE_KIND_JUMP_TABLE32:
1135 outs() << "JUMP_TABLE32";
1136 break;
1137 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
1138 outs() << "ABS_JUMP_TABLE32";
1139 break;
1140 default:
1141 outs() << format(Fmt: "0x%04" PRIx32, Vals: Kind);
1142 break;
1143 }
1144 } else
1145 outs() << format(Fmt: "0x%04" PRIx32, Vals: Kind);
1146 outs() << "\n";
1147 }
1148}
1149
1150static void PrintLinkOptHints(MachOObjectFile *O) {
1151 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
1152 const char *loh = O->getData().substr(Start: LohLC.dataoff, N: 1).data();
1153 uint32_t nloh = LohLC.datasize;
1154 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
1155 for (uint32_t i = 0; i < nloh;) {
1156 unsigned n;
1157 uint64_t identifier = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1158 i += n;
1159 outs() << " identifier " << identifier << " ";
1160 if (i >= nloh)
1161 return;
1162 switch (identifier) {
1163 case 1:
1164 outs() << "AdrpAdrp\n";
1165 break;
1166 case 2:
1167 outs() << "AdrpLdr\n";
1168 break;
1169 case 3:
1170 outs() << "AdrpAddLdr\n";
1171 break;
1172 case 4:
1173 outs() << "AdrpLdrGotLdr\n";
1174 break;
1175 case 5:
1176 outs() << "AdrpAddStr\n";
1177 break;
1178 case 6:
1179 outs() << "AdrpLdrGotStr\n";
1180 break;
1181 case 7:
1182 outs() << "AdrpAdd\n";
1183 break;
1184 case 8:
1185 outs() << "AdrpLdrGot\n";
1186 break;
1187 default:
1188 outs() << "Unknown identifier value\n";
1189 break;
1190 }
1191 uint64_t narguments = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1192 i += n;
1193 outs() << " narguments " << narguments << "\n";
1194 if (i >= nloh)
1195 return;
1196
1197 for (uint32_t j = 0; j < narguments; j++) {
1198 uint64_t value = decodeULEB128(p: (const uint8_t *)(loh + i), n: &n);
1199 i += n;
1200 outs() << "\tvalue " << format(Fmt: "0x%" PRIx64, Vals: value) << "\n";
1201 if (i >= nloh)
1202 return;
1203 }
1204 }
1205}
1206
1207static SmallVector<std::string> GetSegmentNames(object::MachOObjectFile *O) {
1208 SmallVector<std::string> Ret;
1209 for (const MachOObjectFile::LoadCommandInfo &Command : O->load_commands()) {
1210 if (Command.C.cmd == MachO::LC_SEGMENT) {
1211 MachO::segment_command SLC = O->getSegmentLoadCommand(L: Command);
1212 Ret.push_back(Elt: SLC.segname);
1213 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
1214 MachO::segment_command_64 SLC = O->getSegment64LoadCommand(L: Command);
1215 Ret.push_back(Elt: SLC.segname);
1216 }
1217 }
1218 return Ret;
1219}
1220
1221static void
1222PrintChainedFixupsHeader(const MachO::dyld_chained_fixups_header &H) {
1223 outs() << "chained fixups header (LC_DYLD_CHAINED_FIXUPS)\n";
1224 outs() << " fixups_version = " << H.fixups_version << '\n';
1225 outs() << " starts_offset = " << H.starts_offset << '\n';
1226 outs() << " imports_offset = " << H.imports_offset << '\n';
1227 outs() << " symbols_offset = " << H.symbols_offset << '\n';
1228 outs() << " imports_count = " << H.imports_count << '\n';
1229
1230 outs() << " imports_format = " << H.imports_format;
1231 switch (H.imports_format) {
1232 case llvm::MachO::DYLD_CHAINED_IMPORT:
1233 outs() << " (DYLD_CHAINED_IMPORT)";
1234 break;
1235 case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND:
1236 outs() << " (DYLD_CHAINED_IMPORT_ADDEND)";
1237 break;
1238 case llvm::MachO::DYLD_CHAINED_IMPORT_ADDEND64:
1239 outs() << " (DYLD_CHAINED_IMPORT_ADDEND64)";
1240 break;
1241 }
1242 outs() << '\n';
1243
1244 outs() << " symbols_format = " << H.symbols_format;
1245 if (H.symbols_format == llvm::MachO::DYLD_CHAINED_SYMBOL_ZLIB)
1246 outs() << " (zlib compressed)";
1247 outs() << '\n';
1248}
1249
1250static constexpr std::array<StringRef, 13> PointerFormats{
1251 "DYLD_CHAINED_PTR_ARM64E",
1252 "DYLD_CHAINED_PTR_64",
1253 "DYLD_CHAINED_PTR_32",
1254 "DYLD_CHAINED_PTR_32_CACHE",
1255 "DYLD_CHAINED_PTR_32_FIRMWARE",
1256 "DYLD_CHAINED_PTR_64_OFFSET",
1257 "DYLD_CHAINED_PTR_ARM64E_KERNEL",
1258 "DYLD_CHAINED_PTR_64_KERNEL_CACHE",
1259 "DYLD_CHAINED_PTR_ARM64E_USERLAND",
1260 "DYLD_CHAINED_PTR_ARM64E_FIRMWARE",
1261 "DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE",
1262 "DYLD_CHAINED_PTR_ARM64E_USERLAND24",
1263};
1264
1265static void PrintChainedFixupsSegment(const ChainedFixupsSegment &Segment,
1266 StringRef SegName) {
1267 outs() << "chained starts in segment " << Segment.SegIdx << " (" << SegName
1268 << ")\n";
1269 outs() << " size = " << Segment.Header.size << '\n';
1270 outs() << " page_size = " << format(Fmt: "0x%0" PRIx16, Vals: Segment.Header.page_size)
1271 << '\n';
1272
1273 outs() << " pointer_format = " << Segment.Header.pointer_format;
1274 if ((Segment.Header.pointer_format - 1) <
1275 MachO::DYLD_CHAINED_PTR_ARM64E_USERLAND24)
1276 outs() << " (" << PointerFormats[Segment.Header.pointer_format - 1] << ")";
1277 outs() << '\n';
1278
1279 outs() << " segment_offset = "
1280 << format(Fmt: "0x%0" PRIx64, Vals: Segment.Header.segment_offset) << '\n';
1281 outs() << " max_valid_pointer = " << Segment.Header.max_valid_pointer
1282 << '\n';
1283 outs() << " page_count = " << Segment.Header.page_count << '\n';
1284 for (auto [Index, PageStart] : enumerate(First: Segment.PageStarts)) {
1285 outs() << " page_start[" << Index << "] = " << PageStart;
1286 // FIXME: Support DYLD_CHAINED_PTR_START_MULTI (32-bit only)
1287 if (PageStart == MachO::DYLD_CHAINED_PTR_START_NONE)
1288 outs() << " (DYLD_CHAINED_PTR_START_NONE)";
1289 outs() << '\n';
1290 }
1291}
1292
1293static void PrintChainedFixupTarget(ChainedFixupTarget &Target, size_t Idx,
1294 int Format, MachOObjectFile *O) {
1295 if (Format == MachO::DYLD_CHAINED_IMPORT)
1296 outs() << "dyld chained import";
1297 else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND)
1298 outs() << "dyld chained import addend";
1299 else if (Format == MachO::DYLD_CHAINED_IMPORT_ADDEND64)
1300 outs() << "dyld chained import addend64";
1301 // FIXME: otool prints the encoded value as well.
1302 outs() << '[' << Idx << "]\n";
1303
1304 outs() << " lib_ordinal = " << Target.libOrdinal() << " ("
1305 << ordinalName(O, Target.libOrdinal()) << ")\n";
1306 outs() << " weak_import = " << Target.weakImport() << '\n';
1307 outs() << " name_offset = " << Target.nameOffset() << " ("
1308 << Target.symbolName() << ")\n";
1309 if (Format != MachO::DYLD_CHAINED_IMPORT)
1310 outs() << " addend = " << (int64_t)Target.addend() << '\n';
1311}
1312
1313static void PrintChainedFixups(MachOObjectFile *O) {
1314 // MachOObjectFile::getChainedFixupsHeader() reads LC_DYLD_CHAINED_FIXUPS.
1315 // FIXME: Support chained fixups in __TEXT,__chain_starts section too.
1316 auto ChainedFixupHeader =
1317 unwrapOrError(EO: O->getChainedFixupsHeader(), Args: O->getFileName());
1318 if (!ChainedFixupHeader)
1319 return;
1320
1321 PrintChainedFixupsHeader(H: *ChainedFixupHeader);
1322
1323 auto [SegCount, Segments] =
1324 unwrapOrError(EO: O->getChainedFixupsSegments(), Args: O->getFileName());
1325
1326 auto SegNames = GetSegmentNames(O);
1327
1328 size_t StartsIdx = 0;
1329 outs() << "chained starts in image\n";
1330 outs() << " seg_count = " << SegCount << '\n';
1331 for (size_t I = 0; I < SegCount; ++I) {
1332 uint64_t SegOffset = 0;
1333 if (StartsIdx < Segments.size() && I == Segments[StartsIdx].SegIdx) {
1334 SegOffset = Segments[StartsIdx].Offset;
1335 ++StartsIdx;
1336 }
1337
1338 outs() << " seg_offset[" << I << "] = " << SegOffset << " ("
1339 << SegNames[I] << ")\n";
1340 }
1341
1342 for (const ChainedFixupsSegment &S : Segments)
1343 PrintChainedFixupsSegment(Segment: S, SegName: SegNames[S.SegIdx]);
1344
1345 auto FixupTargets =
1346 unwrapOrError(EO: O->getDyldChainedFixupTargets(), Args: O->getFileName());
1347
1348 uint32_t ImportsFormat = ChainedFixupHeader->imports_format;
1349 for (auto [Idx, Target] : enumerate(First&: FixupTargets))
1350 PrintChainedFixupTarget(Target, Idx, Format: ImportsFormat, O);
1351}
1352
1353static void PrintDyldInfo(MachOObjectFile *O) {
1354 Error Err = Error::success();
1355
1356 size_t SegmentWidth = strlen(s: "segment");
1357 size_t SectionWidth = strlen(s: "section");
1358 size_t AddressWidth = strlen(s: "address");
1359 size_t AddendWidth = strlen(s: "addend");
1360 size_t DylibWidth = strlen(s: "dylib");
1361 const size_t PointerWidth = 2 + O->getBytesInAddress() * 2;
1362
1363 auto HexLength = [](uint64_t Num) {
1364 return Num ? (size_t)divideCeil(Numerator: Log2_64(Value: Num), Denominator: 4) : 1;
1365 };
1366 for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1367 SegmentWidth = std::max(a: SegmentWidth, b: Entry.segmentName().size());
1368 SectionWidth = std::max(a: SectionWidth, b: Entry.sectionName().size());
1369 AddressWidth = std::max(a: AddressWidth, b: HexLength(Entry.address()) + 2);
1370 if (Entry.isBind()) {
1371 AddendWidth = std::max(a: AddendWidth, b: HexLength(Entry.addend()) + 2);
1372 DylibWidth = std::max(a: DylibWidth, b: Entry.symbolName().size());
1373 }
1374 }
1375 // Errors will be handled when printing the table.
1376 if (Err)
1377 consumeError(Err: std::move(Err));
1378
1379 outs() << "dyld information:\n";
1380 outs() << left_justify(Str: "segment", Width: SegmentWidth) << ' '
1381 << left_justify(Str: "section", Width: SectionWidth) << ' '
1382 << left_justify(Str: "address", Width: AddressWidth) << ' '
1383 << left_justify(Str: "pointer", Width: PointerWidth) << " type "
1384 << left_justify(Str: "addend", Width: AddendWidth) << ' '
1385 << left_justify(Str: "dylib", Width: DylibWidth) << " symbol/vm address\n";
1386 for (const object::MachOChainedFixupEntry &Entry : O->fixupTable(Err)) {
1387 outs() << left_justify(Str: Entry.segmentName(), Width: SegmentWidth) << ' '
1388 << left_justify(Str: Entry.sectionName(), Width: SectionWidth) << ' ' << "0x"
1389 << left_justify(Str: utohexstr(X: Entry.address()), Width: AddressWidth - 2) << ' '
1390 << format_hex(N: Entry.rawValue(), Width: PointerWidth, Upper: true) << ' ';
1391 if (Entry.isBind()) {
1392 outs() << "bind "
1393 << "0x" << left_justify(Str: utohexstr(X: Entry.addend()), Width: AddendWidth - 2)
1394 << ' ' << left_justify(Str: ordinalName(O, Entry.ordinal()), Width: DylibWidth)
1395 << ' ' << Entry.symbolName();
1396 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
1397 outs() << " (weak import)";
1398 outs() << '\n';
1399 } else {
1400 assert(Entry.isRebase());
1401 outs() << "rebase";
1402 outs().indent(NumSpaces: AddendWidth + DylibWidth + 2);
1403 outs() << format(Fmt: "0x%" PRIX64, Vals: Entry.pointerValue()) << '\n';
1404 }
1405 }
1406 if (Err)
1407 reportError(E: std::move(Err), FileName: O->getFileName());
1408
1409 // TODO: Print opcode-based fixups if the object uses those.
1410}
1411
1412static void PrintDylibs(MachOObjectFile *O, bool JustId) {
1413 unsigned Index = 0;
1414 for (const auto &Load : O->load_commands()) {
1415 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
1416 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
1417 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
1418 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
1419 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
1420 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
1421 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
1422 MachO::dylib_command dl = O->getDylibIDLoadCommand(L: Load);
1423 if (dl.dylib.name < dl.cmdsize) {
1424 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
1425 if (JustId)
1426 outs() << p << "\n";
1427 else {
1428 outs() << "\t" << p;
1429 outs() << " (compatibility version "
1430 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
1431 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
1432 << (dl.dylib.compatibility_version & 0xff) << ",";
1433 outs() << " current version "
1434 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
1435 << ((dl.dylib.current_version >> 8) & 0xff) << "."
1436 << (dl.dylib.current_version & 0xff);
1437 if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1438 outs() << ", weak";
1439 if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1440 outs() << ", reexport";
1441 if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1442 outs() << ", upward";
1443 if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1444 outs() << ", lazy";
1445 outs() << ")\n";
1446 }
1447 } else {
1448 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
1449 if (Load.C.cmd == MachO::LC_ID_DYLIB)
1450 outs() << "LC_ID_DYLIB ";
1451 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
1452 outs() << "LC_LOAD_DYLIB ";
1453 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
1454 outs() << "LC_LOAD_WEAK_DYLIB ";
1455 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
1456 outs() << "LC_LAZY_LOAD_DYLIB ";
1457 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
1458 outs() << "LC_REEXPORT_DYLIB ";
1459 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
1460 outs() << "LC_LOAD_UPWARD_DYLIB ";
1461 else
1462 outs() << "LC_??? ";
1463 outs() << "command " << Index++ << "\n";
1464 }
1465 }
1466 }
1467}
1468
1469static void printRpaths(MachOObjectFile *O) {
1470 for (const auto &Command : O->load_commands()) {
1471 if (Command.C.cmd == MachO::LC_RPATH) {
1472 auto Rpath = O->getRpathCommand(L: Command);
1473 const char *P = (const char *)(Command.Ptr) + Rpath.path;
1474 outs() << P << "\n";
1475 }
1476 }
1477}
1478
1479typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
1480
1481static void CreateSymbolAddressMap(MachOObjectFile *O,
1482 SymbolAddressMap *AddrMap) {
1483 // Create a map of symbol addresses to symbol names.
1484 const StringRef FileName = O->getFileName();
1485 for (const SymbolRef &Symbol : O->symbols()) {
1486 SymbolRef::Type ST = unwrapOrError(EO: Symbol.getType(), Args: FileName);
1487 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
1488 ST == SymbolRef::ST_Other) {
1489 uint64_t Address = cantFail(ValOrErr: Symbol.getValue());
1490 StringRef SymName = unwrapOrError(EO: Symbol.getName(), Args: FileName);
1491 if (!SymName.starts_with(Prefix: ".objc"))
1492 (*AddrMap)[Address] = SymName;
1493 }
1494 }
1495}
1496
1497// GuessSymbolName is passed the address of what might be a symbol and a
1498// pointer to the SymbolAddressMap. It returns the name of a symbol
1499// with that address or nullptr if no symbol is found with that address.
1500static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
1501 const char *SymbolName = nullptr;
1502 // A DenseMap can't lookup up some values.
1503 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
1504 StringRef name = AddrMap->lookup(Val: value);
1505 if (!name.empty())
1506 SymbolName = name.data();
1507 }
1508 return SymbolName;
1509}
1510
1511static void DumpCstringChar(const char c) {
1512 char p[2];
1513 p[0] = c;
1514 p[1] = '\0';
1515 outs().write_escaped(Str: p);
1516}
1517
1518static void DumpCstringSection(MachOObjectFile *O, const char *sect,
1519 uint32_t sect_size, uint64_t sect_addr,
1520 bool print_addresses) {
1521 for (uint32_t i = 0; i < sect_size; i++) {
1522 if (print_addresses) {
1523 if (O->is64Bit())
1524 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1525 else
1526 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1527 }
1528 for (; i < sect_size && sect[i] != '\0'; i++)
1529 DumpCstringChar(c: sect[i]);
1530 if (i < sect_size && sect[i] == '\0')
1531 outs() << "\n";
1532 }
1533}
1534
1535static void DumpLiteral4(uint32_t l, float f) {
1536 outs() << format(Fmt: "0x%08" PRIx32, Vals: l);
1537 if ((l & 0x7f800000) != 0x7f800000)
1538 outs() << format(Fmt: " (%.16e)\n", Vals: f);
1539 else {
1540 if (l == 0x7f800000)
1541 outs() << " (+Infinity)\n";
1542 else if (l == 0xff800000)
1543 outs() << " (-Infinity)\n";
1544 else if ((l & 0x00400000) == 0x00400000)
1545 outs() << " (non-signaling Not-a-Number)\n";
1546 else
1547 outs() << " (signaling Not-a-Number)\n";
1548 }
1549}
1550
1551static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
1552 uint32_t sect_size, uint64_t sect_addr,
1553 bool print_addresses) {
1554 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
1555 if (print_addresses) {
1556 if (O->is64Bit())
1557 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1558 else
1559 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1560 }
1561 float f;
1562 memcpy(dest: &f, src: sect + i, n: sizeof(float));
1563 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1564 sys::swapByteOrder(Value&: f);
1565 uint32_t l;
1566 memcpy(dest: &l, src: sect + i, n: sizeof(uint32_t));
1567 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1568 sys::swapByteOrder(Value&: l);
1569 DumpLiteral4(l, f);
1570 }
1571}
1572
1573static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
1574 double d) {
1575 outs() << format(Fmt: "0x%08" PRIx32, Vals: l0) << " " << format(Fmt: "0x%08" PRIx32, Vals: l1);
1576 uint32_t Hi, Lo;
1577 Hi = (O->isLittleEndian()) ? l1 : l0;
1578 Lo = (O->isLittleEndian()) ? l0 : l1;
1579
1580 // Hi is the high word, so this is equivalent to if(isfinite(d))
1581 if ((Hi & 0x7ff00000) != 0x7ff00000)
1582 outs() << format(Fmt: " (%.16e)\n", Vals: d);
1583 else {
1584 if (Hi == 0x7ff00000 && Lo == 0)
1585 outs() << " (+Infinity)\n";
1586 else if (Hi == 0xfff00000 && Lo == 0)
1587 outs() << " (-Infinity)\n";
1588 else if ((Hi & 0x00080000) == 0x00080000)
1589 outs() << " (non-signaling Not-a-Number)\n";
1590 else
1591 outs() << " (signaling Not-a-Number)\n";
1592 }
1593}
1594
1595static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
1596 uint32_t sect_size, uint64_t sect_addr,
1597 bool print_addresses) {
1598 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
1599 if (print_addresses) {
1600 if (O->is64Bit())
1601 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1602 else
1603 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1604 }
1605 double d;
1606 memcpy(dest: &d, src: sect + i, n: sizeof(double));
1607 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1608 sys::swapByteOrder(Value&: d);
1609 uint32_t l0, l1;
1610 memcpy(dest: &l0, src: sect + i, n: sizeof(uint32_t));
1611 memcpy(dest: &l1, src: sect + i + sizeof(uint32_t), n: sizeof(uint32_t));
1612 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1613 sys::swapByteOrder(Value&: l0);
1614 sys::swapByteOrder(Value&: l1);
1615 }
1616 DumpLiteral8(O, l0, l1, d);
1617 }
1618}
1619
1620static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
1621 outs() << format(Fmt: "0x%08" PRIx32, Vals: l0) << " ";
1622 outs() << format(Fmt: "0x%08" PRIx32, Vals: l1) << " ";
1623 outs() << format(Fmt: "0x%08" PRIx32, Vals: l2) << " ";
1624 outs() << format(Fmt: "0x%08" PRIx32, Vals: l3) << "\n";
1625}
1626
1627static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
1628 uint32_t sect_size, uint64_t sect_addr,
1629 bool print_addresses) {
1630 for (uint32_t i = 0; i < sect_size; i += 16) {
1631 if (print_addresses) {
1632 if (O->is64Bit())
1633 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1634 else
1635 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1636 }
1637 uint32_t l0, l1, l2, l3;
1638 memcpy(dest: &l0, src: sect + i, n: sizeof(uint32_t));
1639 memcpy(dest: &l1, src: sect + i + sizeof(uint32_t), n: sizeof(uint32_t));
1640 memcpy(dest: &l2, src: sect + i + 2 * sizeof(uint32_t), n: sizeof(uint32_t));
1641 memcpy(dest: &l3, src: sect + i + 3 * sizeof(uint32_t), n: sizeof(uint32_t));
1642 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1643 sys::swapByteOrder(Value&: l0);
1644 sys::swapByteOrder(Value&: l1);
1645 sys::swapByteOrder(Value&: l2);
1646 sys::swapByteOrder(Value&: l3);
1647 }
1648 DumpLiteral16(l0, l1, l2, l3);
1649 }
1650}
1651
1652static void DumpLiteralPointerSection(MachOObjectFile *O,
1653 const SectionRef &Section,
1654 const char *sect, uint32_t sect_size,
1655 uint64_t sect_addr,
1656 bool print_addresses) {
1657 // Collect the literal sections in this Mach-O file.
1658 std::vector<SectionRef> LiteralSections;
1659 for (const SectionRef &Section : O->sections()) {
1660 DataRefImpl Ref = Section.getRawDataRefImpl();
1661 uint32_t section_type;
1662 if (O->is64Bit()) {
1663 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1664 section_type = Sec.flags & MachO::SECTION_TYPE;
1665 } else {
1666 const MachO::section Sec = O->getSection(DRI: Ref);
1667 section_type = Sec.flags & MachO::SECTION_TYPE;
1668 }
1669 if (section_type == MachO::S_CSTRING_LITERALS ||
1670 section_type == MachO::S_4BYTE_LITERALS ||
1671 section_type == MachO::S_8BYTE_LITERALS ||
1672 section_type == MachO::S_16BYTE_LITERALS)
1673 LiteralSections.push_back(x: Section);
1674 }
1675
1676 // Set the size of the literal pointer.
1677 uint32_t lp_size = O->is64Bit() ? 8 : 4;
1678
1679 // Collect the external relocation symbols for the literal pointers.
1680 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1681 for (const RelocationRef &Reloc : Section.relocations()) {
1682 DataRefImpl Rel;
1683 MachO::any_relocation_info RE;
1684 bool isExtern = false;
1685 Rel = Reloc.getRawDataRefImpl();
1686 RE = O->getRelocation(Rel);
1687 isExtern = O->getPlainRelocationExternal(RE);
1688 if (isExtern) {
1689 uint64_t RelocOffset = Reloc.getOffset();
1690 symbol_iterator RelocSym = Reloc.getSymbol();
1691 Relocs.push_back(x: std::make_pair(x&: RelocOffset, y: *RelocSym));
1692 }
1693 }
1694 array_pod_sort(Start: Relocs.begin(), End: Relocs.end());
1695
1696 // Dump each literal pointer.
1697 for (uint32_t i = 0; i < sect_size; i += lp_size) {
1698 if (print_addresses) {
1699 if (O->is64Bit())
1700 outs() << format(Fmt: "%016" PRIx64, Vals: sect_addr + i) << " ";
1701 else
1702 outs() << format(Fmt: "%08" PRIx64, Vals: sect_addr + i) << " ";
1703 }
1704 uint64_t lp;
1705 if (O->is64Bit()) {
1706 memcpy(dest: &lp, src: sect + i, n: sizeof(uint64_t));
1707 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1708 sys::swapByteOrder(Value&: lp);
1709 } else {
1710 uint32_t li;
1711 memcpy(dest: &li, src: sect + i, n: sizeof(uint32_t));
1712 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1713 sys::swapByteOrder(Value&: li);
1714 lp = li;
1715 }
1716
1717 // First look for an external relocation entry for this literal pointer.
1718 auto Reloc = find_if(Range&: Relocs, P: [&](const std::pair<uint64_t, SymbolRef> &P) {
1719 return P.first == i;
1720 });
1721 if (Reloc != Relocs.end()) {
1722 symbol_iterator RelocSym = Reloc->second;
1723 StringRef SymName = unwrapOrError(EO: RelocSym->getName(), Args: O->getFileName());
1724 outs() << "external relocation entry for symbol:" << SymName << "\n";
1725 continue;
1726 }
1727
1728 // For local references see what the section the literal pointer points to.
1729 auto Sect = find_if(Range&: LiteralSections, P: [&](const SectionRef &R) {
1730 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
1731 });
1732 if (Sect == LiteralSections.end()) {
1733 outs() << format(Fmt: "0x%" PRIx64, Vals: lp) << " (not in a literal section)\n";
1734 continue;
1735 }
1736
1737 uint64_t SectAddress = Sect->getAddress();
1738 uint64_t SectSize = Sect->getSize();
1739
1740 StringRef SectName;
1741 Expected<StringRef> SectNameOrErr = Sect->getName();
1742 if (SectNameOrErr)
1743 SectName = *SectNameOrErr;
1744 else
1745 consumeError(Err: SectNameOrErr.takeError());
1746
1747 DataRefImpl Ref = Sect->getRawDataRefImpl();
1748 StringRef SegmentName = O->getSectionFinalSegmentName(Sec: Ref);
1749 outs() << SegmentName << ":" << SectName << ":";
1750
1751 uint32_t section_type;
1752 if (O->is64Bit()) {
1753 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1754 section_type = Sec.flags & MachO::SECTION_TYPE;
1755 } else {
1756 const MachO::section Sec = O->getSection(DRI: Ref);
1757 section_type = Sec.flags & MachO::SECTION_TYPE;
1758 }
1759
1760 StringRef BytesStr = unwrapOrError(EO: Sect->getContents(), Args: O->getFileName());
1761
1762 const char *Contents = BytesStr.data();
1763
1764 switch (section_type) {
1765 case MachO::S_CSTRING_LITERALS:
1766 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
1767 i++) {
1768 DumpCstringChar(c: Contents[i]);
1769 }
1770 outs() << "\n";
1771 break;
1772 case MachO::S_4BYTE_LITERALS:
1773 float f;
1774 memcpy(dest: &f, src: Contents + (lp - SectAddress), n: sizeof(float));
1775 uint32_t l;
1776 memcpy(dest: &l, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1777 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1778 sys::swapByteOrder(Value&: f);
1779 sys::swapByteOrder(Value&: l);
1780 }
1781 DumpLiteral4(l, f);
1782 break;
1783 case MachO::S_8BYTE_LITERALS: {
1784 double d;
1785 memcpy(dest: &d, src: Contents + (lp - SectAddress), n: sizeof(double));
1786 uint32_t l0, l1;
1787 memcpy(dest: &l0, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1788 memcpy(dest: &l1, src: Contents + (lp - SectAddress) + sizeof(uint32_t),
1789 n: sizeof(uint32_t));
1790 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1791 sys::swapByteOrder(Value&: f);
1792 sys::swapByteOrder(Value&: l0);
1793 sys::swapByteOrder(Value&: l1);
1794 }
1795 DumpLiteral8(O, l0, l1, d);
1796 break;
1797 }
1798 case MachO::S_16BYTE_LITERALS: {
1799 uint32_t l0, l1, l2, l3;
1800 memcpy(dest: &l0, src: Contents + (lp - SectAddress), n: sizeof(uint32_t));
1801 memcpy(dest: &l1, src: Contents + (lp - SectAddress) + sizeof(uint32_t),
1802 n: sizeof(uint32_t));
1803 memcpy(dest: &l2, src: Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
1804 n: sizeof(uint32_t));
1805 memcpy(dest: &l3, src: Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
1806 n: sizeof(uint32_t));
1807 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
1808 sys::swapByteOrder(Value&: l0);
1809 sys::swapByteOrder(Value&: l1);
1810 sys::swapByteOrder(Value&: l2);
1811 sys::swapByteOrder(Value&: l3);
1812 }
1813 DumpLiteral16(l0, l1, l2, l3);
1814 break;
1815 }
1816 }
1817 }
1818}
1819
1820static void DumpInitTermPointerSection(MachOObjectFile *O,
1821 const SectionRef &Section,
1822 const char *sect,
1823 uint32_t sect_size, uint64_t sect_addr,
1824 SymbolAddressMap *AddrMap,
1825 bool verbose) {
1826 uint32_t stride;
1827 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
1828
1829 // Collect the external relocation symbols for the pointers.
1830 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
1831 for (const RelocationRef &Reloc : Section.relocations()) {
1832 DataRefImpl Rel;
1833 MachO::any_relocation_info RE;
1834 bool isExtern = false;
1835 Rel = Reloc.getRawDataRefImpl();
1836 RE = O->getRelocation(Rel);
1837 isExtern = O->getPlainRelocationExternal(RE);
1838 if (isExtern) {
1839 uint64_t RelocOffset = Reloc.getOffset();
1840 symbol_iterator RelocSym = Reloc.getSymbol();
1841 Relocs.push_back(x: std::make_pair(x&: RelocOffset, y: *RelocSym));
1842 }
1843 }
1844 array_pod_sort(Start: Relocs.begin(), End: Relocs.end());
1845
1846 for (uint32_t i = 0; i < sect_size; i += stride) {
1847 const char *SymbolName = nullptr;
1848 uint64_t p;
1849 if (O->is64Bit()) {
1850 outs() << format(Fmt: "0x%016" PRIx64, Vals: sect_addr + i * stride) << " ";
1851 uint64_t pointer_value;
1852 memcpy(dest: &pointer_value, src: sect + i, n: stride);
1853 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1854 sys::swapByteOrder(Value&: pointer_value);
1855 outs() << format(Fmt: "0x%016" PRIx64, Vals: pointer_value);
1856 p = pointer_value;
1857 } else {
1858 outs() << format(Fmt: "0x%08" PRIx64, Vals: sect_addr + i * stride) << " ";
1859 uint32_t pointer_value;
1860 memcpy(dest: &pointer_value, src: sect + i, n: stride);
1861 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1862 sys::swapByteOrder(Value&: pointer_value);
1863 outs() << format(Fmt: "0x%08" PRIx32, Vals: pointer_value);
1864 p = pointer_value;
1865 }
1866 if (verbose) {
1867 // First look for an external relocation entry for this pointer.
1868 auto Reloc = find_if(Range&: Relocs, P: [&](const std::pair<uint64_t, SymbolRef> &P) {
1869 return P.first == i;
1870 });
1871 if (Reloc != Relocs.end()) {
1872 symbol_iterator RelocSym = Reloc->second;
1873 outs() << " " << unwrapOrError(EO: RelocSym->getName(), Args: O->getFileName());
1874 } else {
1875 SymbolName = GuessSymbolName(value: p, AddrMap);
1876 if (SymbolName)
1877 outs() << " " << SymbolName;
1878 }
1879 }
1880 outs() << "\n";
1881 }
1882}
1883
1884static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1885 uint32_t size, uint64_t addr) {
1886 uint32_t cputype = O->getHeader().cputype;
1887 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1888 uint32_t j;
1889 for (uint32_t i = 0; i < size; i += j, addr += j) {
1890 if (O->is64Bit())
1891 outs() << format(Fmt: "%016" PRIx64, Vals: addr) << "\t";
1892 else
1893 outs() << format(Fmt: "%08" PRIx64, Vals: addr) << "\t";
1894 for (j = 0; j < 16 && i + j < size; j++) {
1895 uint8_t byte_word = *(sect + i + j);
1896 outs() << format(Fmt: "%02" PRIx32, Vals: (uint32_t)byte_word) << " ";
1897 }
1898 outs() << "\n";
1899 }
1900 } else {
1901 uint32_t j;
1902 for (uint32_t i = 0; i < size; i += j, addr += j) {
1903 if (O->is64Bit())
1904 outs() << format(Fmt: "%016" PRIx64, Vals: addr) << "\t";
1905 else
1906 outs() << format(Fmt: "%08" PRIx64, Vals: addr) << "\t";
1907 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1908 j += sizeof(int32_t)) {
1909 if (i + j + sizeof(int32_t) <= size) {
1910 uint32_t long_word;
1911 memcpy(dest: &long_word, src: sect + i + j, n: sizeof(int32_t));
1912 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1913 sys::swapByteOrder(Value&: long_word);
1914 outs() << format(Fmt: "%08" PRIx32, Vals: long_word) << " ";
1915 } else {
1916 for (uint32_t k = 0; i + j + k < size; k++) {
1917 uint8_t byte_word = *(sect + i + j + k);
1918 outs() << format(Fmt: "%02" PRIx32, Vals: (uint32_t)byte_word) << " ";
1919 }
1920 }
1921 }
1922 outs() << "\n";
1923 }
1924 }
1925}
1926
1927static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1928 StringRef DisSegName, StringRef DisSectName);
1929static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1930 uint32_t size, uint32_t addr);
1931static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1932 bool verbose) {
1933 SymbolAddressMap AddrMap;
1934 if (verbose)
1935 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
1936
1937 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1938 StringRef DumpSection = FilterSections[i];
1939 std::pair<StringRef, StringRef> DumpSegSectName;
1940 DumpSegSectName = DumpSection.split(Separator: ',');
1941 StringRef DumpSegName, DumpSectName;
1942 if (!DumpSegSectName.second.empty()) {
1943 DumpSegName = DumpSegSectName.first;
1944 DumpSectName = DumpSegSectName.second;
1945 } else {
1946 DumpSegName = "";
1947 DumpSectName = DumpSegSectName.first;
1948 }
1949 for (const SectionRef &Section : O->sections()) {
1950 StringRef SectName;
1951 Expected<StringRef> SecNameOrErr = Section.getName();
1952 if (SecNameOrErr)
1953 SectName = *SecNameOrErr;
1954 else
1955 consumeError(Err: SecNameOrErr.takeError());
1956
1957 if (!DumpSection.empty())
1958 FoundSectionSet.insert(key: DumpSection);
1959
1960 DataRefImpl Ref = Section.getRawDataRefImpl();
1961 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
1962 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1963 (SectName == DumpSectName)) {
1964
1965 uint32_t section_flags;
1966 if (O->is64Bit()) {
1967 const MachO::section_64 Sec = O->getSection64(DRI: Ref);
1968 section_flags = Sec.flags;
1969
1970 } else {
1971 const MachO::section Sec = O->getSection(DRI: Ref);
1972 section_flags = Sec.flags;
1973 }
1974 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1975
1976 StringRef BytesStr =
1977 unwrapOrError(EO: Section.getContents(), Args: O->getFileName());
1978 const char *sect = BytesStr.data();
1979 uint32_t sect_size = BytesStr.size();
1980 uint64_t sect_addr = Section.getAddress();
1981
1982 if (LeadingHeaders)
1983 outs() << "Contents of (" << SegName << "," << SectName
1984 << ") section\n";
1985
1986 if (verbose) {
1987 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1988 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1989 DisassembleMachO(Filename, MachOOF: O, DisSegName: SegName, DisSectName: SectName);
1990 continue;
1991 }
1992 if (SegName == "__TEXT" && SectName == "__info_plist") {
1993 outs() << sect;
1994 continue;
1995 }
1996 if (SegName == "__OBJC" && SectName == "__protocol") {
1997 DumpProtocolSection(O, sect, size: sect_size, addr: sect_addr);
1998 continue;
1999 }
2000 switch (section_type) {
2001 case MachO::S_REGULAR:
2002 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2003 break;
2004 case MachO::S_ZEROFILL:
2005 outs() << "zerofill section and has no contents in the file\n";
2006 break;
2007 case MachO::S_CSTRING_LITERALS:
2008 DumpCstringSection(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2009 break;
2010 case MachO::S_4BYTE_LITERALS:
2011 DumpLiteral4Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2012 break;
2013 case MachO::S_8BYTE_LITERALS:
2014 DumpLiteral8Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2015 break;
2016 case MachO::S_16BYTE_LITERALS:
2017 DumpLiteral16Section(O, sect, sect_size, sect_addr, print_addresses: LeadingAddr);
2018 break;
2019 case MachO::S_LITERAL_POINTERS:
2020 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
2021 print_addresses: LeadingAddr);
2022 break;
2023 case MachO::S_MOD_INIT_FUNC_POINTERS:
2024 case MachO::S_MOD_TERM_FUNC_POINTERS:
2025 DumpInitTermPointerSection(O, Section, sect, sect_size, sect_addr,
2026 AddrMap: &AddrMap, verbose);
2027 break;
2028 default:
2029 outs() << "Unknown section type ("
2030 << format(Fmt: "0x%08" PRIx32, Vals: section_type) << ")\n";
2031 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2032 break;
2033 }
2034 } else {
2035 if (section_type == MachO::S_ZEROFILL)
2036 outs() << "zerofill section and has no contents in the file\n";
2037 else
2038 DumpRawSectionContents(O, sect, size: sect_size, addr: sect_addr);
2039 }
2040 }
2041 }
2042 }
2043}
2044
2045static void DumpInfoPlistSectionContents(StringRef Filename,
2046 MachOObjectFile *O) {
2047 for (const SectionRef &Section : O->sections()) {
2048 StringRef SectName;
2049 Expected<StringRef> SecNameOrErr = Section.getName();
2050 if (SecNameOrErr)
2051 SectName = *SecNameOrErr;
2052 else
2053 consumeError(Err: SecNameOrErr.takeError());
2054
2055 DataRefImpl Ref = Section.getRawDataRefImpl();
2056 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
2057 if (SegName == "__TEXT" && SectName == "__info_plist") {
2058 if (LeadingHeaders)
2059 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
2060 StringRef BytesStr =
2061 unwrapOrError(EO: Section.getContents(), Args: O->getFileName());
2062 const char *sect = BytesStr.data();
2063 outs() << format(Fmt: "%.*s", Vals: BytesStr.size(), Vals: sect) << "\n";
2064 return;
2065 }
2066 }
2067}
2068
2069// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
2070// and if it is and there is a list of architecture flags is specified then
2071// check to make sure this Mach-O file is one of those architectures or all
2072// architectures were specified. If not then an error is generated and this
2073// routine returns false. Else it returns true.
2074static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
2075 auto *MachO = dyn_cast<MachOObjectFile>(Val: O);
2076
2077 if (!MachO || ArchAll || ArchFlags.empty())
2078 return true;
2079
2080 MachO::mach_header H;
2081 MachO::mach_header_64 H_64;
2082 Triple T;
2083 const char *McpuDefault, *ArchFlag;
2084 if (MachO->is64Bit()) {
2085 H_64 = MachO->MachOObjectFile::getHeader64();
2086 T = MachOObjectFile::getArchTriple(CPUType: H_64.cputype, CPUSubType: H_64.cpusubtype,
2087 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2088 } else {
2089 H = MachO->MachOObjectFile::getHeader();
2090 T = MachOObjectFile::getArchTriple(CPUType: H.cputype, CPUSubType: H.cpusubtype,
2091 McpuDefault: &McpuDefault, ArchFlag: &ArchFlag);
2092 }
2093 const std::string ArchFlagName(ArchFlag);
2094 if (!llvm::is_contained(Range&: ArchFlags, Element: ArchFlagName)) {
2095 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2096 << Filename << ": no architecture specified.\n";
2097 return false;
2098 }
2099 return true;
2100}
2101
2102static void printObjcMetaData(MachOObjectFile *O, bool verbose);
2103
2104// ProcessMachO() is passed a single opened Mach-O file, which may be an
2105// archive member and or in a slice of a universal file. It prints the
2106// the file name and header info and then processes it according to the
2107// command line options.
2108static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
2109 StringRef ArchiveMemberName = StringRef(),
2110 StringRef ArchitectureName = StringRef()) {
2111 std::unique_ptr<Dumper> D = createMachODumper(Obj: *MachOOF);
2112
2113 // If we are doing some processing here on the Mach-O file print the header
2114 // info. And don't print it otherwise like in the case of printing the
2115 // UniversalHeaders or ArchiveHeaders.
2116 if (Disassemble || Relocations || PrivateHeaders || ExportsTrie || Rebase ||
2117 Bind || SymbolTable || LazyBind || WeakBind || IndirectSymbols ||
2118 DataInCode || FunctionStartsType != FunctionStartsMode::None ||
2119 LinkOptHints || ChainedFixups || DyldInfo || DylibsUsed || DylibId ||
2120 Rpaths || ObjcMetaData || (!FilterSections.empty())) {
2121 if (LeadingHeaders) {
2122 outs() << Name;
2123 if (!ArchiveMemberName.empty())
2124 outs() << '(' << ArchiveMemberName << ')';
2125 if (!ArchitectureName.empty())
2126 outs() << " (architecture " << ArchitectureName << ")";
2127 outs() << ":\n";
2128 }
2129 }
2130 // To use the report_error() form with an ArchiveName and FileName set
2131 // these up based on what is passed for Name and ArchiveMemberName.
2132 StringRef ArchiveName;
2133 StringRef FileName;
2134 if (!ArchiveMemberName.empty()) {
2135 ArchiveName = Name;
2136 FileName = ArchiveMemberName;
2137 } else {
2138 ArchiveName = StringRef();
2139 FileName = Name;
2140 }
2141
2142 // If we need the symbol table to do the operation then check it here to
2143 // produce a good error message as to where the Mach-O file comes from in
2144 // the error message.
2145 if (Disassemble || IndirectSymbols || !FilterSections.empty() || UnwindInfo)
2146 if (Error Err = MachOOF->checkSymbolTable())
2147 reportError(E: std::move(Err), FileName, ArchiveName, ArchitectureName);
2148
2149 if (DisassembleAll) {
2150 for (const SectionRef &Section : MachOOF->sections()) {
2151 StringRef SectName;
2152 if (Expected<StringRef> NameOrErr = Section.getName())
2153 SectName = *NameOrErr;
2154 else
2155 consumeError(Err: NameOrErr.takeError());
2156
2157 if (SectName == "__text") {
2158 DataRefImpl Ref = Section.getRawDataRefImpl();
2159 StringRef SegName = MachOOF->getSectionFinalSegmentName(Sec: Ref);
2160 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: SegName, DisSectName: SectName);
2161 }
2162 }
2163 }
2164 else if (Disassemble) {
2165 if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
2166 MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
2167 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: "__TEXT_EXEC", DisSectName: "__text");
2168 else
2169 DisassembleMachO(Filename: FileName, MachOOF, DisSegName: "__TEXT", DisSectName: "__text");
2170 }
2171 if (IndirectSymbols)
2172 PrintIndirectSymbols(O: MachOOF, verbose: Verbose);
2173 if (DataInCode)
2174 PrintDataInCodeTable(O: MachOOF, verbose: Verbose);
2175 if (FunctionStartsType != FunctionStartsMode::None)
2176 PrintFunctionStarts(O: MachOOF);
2177 if (LinkOptHints)
2178 PrintLinkOptHints(O: MachOOF);
2179 if (Relocations)
2180 PrintRelocations(O: MachOOF, verbose: Verbose);
2181 if (SectionHeaders)
2182 printSectionHeaders(O&: *MachOOF);
2183 if (SectionContents)
2184 printSectionContents(O: MachOOF);
2185 if (!FilterSections.empty())
2186 DumpSectionContents(Filename: FileName, O: MachOOF, verbose: Verbose);
2187 if (InfoPlist)
2188 DumpInfoPlistSectionContents(Filename: FileName, O: MachOOF);
2189 if (DyldInfo)
2190 PrintDyldInfo(O: MachOOF);
2191 if (ChainedFixups)
2192 PrintChainedFixups(O: MachOOF);
2193 if (DylibsUsed)
2194 PrintDylibs(O: MachOOF, JustId: false);
2195 if (DylibId)
2196 PrintDylibs(O: MachOOF, JustId: true);
2197 if (SymbolTable)
2198 D->printSymbolTable(ArchiveName, ArchitectureName);
2199 if (UnwindInfo)
2200 printMachOUnwindInfo(O: MachOOF);
2201 if (PrivateHeaders) {
2202 printMachOFileHeader(O: MachOOF);
2203 printMachOLoadCommands(O: MachOOF);
2204 }
2205 if (FirstPrivateHeader)
2206 printMachOFileHeader(O: MachOOF);
2207 if (ObjcMetaData)
2208 printObjcMetaData(O: MachOOF, verbose: Verbose);
2209 if (ExportsTrie)
2210 printExportsTrie(O: MachOOF);
2211 if (Rebase)
2212 printRebaseTable(O: MachOOF);
2213 if (Rpaths)
2214 printRpaths(O: MachOOF);
2215 if (Bind)
2216 printBindTable(O: MachOOF);
2217 if (LazyBind)
2218 printLazyBindTable(O: MachOOF);
2219 if (WeakBind)
2220 printWeakBindTable(O: MachOOF);
2221
2222 if (DwarfDumpType != DIDT_Null) {
2223 std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj: *MachOOF);
2224 // Dump the complete DWARF structure.
2225 DIDumpOptions DumpOpts;
2226 DumpOpts.DumpType = DwarfDumpType;
2227 DICtx->dump(OS&: outs(), DumpOpts);
2228 }
2229}
2230
2231// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
2232static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
2233 outs() << " cputype (" << cputype << ")\n";
2234 outs() << " cpusubtype (" << cpusubtype << ")\n";
2235}
2236
2237// printCPUType() helps print_fat_headers by printing the cputype and
2238// pusubtype (symbolically for the one's it knows about).
2239static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
2240 switch (cputype) {
2241 case MachO::CPU_TYPE_I386:
2242 switch (cpusubtype) {
2243 case MachO::CPU_SUBTYPE_I386_ALL:
2244 outs() << " cputype CPU_TYPE_I386\n";
2245 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
2246 break;
2247 default:
2248 printUnknownCPUType(cputype, cpusubtype);
2249 break;
2250 }
2251 break;
2252 case MachO::CPU_TYPE_X86_64:
2253 switch (cpusubtype) {
2254 case MachO::CPU_SUBTYPE_X86_64_ALL:
2255 outs() << " cputype CPU_TYPE_X86_64\n";
2256 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
2257 break;
2258 case MachO::CPU_SUBTYPE_X86_64_H:
2259 outs() << " cputype CPU_TYPE_X86_64\n";
2260 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
2261 break;
2262 default:
2263 printUnknownCPUType(cputype, cpusubtype);
2264 break;
2265 }
2266 break;
2267 case MachO::CPU_TYPE_ARM:
2268 switch (cpusubtype) {
2269 case MachO::CPU_SUBTYPE_ARM_ALL:
2270 outs() << " cputype CPU_TYPE_ARM\n";
2271 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
2272 break;
2273 case MachO::CPU_SUBTYPE_ARM_V4T:
2274 outs() << " cputype CPU_TYPE_ARM\n";
2275 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
2276 break;
2277 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
2278 outs() << " cputype CPU_TYPE_ARM\n";
2279 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
2280 break;
2281 case MachO::CPU_SUBTYPE_ARM_XSCALE:
2282 outs() << " cputype CPU_TYPE_ARM\n";
2283 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
2284 break;
2285 case MachO::CPU_SUBTYPE_ARM_V6:
2286 outs() << " cputype CPU_TYPE_ARM\n";
2287 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
2288 break;
2289 case MachO::CPU_SUBTYPE_ARM_V6M:
2290 outs() << " cputype CPU_TYPE_ARM\n";
2291 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
2292 break;
2293 case MachO::CPU_SUBTYPE_ARM_V7:
2294 outs() << " cputype CPU_TYPE_ARM\n";
2295 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
2296 break;
2297 case MachO::CPU_SUBTYPE_ARM_V7EM:
2298 outs() << " cputype CPU_TYPE_ARM\n";
2299 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
2300 break;
2301 case MachO::CPU_SUBTYPE_ARM_V7K:
2302 outs() << " cputype CPU_TYPE_ARM\n";
2303 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
2304 break;
2305 case MachO::CPU_SUBTYPE_ARM_V7M:
2306 outs() << " cputype CPU_TYPE_ARM\n";
2307 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
2308 break;
2309 case MachO::CPU_SUBTYPE_ARM_V7S:
2310 outs() << " cputype CPU_TYPE_ARM\n";
2311 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
2312 break;
2313 default:
2314 printUnknownCPUType(cputype, cpusubtype);
2315 break;
2316 }
2317 break;
2318 case MachO::CPU_TYPE_ARM64:
2319 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2320 case MachO::CPU_SUBTYPE_ARM64_ALL:
2321 outs() << " cputype CPU_TYPE_ARM64\n";
2322 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
2323 break;
2324 case MachO::CPU_SUBTYPE_ARM64_V8:
2325 outs() << " cputype CPU_TYPE_ARM64\n";
2326 outs() << " cpusubtype CPU_SUBTYPE_ARM64_V8\n";
2327 break;
2328 case MachO::CPU_SUBTYPE_ARM64E:
2329 outs() << " cputype CPU_TYPE_ARM64\n";
2330 outs() << " cpusubtype CPU_SUBTYPE_ARM64E\n";
2331 break;
2332 default:
2333 printUnknownCPUType(cputype, cpusubtype);
2334 break;
2335 }
2336 break;
2337 case MachO::CPU_TYPE_ARM64_32:
2338 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
2339 case MachO::CPU_SUBTYPE_ARM64_32_V8:
2340 outs() << " cputype CPU_TYPE_ARM64_32\n";
2341 outs() << " cpusubtype CPU_SUBTYPE_ARM64_32_V8\n";
2342 break;
2343 default:
2344 printUnknownCPUType(cputype, cpusubtype);
2345 break;
2346 }
2347 break;
2348 default:
2349 printUnknownCPUType(cputype, cpusubtype);
2350 break;
2351 }
2352}
2353
2354static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
2355 bool verbose) {
2356 outs() << "Fat headers\n";
2357 if (verbose) {
2358 if (UB->getMagic() == MachO::FAT_MAGIC)
2359 outs() << "fat_magic FAT_MAGIC\n";
2360 else // UB->getMagic() == MachO::FAT_MAGIC_64
2361 outs() << "fat_magic FAT_MAGIC_64\n";
2362 } else
2363 outs() << "fat_magic " << format(Fmt: "0x%" PRIx32, Vals: MachO::FAT_MAGIC) << "\n";
2364
2365 uint32_t nfat_arch = UB->getNumberOfObjects();
2366 StringRef Buf = UB->getData();
2367 uint64_t size = Buf.size();
2368 uint64_t big_size = sizeof(struct MachO::fat_header) +
2369 nfat_arch * sizeof(struct MachO::fat_arch);
2370 outs() << "nfat_arch " << UB->getNumberOfObjects();
2371 if (nfat_arch == 0)
2372 outs() << " (malformed, contains zero architecture types)\n";
2373 else if (big_size > size)
2374 outs() << " (malformed, architectures past end of file)\n";
2375 else
2376 outs() << "\n";
2377
2378 for (uint32_t i = 0; i < nfat_arch; ++i) {
2379 MachOUniversalBinary::ObjectForArch OFA(UB, i);
2380 uint32_t cputype = OFA.getCPUType();
2381 uint32_t cpusubtype = OFA.getCPUSubType();
2382 outs() << "architecture ";
2383 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
2384 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
2385 uint32_t other_cputype = other_OFA.getCPUType();
2386 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
2387 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
2388 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
2389 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
2390 outs() << "(illegal duplicate architecture) ";
2391 break;
2392 }
2393 }
2394 if (verbose) {
2395 outs() << OFA.getArchFlagName() << "\n";
2396 printCPUType(cputype, cpusubtype: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
2397 } else {
2398 outs() << i << "\n";
2399 outs() << " cputype " << cputype << "\n";
2400 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
2401 << "\n";
2402 }
2403 if (verbose && cputype == MachO::CPU_TYPE_ARM64 &&
2404 MachO::CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(ST: cpusubtype)) {
2405 outs() << " capabilities CPU_SUBTYPE_ARM64E_";
2406 if (MachO::CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(ST: cpusubtype))
2407 outs() << "KERNEL_";
2408 outs() << format(Fmt: "PTRAUTH_VERSION %d",
2409 Vals: MachO::CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(ST: cpusubtype))
2410 << "\n";
2411 } else if (verbose && (cpusubtype & MachO::CPU_SUBTYPE_MASK) ==
2412 MachO::CPU_SUBTYPE_LIB64)
2413 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
2414 else
2415 outs() << " capabilities "
2416 << format(Fmt: "0x%" PRIx32,
2417 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
2418 outs() << " offset " << OFA.getOffset();
2419 if (OFA.getOffset() > size)
2420 outs() << " (past end of file)";
2421 if (OFA.getOffset() % (1ull << OFA.getAlign()) != 0)
2422 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
2423 outs() << "\n";
2424 outs() << " size " << OFA.getSize();
2425 big_size = OFA.getOffset() + OFA.getSize();
2426 if (big_size > size)
2427 outs() << " (past end of file)";
2428 outs() << "\n";
2429 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
2430 << ")\n";
2431 }
2432}
2433
2434static void printArchiveChild(StringRef Filename, const Archive::Child &C,
2435 size_t ChildIndex, bool verbose,
2436 bool print_offset,
2437 StringRef ArchitectureName = StringRef()) {
2438 if (print_offset)
2439 outs() << C.getChildOffset() << "\t";
2440 sys::fs::perms Mode =
2441 unwrapOrError(EO: C.getAccessMode(), Args: getFileNameForError(C, Index: ChildIndex),
2442 Args&: Filename, Args&: ArchitectureName);
2443 if (verbose) {
2444 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
2445 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
2446 outs() << "-";
2447 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2448 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2449 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2450 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2451 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2452 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2453 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2454 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2455 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2456 } else {
2457 outs() << format(Fmt: "0%o ", Vals: Mode);
2458 }
2459
2460 outs() << format(Fmt: "%3d/%-3d %5" PRId64 " ",
2461 Vals: unwrapOrError(EO: C.getUID(), Args: getFileNameForError(C, Index: ChildIndex),
2462 Args&: Filename, Args&: ArchitectureName),
2463 Vals: unwrapOrError(EO: C.getGID(), Args: getFileNameForError(C, Index: ChildIndex),
2464 Args&: Filename, Args&: ArchitectureName),
2465 Vals: unwrapOrError(EO: C.getRawSize(),
2466 Args: getFileNameForError(C, Index: ChildIndex), Args&: Filename,
2467 Args&: ArchitectureName));
2468
2469 StringRef RawLastModified = C.getRawLastModified();
2470 if (verbose) {
2471 unsigned Seconds;
2472 if (RawLastModified.getAsInteger(Radix: 10, Result&: Seconds))
2473 outs() << "(date: \"" << RawLastModified
2474 << "\" contains non-decimal chars) ";
2475 else {
2476 // Since cime(3) returns a 26 character string of the form:
2477 // "Sun Sep 16 01:03:52 1973\n\0"
2478 // just print 24 characters.
2479 time_t t = Seconds;
2480 outs() << format(Fmt: "%.24s ", Vals: ctime(timer: &t));
2481 }
2482 } else {
2483 outs() << RawLastModified << " ";
2484 }
2485
2486 if (verbose) {
2487 Expected<StringRef> NameOrErr = C.getName();
2488 if (!NameOrErr) {
2489 consumeError(Err: NameOrErr.takeError());
2490 outs() << unwrapOrError(EO: C.getRawName(),
2491 Args: getFileNameForError(C, Index: ChildIndex), Args&: Filename,
2492 Args&: ArchitectureName)
2493 << "\n";
2494 } else {
2495 StringRef Name = NameOrErr.get();
2496 outs() << Name << "\n";
2497 }
2498 } else {
2499 outs() << unwrapOrError(EO: C.getRawName(), Args: getFileNameForError(C, Index: ChildIndex),
2500 Args&: Filename, Args&: ArchitectureName)
2501 << "\n";
2502 }
2503}
2504
2505static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
2506 bool print_offset,
2507 StringRef ArchitectureName = StringRef()) {
2508 Error Err = Error::success();
2509 size_t I = 0;
2510 for (const auto &C : A->children(Err, SkipInternal: false))
2511 printArchiveChild(Filename, C, ChildIndex: I++, verbose, print_offset,
2512 ArchitectureName);
2513
2514 if (Err)
2515 reportError(E: std::move(Err), FileName: Filename, ArchiveName: "", ArchitectureName);
2516}
2517
2518static bool ValidateArchFlags() {
2519 // Check for -arch all and verifiy the -arch flags are valid.
2520 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2521 if (ArchFlags[i] == "all") {
2522 ArchAll = true;
2523 } else {
2524 if (!MachOObjectFile::isValidArch(ArchFlag: ArchFlags[i])) {
2525 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2526 << "unknown architecture named '" + ArchFlags[i] +
2527 "'for the -arch option\n";
2528 return false;
2529 }
2530 }
2531 }
2532 return true;
2533}
2534
2535// ParseInputMachO() parses the named Mach-O file in Filename and handles the
2536// -arch flags selecting just those slices as specified by them and also parses
2537// archive files. Then for each individual Mach-O file ProcessMachO() is
2538// called to process the file based on the command line options.
2539void objdump::parseInputMachO(StringRef Filename) {
2540 if (!ValidateArchFlags())
2541 return;
2542
2543 // Attempt to open the binary.
2544 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Path: Filename);
2545 if (!BinaryOrErr) {
2546 if (Error E = isNotObjectErrorInvalidFileType(Err: BinaryOrErr.takeError()))
2547 reportError(E: std::move(E), FileName: Filename);
2548 else
2549 outs() << Filename << ": is not an object file\n";
2550 return;
2551 }
2552 Binary &Bin = *BinaryOrErr.get().getBinary();
2553
2554 if (Archive *A = dyn_cast<Archive>(Val: &Bin)) {
2555 outs() << "Archive : " << Filename << "\n";
2556 if (ArchiveHeaders)
2557 printArchiveHeaders(Filename, A, verbose: Verbose, print_offset: ArchiveMemberOffsets);
2558
2559 Error Err = Error::success();
2560 unsigned I = -1;
2561 for (auto &C : A->children(Err)) {
2562 ++I;
2563 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2564 if (!ChildOrErr) {
2565 if (Error E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2566 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename);
2567 continue;
2568 }
2569 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get())) {
2570 if (!checkMachOAndArchFlags(O, Filename))
2571 return;
2572 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName());
2573 }
2574 }
2575 if (Err)
2576 reportError(E: std::move(Err), FileName: Filename);
2577 return;
2578 }
2579 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Bin)) {
2580 parseInputMachO(UB);
2581 return;
2582 }
2583 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Bin)) {
2584 if (!checkMachOAndArchFlags(O, Filename))
2585 return;
2586 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &*O))
2587 ProcessMachO(Name: Filename, MachOOF);
2588 else
2589 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2590 << Filename << "': "
2591 << "object is not a Mach-O file type.\n";
2592 return;
2593 }
2594 llvm_unreachable("Input object can't be invalid at this point");
2595}
2596
2597void objdump::parseInputMachO(MachOUniversalBinary *UB) {
2598 if (!ValidateArchFlags())
2599 return;
2600
2601 auto Filename = UB->getFileName();
2602
2603 if (UniversalHeaders)
2604 printMachOUniversalHeaders(UB, verbose: Verbose);
2605
2606 // If we have a list of architecture flags specified dump only those.
2607 if (!ArchAll && !ArchFlags.empty()) {
2608 // Look for a slice in the universal binary that matches each ArchFlag.
2609 bool ArchFound;
2610 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
2611 ArchFound = false;
2612 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2613 E = UB->end_objects();
2614 I != E; ++I) {
2615 if (ArchFlags[i] == I->getArchFlagName()) {
2616 ArchFound = true;
2617 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
2618 I->getAsObjectFile();
2619 std::string ArchitectureName;
2620 if (ArchFlags.size() > 1)
2621 ArchitectureName = I->getArchFlagName();
2622 if (ObjOrErr) {
2623 ObjectFile &O = *ObjOrErr.get();
2624 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &O))
2625 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: "", ArchitectureName);
2626 } else if (Error E = isNotObjectErrorInvalidFileType(
2627 Err: ObjOrErr.takeError())) {
2628 reportError(E: std::move(E), FileName: "", ArchiveName: Filename, ArchitectureName);
2629 continue;
2630 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2631 I->getAsArchive()) {
2632 std::unique_ptr<Archive> &A = *AOrErr;
2633 outs() << "Archive : " << Filename;
2634 if (!ArchitectureName.empty())
2635 outs() << " (architecture " << ArchitectureName << ")";
2636 outs() << "\n";
2637 if (ArchiveHeaders)
2638 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose,
2639 print_offset: ArchiveMemberOffsets, ArchitectureName);
2640 Error Err = Error::success();
2641 unsigned I = -1;
2642 for (auto &C : A->children(Err)) {
2643 ++I;
2644 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2645 if (!ChildOrErr) {
2646 if (Error E =
2647 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2648 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename,
2649 ArchitectureName);
2650 continue;
2651 }
2652 if (MachOObjectFile *O =
2653 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get()))
2654 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName(), ArchitectureName);
2655 }
2656 if (Err)
2657 reportError(E: std::move(Err), FileName: Filename);
2658 } else {
2659 consumeError(Err: AOrErr.takeError());
2660 reportError(File: Filename,
2661 Message: "Mach-O universal file for architecture " +
2662 StringRef(I->getArchFlagName()) +
2663 " is not a Mach-O file or an archive file");
2664 }
2665 }
2666 }
2667 if (!ArchFound) {
2668 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
2669 << "file: " + Filename + " does not contain "
2670 << "architecture: " + ArchFlags[i] + "\n";
2671 return;
2672 }
2673 }
2674 return;
2675 }
2676 // No architecture flags were specified so if this contains a slice that
2677 // matches the host architecture dump only that.
2678 if (!ArchAll) {
2679 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2680 E = UB->end_objects();
2681 I != E; ++I) {
2682 if (MachOObjectFile::getHostArch().getArchName() ==
2683 I->getArchFlagName()) {
2684 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2685 std::string ArchiveName;
2686 ArchiveName.clear();
2687 if (ObjOrErr) {
2688 ObjectFile &O = *ObjOrErr.get();
2689 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &O))
2690 ProcessMachO(Name: Filename, MachOOF);
2691 } else if (Error E =
2692 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2693 reportError(E: std::move(E), FileName: Filename);
2694 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
2695 I->getAsArchive()) {
2696 std::unique_ptr<Archive> &A = *AOrErr;
2697 outs() << "Archive : " << Filename << "\n";
2698 if (ArchiveHeaders)
2699 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose,
2700 print_offset: ArchiveMemberOffsets);
2701 Error Err = Error::success();
2702 unsigned I = -1;
2703 for (auto &C : A->children(Err)) {
2704 ++I;
2705 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2706 if (!ChildOrErr) {
2707 if (Error E =
2708 isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2709 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename);
2710 continue;
2711 }
2712 if (MachOObjectFile *O =
2713 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get()))
2714 ProcessMachO(Name: Filename, MachOOF: O, ArchiveMemberName: O->getFileName());
2715 }
2716 if (Err)
2717 reportError(E: std::move(Err), FileName: Filename);
2718 } else {
2719 consumeError(Err: AOrErr.takeError());
2720 reportError(File: Filename, Message: "Mach-O universal file for architecture " +
2721 StringRef(I->getArchFlagName()) +
2722 " is not a Mach-O file or an archive file");
2723 }
2724 return;
2725 }
2726 }
2727 }
2728 // Either all architectures have been specified or none have been specified
2729 // and this does not contain the host architecture so dump all the slices.
2730 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
2731 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
2732 E = UB->end_objects();
2733 I != E; ++I) {
2734 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
2735 std::string ArchitectureName;
2736 if (moreThanOneArch)
2737 ArchitectureName = I->getArchFlagName();
2738 if (ObjOrErr) {
2739 ObjectFile &Obj = *ObjOrErr.get();
2740 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &Obj))
2741 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: "", ArchitectureName);
2742 } else if (Error E =
2743 isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError())) {
2744 reportError(E: std::move(E), FileName: Filename, ArchiveName: "", ArchitectureName);
2745 } else if (Expected<std::unique_ptr<Archive>> AOrErr = I->getAsArchive()) {
2746 std::unique_ptr<Archive> &A = *AOrErr;
2747 outs() << "Archive : " << Filename;
2748 if (!ArchitectureName.empty())
2749 outs() << " (architecture " << ArchitectureName << ")";
2750 outs() << "\n";
2751 if (ArchiveHeaders)
2752 printArchiveHeaders(Filename, A: A.get(), verbose: Verbose, print_offset: ArchiveMemberOffsets,
2753 ArchitectureName);
2754 Error Err = Error::success();
2755 unsigned I = -1;
2756 for (auto &C : A->children(Err)) {
2757 ++I;
2758 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2759 if (!ChildOrErr) {
2760 if (Error E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
2761 reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: Filename,
2762 ArchitectureName);
2763 continue;
2764 }
2765 if (MachOObjectFile *O =
2766 dyn_cast<MachOObjectFile>(Val: &*ChildOrErr.get())) {
2767 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: O))
2768 ProcessMachO(Name: Filename, MachOOF, ArchiveMemberName: MachOOF->getFileName(),
2769 ArchitectureName);
2770 }
2771 }
2772 if (Err)
2773 reportError(E: std::move(Err), FileName: Filename);
2774 } else {
2775 consumeError(Err: AOrErr.takeError());
2776 reportError(File: Filename, Message: "Mach-O universal file for architecture " +
2777 StringRef(I->getArchFlagName()) +
2778 " is not a Mach-O file or an archive file");
2779 }
2780 }
2781}
2782
2783namespace {
2784// The block of info used by the Symbolizer call backs.
2785struct DisassembleInfo {
2786 DisassembleInfo(MachOObjectFile *O, SymbolAddressMap *AddrMap,
2787 std::vector<SectionRef> *Sections, bool verbose)
2788 : verbose(verbose), O(O), AddrMap(AddrMap), Sections(Sections) {}
2789 bool verbose;
2790 MachOObjectFile *O;
2791 SectionRef S;
2792 SymbolAddressMap *AddrMap;
2793 std::vector<SectionRef> *Sections;
2794 const char *class_name = nullptr;
2795 const char *selector_name = nullptr;
2796 std::unique_ptr<char[]> method = nullptr;
2797 char *demangled_name = nullptr;
2798 uint64_t adrp_addr = 0;
2799 uint32_t adrp_inst = 0;
2800 std::unique_ptr<SymbolAddressMap> bindtable;
2801 uint32_t depth = 0;
2802};
2803} // namespace
2804
2805// SymbolizerGetOpInfo() is the operand information call back function.
2806// This is called to get the symbolic information for operand(s) of an
2807// instruction when it is being done. This routine does this from
2808// the relocation information, symbol table, etc. That block of information
2809// is a pointer to the struct DisassembleInfo that was passed when the
2810// disassembler context was created and passed to back to here when
2811// called back by the disassembler for instruction operands that could have
2812// relocation information. The address of the instruction containing operand is
2813// at the Pc parameter. The immediate value the operand has is passed in
2814// op_info->Value and is at Offset past the start of the instruction and has a
2815// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
2816// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
2817// names and addends of the symbolic expression to add for the operand. The
2818// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
2819// information is returned then this function returns 1 else it returns 0.
2820static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
2821 uint64_t OpSize, uint64_t InstSize, int TagType,
2822 void *TagBuf) {
2823 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
2824 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
2825 uint64_t value = op_info->Value;
2826
2827 // Make sure all fields returned are zero if we don't set them.
2828 memset(s: (void *)op_info, c: '\0', n: sizeof(struct LLVMOpInfo1));
2829 op_info->Value = value;
2830
2831 // If the TagType is not the value 1 which it code knows about or if no
2832 // verbose symbolic information is wanted then just return 0, indicating no
2833 // information is being returned.
2834 if (TagType != 1 || !info->verbose)
2835 return 0;
2836
2837 unsigned int Arch = info->O->getArch();
2838 if (Arch == Triple::x86) {
2839 if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2840 return 0;
2841 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2842 // TODO:
2843 // Search the external relocation entries of a fully linked image
2844 // (if any) for an entry that matches this segment offset.
2845 // uint32_t seg_offset = (Pc + Offset);
2846 return 0;
2847 }
2848 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2849 // for an entry for this section offset.
2850 uint32_t sect_addr = info->S.getAddress();
2851 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2852 bool reloc_found = false;
2853 DataRefImpl Rel;
2854 MachO::any_relocation_info RE;
2855 bool isExtern = false;
2856 SymbolRef Symbol;
2857 bool r_scattered = false;
2858 uint32_t r_value, pair_r_value, r_type;
2859 for (const RelocationRef &Reloc : info->S.relocations()) {
2860 uint64_t RelocOffset = Reloc.getOffset();
2861 if (RelocOffset == sect_offset) {
2862 Rel = Reloc.getRawDataRefImpl();
2863 RE = info->O->getRelocation(Rel);
2864 r_type = info->O->getAnyRelocationType(RE);
2865 r_scattered = info->O->isRelocationScattered(RE);
2866 if (r_scattered) {
2867 r_value = info->O->getScatteredRelocationValue(RE);
2868 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2869 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
2870 DataRefImpl RelNext = Rel;
2871 info->O->moveRelocationNext(Rel&: RelNext);
2872 MachO::any_relocation_info RENext;
2873 RENext = info->O->getRelocation(Rel: RelNext);
2874 if (info->O->isRelocationScattered(RE: RENext))
2875 pair_r_value = info->O->getScatteredRelocationValue(RE: RENext);
2876 else
2877 return 0;
2878 }
2879 } else {
2880 isExtern = info->O->getPlainRelocationExternal(RE);
2881 if (isExtern) {
2882 symbol_iterator RelocSym = Reloc.getSymbol();
2883 Symbol = *RelocSym;
2884 }
2885 }
2886 reloc_found = true;
2887 break;
2888 }
2889 }
2890 if (reloc_found && isExtern) {
2891 op_info->AddSymbol.Present = 1;
2892 op_info->AddSymbol.Name =
2893 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
2894 // For i386 extern relocation entries the value in the instruction is
2895 // the offset from the symbol, and value is already set in op_info->Value.
2896 return 1;
2897 }
2898 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
2899 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
2900 const char *add = GuessSymbolName(value: r_value, AddrMap: info->AddrMap);
2901 const char *sub = GuessSymbolName(value: pair_r_value, AddrMap: info->AddrMap);
2902 uint32_t offset = value - (r_value - pair_r_value);
2903 op_info->AddSymbol.Present = 1;
2904 if (add != nullptr)
2905 op_info->AddSymbol.Name = add;
2906 else
2907 op_info->AddSymbol.Value = r_value;
2908 op_info->SubtractSymbol.Present = 1;
2909 if (sub != nullptr)
2910 op_info->SubtractSymbol.Name = sub;
2911 else
2912 op_info->SubtractSymbol.Value = pair_r_value;
2913 op_info->Value = offset;
2914 return 1;
2915 }
2916 return 0;
2917 }
2918 if (Arch == Triple::x86_64) {
2919 if (OpSize != 1 && OpSize != 2 && OpSize != 4 && OpSize != 0)
2920 return 0;
2921 // For non MH_OBJECT types, like MH_KEXT_BUNDLE, Search the external
2922 // relocation entries of a linked image (if any) for an entry that matches
2923 // this segment offset.
2924 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2925 uint64_t seg_offset = Pc + Offset;
2926 bool reloc_found = false;
2927 DataRefImpl Rel;
2928 MachO::any_relocation_info RE;
2929 bool isExtern = false;
2930 SymbolRef Symbol;
2931 for (const RelocationRef &Reloc : info->O->external_relocations()) {
2932 uint64_t RelocOffset = Reloc.getOffset();
2933 if (RelocOffset == seg_offset) {
2934 Rel = Reloc.getRawDataRefImpl();
2935 RE = info->O->getRelocation(Rel);
2936 // external relocation entries should always be external.
2937 isExtern = info->O->getPlainRelocationExternal(RE);
2938 if (isExtern) {
2939 symbol_iterator RelocSym = Reloc.getSymbol();
2940 Symbol = *RelocSym;
2941 }
2942 reloc_found = true;
2943 break;
2944 }
2945 }
2946 if (reloc_found && isExtern) {
2947 // The Value passed in will be adjusted by the Pc if the instruction
2948 // adds the Pc. But for x86_64 external relocation entries the Value
2949 // is the offset from the external symbol.
2950 if (info->O->getAnyRelocationPCRel(RE))
2951 op_info->Value -= Pc + InstSize;
2952 const char *name =
2953 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
2954 op_info->AddSymbol.Present = 1;
2955 op_info->AddSymbol.Name = name;
2956 return 1;
2957 }
2958 return 0;
2959 }
2960 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2961 // for an entry for this section offset.
2962 uint64_t sect_addr = info->S.getAddress();
2963 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2964 bool reloc_found = false;
2965 DataRefImpl Rel;
2966 MachO::any_relocation_info RE;
2967 bool isExtern = false;
2968 SymbolRef Symbol;
2969 for (const RelocationRef &Reloc : info->S.relocations()) {
2970 uint64_t RelocOffset = Reloc.getOffset();
2971 if (RelocOffset == sect_offset) {
2972 Rel = Reloc.getRawDataRefImpl();
2973 RE = info->O->getRelocation(Rel);
2974 // NOTE: Scattered relocations don't exist on x86_64.
2975 isExtern = info->O->getPlainRelocationExternal(RE);
2976 if (isExtern) {
2977 symbol_iterator RelocSym = Reloc.getSymbol();
2978 Symbol = *RelocSym;
2979 }
2980 reloc_found = true;
2981 break;
2982 }
2983 }
2984 if (reloc_found && isExtern) {
2985 // The Value passed in will be adjusted by the Pc if the instruction
2986 // adds the Pc. But for x86_64 external relocation entries the Value
2987 // is the offset from the external symbol.
2988 if (info->O->getAnyRelocationPCRel(RE))
2989 op_info->Value -= Pc + InstSize;
2990 const char *name =
2991 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
2992 unsigned Type = info->O->getAnyRelocationType(RE);
2993 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
2994 DataRefImpl RelNext = Rel;
2995 info->O->moveRelocationNext(Rel&: RelNext);
2996 MachO::any_relocation_info RENext = info->O->getRelocation(Rel: RelNext);
2997 unsigned TypeNext = info->O->getAnyRelocationType(RE: RENext);
2998 bool isExternNext = info->O->getPlainRelocationExternal(RE: RENext);
2999 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RE: RENext);
3000 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
3001 op_info->SubtractSymbol.Present = 1;
3002 op_info->SubtractSymbol.Name = name;
3003 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(Index: SymbolNum);
3004 Symbol = *RelocSymNext;
3005 name = unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3006 }
3007 }
3008 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
3009 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
3010 op_info->AddSymbol.Present = 1;
3011 op_info->AddSymbol.Name = name;
3012 return 1;
3013 }
3014 return 0;
3015 }
3016 if (Arch == Triple::arm) {
3017 if (Offset != 0 || (InstSize != 4 && InstSize != 2))
3018 return 0;
3019 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3020 // TODO:
3021 // Search the external relocation entries of a fully linked image
3022 // (if any) for an entry that matches this segment offset.
3023 // uint32_t seg_offset = (Pc + Offset);
3024 return 0;
3025 }
3026 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3027 // for an entry for this section offset.
3028 uint32_t sect_addr = info->S.getAddress();
3029 uint32_t sect_offset = (Pc + Offset) - sect_addr;
3030 DataRefImpl Rel;
3031 MachO::any_relocation_info RE;
3032 bool isExtern = false;
3033 SymbolRef Symbol;
3034 bool r_scattered = false;
3035 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
3036 auto Reloc =
3037 find_if(Range: info->S.relocations(), P: [&](const RelocationRef &Reloc) {
3038 uint64_t RelocOffset = Reloc.getOffset();
3039 return RelocOffset == sect_offset;
3040 });
3041
3042 if (Reloc == info->S.relocations().end())
3043 return 0;
3044
3045 Rel = Reloc->getRawDataRefImpl();
3046 RE = info->O->getRelocation(Rel);
3047 r_length = info->O->getAnyRelocationLength(RE);
3048 r_scattered = info->O->isRelocationScattered(RE);
3049 if (r_scattered) {
3050 r_value = info->O->getScatteredRelocationValue(RE);
3051 r_type = info->O->getScatteredRelocationType(RE);
3052 } else {
3053 r_type = info->O->getAnyRelocationType(RE);
3054 isExtern = info->O->getPlainRelocationExternal(RE);
3055 if (isExtern) {
3056 symbol_iterator RelocSym = Reloc->getSymbol();
3057 Symbol = *RelocSym;
3058 }
3059 }
3060 if (r_type == MachO::ARM_RELOC_HALF ||
3061 r_type == MachO::ARM_RELOC_SECTDIFF ||
3062 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
3063 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3064 DataRefImpl RelNext = Rel;
3065 info->O->moveRelocationNext(Rel&: RelNext);
3066 MachO::any_relocation_info RENext;
3067 RENext = info->O->getRelocation(Rel: RelNext);
3068 other_half = info->O->getAnyRelocationAddress(RE: RENext) & 0xffff;
3069 if (info->O->isRelocationScattered(RE: RENext))
3070 pair_r_value = info->O->getScatteredRelocationValue(RE: RENext);
3071 }
3072
3073 if (isExtern) {
3074 const char *name =
3075 unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName()).data();
3076 op_info->AddSymbol.Present = 1;
3077 op_info->AddSymbol.Name = name;
3078 switch (r_type) {
3079 case MachO::ARM_RELOC_HALF:
3080 if ((r_length & 0x1) == 1) {
3081 op_info->Value = value << 16 | other_half;
3082 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3083 } else {
3084 op_info->Value = other_half << 16 | value;
3085 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3086 }
3087 break;
3088 default:
3089 break;
3090 }
3091 return 1;
3092 }
3093 // If we have a branch that is not an external relocation entry then
3094 // return 0 so the code in tryAddingSymbolicOperand() can use the
3095 // SymbolLookUp call back with the branch target address to look up the
3096 // symbol and possibility add an annotation for a symbol stub.
3097 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
3098 r_type == MachO::ARM_THUMB_RELOC_BR22))
3099 return 0;
3100
3101 uint32_t offset = 0;
3102 if (r_type == MachO::ARM_RELOC_HALF ||
3103 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3104 if ((r_length & 0x1) == 1)
3105 value = value << 16 | other_half;
3106 else
3107 value = other_half << 16 | value;
3108 }
3109 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
3110 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
3111 offset = value - r_value;
3112 value = r_value;
3113 }
3114
3115 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
3116 if ((r_length & 0x1) == 1)
3117 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3118 else
3119 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3120 const char *add = GuessSymbolName(value: r_value, AddrMap: info->AddrMap);
3121 const char *sub = GuessSymbolName(value: pair_r_value, AddrMap: info->AddrMap);
3122 int32_t offset = value - (r_value - pair_r_value);
3123 op_info->AddSymbol.Present = 1;
3124 if (add != nullptr)
3125 op_info->AddSymbol.Name = add;
3126 else
3127 op_info->AddSymbol.Value = r_value;
3128 op_info->SubtractSymbol.Present = 1;
3129 if (sub != nullptr)
3130 op_info->SubtractSymbol.Name = sub;
3131 else
3132 op_info->SubtractSymbol.Value = pair_r_value;
3133 op_info->Value = offset;
3134 return 1;
3135 }
3136
3137 op_info->AddSymbol.Present = 1;
3138 op_info->Value = offset;
3139 if (r_type == MachO::ARM_RELOC_HALF) {
3140 if ((r_length & 0x1) == 1)
3141 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI16;
3142 else
3143 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO16;
3144 }
3145 const char *add = GuessSymbolName(value, AddrMap: info->AddrMap);
3146 if (add != nullptr) {
3147 op_info->AddSymbol.Name = add;
3148 return 1;
3149 }
3150 op_info->AddSymbol.Value = value;
3151 return 1;
3152 }
3153 if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32) {
3154 if (Offset != 0 || InstSize != 4)
3155 return 0;
3156 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
3157 // TODO:
3158 // Search the external relocation entries of a fully linked image
3159 // (if any) for an entry that matches this segment offset.
3160 // uint64_t seg_offset = (Pc + Offset);
3161 return 0;
3162 }
3163 // In MH_OBJECT filetypes search the section's relocation entries (if any)
3164 // for an entry for this section offset.
3165 uint64_t sect_addr = info->S.getAddress();
3166 uint64_t sect_offset = (Pc + Offset) - sect_addr;
3167 auto Reloc =
3168 find_if(Range: info->S.relocations(), P: [&](const RelocationRef &Reloc) {
3169 uint64_t RelocOffset = Reloc.getOffset();
3170 return RelocOffset == sect_offset;
3171 });
3172
3173 if (Reloc == info->S.relocations().end())
3174 return 0;
3175
3176 DataRefImpl Rel = Reloc->getRawDataRefImpl();
3177 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
3178 uint32_t r_type = info->O->getAnyRelocationType(RE);
3179 if (r_type == MachO::ARM64_RELOC_ADDEND) {
3180 DataRefImpl RelNext = Rel;
3181 info->O->moveRelocationNext(Rel&: RelNext);
3182 MachO::any_relocation_info RENext = info->O->getRelocation(Rel: RelNext);
3183 if (value == 0) {
3184 value = info->O->getPlainRelocationSymbolNum(RE: RENext);
3185 op_info->Value = value;
3186 }
3187 }
3188 // NOTE: Scattered relocations don't exist on arm64.
3189 if (!info->O->getPlainRelocationExternal(RE))
3190 return 0;
3191 const char *name =
3192 unwrapOrError(EO: Reloc->getSymbol()->getName(), Args: info->O->getFileName())
3193 .data();
3194 op_info->AddSymbol.Present = 1;
3195 op_info->AddSymbol.Name = name;
3196
3197 switch (r_type) {
3198 case MachO::ARM64_RELOC_PAGE21:
3199 /* @page */
3200 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE;
3201 break;
3202 case MachO::ARM64_RELOC_PAGEOFF12:
3203 /* @pageoff */
3204 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF;
3205 break;
3206 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
3207 /* @gotpage */
3208 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE;
3209 break;
3210 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
3211 /* @gotpageoff */
3212 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF;
3213 break;
3214 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
3215 /* @tvlppage is not implemented in llvm-mc */
3216 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP;
3217 break;
3218 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
3219 /* @tvlppageoff is not implemented in llvm-mc */
3220 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF;
3221 break;
3222 default:
3223 case MachO::ARM64_RELOC_BRANCH26:
3224 op_info->VariantKind = LLVMDisassembler_VariantKind_None;
3225 break;
3226 }
3227 return 1;
3228 }
3229 return 0;
3230}
3231
3232// GuessCstringPointer is passed the address of what might be a pointer to a
3233// literal string in a cstring section. If that address is in a cstring section
3234// it returns a pointer to that string. Else it returns nullptr.
3235static const char *GuessCstringPointer(uint64_t ReferenceValue,
3236 struct DisassembleInfo *info) {
3237 for (const auto &Load : info->O->load_commands()) {
3238 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3239 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3240 for (unsigned J = 0; J < Seg.nsects; ++J) {
3241 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3242 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3243 if (section_type == MachO::S_CSTRING_LITERALS &&
3244 ReferenceValue >= Sec.addr &&
3245 ReferenceValue < Sec.addr + Sec.size) {
3246 uint64_t sect_offset = ReferenceValue - Sec.addr;
3247 uint64_t object_offset = Sec.offset + sect_offset;
3248 StringRef MachOContents = info->O->getData();
3249 uint64_t object_size = MachOContents.size();
3250 const char *object_addr = MachOContents.data();
3251 if (object_offset < object_size) {
3252 const char *name = object_addr + object_offset;
3253 return name;
3254 } else {
3255 return nullptr;
3256 }
3257 }
3258 }
3259 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3260 MachO::segment_command Seg = info->O->getSegmentLoadCommand(L: Load);
3261 for (unsigned J = 0; J < Seg.nsects; ++J) {
3262 MachO::section Sec = info->O->getSection(L: Load, Index: J);
3263 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3264 if (section_type == MachO::S_CSTRING_LITERALS &&
3265 ReferenceValue >= Sec.addr &&
3266 ReferenceValue < Sec.addr + Sec.size) {
3267 uint64_t sect_offset = ReferenceValue - Sec.addr;
3268 uint64_t object_offset = Sec.offset + sect_offset;
3269 StringRef MachOContents = info->O->getData();
3270 uint64_t object_size = MachOContents.size();
3271 const char *object_addr = MachOContents.data();
3272 if (object_offset < object_size) {
3273 const char *name = object_addr + object_offset;
3274 return name;
3275 } else {
3276 return nullptr;
3277 }
3278 }
3279 }
3280 }
3281 }
3282 return nullptr;
3283}
3284
3285// GuessIndirectSymbol returns the name of the indirect symbol for the
3286// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
3287// an address of a symbol stub or a lazy or non-lazy pointer to associate the
3288// symbol name being referenced by the stub or pointer.
3289static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
3290 struct DisassembleInfo *info) {
3291 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
3292 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
3293 for (const auto &Load : info->O->load_commands()) {
3294 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3295 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3296 for (unsigned J = 0; J < Seg.nsects; ++J) {
3297 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3298 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3299 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3300 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3301 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3302 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3303 section_type == MachO::S_SYMBOL_STUBS) &&
3304 ReferenceValue >= Sec.addr &&
3305 ReferenceValue < Sec.addr + Sec.size) {
3306 uint32_t stride;
3307 if (section_type == MachO::S_SYMBOL_STUBS)
3308 stride = Sec.reserved2;
3309 else
3310 stride = 8;
3311 if (stride == 0)
3312 return nullptr;
3313 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3314 if (index < Dysymtab.nindirectsyms) {
3315 uint32_t indirect_symbol =
3316 info->O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: index);
3317 if (indirect_symbol < Symtab.nsyms) {
3318 symbol_iterator Sym = info->O->getSymbolByIndex(Index: indirect_symbol);
3319 return unwrapOrError(EO: Sym->getName(), Args: info->O->getFileName())
3320 .data();
3321 }
3322 }
3323 }
3324 }
3325 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
3326 MachO::segment_command Seg = info->O->getSegmentLoadCommand(L: Load);
3327 for (unsigned J = 0; J < Seg.nsects; ++J) {
3328 MachO::section Sec = info->O->getSection(L: Load, Index: J);
3329 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
3330 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
3331 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
3332 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
3333 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
3334 section_type == MachO::S_SYMBOL_STUBS) &&
3335 ReferenceValue >= Sec.addr &&
3336 ReferenceValue < Sec.addr + Sec.size) {
3337 uint32_t stride;
3338 if (section_type == MachO::S_SYMBOL_STUBS)
3339 stride = Sec.reserved2;
3340 else
3341 stride = 4;
3342 if (stride == 0)
3343 return nullptr;
3344 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
3345 if (index < Dysymtab.nindirectsyms) {
3346 uint32_t indirect_symbol =
3347 info->O->getIndirectSymbolTableEntry(DLC: Dysymtab, Index: index);
3348 if (indirect_symbol < Symtab.nsyms) {
3349 symbol_iterator Sym = info->O->getSymbolByIndex(Index: indirect_symbol);
3350 return unwrapOrError(EO: Sym->getName(), Args: info->O->getFileName())
3351 .data();
3352 }
3353 }
3354 }
3355 }
3356 }
3357 }
3358 return nullptr;
3359}
3360
3361// method_reference() is called passing it the ReferenceName that might be
3362// a reference it to an Objective-C method call. If so then it allocates and
3363// assembles a method call string with the values last seen and saved in
3364// the DisassembleInfo's class_name and selector_name fields. This is saved
3365// into the method field of the info and any previous string is free'ed.
3366// Then the class_name field in the info is set to nullptr. The method call
3367// string is set into ReferenceName and ReferenceType is set to
3368// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
3369// then both ReferenceType and ReferenceName are left unchanged.
3370static void method_reference(struct DisassembleInfo *info,
3371 uint64_t *ReferenceType,
3372 const char **ReferenceName) {
3373 unsigned int Arch = info->O->getArch();
3374 if (*ReferenceName != nullptr) {
3375 if (strcmp(s1: *ReferenceName, s2: "_objc_msgSend") == 0) {
3376 if (info->selector_name != nullptr) {
3377 if (info->class_name != nullptr) {
3378 info->method = std::make_unique<char[]>(
3379 num: 5 + strlen(s: info->class_name) + strlen(s: info->selector_name));
3380 char *method = info->method.get();
3381 if (method != nullptr) {
3382 strcpy(dest: method, src: "+[");
3383 strcat(dest: method, src: info->class_name);
3384 strcat(dest: method, src: " ");
3385 strcat(dest: method, src: info->selector_name);
3386 strcat(dest: method, src: "]");
3387 *ReferenceName = method;
3388 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3389 }
3390 } else {
3391 info->method =
3392 std::make_unique<char[]>(num: 9 + strlen(s: info->selector_name));
3393 char *method = info->method.get();
3394 if (method != nullptr) {
3395 if (Arch == Triple::x86_64)
3396 strcpy(dest: method, src: "-[%rdi ");
3397 else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32)
3398 strcpy(dest: method, src: "-[x0 ");
3399 else
3400 strcpy(dest: method, src: "-[r? ");
3401 strcat(dest: method, src: info->selector_name);
3402 strcat(dest: method, src: "]");
3403 *ReferenceName = method;
3404 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3405 }
3406 }
3407 info->class_name = nullptr;
3408 }
3409 } else if (strcmp(s1: *ReferenceName, s2: "_objc_msgSendSuper2") == 0) {
3410 if (info->selector_name != nullptr) {
3411 info->method =
3412 std::make_unique<char[]>(num: 17 + strlen(s: info->selector_name));
3413 char *method = info->method.get();
3414 if (method != nullptr) {
3415 if (Arch == Triple::x86_64)
3416 strcpy(dest: method, src: "-[[%rdi super] ");
3417 else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32)
3418 strcpy(dest: method, src: "-[[x0 super] ");
3419 else
3420 strcpy(dest: method, src: "-[[r? super] ");
3421 strcat(dest: method, src: info->selector_name);
3422 strcat(dest: method, src: "]");
3423 *ReferenceName = method;
3424 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message;
3425 }
3426 info->class_name = nullptr;
3427 }
3428 }
3429 }
3430}
3431
3432// GuessPointerPointer() is passed the address of what might be a pointer to
3433// a reference to an Objective-C class, selector, message ref or cfstring.
3434// If so the value of the pointer is returned and one of the booleans are set
3435// to true. If not zero is returned and all the booleans are set to false.
3436static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
3437 struct DisassembleInfo *info,
3438 bool &classref, bool &selref, bool &msgref,
3439 bool &cfstring) {
3440 classref = false;
3441 selref = false;
3442 msgref = false;
3443 cfstring = false;
3444 for (const auto &Load : info->O->load_commands()) {
3445 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
3446 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(L: Load);
3447 for (unsigned J = 0; J < Seg.nsects; ++J) {
3448 MachO::section_64 Sec = info->O->getSection64(L: Load, Index: J);
3449 if ((strncmp(s1: Sec.sectname, s2: "__objc_selrefs", n: 16) == 0 ||
3450 strncmp(s1: Sec.sectname, s2: "__objc_classrefs", n: 16) == 0 ||
3451 strncmp(s1: Sec.sectname, s2: "__objc_superrefs", n: 16) == 0 ||
3452 strncmp(s1: Sec.sectname, s2: "__objc_msgrefs", n: 16) == 0 ||
3453 strncmp(s1: Sec.sectname, s2: "__cfstring", n: 16) == 0) &&
3454 ReferenceValue >= Sec.addr &&
3455 ReferenceValue < Sec.addr + Sec.size) {
3456 uint64_t sect_offset = ReferenceValue - Sec.addr;
3457 uint64_t object_offset = Sec.offset + sect_offset;
3458 StringRef MachOContents = info->O->getData();
3459 uint64_t object_size = MachOContents.size();
3460 const char *object_addr = MachOContents.data();
3461 if (object_offset < object_size) {
3462 uint64_t pointer_value;
3463 memcpy(dest: &pointer_value, src: object_addr + object_offset,
3464 n: sizeof(uint64_t));
3465 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3466 sys::swapByteOrder(Value&: pointer_value);
3467 if (strncmp(s1: Sec.sectname, s2: "__objc_selrefs", n: 16) == 0)
3468 selref = true;
3469 else if (strncmp(s1: Sec.sectname, s2: "__objc_classrefs", n: 16) == 0 ||
3470 strncmp(s1: Sec.sectname, s2: "__objc_superrefs", n: 16) == 0)
3471 classref = true;
3472 else if (strncmp(s1: Sec.sectname, s2: "__objc_msgrefs", n: 16) == 0 &&
3473 ReferenceValue + 8 < Sec.addr + Sec.size) {
3474 msgref = true;
3475 memcpy(dest: &pointer_value, src: object_addr + object_offset + 8,
3476 n: sizeof(uint64_t));
3477 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3478 sys::swapByteOrder(Value&: pointer_value);
3479 } else if (strncmp(s1: Sec.sectname, s2: "__cfstring", n: 16) == 0)
3480 cfstring = true;
3481 return pointer_value;
3482 } else {
3483 return 0;
3484 }
3485 }
3486 }
3487 }
3488 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
3489 }
3490 return 0;
3491}
3492
3493// get_pointer_64 returns a pointer to the bytes in the object file at the
3494// Address from a section in the Mach-O file. And indirectly returns the
3495// offset into the section, number of bytes left in the section past the offset
3496// and which section is was being referenced. If the Address is not in a
3497// section nullptr is returned.
3498static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
3499 uint32_t &left, SectionRef &S,
3500 DisassembleInfo *info,
3501 bool objc_only = false) {
3502 offset = 0;
3503 left = 0;
3504 S = SectionRef();
3505 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
3506 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
3507 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
3508 if (SectSize == 0)
3509 continue;
3510 if (objc_only) {
3511 StringRef SectName;
3512 Expected<StringRef> SecNameOrErr =
3513 ((*(info->Sections))[SectIdx]).getName();
3514 if (SecNameOrErr)
3515 SectName = *SecNameOrErr;
3516 else
3517 consumeError(Err: SecNameOrErr.takeError());
3518
3519 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
3520 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
3521 if (SegName != "__OBJC" && SectName != "__cstring")
3522 continue;
3523 }
3524 if (Address >= SectAddress && Address < SectAddress + SectSize) {
3525 S = (*(info->Sections))[SectIdx];
3526 offset = Address - SectAddress;
3527 left = SectSize - offset;
3528 StringRef SectContents = unwrapOrError(
3529 EO: ((*(info->Sections))[SectIdx]).getContents(), Args: info->O->getFileName());
3530 return SectContents.data() + offset;
3531 }
3532 }
3533 return nullptr;
3534}
3535
3536static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
3537 uint32_t &left, SectionRef &S,
3538 DisassembleInfo *info,
3539 bool objc_only = false) {
3540 return get_pointer_64(Address, offset, left, S, info, objc_only);
3541}
3542
3543// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
3544// the symbol indirectly through n_value. Based on the relocation information
3545// for the specified section offset in the specified section reference.
3546// If no relocation information is found and a non-zero ReferenceValue for the
3547// symbol is passed, look up that address in the info's AddrMap.
3548static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
3549 DisassembleInfo *info, uint64_t &n_value,
3550 uint64_t ReferenceValue = 0) {
3551 n_value = 0;
3552 if (!info->verbose)
3553 return nullptr;
3554
3555 // See if there is an external relocation entry at the sect_offset.
3556 bool reloc_found = false;
3557 DataRefImpl Rel;
3558 MachO::any_relocation_info RE;
3559 bool isExtern = false;
3560 SymbolRef Symbol;
3561 for (const RelocationRef &Reloc : S.relocations()) {
3562 uint64_t RelocOffset = Reloc.getOffset();
3563 if (RelocOffset == sect_offset) {
3564 Rel = Reloc.getRawDataRefImpl();
3565 RE = info->O->getRelocation(Rel);
3566 if (info->O->isRelocationScattered(RE))
3567 continue;
3568 isExtern = info->O->getPlainRelocationExternal(RE);
3569 if (isExtern) {
3570 symbol_iterator RelocSym = Reloc.getSymbol();
3571 Symbol = *RelocSym;
3572 }
3573 reloc_found = true;
3574 break;
3575 }
3576 }
3577 // If there is an external relocation entry for a symbol in this section
3578 // at this section_offset then use that symbol's value for the n_value
3579 // and return its name.
3580 const char *SymbolName = nullptr;
3581 if (reloc_found && isExtern) {
3582 n_value = cantFail(ValOrErr: Symbol.getValue());
3583 StringRef Name = unwrapOrError(EO: Symbol.getName(), Args: info->O->getFileName());
3584 if (!Name.empty()) {
3585 SymbolName = Name.data();
3586 return SymbolName;
3587 }
3588 }
3589
3590 // TODO: For fully linked images, look through the external relocation
3591 // entries off the dynamic symtab command. For these the r_offset is from the
3592 // start of the first writeable segment in the Mach-O file. So the offset
3593 // to this section from that segment is passed to this routine by the caller,
3594 // as the database_offset. Which is the difference of the section's starting
3595 // address and the first writable segment.
3596 //
3597 // NOTE: need add passing the database_offset to this routine.
3598
3599 // We did not find an external relocation entry so look up the ReferenceValue
3600 // as an address of a symbol and if found return that symbol's name.
3601 SymbolName = GuessSymbolName(value: ReferenceValue, AddrMap: info->AddrMap);
3602
3603 return SymbolName;
3604}
3605
3606static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
3607 DisassembleInfo *info,
3608 uint32_t ReferenceValue) {
3609 uint64_t n_value64;
3610 return get_symbol_64(sect_offset, S, info, n_value&: n_value64, ReferenceValue);
3611}
3612
3613namespace {
3614
3615// These are structs in the Objective-C meta data and read to produce the
3616// comments for disassembly. While these are part of the ABI they are no
3617// public definitions. So the are here not in include/llvm/BinaryFormat/MachO.h
3618// .
3619
3620// The cfstring object in a 64-bit Mach-O file.
3621struct cfstring64_t {
3622 uint64_t isa; // class64_t * (64-bit pointer)
3623 uint64_t flags; // flag bits
3624 uint64_t characters; // char * (64-bit pointer)
3625 uint64_t length; // number of non-NULL characters in above
3626};
3627
3628// The class object in a 64-bit Mach-O file.
3629struct class64_t {
3630 uint64_t isa; // class64_t * (64-bit pointer)
3631 uint64_t superclass; // class64_t * (64-bit pointer)
3632 uint64_t cache; // Cache (64-bit pointer)
3633 uint64_t vtable; // IMP * (64-bit pointer)
3634 uint64_t data; // class_ro64_t * (64-bit pointer)
3635};
3636
3637struct class32_t {
3638 uint32_t isa; /* class32_t * (32-bit pointer) */
3639 uint32_t superclass; /* class32_t * (32-bit pointer) */
3640 uint32_t cache; /* Cache (32-bit pointer) */
3641 uint32_t vtable; /* IMP * (32-bit pointer) */
3642 uint32_t data; /* class_ro32_t * (32-bit pointer) */
3643};
3644
3645struct class_ro64_t {
3646 uint32_t flags;
3647 uint32_t instanceStart;
3648 uint32_t instanceSize;
3649 uint32_t reserved;
3650 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
3651 uint64_t name; // const char * (64-bit pointer)
3652 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
3653 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
3654 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
3655 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
3656 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
3657};
3658
3659struct class_ro32_t {
3660 uint32_t flags;
3661 uint32_t instanceStart;
3662 uint32_t instanceSize;
3663 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
3664 uint32_t name; /* const char * (32-bit pointer) */
3665 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
3666 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
3667 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
3668 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
3669 uint32_t baseProperties; /* const struct objc_property_list *
3670 (32-bit pointer) */
3671};
3672
3673/* Values for class_ro{64,32}_t->flags */
3674#define RO_META (1 << 0)
3675#define RO_ROOT (1 << 1)
3676#define RO_HAS_CXX_STRUCTORS (1 << 2)
3677
3678/* Values for method_list{64,32}_t->entsize */
3679#define ML_HAS_RELATIVE_PTRS (1 << 31)
3680#define ML_ENTSIZE_MASK 0xFFFF
3681
3682struct method_list64_t {
3683 uint32_t entsize;
3684 uint32_t count;
3685 /* struct method64_t first; These structures follow inline */
3686};
3687
3688struct method_list32_t {
3689 uint32_t entsize;
3690 uint32_t count;
3691 /* struct method32_t first; These structures follow inline */
3692};
3693
3694struct method64_t {
3695 uint64_t name; /* SEL (64-bit pointer) */
3696 uint64_t types; /* const char * (64-bit pointer) */
3697 uint64_t imp; /* IMP (64-bit pointer) */
3698};
3699
3700struct method32_t {
3701 uint32_t name; /* SEL (32-bit pointer) */
3702 uint32_t types; /* const char * (32-bit pointer) */
3703 uint32_t imp; /* IMP (32-bit pointer) */
3704};
3705
3706struct method_relative_t {
3707 int32_t name; /* SEL (32-bit relative) */
3708 int32_t types; /* const char * (32-bit relative) */
3709 int32_t imp; /* IMP (32-bit relative) */
3710};
3711
3712struct protocol_list64_t {
3713 uint64_t count; /* uintptr_t (a 64-bit value) */
3714 /* struct protocol64_t * list[0]; These pointers follow inline */
3715};
3716
3717struct protocol_list32_t {
3718 uint32_t count; /* uintptr_t (a 32-bit value) */
3719 /* struct protocol32_t * list[0]; These pointers follow inline */
3720};
3721
3722struct protocol64_t {
3723 uint64_t isa; /* id * (64-bit pointer) */
3724 uint64_t name; /* const char * (64-bit pointer) */
3725 uint64_t protocols; /* struct protocol_list64_t *
3726 (64-bit pointer) */
3727 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
3728 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
3729 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
3730 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
3731 uint64_t instanceProperties; /* struct objc_property_list *
3732 (64-bit pointer) */
3733};
3734
3735struct protocol32_t {
3736 uint32_t isa; /* id * (32-bit pointer) */
3737 uint32_t name; /* const char * (32-bit pointer) */
3738 uint32_t protocols; /* struct protocol_list_t *
3739 (32-bit pointer) */
3740 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
3741 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
3742 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
3743 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
3744 uint32_t instanceProperties; /* struct objc_property_list *
3745 (32-bit pointer) */
3746};
3747
3748struct ivar_list64_t {
3749 uint32_t entsize;
3750 uint32_t count;
3751 /* struct ivar64_t first; These structures follow inline */
3752};
3753
3754struct ivar_list32_t {
3755 uint32_t entsize;
3756 uint32_t count;
3757 /* struct ivar32_t first; These structures follow inline */
3758};
3759
3760struct ivar64_t {
3761 uint64_t offset; /* uintptr_t * (64-bit pointer) */
3762 uint64_t name; /* const char * (64-bit pointer) */
3763 uint64_t type; /* const char * (64-bit pointer) */
3764 uint32_t alignment;
3765 uint32_t size;
3766};
3767
3768struct ivar32_t {
3769 uint32_t offset; /* uintptr_t * (32-bit pointer) */
3770 uint32_t name; /* const char * (32-bit pointer) */
3771 uint32_t type; /* const char * (32-bit pointer) */
3772 uint32_t alignment;
3773 uint32_t size;
3774};
3775
3776struct objc_property_list64 {
3777 uint32_t entsize;
3778 uint32_t count;
3779 /* struct objc_property64 first; These structures follow inline */
3780};
3781
3782struct objc_property_list32 {
3783 uint32_t entsize;
3784 uint32_t count;
3785 /* struct objc_property32 first; These structures follow inline */
3786};
3787
3788struct objc_property64 {
3789 uint64_t name; /* const char * (64-bit pointer) */
3790 uint64_t attributes; /* const char * (64-bit pointer) */
3791};
3792
3793struct objc_property32 {
3794 uint32_t name; /* const char * (32-bit pointer) */
3795 uint32_t attributes; /* const char * (32-bit pointer) */
3796};
3797
3798struct category64_t {
3799 uint64_t name; /* const char * (64-bit pointer) */
3800 uint64_t cls; /* struct class_t * (64-bit pointer) */
3801 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
3802 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
3803 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
3804 uint64_t instanceProperties; /* struct objc_property_list *
3805 (64-bit pointer) */
3806};
3807
3808struct category32_t {
3809 uint32_t name; /* const char * (32-bit pointer) */
3810 uint32_t cls; /* struct class_t * (32-bit pointer) */
3811 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
3812 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
3813 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
3814 uint32_t instanceProperties; /* struct objc_property_list *
3815 (32-bit pointer) */
3816};
3817
3818struct objc_image_info64 {
3819 uint32_t version;
3820 uint32_t flags;
3821};
3822struct objc_image_info32 {
3823 uint32_t version;
3824 uint32_t flags;
3825};
3826struct imageInfo_t {
3827 uint32_t version;
3828 uint32_t flags;
3829};
3830/* masks for objc_image_info.flags */
3831#define OBJC_IMAGE_IS_REPLACEMENT (1 << 0)
3832#define OBJC_IMAGE_SUPPORTS_GC (1 << 1)
3833#define OBJC_IMAGE_IS_SIMULATED (1 << 5)
3834#define OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES (1 << 6)
3835
3836struct message_ref64 {
3837 uint64_t imp; /* IMP (64-bit pointer) */
3838 uint64_t sel; /* SEL (64-bit pointer) */
3839};
3840
3841struct message_ref32 {
3842 uint32_t imp; /* IMP (32-bit pointer) */
3843 uint32_t sel; /* SEL (32-bit pointer) */
3844};
3845
3846// Objective-C 1 (32-bit only) meta data structs.
3847
3848struct objc_module_t {
3849 uint32_t version;
3850 uint32_t size;
3851 uint32_t name; /* char * (32-bit pointer) */
3852 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
3853};
3854
3855struct objc_symtab_t {
3856 uint32_t sel_ref_cnt;
3857 uint32_t refs; /* SEL * (32-bit pointer) */
3858 uint16_t cls_def_cnt;
3859 uint16_t cat_def_cnt;
3860 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
3861};
3862
3863struct objc_class_t {
3864 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3865 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
3866 uint32_t name; /* const char * (32-bit pointer) */
3867 int32_t version;
3868 int32_t info;
3869 int32_t instance_size;
3870 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
3871 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
3872 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
3873 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
3874};
3875
3876#define CLS_GETINFO(cls, infomask) ((cls)->info & (infomask))
3877// class is not a metaclass
3878#define CLS_CLASS 0x1
3879// class is a metaclass
3880#define CLS_META 0x2
3881
3882struct objc_category_t {
3883 uint32_t category_name; /* char * (32-bit pointer) */
3884 uint32_t class_name; /* char * (32-bit pointer) */
3885 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
3886 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
3887 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
3888};
3889
3890struct objc_ivar_t {
3891 uint32_t ivar_name; /* char * (32-bit pointer) */
3892 uint32_t ivar_type; /* char * (32-bit pointer) */
3893 int32_t ivar_offset;
3894};
3895
3896struct objc_ivar_list_t {
3897 int32_t ivar_count;
3898 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
3899};
3900
3901struct objc_method_list_t {
3902 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
3903 int32_t method_count;
3904 // struct objc_method_t method_list[1]; /* variable length structure */
3905};
3906
3907struct objc_method_t {
3908 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3909 uint32_t method_types; /* char * (32-bit pointer) */
3910 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
3911 (32-bit pointer) */
3912};
3913
3914struct objc_protocol_list_t {
3915 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
3916 int32_t count;
3917 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
3918 // (32-bit pointer) */
3919};
3920
3921struct objc_protocol_t {
3922 uint32_t isa; /* struct objc_class * (32-bit pointer) */
3923 uint32_t protocol_name; /* char * (32-bit pointer) */
3924 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
3925 uint32_t instance_methods; /* struct objc_method_description_list *
3926 (32-bit pointer) */
3927 uint32_t class_methods; /* struct objc_method_description_list *
3928 (32-bit pointer) */
3929};
3930
3931struct objc_method_description_list_t {
3932 int32_t count;
3933 // struct objc_method_description_t list[1];
3934};
3935
3936struct objc_method_description_t {
3937 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
3938 uint32_t types; /* char * (32-bit pointer) */
3939};
3940
3941inline void swapStruct(struct cfstring64_t &cfs) {
3942 sys::swapByteOrder(Value&: cfs.isa);
3943 sys::swapByteOrder(Value&: cfs.flags);
3944 sys::swapByteOrder(Value&: cfs.characters);
3945 sys::swapByteOrder(Value&: cfs.length);
3946}
3947
3948inline void swapStruct(struct class64_t &c) {
3949 sys::swapByteOrder(Value&: c.isa);
3950 sys::swapByteOrder(Value&: c.superclass);
3951 sys::swapByteOrder(Value&: c.cache);
3952 sys::swapByteOrder(Value&: c.vtable);
3953 sys::swapByteOrder(Value&: c.data);
3954}
3955
3956inline void swapStruct(struct class32_t &c) {
3957 sys::swapByteOrder(Value&: c.isa);
3958 sys::swapByteOrder(Value&: c.superclass);
3959 sys::swapByteOrder(Value&: c.cache);
3960 sys::swapByteOrder(Value&: c.vtable);
3961 sys::swapByteOrder(Value&: c.data);
3962}
3963
3964inline void swapStruct(struct class_ro64_t &cro) {
3965 sys::swapByteOrder(Value&: cro.flags);
3966 sys::swapByteOrder(Value&: cro.instanceStart);
3967 sys::swapByteOrder(Value&: cro.instanceSize);
3968 sys::swapByteOrder(Value&: cro.reserved);
3969 sys::swapByteOrder(Value&: cro.ivarLayout);
3970 sys::swapByteOrder(Value&: cro.name);
3971 sys::swapByteOrder(Value&: cro.baseMethods);
3972 sys::swapByteOrder(Value&: cro.baseProtocols);
3973 sys::swapByteOrder(Value&: cro.ivars);
3974 sys::swapByteOrder(Value&: cro.weakIvarLayout);
3975 sys::swapByteOrder(Value&: cro.baseProperties);
3976}
3977
3978inline void swapStruct(struct class_ro32_t &cro) {
3979 sys::swapByteOrder(Value&: cro.flags);
3980 sys::swapByteOrder(Value&: cro.instanceStart);
3981 sys::swapByteOrder(Value&: cro.instanceSize);
3982 sys::swapByteOrder(Value&: cro.ivarLayout);
3983 sys::swapByteOrder(Value&: cro.name);
3984 sys::swapByteOrder(Value&: cro.baseMethods);
3985 sys::swapByteOrder(Value&: cro.baseProtocols);
3986 sys::swapByteOrder(Value&: cro.ivars);
3987 sys::swapByteOrder(Value&: cro.weakIvarLayout);
3988 sys::swapByteOrder(Value&: cro.baseProperties);
3989}
3990
3991inline void swapStruct(struct method_list64_t &ml) {
3992 sys::swapByteOrder(Value&: ml.entsize);
3993 sys::swapByteOrder(Value&: ml.count);
3994}
3995
3996inline void swapStruct(struct method_list32_t &ml) {
3997 sys::swapByteOrder(Value&: ml.entsize);
3998 sys::swapByteOrder(Value&: ml.count);
3999}
4000
4001inline void swapStruct(struct method64_t &m) {
4002 sys::swapByteOrder(Value&: m.name);
4003 sys::swapByteOrder(Value&: m.types);
4004 sys::swapByteOrder(Value&: m.imp);
4005}
4006
4007inline void swapStruct(struct method32_t &m) {
4008 sys::swapByteOrder(Value&: m.name);
4009 sys::swapByteOrder(Value&: m.types);
4010 sys::swapByteOrder(Value&: m.imp);
4011}
4012
4013inline void swapStruct(struct method_relative_t &m) {
4014 sys::swapByteOrder(Value&: m.name);
4015 sys::swapByteOrder(Value&: m.types);
4016 sys::swapByteOrder(Value&: m.imp);
4017}
4018
4019inline void swapStruct(struct protocol_list64_t &pl) {
4020 sys::swapByteOrder(Value&: pl.count);
4021}
4022
4023inline void swapStruct(struct protocol_list32_t &pl) {
4024 sys::swapByteOrder(Value&: pl.count);
4025}
4026
4027inline void swapStruct(struct protocol64_t &p) {
4028 sys::swapByteOrder(Value&: p.isa);
4029 sys::swapByteOrder(Value&: p.name);
4030 sys::swapByteOrder(Value&: p.protocols);
4031 sys::swapByteOrder(Value&: p.instanceMethods);
4032 sys::swapByteOrder(Value&: p.classMethods);
4033 sys::swapByteOrder(Value&: p.optionalInstanceMethods);
4034 sys::swapByteOrder(Value&: p.optionalClassMethods);
4035 sys::swapByteOrder(Value&: p.instanceProperties);
4036}
4037
4038inline void swapStruct(struct protocol32_t &p) {
4039 sys::swapByteOrder(Value&: p.isa);
4040 sys::swapByteOrder(Value&: p.name);
4041 sys::swapByteOrder(Value&: p.protocols);
4042 sys::swapByteOrder(Value&: p.instanceMethods);
4043 sys::swapByteOrder(Value&: p.classMethods);
4044 sys::swapByteOrder(Value&: p.optionalInstanceMethods);
4045 sys::swapByteOrder(Value&: p.optionalClassMethods);
4046 sys::swapByteOrder(Value&: p.instanceProperties);
4047}
4048
4049inline void swapStruct(struct ivar_list64_t &il) {
4050 sys::swapByteOrder(Value&: il.entsize);
4051 sys::swapByteOrder(Value&: il.count);
4052}
4053
4054inline void swapStruct(struct ivar_list32_t &il) {
4055 sys::swapByteOrder(Value&: il.entsize);
4056 sys::swapByteOrder(Value&: il.count);
4057}
4058
4059inline void swapStruct(struct ivar64_t &i) {
4060 sys::swapByteOrder(Value&: i.offset);
4061 sys::swapByteOrder(Value&: i.name);
4062 sys::swapByteOrder(Value&: i.type);
4063 sys::swapByteOrder(Value&: i.alignment);
4064 sys::swapByteOrder(Value&: i.size);
4065}
4066
4067inline void swapStruct(struct ivar32_t &i) {
4068 sys::swapByteOrder(Value&: i.offset);
4069 sys::swapByteOrder(Value&: i.name);
4070 sys::swapByteOrder(Value&: i.type);
4071 sys::swapByteOrder(Value&: i.alignment);
4072 sys::swapByteOrder(Value&: i.size);
4073}
4074
4075inline void swapStruct(struct objc_property_list64 &pl) {
4076 sys::swapByteOrder(Value&: pl.entsize);
4077 sys::swapByteOrder(Value&: pl.count);
4078}
4079
4080inline void swapStruct(struct objc_property_list32 &pl) {
4081 sys::swapByteOrder(Value&: pl.entsize);
4082 sys::swapByteOrder(Value&: pl.count);
4083}
4084
4085inline void swapStruct(struct objc_property64 &op) {
4086 sys::swapByteOrder(Value&: op.name);
4087 sys::swapByteOrder(Value&: op.attributes);
4088}
4089
4090inline void swapStruct(struct objc_property32 &op) {
4091 sys::swapByteOrder(Value&: op.name);
4092 sys::swapByteOrder(Value&: op.attributes);
4093}
4094
4095inline void swapStruct(struct category64_t &c) {
4096 sys::swapByteOrder(Value&: c.name);
4097 sys::swapByteOrder(Value&: c.cls);
4098 sys::swapByteOrder(Value&: c.instanceMethods);
4099 sys::swapByteOrder(Value&: c.classMethods);
4100 sys::swapByteOrder(Value&: c.protocols);
4101 sys::swapByteOrder(Value&: c.instanceProperties);
4102}
4103
4104inline void swapStruct(struct category32_t &c) {
4105 sys::swapByteOrder(Value&: c.name);
4106 sys::swapByteOrder(Value&: c.cls);
4107 sys::swapByteOrder(Value&: c.instanceMethods);
4108 sys::swapByteOrder(Value&: c.classMethods);
4109 sys::swapByteOrder(Value&: c.protocols);
4110 sys::swapByteOrder(Value&: c.instanceProperties);
4111}
4112
4113inline void swapStruct(struct objc_image_info64 &o) {
4114 sys::swapByteOrder(Value&: o.version);
4115 sys::swapByteOrder(Value&: o.flags);
4116}
4117
4118inline void swapStruct(struct objc_image_info32 &o) {
4119 sys::swapByteOrder(Value&: o.version);
4120 sys::swapByteOrder(Value&: o.flags);
4121}
4122
4123inline void swapStruct(struct imageInfo_t &o) {
4124 sys::swapByteOrder(Value&: o.version);
4125 sys::swapByteOrder(Value&: o.flags);
4126}
4127
4128inline void swapStruct(struct message_ref64 &mr) {
4129 sys::swapByteOrder(Value&: mr.imp);
4130 sys::swapByteOrder(Value&: mr.sel);
4131}
4132
4133inline void swapStruct(struct message_ref32 &mr) {
4134 sys::swapByteOrder(Value&: mr.imp);
4135 sys::swapByteOrder(Value&: mr.sel);
4136}
4137
4138inline void swapStruct(struct objc_module_t &module) {
4139 sys::swapByteOrder(Value&: module.version);
4140 sys::swapByteOrder(Value&: module.size);
4141 sys::swapByteOrder(Value&: module.name);
4142 sys::swapByteOrder(Value&: module.symtab);
4143}
4144
4145inline void swapStruct(struct objc_symtab_t &symtab) {
4146 sys::swapByteOrder(Value&: symtab.sel_ref_cnt);
4147 sys::swapByteOrder(Value&: symtab.refs);
4148 sys::swapByteOrder(Value&: symtab.cls_def_cnt);
4149 sys::swapByteOrder(Value&: symtab.cat_def_cnt);
4150}
4151
4152inline void swapStruct(struct objc_class_t &objc_class) {
4153 sys::swapByteOrder(Value&: objc_class.isa);
4154 sys::swapByteOrder(Value&: objc_class.super_class);
4155 sys::swapByteOrder(Value&: objc_class.name);
4156 sys::swapByteOrder(Value&: objc_class.version);
4157 sys::swapByteOrder(Value&: objc_class.info);
4158 sys::swapByteOrder(Value&: objc_class.instance_size);
4159 sys::swapByteOrder(Value&: objc_class.ivars);
4160 sys::swapByteOrder(Value&: objc_class.methodLists);
4161 sys::swapByteOrder(Value&: objc_class.cache);
4162 sys::swapByteOrder(Value&: objc_class.protocols);
4163}
4164
4165inline void swapStruct(struct objc_category_t &objc_category) {
4166 sys::swapByteOrder(Value&: objc_category.category_name);
4167 sys::swapByteOrder(Value&: objc_category.class_name);
4168 sys::swapByteOrder(Value&: objc_category.instance_methods);
4169 sys::swapByteOrder(Value&: objc_category.class_methods);
4170 sys::swapByteOrder(Value&: objc_category.protocols);
4171}
4172
4173inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
4174 sys::swapByteOrder(Value&: objc_ivar_list.ivar_count);
4175}
4176
4177inline void swapStruct(struct objc_ivar_t &objc_ivar) {
4178 sys::swapByteOrder(Value&: objc_ivar.ivar_name);
4179 sys::swapByteOrder(Value&: objc_ivar.ivar_type);
4180 sys::swapByteOrder(Value&: objc_ivar.ivar_offset);
4181}
4182
4183inline void swapStruct(struct objc_method_list_t &method_list) {
4184 sys::swapByteOrder(Value&: method_list.obsolete);
4185 sys::swapByteOrder(Value&: method_list.method_count);
4186}
4187
4188inline void swapStruct(struct objc_method_t &method) {
4189 sys::swapByteOrder(Value&: method.method_name);
4190 sys::swapByteOrder(Value&: method.method_types);
4191 sys::swapByteOrder(Value&: method.method_imp);
4192}
4193
4194inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
4195 sys::swapByteOrder(Value&: protocol_list.next);
4196 sys::swapByteOrder(Value&: protocol_list.count);
4197}
4198
4199inline void swapStruct(struct objc_protocol_t &protocol) {
4200 sys::swapByteOrder(Value&: protocol.isa);
4201 sys::swapByteOrder(Value&: protocol.protocol_name);
4202 sys::swapByteOrder(Value&: protocol.protocol_list);
4203 sys::swapByteOrder(Value&: protocol.instance_methods);
4204 sys::swapByteOrder(Value&: protocol.class_methods);
4205}
4206
4207inline void swapStruct(struct objc_method_description_list_t &mdl) {
4208 sys::swapByteOrder(Value&: mdl.count);
4209}
4210
4211inline void swapStruct(struct objc_method_description_t &md) {
4212 sys::swapByteOrder(Value&: md.name);
4213 sys::swapByteOrder(Value&: md.types);
4214}
4215
4216} // namespace
4217
4218static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
4219 struct DisassembleInfo *info);
4220
4221// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
4222// to an Objective-C class and returns the class name. It is also passed the
4223// address of the pointer, so when the pointer is zero as it can be in an .o
4224// file, that is used to look for an external relocation entry with a symbol
4225// name.
4226static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
4227 uint64_t ReferenceValue,
4228 struct DisassembleInfo *info) {
4229 const char *r;
4230 uint32_t offset, left;
4231 SectionRef S;
4232
4233 // The pointer_value can be 0 in an object file and have a relocation
4234 // entry for the class symbol at the ReferenceValue (the address of the
4235 // pointer).
4236 if (pointer_value == 0) {
4237 r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4238 if (r == nullptr || left < sizeof(uint64_t))
4239 return nullptr;
4240 uint64_t n_value;
4241 const char *symbol_name = get_symbol_64(sect_offset: offset, S, info, n_value);
4242 if (symbol_name == nullptr)
4243 return nullptr;
4244 const char *class_name = strrchr(s: symbol_name, c: '$');
4245 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
4246 return class_name + 2;
4247 else
4248 return nullptr;
4249 }
4250
4251 // The case were the pointer_value is non-zero and points to a class defined
4252 // in this Mach-O file.
4253 r = get_pointer_64(Address: pointer_value, offset, left, S, info);
4254 if (r == nullptr || left < sizeof(struct class64_t))
4255 return nullptr;
4256 struct class64_t c;
4257 memcpy(dest: &c, src: r, n: sizeof(struct class64_t));
4258 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4259 swapStruct(c);
4260 if (c.data == 0)
4261 return nullptr;
4262 r = get_pointer_64(Address: c.data, offset, left, S, info);
4263 if (r == nullptr || left < sizeof(struct class_ro64_t))
4264 return nullptr;
4265 struct class_ro64_t cro;
4266 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro64_t));
4267 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4268 swapStruct(cro);
4269 if (cro.name == 0)
4270 return nullptr;
4271 const char *name = get_pointer_64(Address: cro.name, offset, left, S, info);
4272 return name;
4273}
4274
4275// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
4276// pointer to a cfstring and returns its name or nullptr.
4277static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
4278 struct DisassembleInfo *info) {
4279 const char *r, *name;
4280 uint32_t offset, left;
4281 SectionRef S;
4282 struct cfstring64_t cfs;
4283 uint64_t cfs_characters;
4284
4285 r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4286 if (r == nullptr || left < sizeof(struct cfstring64_t))
4287 return nullptr;
4288 memcpy(dest: &cfs, src: r, n: sizeof(struct cfstring64_t));
4289 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4290 swapStruct(cfs);
4291 if (cfs.characters == 0) {
4292 uint64_t n_value;
4293 const char *symbol_name = get_symbol_64(
4294 sect_offset: offset + offsetof(struct cfstring64_t, characters), S, info, n_value);
4295 if (symbol_name == nullptr)
4296 return nullptr;
4297 cfs_characters = n_value;
4298 } else
4299 cfs_characters = cfs.characters;
4300 name = get_pointer_64(Address: cfs_characters, offset, left, S, info);
4301
4302 return name;
4303}
4304
4305// get_objc2_64bit_selref() is used for disassembly and is passed a the address
4306// of a pointer to an Objective-C selector reference when the pointer value is
4307// zero as in a .o file and is likely to have a external relocation entry with
4308// who's symbol's n_value is the real pointer to the selector name. If that is
4309// the case the real pointer to the selector name is returned else 0 is
4310// returned
4311static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
4312 struct DisassembleInfo *info) {
4313 uint32_t offset, left;
4314 SectionRef S;
4315
4316 const char *r = get_pointer_64(Address: ReferenceValue, offset, left, S, info);
4317 if (r == nullptr || left < sizeof(uint64_t))
4318 return 0;
4319 uint64_t n_value;
4320 const char *symbol_name = get_symbol_64(sect_offset: offset, S, info, n_value);
4321 if (symbol_name == nullptr)
4322 return 0;
4323 return n_value;
4324}
4325
4326static const SectionRef get_section(MachOObjectFile *O, const char *segname,
4327 const char *sectname) {
4328 for (const SectionRef &Section : O->sections()) {
4329 StringRef SectName;
4330 Expected<StringRef> SecNameOrErr = Section.getName();
4331 if (SecNameOrErr)
4332 SectName = *SecNameOrErr;
4333 else
4334 consumeError(Err: SecNameOrErr.takeError());
4335
4336 DataRefImpl Ref = Section.getRawDataRefImpl();
4337 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4338 if (SegName == segname && SectName == sectname)
4339 return Section;
4340 }
4341 return SectionRef();
4342}
4343
4344static void
4345walk_pointer_list_64(const char *listname, const SectionRef S,
4346 MachOObjectFile *O, struct DisassembleInfo *info,
4347 void (*func)(uint64_t, struct DisassembleInfo *info)) {
4348 if (S == SectionRef())
4349 return;
4350
4351 StringRef SectName;
4352 Expected<StringRef> SecNameOrErr = S.getName();
4353 if (SecNameOrErr)
4354 SectName = *SecNameOrErr;
4355 else
4356 consumeError(Err: SecNameOrErr.takeError());
4357
4358 DataRefImpl Ref = S.getRawDataRefImpl();
4359 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4360 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4361
4362 StringRef BytesStr = unwrapOrError(EO: S.getContents(), Args: O->getFileName());
4363 const char *Contents = BytesStr.data();
4364
4365 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
4366 uint32_t left = S.getSize() - i;
4367 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
4368 uint64_t p = 0;
4369 memcpy(dest: &p, src: Contents + i, n: size);
4370 if (i + sizeof(uint64_t) > S.getSize())
4371 outs() << listname << " list pointer extends past end of (" << SegName
4372 << "," << SectName << ") section\n";
4373 outs() << format(Fmt: "%016" PRIx64, Vals: S.getAddress() + i) << " ";
4374
4375 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4376 sys::swapByteOrder(Value&: p);
4377
4378 uint64_t n_value = 0;
4379 const char *name = get_symbol_64(sect_offset: i, S, info, n_value, ReferenceValue: p);
4380 if (name == nullptr)
4381 name = get_dyld_bind_info_symbolname(ReferenceValue: S.getAddress() + i, info);
4382
4383 if (n_value != 0) {
4384 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4385 if (p != 0)
4386 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: p);
4387 } else
4388 outs() << format(Fmt: "0x%" PRIx64, Vals: p);
4389 if (name != nullptr)
4390 outs() << " " << name;
4391 outs() << "\n";
4392
4393 p += n_value;
4394 if (func)
4395 func(p, info);
4396 }
4397}
4398
4399static void
4400walk_pointer_list_32(const char *listname, const SectionRef S,
4401 MachOObjectFile *O, struct DisassembleInfo *info,
4402 void (*func)(uint32_t, struct DisassembleInfo *info)) {
4403 if (S == SectionRef())
4404 return;
4405
4406 StringRef SectName = unwrapOrError(EO: S.getName(), Args: O->getFileName());
4407 DataRefImpl Ref = S.getRawDataRefImpl();
4408 StringRef SegName = O->getSectionFinalSegmentName(Sec: Ref);
4409 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
4410
4411 StringRef BytesStr = unwrapOrError(EO: S.getContents(), Args: O->getFileName());
4412 const char *Contents = BytesStr.data();
4413
4414 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
4415 uint32_t left = S.getSize() - i;
4416 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
4417 uint32_t p = 0;
4418 memcpy(dest: &p, src: Contents + i, n: size);
4419 if (i + sizeof(uint32_t) > S.getSize())
4420 outs() << listname << " list pointer extends past end of (" << SegName
4421 << "," << SectName << ") section\n";
4422 uint32_t Address = S.getAddress() + i;
4423 outs() << format(Fmt: "%08" PRIx32, Vals: Address) << " ";
4424
4425 if (O->isLittleEndian() != sys::IsLittleEndianHost)
4426 sys::swapByteOrder(Value&: p);
4427 outs() << format(Fmt: "0x%" PRIx32, Vals: p);
4428
4429 const char *name = get_symbol_32(sect_offset: i, S, info, ReferenceValue: p);
4430 if (name != nullptr)
4431 outs() << " " << name;
4432 outs() << "\n";
4433
4434 if (func)
4435 func(p, info);
4436 }
4437}
4438
4439static void print_layout_map(const char *layout_map, uint32_t left) {
4440 if (layout_map == nullptr)
4441 return;
4442 outs() << " layout map: ";
4443 do {
4444 outs() << format(Fmt: "0x%02" PRIx32, Vals: (*layout_map) & 0xff) << " ";
4445 left--;
4446 layout_map++;
4447 } while (*layout_map != '\0' && left != 0);
4448 outs() << "\n";
4449}
4450
4451static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
4452 uint32_t offset, left;
4453 SectionRef S;
4454 const char *layout_map;
4455
4456 if (p == 0)
4457 return;
4458 layout_map = get_pointer_64(Address: p, offset, left, S, info);
4459 print_layout_map(layout_map, left);
4460}
4461
4462static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
4463 uint32_t offset, left;
4464 SectionRef S;
4465 const char *layout_map;
4466
4467 if (p == 0)
4468 return;
4469 layout_map = get_pointer_32(Address: p, offset, left, S, info);
4470 print_layout_map(layout_map, left);
4471}
4472
4473static void print_relative_method_list(uint32_t structSizeAndFlags,
4474 uint32_t structCount, uint64_t p,
4475 struct DisassembleInfo *info,
4476 const char *indent,
4477 uint32_t pointerBits) {
4478 struct method_relative_t m;
4479 const char *r, *name;
4480 uint32_t offset, xoffset, left, i;
4481 SectionRef S, xS;
4482
4483 assert(((structSizeAndFlags & ML_HAS_RELATIVE_PTRS) != 0) &&
4484 "expected structSizeAndFlags to have ML_HAS_RELATIVE_PTRS flag");
4485
4486 outs() << indent << "\t\t entsize "
4487 << (structSizeAndFlags & ML_ENTSIZE_MASK) << " (relative) \n";
4488 outs() << indent << "\t\t count " << structCount << "\n";
4489
4490 for (i = 0; i < structCount; i++) {
4491 r = get_pointer_64(Address: p, offset, left, S, info);
4492 memset(s: &m, c: '\0', n: sizeof(struct method_relative_t));
4493 if (left < sizeof(struct method_relative_t)) {
4494 memcpy(dest: &m, src: r, n: left);
4495 outs() << indent << " (method_t extends past the end of the section)\n";
4496 } else
4497 memcpy(dest: &m, src: r, n: sizeof(struct method_relative_t));
4498 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4499 swapStruct(m);
4500
4501 outs() << indent << "\t\t name " << format(Fmt: "0x%" PRIx32, Vals: m.name);
4502 uint64_t relNameRefVA = p + offsetof(struct method_relative_t, name);
4503 uint64_t absNameRefVA = relNameRefVA + m.name;
4504 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absNameRefVA) << ")";
4505
4506 // since this is a relative list, absNameRefVA is the address of the
4507 // __objc_selrefs entry, so a pointer, not the actual name
4508 const char *nameRefPtr =
4509 get_pointer_64(Address: absNameRefVA, offset&: xoffset, left, S&: xS, info);
4510 if (nameRefPtr) {
4511 uint32_t pointerSize = pointerBits / CHAR_BIT;
4512 if (left < pointerSize)
4513 outs() << indent << " (nameRefPtr extends past the end of the section)";
4514 else {
4515 if (pointerSize == 64) {
4516 uint64_t nameOff_64 = *reinterpret_cast<const uint64_t *>(nameRefPtr);
4517 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4518 sys::swapByteOrder(Value&: nameOff_64);
4519 name = get_pointer_64(Address: nameOff_64, offset&: xoffset, left, S&: xS, info);
4520 } else {
4521 uint32_t nameOff_32 = *reinterpret_cast<const uint32_t *>(nameRefPtr);
4522 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4523 sys::swapByteOrder(Value&: nameOff_32);
4524 name = get_pointer_32(Address: nameOff_32, offset&: xoffset, left, S&: xS, info);
4525 }
4526 if (name != nullptr)
4527 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4528 }
4529 }
4530 outs() << "\n";
4531
4532 outs() << indent << "\t\t types " << format(Fmt: "0x%" PRIx32, Vals: m.types);
4533 uint64_t relTypesVA = p + offsetof(struct method_relative_t, types);
4534 uint64_t absTypesVA = relTypesVA + m.types;
4535 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absTypesVA) << ")";
4536 name = get_pointer_32(Address: absTypesVA, offset&: xoffset, left, S&: xS, info);
4537 if (name != nullptr)
4538 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4539 outs() << "\n";
4540
4541 outs() << indent << "\t\t imp " << format(Fmt: "0x%" PRIx32, Vals: m.imp);
4542 uint64_t relImpVA = p + offsetof(struct method_relative_t, imp);
4543 uint64_t absImpVA = relImpVA + m.imp;
4544 outs() << " (" << format(Fmt: "0x%" PRIx32, Vals: absImpVA) << ")";
4545 name = GuessSymbolName(value: absImpVA, AddrMap: info->AddrMap);
4546 if (name != nullptr)
4547 outs() << " " << name;
4548 outs() << "\n";
4549
4550 p += sizeof(struct method_relative_t);
4551 offset += sizeof(struct method_relative_t);
4552 }
4553}
4554
4555static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
4556 const char *indent) {
4557 struct method_list64_t ml;
4558 struct method64_t m;
4559 const char *r;
4560 uint32_t offset, xoffset, left, i;
4561 SectionRef S, xS;
4562 const char *name, *sym_name;
4563 uint64_t n_value;
4564
4565 r = get_pointer_64(Address: p, offset, left, S, info);
4566 if (r == nullptr)
4567 return;
4568 memset(s: &ml, c: '\0', n: sizeof(struct method_list64_t));
4569 if (left < sizeof(struct method_list64_t)) {
4570 memcpy(dest: &ml, src: r, n: left);
4571 outs() << " (method_list_t entends past the end of the section)\n";
4572 } else
4573 memcpy(dest: &ml, src: r, n: sizeof(struct method_list64_t));
4574 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4575 swapStruct(ml);
4576 p += sizeof(struct method_list64_t);
4577
4578 if ((ml.entsize & ML_HAS_RELATIVE_PTRS) != 0) {
4579 print_relative_method_list(structSizeAndFlags: ml.entsize, structCount: ml.count, p, info, indent,
4580 /*pointerBits=*/64);
4581 return;
4582 }
4583
4584 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4585 outs() << indent << "\t\t count " << ml.count << "\n";
4586
4587 offset += sizeof(struct method_list64_t);
4588 for (i = 0; i < ml.count; i++) {
4589 r = get_pointer_64(Address: p, offset, left, S, info);
4590 if (r == nullptr)
4591 return;
4592 memset(s: &m, c: '\0', n: sizeof(struct method64_t));
4593 if (left < sizeof(struct method64_t)) {
4594 memcpy(dest: &m, src: r, n: left);
4595 outs() << indent << " (method_t extends past the end of the section)\n";
4596 } else
4597 memcpy(dest: &m, src: r, n: sizeof(struct method64_t));
4598 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4599 swapStruct(m);
4600
4601 outs() << indent << "\t\t name ";
4602 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, name), S,
4603 info, n_value, ReferenceValue: m.name);
4604 if (n_value != 0) {
4605 if (info->verbose && sym_name != nullptr)
4606 outs() << sym_name;
4607 else
4608 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4609 if (m.name != 0)
4610 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: m.name);
4611 } else
4612 outs() << format(Fmt: "0x%" PRIx64, Vals: m.name);
4613 name = get_pointer_64(Address: m.name + n_value, offset&: xoffset, left, S&: xS, info);
4614 if (name != nullptr)
4615 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4616 outs() << "\n";
4617
4618 outs() << indent << "\t\t types ";
4619 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, types), S,
4620 info, n_value, ReferenceValue: m.types);
4621 if (n_value != 0) {
4622 if (info->verbose && sym_name != nullptr)
4623 outs() << sym_name;
4624 else
4625 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4626 if (m.types != 0)
4627 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: m.types);
4628 } else
4629 outs() << format(Fmt: "0x%" PRIx64, Vals: m.types);
4630 name = get_pointer_64(Address: m.types + n_value, offset&: xoffset, left, S&: xS, info);
4631 if (name != nullptr)
4632 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4633 outs() << "\n";
4634
4635 outs() << indent << "\t\t imp ";
4636 name = get_symbol_64(sect_offset: offset + offsetof(struct method64_t, imp), S, info,
4637 n_value, ReferenceValue: m.imp);
4638 if (info->verbose && name == nullptr) {
4639 if (n_value != 0) {
4640 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value) << " ";
4641 if (m.imp != 0)
4642 outs() << "+ " << format(Fmt: "0x%" PRIx64, Vals: m.imp) << " ";
4643 } else
4644 outs() << format(Fmt: "0x%" PRIx64, Vals: m.imp) << " ";
4645 }
4646 if (name != nullptr)
4647 outs() << name;
4648 outs() << "\n";
4649
4650 p += sizeof(struct method64_t);
4651 offset += sizeof(struct method64_t);
4652 }
4653}
4654
4655static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
4656 const char *indent) {
4657 struct method_list32_t ml;
4658 struct method32_t m;
4659 const char *r, *name;
4660 uint32_t offset, xoffset, left, i;
4661 SectionRef S, xS;
4662
4663 r = get_pointer_32(Address: p, offset, left, S, info);
4664 if (r == nullptr)
4665 return;
4666 memset(s: &ml, c: '\0', n: sizeof(struct method_list32_t));
4667 if (left < sizeof(struct method_list32_t)) {
4668 memcpy(dest: &ml, src: r, n: left);
4669 outs() << " (method_list_t entends past the end of the section)\n";
4670 } else
4671 memcpy(dest: &ml, src: r, n: sizeof(struct method_list32_t));
4672 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4673 swapStruct(ml);
4674 p += sizeof(struct method_list32_t);
4675
4676 if ((ml.entsize & ML_HAS_RELATIVE_PTRS) != 0) {
4677 print_relative_method_list(structSizeAndFlags: ml.entsize, structCount: ml.count, p, info, indent,
4678 /*pointerBits=*/32);
4679 return;
4680 }
4681
4682 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
4683 outs() << indent << "\t\t count " << ml.count << "\n";
4684
4685 offset += sizeof(struct method_list32_t);
4686 for (i = 0; i < ml.count; i++) {
4687 r = get_pointer_32(Address: p, offset, left, S, info);
4688 if (r == nullptr)
4689 return;
4690 memset(s: &m, c: '\0', n: sizeof(struct method32_t));
4691 if (left < sizeof(struct method32_t)) {
4692 memcpy(dest: &ml, src: r, n: left);
4693 outs() << indent << " (method_t entends past the end of the section)\n";
4694 } else
4695 memcpy(dest: &m, src: r, n: sizeof(struct method32_t));
4696 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4697 swapStruct(m);
4698
4699 outs() << indent << "\t\t name " << format(Fmt: "0x%" PRIx32, Vals: m.name);
4700 name = get_pointer_32(Address: m.name, offset&: xoffset, left, S&: xS, info);
4701 if (name != nullptr)
4702 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4703 outs() << "\n";
4704
4705 outs() << indent << "\t\t types " << format(Fmt: "0x%" PRIx32, Vals: m.types);
4706 name = get_pointer_32(Address: m.types, offset&: xoffset, left, S&: xS, info);
4707 if (name != nullptr)
4708 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4709 outs() << "\n";
4710
4711 outs() << indent << "\t\t imp " << format(Fmt: "0x%" PRIx32, Vals: m.imp);
4712 name = get_symbol_32(sect_offset: offset + offsetof(struct method32_t, imp), S, info,
4713 ReferenceValue: m.imp);
4714 if (name != nullptr)
4715 outs() << " " << name;
4716 outs() << "\n";
4717
4718 p += sizeof(struct method32_t);
4719 offset += sizeof(struct method32_t);
4720 }
4721}
4722
4723static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
4724 uint32_t offset, left, xleft;
4725 SectionRef S;
4726 struct objc_method_list_t method_list;
4727 struct objc_method_t method;
4728 const char *r, *methods, *name, *SymbolName;
4729 int32_t i;
4730
4731 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
4732 if (r == nullptr)
4733 return true;
4734
4735 outs() << "\n";
4736 if (left > sizeof(struct objc_method_list_t)) {
4737 memcpy(dest: &method_list, src: r, n: sizeof(struct objc_method_list_t));
4738 } else {
4739 outs() << "\t\t objc_method_list extends past end of the section\n";
4740 memset(s: &method_list, c: '\0', n: sizeof(struct objc_method_list_t));
4741 memcpy(dest: &method_list, src: r, n: left);
4742 }
4743 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4744 swapStruct(method_list);
4745
4746 outs() << "\t\t obsolete "
4747 << format(Fmt: "0x%08" PRIx32, Vals: method_list.obsolete) << "\n";
4748 outs() << "\t\t method_count " << method_list.method_count << "\n";
4749
4750 methods = r + sizeof(struct objc_method_list_t);
4751 for (i = 0; i < method_list.method_count; i++) {
4752 if ((i + 1) * sizeof(struct objc_method_t) > left) {
4753 outs() << "\t\t remaining method's extend past the of the section\n";
4754 break;
4755 }
4756 memcpy(dest: &method, src: methods + i * sizeof(struct objc_method_t),
4757 n: sizeof(struct objc_method_t));
4758 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4759 swapStruct(method);
4760
4761 outs() << "\t\t method_name "
4762 << format(Fmt: "0x%08" PRIx32, Vals: method.method_name);
4763 if (info->verbose) {
4764 name = get_pointer_32(Address: method.method_name, offset, left&: xleft, S, info, objc_only: true);
4765 if (name != nullptr)
4766 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
4767 else
4768 outs() << " (not in an __OBJC section)";
4769 }
4770 outs() << "\n";
4771
4772 outs() << "\t\t method_types "
4773 << format(Fmt: "0x%08" PRIx32, Vals: method.method_types);
4774 if (info->verbose) {
4775 name = get_pointer_32(Address: method.method_types, offset, left&: xleft, S, info, objc_only: true);
4776 if (name != nullptr)
4777 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
4778 else
4779 outs() << " (not in an __OBJC section)";
4780 }
4781 outs() << "\n";
4782
4783 outs() << "\t\t method_imp "
4784 << format(Fmt: "0x%08" PRIx32, Vals: method.method_imp) << " ";
4785 if (info->verbose) {
4786 SymbolName = GuessSymbolName(value: method.method_imp, AddrMap: info->AddrMap);
4787 if (SymbolName != nullptr)
4788 outs() << SymbolName;
4789 }
4790 outs() << "\n";
4791 }
4792 return false;
4793}
4794
4795static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
4796 struct protocol_list64_t pl;
4797 uint64_t q, n_value;
4798 struct protocol64_t pc;
4799 const char *r;
4800 uint32_t offset, xoffset, left, i;
4801 SectionRef S, xS;
4802 const char *name, *sym_name;
4803
4804 r = get_pointer_64(Address: p, offset, left, S, info);
4805 if (r == nullptr)
4806 return;
4807 memset(s: &pl, c: '\0', n: sizeof(struct protocol_list64_t));
4808 if (left < sizeof(struct protocol_list64_t)) {
4809 memcpy(dest: &pl, src: r, n: left);
4810 outs() << " (protocol_list_t entends past the end of the section)\n";
4811 } else
4812 memcpy(dest: &pl, src: r, n: sizeof(struct protocol_list64_t));
4813 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4814 swapStruct(pl);
4815 outs() << " count " << pl.count << "\n";
4816
4817 p += sizeof(struct protocol_list64_t);
4818 offset += sizeof(struct protocol_list64_t);
4819 for (i = 0; i < pl.count; i++) {
4820 r = get_pointer_64(Address: p, offset, left, S, info);
4821 if (r == nullptr)
4822 return;
4823 q = 0;
4824 if (left < sizeof(uint64_t)) {
4825 memcpy(dest: &q, src: r, n: left);
4826 outs() << " (protocol_t * entends past the end of the section)\n";
4827 } else
4828 memcpy(dest: &q, src: r, n: sizeof(uint64_t));
4829 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4830 sys::swapByteOrder(Value&: q);
4831
4832 outs() << "\t\t list[" << i << "] ";
4833 sym_name = get_symbol_64(sect_offset: offset, S, info, n_value, ReferenceValue: q);
4834 if (n_value != 0) {
4835 if (info->verbose && sym_name != nullptr)
4836 outs() << sym_name;
4837 else
4838 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4839 if (q != 0)
4840 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: q);
4841 } else
4842 outs() << format(Fmt: "0x%" PRIx64, Vals: q);
4843 outs() << " (struct protocol_t *)\n";
4844
4845 r = get_pointer_64(Address: q + n_value, offset, left, S, info);
4846 if (r == nullptr)
4847 return;
4848 memset(s: &pc, c: '\0', n: sizeof(struct protocol64_t));
4849 if (left < sizeof(struct protocol64_t)) {
4850 memcpy(dest: &pc, src: r, n: left);
4851 outs() << " (protocol_t entends past the end of the section)\n";
4852 } else
4853 memcpy(dest: &pc, src: r, n: sizeof(struct protocol64_t));
4854 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4855 swapStruct(p&: pc);
4856
4857 outs() << "\t\t\t isa " << format(Fmt: "0x%" PRIx64, Vals: pc.isa) << "\n";
4858
4859 outs() << "\t\t\t name ";
4860 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, name), S,
4861 info, n_value, ReferenceValue: pc.name);
4862 if (n_value != 0) {
4863 if (info->verbose && sym_name != nullptr)
4864 outs() << sym_name;
4865 else
4866 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4867 if (pc.name != 0)
4868 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.name);
4869 } else
4870 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.name);
4871 name = get_pointer_64(Address: pc.name + n_value, offset&: xoffset, left, S&: xS, info);
4872 if (name != nullptr)
4873 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4874 outs() << "\n";
4875
4876 outs() << "\t\t\tprotocols " << format(Fmt: "0x%" PRIx64, Vals: pc.protocols) << "\n";
4877
4878 outs() << "\t\t instanceMethods ";
4879 sym_name =
4880 get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, instanceMethods),
4881 S, info, n_value, ReferenceValue: pc.instanceMethods);
4882 if (n_value != 0) {
4883 if (info->verbose && sym_name != nullptr)
4884 outs() << sym_name;
4885 else
4886 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4887 if (pc.instanceMethods != 0)
4888 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.instanceMethods);
4889 } else
4890 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.instanceMethods);
4891 outs() << " (struct method_list_t *)\n";
4892 if (pc.instanceMethods + n_value != 0)
4893 print_method_list64_t(p: pc.instanceMethods + n_value, info, indent: "\t");
4894
4895 outs() << "\t\t classMethods ";
4896 sym_name =
4897 get_symbol_64(sect_offset: offset + offsetof(struct protocol64_t, classMethods), S,
4898 info, n_value, ReferenceValue: pc.classMethods);
4899 if (n_value != 0) {
4900 if (info->verbose && sym_name != nullptr)
4901 outs() << sym_name;
4902 else
4903 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
4904 if (pc.classMethods != 0)
4905 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: pc.classMethods);
4906 } else
4907 outs() << format(Fmt: "0x%" PRIx64, Vals: pc.classMethods);
4908 outs() << " (struct method_list_t *)\n";
4909 if (pc.classMethods + n_value != 0)
4910 print_method_list64_t(p: pc.classMethods + n_value, info, indent: "\t");
4911
4912 outs() << "\t optionalInstanceMethods "
4913 << format(Fmt: "0x%" PRIx64, Vals: pc.optionalInstanceMethods) << "\n";
4914 outs() << "\t optionalClassMethods "
4915 << format(Fmt: "0x%" PRIx64, Vals: pc.optionalClassMethods) << "\n";
4916 outs() << "\t instanceProperties "
4917 << format(Fmt: "0x%" PRIx64, Vals: pc.instanceProperties) << "\n";
4918
4919 p += sizeof(uint64_t);
4920 offset += sizeof(uint64_t);
4921 }
4922}
4923
4924static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
4925 struct protocol_list32_t pl;
4926 uint32_t q;
4927 struct protocol32_t pc;
4928 const char *r;
4929 uint32_t offset, xoffset, left, i;
4930 SectionRef S, xS;
4931 const char *name;
4932
4933 r = get_pointer_32(Address: p, offset, left, S, info);
4934 if (r == nullptr)
4935 return;
4936 memset(s: &pl, c: '\0', n: sizeof(struct protocol_list32_t));
4937 if (left < sizeof(struct protocol_list32_t)) {
4938 memcpy(dest: &pl, src: r, n: left);
4939 outs() << " (protocol_list_t entends past the end of the section)\n";
4940 } else
4941 memcpy(dest: &pl, src: r, n: sizeof(struct protocol_list32_t));
4942 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4943 swapStruct(pl);
4944 outs() << " count " << pl.count << "\n";
4945
4946 p += sizeof(struct protocol_list32_t);
4947 offset += sizeof(struct protocol_list32_t);
4948 for (i = 0; i < pl.count; i++) {
4949 r = get_pointer_32(Address: p, offset, left, S, info);
4950 if (r == nullptr)
4951 return;
4952 q = 0;
4953 if (left < sizeof(uint32_t)) {
4954 memcpy(dest: &q, src: r, n: left);
4955 outs() << " (protocol_t * entends past the end of the section)\n";
4956 } else
4957 memcpy(dest: &q, src: r, n: sizeof(uint32_t));
4958 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4959 sys::swapByteOrder(Value&: q);
4960 outs() << "\t\t list[" << i << "] " << format(Fmt: "0x%" PRIx32, Vals: q)
4961 << " (struct protocol_t *)\n";
4962 r = get_pointer_32(Address: q, offset, left, S, info);
4963 if (r == nullptr)
4964 return;
4965 memset(s: &pc, c: '\0', n: sizeof(struct protocol32_t));
4966 if (left < sizeof(struct protocol32_t)) {
4967 memcpy(dest: &pc, src: r, n: left);
4968 outs() << " (protocol_t entends past the end of the section)\n";
4969 } else
4970 memcpy(dest: &pc, src: r, n: sizeof(struct protocol32_t));
4971 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4972 swapStruct(p&: pc);
4973 outs() << "\t\t\t isa " << format(Fmt: "0x%" PRIx32, Vals: pc.isa) << "\n";
4974 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: pc.name);
4975 name = get_pointer_32(Address: pc.name, offset&: xoffset, left, S&: xS, info);
4976 if (name != nullptr)
4977 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
4978 outs() << "\n";
4979 outs() << "\t\t\tprotocols " << format(Fmt: "0x%" PRIx32, Vals: pc.protocols) << "\n";
4980 outs() << "\t\t instanceMethods "
4981 << format(Fmt: "0x%" PRIx32, Vals: pc.instanceMethods)
4982 << " (struct method_list_t *)\n";
4983 if (pc.instanceMethods != 0)
4984 print_method_list32_t(p: pc.instanceMethods, info, indent: "\t");
4985 outs() << "\t\t classMethods " << format(Fmt: "0x%" PRIx32, Vals: pc.classMethods)
4986 << " (struct method_list_t *)\n";
4987 if (pc.classMethods != 0)
4988 print_method_list32_t(p: pc.classMethods, info, indent: "\t");
4989 outs() << "\t optionalInstanceMethods "
4990 << format(Fmt: "0x%" PRIx32, Vals: pc.optionalInstanceMethods) << "\n";
4991 outs() << "\t optionalClassMethods "
4992 << format(Fmt: "0x%" PRIx32, Vals: pc.optionalClassMethods) << "\n";
4993 outs() << "\t instanceProperties "
4994 << format(Fmt: "0x%" PRIx32, Vals: pc.instanceProperties) << "\n";
4995 p += sizeof(uint32_t);
4996 offset += sizeof(uint32_t);
4997 }
4998}
4999
5000static void print_indent(uint32_t indent) {
5001 for (uint32_t i = 0; i < indent;) {
5002 if (indent - i >= 8) {
5003 outs() << "\t";
5004 i += 8;
5005 } else {
5006 for (uint32_t j = i; j < indent; j++)
5007 outs() << " ";
5008 return;
5009 }
5010 }
5011}
5012
5013static bool print_method_description_list(uint32_t p, uint32_t indent,
5014 struct DisassembleInfo *info) {
5015 uint32_t offset, left, xleft;
5016 SectionRef S;
5017 struct objc_method_description_list_t mdl;
5018 struct objc_method_description_t md;
5019 const char *r, *list, *name;
5020 int32_t i;
5021
5022 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5023 if (r == nullptr)
5024 return true;
5025
5026 outs() << "\n";
5027 if (left > sizeof(struct objc_method_description_list_t)) {
5028 memcpy(dest: &mdl, src: r, n: sizeof(struct objc_method_description_list_t));
5029 } else {
5030 print_indent(indent);
5031 outs() << " objc_method_description_list extends past end of the section\n";
5032 memset(s: &mdl, c: '\0', n: sizeof(struct objc_method_description_list_t));
5033 memcpy(dest: &mdl, src: r, n: left);
5034 }
5035 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5036 swapStruct(mdl);
5037
5038 print_indent(indent);
5039 outs() << " count " << mdl.count << "\n";
5040
5041 list = r + sizeof(struct objc_method_description_list_t);
5042 for (i = 0; i < mdl.count; i++) {
5043 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
5044 print_indent(indent);
5045 outs() << " remaining list entries extend past the of the section\n";
5046 break;
5047 }
5048 print_indent(indent);
5049 outs() << " list[" << i << "]\n";
5050 memcpy(dest: &md, src: list + i * sizeof(struct objc_method_description_t),
5051 n: sizeof(struct objc_method_description_t));
5052 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5053 swapStruct(md);
5054
5055 print_indent(indent);
5056 outs() << " name " << format(Fmt: "0x%08" PRIx32, Vals: md.name);
5057 if (info->verbose) {
5058 name = get_pointer_32(Address: md.name, offset, left&: xleft, S, info, objc_only: true);
5059 if (name != nullptr)
5060 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5061 else
5062 outs() << " (not in an __OBJC section)";
5063 }
5064 outs() << "\n";
5065
5066 print_indent(indent);
5067 outs() << " types " << format(Fmt: "0x%08" PRIx32, Vals: md.types);
5068 if (info->verbose) {
5069 name = get_pointer_32(Address: md.types, offset, left&: xleft, S, info, objc_only: true);
5070 if (name != nullptr)
5071 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5072 else
5073 outs() << " (not in an __OBJC section)";
5074 }
5075 outs() << "\n";
5076 }
5077 return false;
5078}
5079
5080static bool print_protocol_list(uint32_t p, uint32_t indent,
5081 struct DisassembleInfo *info);
5082
5083static bool print_protocol(uint32_t p, uint32_t indent,
5084 struct DisassembleInfo *info) {
5085 uint32_t offset, left;
5086 SectionRef S;
5087 struct objc_protocol_t protocol;
5088 const char *r, *name;
5089
5090 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5091 if (r == nullptr)
5092 return true;
5093
5094 outs() << "\n";
5095 if (left >= sizeof(struct objc_protocol_t)) {
5096 memcpy(dest: &protocol, src: r, n: sizeof(struct objc_protocol_t));
5097 } else {
5098 print_indent(indent);
5099 outs() << " Protocol extends past end of the section\n";
5100 memset(s: &protocol, c: '\0', n: sizeof(struct objc_protocol_t));
5101 memcpy(dest: &protocol, src: r, n: left);
5102 }
5103 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5104 swapStruct(protocol);
5105
5106 print_indent(indent);
5107 outs() << " isa " << format(Fmt: "0x%08" PRIx32, Vals: protocol.isa)
5108 << "\n";
5109
5110 print_indent(indent);
5111 outs() << " protocol_name "
5112 << format(Fmt: "0x%08" PRIx32, Vals: protocol.protocol_name);
5113 if (info->verbose) {
5114 name = get_pointer_32(Address: protocol.protocol_name, offset, left, S, info, objc_only: true);
5115 if (name != nullptr)
5116 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5117 else
5118 outs() << " (not in an __OBJC section)";
5119 }
5120 outs() << "\n";
5121
5122 print_indent(indent);
5123 outs() << " protocol_list "
5124 << format(Fmt: "0x%08" PRIx32, Vals: protocol.protocol_list);
5125 if (print_protocol_list(p: protocol.protocol_list, indent: indent + 4, info))
5126 outs() << " (not in an __OBJC section)\n";
5127
5128 print_indent(indent);
5129 outs() << " instance_methods "
5130 << format(Fmt: "0x%08" PRIx32, Vals: protocol.instance_methods);
5131 if (print_method_description_list(p: protocol.instance_methods, indent, info))
5132 outs() << " (not in an __OBJC section)\n";
5133
5134 print_indent(indent);
5135 outs() << " class_methods "
5136 << format(Fmt: "0x%08" PRIx32, Vals: protocol.class_methods);
5137 if (print_method_description_list(p: protocol.class_methods, indent, info))
5138 outs() << " (not in an __OBJC section)\n";
5139
5140 return false;
5141}
5142
5143static bool print_protocol_list(uint32_t p, uint32_t indent,
5144 struct DisassembleInfo *info) {
5145 uint32_t offset, left, l;
5146 SectionRef S;
5147 struct objc_protocol_list_t protocol_list;
5148 const char *r, *list;
5149 int32_t i;
5150
5151 r = get_pointer_32(Address: p, offset, left, S, info, objc_only: true);
5152 if (r == nullptr)
5153 return true;
5154
5155 outs() << "\n";
5156 if (left > sizeof(struct objc_protocol_list_t)) {
5157 memcpy(dest: &protocol_list, src: r, n: sizeof(struct objc_protocol_list_t));
5158 } else {
5159 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
5160 memset(s: &protocol_list, c: '\0', n: sizeof(struct objc_protocol_list_t));
5161 memcpy(dest: &protocol_list, src: r, n: left);
5162 }
5163 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5164 swapStruct(protocol_list);
5165
5166 print_indent(indent);
5167 outs() << " next " << format(Fmt: "0x%08" PRIx32, Vals: protocol_list.next)
5168 << "\n";
5169 print_indent(indent);
5170 outs() << " count " << protocol_list.count << "\n";
5171
5172 list = r + sizeof(struct objc_protocol_list_t);
5173 for (i = 0; i < protocol_list.count; i++) {
5174 if ((i + 1) * sizeof(uint32_t) > left) {
5175 outs() << "\t\t remaining list entries extend past the of the section\n";
5176 break;
5177 }
5178 memcpy(dest: &l, src: list + i * sizeof(uint32_t), n: sizeof(uint32_t));
5179 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5180 sys::swapByteOrder(Value&: l);
5181
5182 print_indent(indent);
5183 outs() << " list[" << i << "] " << format(Fmt: "0x%08" PRIx32, Vals: l);
5184 if (print_protocol(p: l, indent, info))
5185 outs() << "(not in an __OBJC section)\n";
5186 }
5187 return false;
5188}
5189
5190static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
5191 struct ivar_list64_t il;
5192 struct ivar64_t i;
5193 const char *r;
5194 uint32_t offset, xoffset, left, j;
5195 SectionRef S, xS;
5196 const char *name, *sym_name, *ivar_offset_p;
5197 uint64_t ivar_offset, n_value;
5198
5199 r = get_pointer_64(Address: p, offset, left, S, info);
5200 if (r == nullptr)
5201 return;
5202 memset(s: &il, c: '\0', n: sizeof(struct ivar_list64_t));
5203 if (left < sizeof(struct ivar_list64_t)) {
5204 memcpy(dest: &il, src: r, n: left);
5205 outs() << " (ivar_list_t entends past the end of the section)\n";
5206 } else
5207 memcpy(dest: &il, src: r, n: sizeof(struct ivar_list64_t));
5208 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5209 swapStruct(il);
5210 outs() << " entsize " << il.entsize << "\n";
5211 outs() << " count " << il.count << "\n";
5212
5213 p += sizeof(struct ivar_list64_t);
5214 offset += sizeof(struct ivar_list64_t);
5215 for (j = 0; j < il.count; j++) {
5216 r = get_pointer_64(Address: p, offset, left, S, info);
5217 if (r == nullptr)
5218 return;
5219 memset(s: &i, c: '\0', n: sizeof(struct ivar64_t));
5220 if (left < sizeof(struct ivar64_t)) {
5221 memcpy(dest: &i, src: r, n: left);
5222 outs() << " (ivar_t entends past the end of the section)\n";
5223 } else
5224 memcpy(dest: &i, src: r, n: sizeof(struct ivar64_t));
5225 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5226 swapStruct(i);
5227
5228 outs() << "\t\t\t offset ";
5229 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, offset), S,
5230 info, n_value, ReferenceValue: i.offset);
5231 if (n_value != 0) {
5232 if (info->verbose && sym_name != nullptr)
5233 outs() << sym_name;
5234 else
5235 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5236 if (i.offset != 0)
5237 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.offset);
5238 } else
5239 outs() << format(Fmt: "0x%" PRIx64, Vals: i.offset);
5240 ivar_offset_p = get_pointer_64(Address: i.offset + n_value, offset&: xoffset, left, S&: xS, info);
5241 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5242 memcpy(dest: &ivar_offset, src: ivar_offset_p, n: sizeof(ivar_offset));
5243 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5244 sys::swapByteOrder(Value&: ivar_offset);
5245 outs() << " " << ivar_offset << "\n";
5246 } else
5247 outs() << "\n";
5248
5249 outs() << "\t\t\t name ";
5250 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, name), S, info,
5251 n_value, ReferenceValue: i.name);
5252 if (n_value != 0) {
5253 if (info->verbose && sym_name != nullptr)
5254 outs() << sym_name;
5255 else
5256 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5257 if (i.name != 0)
5258 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.name);
5259 } else
5260 outs() << format(Fmt: "0x%" PRIx64, Vals: i.name);
5261 name = get_pointer_64(Address: i.name + n_value, offset&: xoffset, left, S&: xS, info);
5262 if (name != nullptr)
5263 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5264 outs() << "\n";
5265
5266 outs() << "\t\t\t type ";
5267 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct ivar64_t, type), S, info,
5268 n_value, ReferenceValue: i.name);
5269 name = get_pointer_64(Address: i.type + n_value, offset&: xoffset, left, S&: xS, info);
5270 if (n_value != 0) {
5271 if (info->verbose && sym_name != nullptr)
5272 outs() << sym_name;
5273 else
5274 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5275 if (i.type != 0)
5276 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: i.type);
5277 } else
5278 outs() << format(Fmt: "0x%" PRIx64, Vals: i.type);
5279 if (name != nullptr)
5280 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5281 outs() << "\n";
5282
5283 outs() << "\t\t\talignment " << i.alignment << "\n";
5284 outs() << "\t\t\t size " << i.size << "\n";
5285
5286 p += sizeof(struct ivar64_t);
5287 offset += sizeof(struct ivar64_t);
5288 }
5289}
5290
5291static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
5292 struct ivar_list32_t il;
5293 struct ivar32_t i;
5294 const char *r;
5295 uint32_t offset, xoffset, left, j;
5296 SectionRef S, xS;
5297 const char *name, *ivar_offset_p;
5298 uint32_t ivar_offset;
5299
5300 r = get_pointer_32(Address: p, offset, left, S, info);
5301 if (r == nullptr)
5302 return;
5303 memset(s: &il, c: '\0', n: sizeof(struct ivar_list32_t));
5304 if (left < sizeof(struct ivar_list32_t)) {
5305 memcpy(dest: &il, src: r, n: left);
5306 outs() << " (ivar_list_t entends past the end of the section)\n";
5307 } else
5308 memcpy(dest: &il, src: r, n: sizeof(struct ivar_list32_t));
5309 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5310 swapStruct(il);
5311 outs() << " entsize " << il.entsize << "\n";
5312 outs() << " count " << il.count << "\n";
5313
5314 p += sizeof(struct ivar_list32_t);
5315 offset += sizeof(struct ivar_list32_t);
5316 for (j = 0; j < il.count; j++) {
5317 r = get_pointer_32(Address: p, offset, left, S, info);
5318 if (r == nullptr)
5319 return;
5320 memset(s: &i, c: '\0', n: sizeof(struct ivar32_t));
5321 if (left < sizeof(struct ivar32_t)) {
5322 memcpy(dest: &i, src: r, n: left);
5323 outs() << " (ivar_t entends past the end of the section)\n";
5324 } else
5325 memcpy(dest: &i, src: r, n: sizeof(struct ivar32_t));
5326 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5327 swapStruct(i);
5328
5329 outs() << "\t\t\t offset " << format(Fmt: "0x%" PRIx32, Vals: i.offset);
5330 ivar_offset_p = get_pointer_32(Address: i.offset, offset&: xoffset, left, S&: xS, info);
5331 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
5332 memcpy(dest: &ivar_offset, src: ivar_offset_p, n: sizeof(ivar_offset));
5333 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5334 sys::swapByteOrder(Value&: ivar_offset);
5335 outs() << " " << ivar_offset << "\n";
5336 } else
5337 outs() << "\n";
5338
5339 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: i.name);
5340 name = get_pointer_32(Address: i.name, offset&: xoffset, left, S&: xS, info);
5341 if (name != nullptr)
5342 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5343 outs() << "\n";
5344
5345 outs() << "\t\t\t type " << format(Fmt: "0x%" PRIx32, Vals: i.type);
5346 name = get_pointer_32(Address: i.type, offset&: xoffset, left, S&: xS, info);
5347 if (name != nullptr)
5348 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5349 outs() << "\n";
5350
5351 outs() << "\t\t\talignment " << i.alignment << "\n";
5352 outs() << "\t\t\t size " << i.size << "\n";
5353
5354 p += sizeof(struct ivar32_t);
5355 offset += sizeof(struct ivar32_t);
5356 }
5357}
5358
5359static void print_objc_property_list64(uint64_t p,
5360 struct DisassembleInfo *info) {
5361 struct objc_property_list64 opl;
5362 struct objc_property64 op;
5363 const char *r;
5364 uint32_t offset, xoffset, left, j;
5365 SectionRef S, xS;
5366 const char *name, *sym_name;
5367 uint64_t n_value;
5368
5369 r = get_pointer_64(Address: p, offset, left, S, info);
5370 if (r == nullptr)
5371 return;
5372 memset(s: &opl, c: '\0', n: sizeof(struct objc_property_list64));
5373 if (left < sizeof(struct objc_property_list64)) {
5374 memcpy(dest: &opl, src: r, n: left);
5375 outs() << " (objc_property_list entends past the end of the section)\n";
5376 } else
5377 memcpy(dest: &opl, src: r, n: sizeof(struct objc_property_list64));
5378 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5379 swapStruct(pl&: opl);
5380 outs() << " entsize " << opl.entsize << "\n";
5381 outs() << " count " << opl.count << "\n";
5382
5383 p += sizeof(struct objc_property_list64);
5384 offset += sizeof(struct objc_property_list64);
5385 for (j = 0; j < opl.count; j++) {
5386 r = get_pointer_64(Address: p, offset, left, S, info);
5387 if (r == nullptr)
5388 return;
5389 memset(s: &op, c: '\0', n: sizeof(struct objc_property64));
5390 if (left < sizeof(struct objc_property64)) {
5391 memcpy(dest: &op, src: r, n: left);
5392 outs() << " (objc_property entends past the end of the section)\n";
5393 } else
5394 memcpy(dest: &op, src: r, n: sizeof(struct objc_property64));
5395 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5396 swapStruct(op);
5397
5398 outs() << "\t\t\t name ";
5399 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct objc_property64, name), S,
5400 info, n_value, ReferenceValue: op.name);
5401 if (n_value != 0) {
5402 if (info->verbose && sym_name != nullptr)
5403 outs() << sym_name;
5404 else
5405 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5406 if (op.name != 0)
5407 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: op.name);
5408 } else
5409 outs() << format(Fmt: "0x%" PRIx64, Vals: op.name);
5410 name = get_pointer_64(Address: op.name + n_value, offset&: xoffset, left, S&: xS, info);
5411 if (name != nullptr)
5412 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5413 outs() << "\n";
5414
5415 outs() << "\t\t\tattributes ";
5416 sym_name =
5417 get_symbol_64(sect_offset: offset + offsetof(struct objc_property64, attributes), S,
5418 info, n_value, ReferenceValue: op.attributes);
5419 if (n_value != 0) {
5420 if (info->verbose && sym_name != nullptr)
5421 outs() << sym_name;
5422 else
5423 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5424 if (op.attributes != 0)
5425 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: op.attributes);
5426 } else
5427 outs() << format(Fmt: "0x%" PRIx64, Vals: op.attributes);
5428 name = get_pointer_64(Address: op.attributes + n_value, offset&: xoffset, left, S&: xS, info);
5429 if (name != nullptr)
5430 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5431 outs() << "\n";
5432
5433 p += sizeof(struct objc_property64);
5434 offset += sizeof(struct objc_property64);
5435 }
5436}
5437
5438static void print_objc_property_list32(uint32_t p,
5439 struct DisassembleInfo *info) {
5440 struct objc_property_list32 opl;
5441 struct objc_property32 op;
5442 const char *r;
5443 uint32_t offset, xoffset, left, j;
5444 SectionRef S, xS;
5445 const char *name;
5446
5447 r = get_pointer_32(Address: p, offset, left, S, info);
5448 if (r == nullptr)
5449 return;
5450 memset(s: &opl, c: '\0', n: sizeof(struct objc_property_list32));
5451 if (left < sizeof(struct objc_property_list32)) {
5452 memcpy(dest: &opl, src: r, n: left);
5453 outs() << " (objc_property_list entends past the end of the section)\n";
5454 } else
5455 memcpy(dest: &opl, src: r, n: sizeof(struct objc_property_list32));
5456 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5457 swapStruct(pl&: opl);
5458 outs() << " entsize " << opl.entsize << "\n";
5459 outs() << " count " << opl.count << "\n";
5460
5461 p += sizeof(struct objc_property_list32);
5462 offset += sizeof(struct objc_property_list32);
5463 for (j = 0; j < opl.count; j++) {
5464 r = get_pointer_32(Address: p, offset, left, S, info);
5465 if (r == nullptr)
5466 return;
5467 memset(s: &op, c: '\0', n: sizeof(struct objc_property32));
5468 if (left < sizeof(struct objc_property32)) {
5469 memcpy(dest: &op, src: r, n: left);
5470 outs() << " (objc_property entends past the end of the section)\n";
5471 } else
5472 memcpy(dest: &op, src: r, n: sizeof(struct objc_property32));
5473 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5474 swapStruct(op);
5475
5476 outs() << "\t\t\t name " << format(Fmt: "0x%" PRIx32, Vals: op.name);
5477 name = get_pointer_32(Address: op.name, offset&: xoffset, left, S&: xS, info);
5478 if (name != nullptr)
5479 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5480 outs() << "\n";
5481
5482 outs() << "\t\t\tattributes " << format(Fmt: "0x%" PRIx32, Vals: op.attributes);
5483 name = get_pointer_32(Address: op.attributes, offset&: xoffset, left, S&: xS, info);
5484 if (name != nullptr)
5485 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5486 outs() << "\n";
5487
5488 p += sizeof(struct objc_property32);
5489 offset += sizeof(struct objc_property32);
5490 }
5491}
5492
5493static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
5494 bool &is_meta_class) {
5495 struct class_ro64_t cro;
5496 const char *r;
5497 uint32_t offset, xoffset, left;
5498 SectionRef S, xS;
5499 const char *name, *sym_name;
5500 uint64_t n_value;
5501
5502 r = get_pointer_64(Address: p, offset, left, S, info);
5503 if (r == nullptr || left < sizeof(struct class_ro64_t))
5504 return false;
5505 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro64_t));
5506 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5507 swapStruct(cro);
5508 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: cro.flags);
5509 if (cro.flags & RO_META)
5510 outs() << " RO_META";
5511 if (cro.flags & RO_ROOT)
5512 outs() << " RO_ROOT";
5513 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5514 outs() << " RO_HAS_CXX_STRUCTORS";
5515 outs() << "\n";
5516 outs() << " instanceStart " << cro.instanceStart << "\n";
5517 outs() << " instanceSize " << cro.instanceSize << "\n";
5518 outs() << " reserved " << format(Fmt: "0x%" PRIx32, Vals: cro.reserved)
5519 << "\n";
5520 outs() << " ivarLayout " << format(Fmt: "0x%" PRIx64, Vals: cro.ivarLayout)
5521 << "\n";
5522 print_layout_map64(p: cro.ivarLayout, info);
5523
5524 outs() << " name ";
5525 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, name), S,
5526 info, n_value, ReferenceValue: cro.name);
5527 if (n_value != 0) {
5528 if (info->verbose && sym_name != nullptr)
5529 outs() << sym_name;
5530 else
5531 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5532 if (cro.name != 0)
5533 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.name);
5534 } else
5535 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.name);
5536 name = get_pointer_64(Address: cro.name + n_value, offset&: xoffset, left, S&: xS, info);
5537 if (name != nullptr)
5538 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5539 outs() << "\n";
5540
5541 outs() << " baseMethods ";
5542 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseMethods),
5543 S, info, n_value, ReferenceValue: cro.baseMethods);
5544 if (n_value != 0) {
5545 if (info->verbose && sym_name != nullptr)
5546 outs() << sym_name;
5547 else
5548 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5549 if (cro.baseMethods != 0)
5550 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseMethods);
5551 } else
5552 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseMethods);
5553 outs() << " (struct method_list_t *)\n";
5554 if (cro.baseMethods + n_value != 0)
5555 print_method_list64_t(p: cro.baseMethods + n_value, info, indent: "");
5556
5557 outs() << " baseProtocols ";
5558 sym_name =
5559 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseProtocols), S,
5560 info, n_value, ReferenceValue: cro.baseProtocols);
5561 if (n_value != 0) {
5562 if (info->verbose && sym_name != nullptr)
5563 outs() << sym_name;
5564 else
5565 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5566 if (cro.baseProtocols != 0)
5567 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseProtocols);
5568 } else
5569 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseProtocols);
5570 outs() << "\n";
5571 if (cro.baseProtocols + n_value != 0)
5572 print_protocol_list64_t(p: cro.baseProtocols + n_value, info);
5573
5574 outs() << " ivars ";
5575 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, ivars), S,
5576 info, n_value, ReferenceValue: cro.ivars);
5577 if (n_value != 0) {
5578 if (info->verbose && sym_name != nullptr)
5579 outs() << sym_name;
5580 else
5581 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5582 if (cro.ivars != 0)
5583 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.ivars);
5584 } else
5585 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.ivars);
5586 outs() << "\n";
5587 if (cro.ivars + n_value != 0)
5588 print_ivar_list64_t(p: cro.ivars + n_value, info);
5589
5590 outs() << " weakIvarLayout ";
5591 sym_name =
5592 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, weakIvarLayout), S,
5593 info, n_value, ReferenceValue: cro.weakIvarLayout);
5594 if (n_value != 0) {
5595 if (info->verbose && sym_name != nullptr)
5596 outs() << sym_name;
5597 else
5598 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5599 if (cro.weakIvarLayout != 0)
5600 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.weakIvarLayout);
5601 } else
5602 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.weakIvarLayout);
5603 outs() << "\n";
5604 print_layout_map64(p: cro.weakIvarLayout + n_value, info);
5605
5606 outs() << " baseProperties ";
5607 sym_name =
5608 get_symbol_64(sect_offset: offset + offsetof(struct class_ro64_t, baseProperties), S,
5609 info, n_value, ReferenceValue: cro.baseProperties);
5610 if (n_value != 0) {
5611 if (info->verbose && sym_name != nullptr)
5612 outs() << sym_name;
5613 else
5614 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5615 if (cro.baseProperties != 0)
5616 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: cro.baseProperties);
5617 } else
5618 outs() << format(Fmt: "0x%" PRIx64, Vals: cro.baseProperties);
5619 outs() << "\n";
5620 if (cro.baseProperties + n_value != 0)
5621 print_objc_property_list64(p: cro.baseProperties + n_value, info);
5622
5623 is_meta_class = (cro.flags & RO_META) != 0;
5624 return true;
5625}
5626
5627static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
5628 bool &is_meta_class) {
5629 struct class_ro32_t cro;
5630 const char *r;
5631 uint32_t offset, xoffset, left;
5632 SectionRef S, xS;
5633 const char *name;
5634
5635 r = get_pointer_32(Address: p, offset, left, S, info);
5636 if (r == nullptr)
5637 return false;
5638 memset(s: &cro, c: '\0', n: sizeof(struct class_ro32_t));
5639 if (left < sizeof(struct class_ro32_t)) {
5640 memcpy(dest: &cro, src: r, n: left);
5641 outs() << " (class_ro_t entends past the end of the section)\n";
5642 } else
5643 memcpy(dest: &cro, src: r, n: sizeof(struct class_ro32_t));
5644 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5645 swapStruct(cro);
5646 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: cro.flags);
5647 if (cro.flags & RO_META)
5648 outs() << " RO_META";
5649 if (cro.flags & RO_ROOT)
5650 outs() << " RO_ROOT";
5651 if (cro.flags & RO_HAS_CXX_STRUCTORS)
5652 outs() << " RO_HAS_CXX_STRUCTORS";
5653 outs() << "\n";
5654 outs() << " instanceStart " << cro.instanceStart << "\n";
5655 outs() << " instanceSize " << cro.instanceSize << "\n";
5656 outs() << " ivarLayout " << format(Fmt: "0x%" PRIx32, Vals: cro.ivarLayout)
5657 << "\n";
5658 print_layout_map32(p: cro.ivarLayout, info);
5659
5660 outs() << " name " << format(Fmt: "0x%" PRIx32, Vals: cro.name);
5661 name = get_pointer_32(Address: cro.name, offset&: xoffset, left, S&: xS, info);
5662 if (name != nullptr)
5663 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5664 outs() << "\n";
5665
5666 outs() << " baseMethods "
5667 << format(Fmt: "0x%" PRIx32, Vals: cro.baseMethods)
5668 << " (struct method_list_t *)\n";
5669 if (cro.baseMethods != 0)
5670 print_method_list32_t(p: cro.baseMethods, info, indent: "");
5671
5672 outs() << " baseProtocols "
5673 << format(Fmt: "0x%" PRIx32, Vals: cro.baseProtocols) << "\n";
5674 if (cro.baseProtocols != 0)
5675 print_protocol_list32_t(p: cro.baseProtocols, info);
5676 outs() << " ivars " << format(Fmt: "0x%" PRIx32, Vals: cro.ivars)
5677 << "\n";
5678 if (cro.ivars != 0)
5679 print_ivar_list32_t(p: cro.ivars, info);
5680 outs() << " weakIvarLayout "
5681 << format(Fmt: "0x%" PRIx32, Vals: cro.weakIvarLayout) << "\n";
5682 print_layout_map32(p: cro.weakIvarLayout, info);
5683 outs() << " baseProperties "
5684 << format(Fmt: "0x%" PRIx32, Vals: cro.baseProperties) << "\n";
5685 if (cro.baseProperties != 0)
5686 print_objc_property_list32(p: cro.baseProperties, info);
5687 is_meta_class = (cro.flags & RO_META) != 0;
5688 return true;
5689}
5690
5691static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
5692 struct class64_t c;
5693 const char *r;
5694 uint32_t offset, left;
5695 SectionRef S;
5696 const char *name;
5697 uint64_t isa_n_value, n_value;
5698
5699 r = get_pointer_64(Address: p, offset, left, S, info);
5700 if (r == nullptr || left < sizeof(struct class64_t))
5701 return;
5702 memcpy(dest: &c, src: r, n: sizeof(struct class64_t));
5703 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5704 swapStruct(c);
5705
5706 outs() << " isa " << format(Fmt: "0x%" PRIx64, Vals: c.isa);
5707 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, isa), S, info,
5708 n_value&: isa_n_value, ReferenceValue: c.isa);
5709 if (name != nullptr)
5710 outs() << " " << name;
5711 outs() << "\n";
5712
5713 outs() << " superclass " << format(Fmt: "0x%" PRIx64, Vals: c.superclass);
5714 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, superclass), S, info,
5715 n_value, ReferenceValue: c.superclass);
5716 if (name != nullptr)
5717 outs() << " " << name;
5718 else {
5719 name = get_dyld_bind_info_symbolname(ReferenceValue: S.getAddress() +
5720 offset + offsetof(struct class64_t, superclass), info);
5721 if (name != nullptr)
5722 outs() << " " << name;
5723 }
5724 outs() << "\n";
5725
5726 outs() << " cache " << format(Fmt: "0x%" PRIx64, Vals: c.cache);
5727 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, cache), S, info,
5728 n_value, ReferenceValue: c.cache);
5729 if (name != nullptr)
5730 outs() << " " << name;
5731 outs() << "\n";
5732
5733 outs() << " vtable " << format(Fmt: "0x%" PRIx64, Vals: c.vtable);
5734 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, vtable), S, info,
5735 n_value, ReferenceValue: c.vtable);
5736 if (name != nullptr)
5737 outs() << " " << name;
5738 outs() << "\n";
5739
5740 name = get_symbol_64(sect_offset: offset + offsetof(struct class64_t, data), S, info,
5741 n_value, ReferenceValue: c.data);
5742 outs() << " data ";
5743 if (n_value != 0) {
5744 if (info->verbose && name != nullptr)
5745 outs() << name;
5746 else
5747 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
5748 if (c.data != 0)
5749 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.data);
5750 } else
5751 outs() << format(Fmt: "0x%" PRIx64, Vals: c.data);
5752 outs() << " (struct class_ro_t *)";
5753
5754 // This is a Swift class if some of the low bits of the pointer are set.
5755 if ((c.data + n_value) & 0x7)
5756 outs() << " Swift class";
5757 outs() << "\n";
5758 bool is_meta_class;
5759 if (!print_class_ro64_t(p: (c.data + n_value) & ~0x7, info, is_meta_class))
5760 return;
5761
5762 if (!is_meta_class &&
5763 c.isa + isa_n_value != p &&
5764 c.isa + isa_n_value != 0 &&
5765 info->depth < 100) {
5766 info->depth++;
5767 outs() << "Meta Class\n";
5768 print_class64_t(p: c.isa + isa_n_value, info);
5769 }
5770}
5771
5772static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
5773 struct class32_t c;
5774 const char *r;
5775 uint32_t offset, left;
5776 SectionRef S;
5777 const char *name;
5778
5779 r = get_pointer_32(Address: p, offset, left, S, info);
5780 if (r == nullptr)
5781 return;
5782 memset(s: &c, c: '\0', n: sizeof(struct class32_t));
5783 if (left < sizeof(struct class32_t)) {
5784 memcpy(dest: &c, src: r, n: left);
5785 outs() << " (class_t entends past the end of the section)\n";
5786 } else
5787 memcpy(dest: &c, src: r, n: sizeof(struct class32_t));
5788 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5789 swapStruct(c);
5790
5791 outs() << " isa " << format(Fmt: "0x%" PRIx32, Vals: c.isa);
5792 name =
5793 get_symbol_32(sect_offset: offset + offsetof(struct class32_t, isa), S, info, ReferenceValue: c.isa);
5794 if (name != nullptr)
5795 outs() << " " << name;
5796 outs() << "\n";
5797
5798 outs() << " superclass " << format(Fmt: "0x%" PRIx32, Vals: c.superclass);
5799 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, superclass), S, info,
5800 ReferenceValue: c.superclass);
5801 if (name != nullptr)
5802 outs() << " " << name;
5803 outs() << "\n";
5804
5805 outs() << " cache " << format(Fmt: "0x%" PRIx32, Vals: c.cache);
5806 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, cache), S, info,
5807 ReferenceValue: c.cache);
5808 if (name != nullptr)
5809 outs() << " " << name;
5810 outs() << "\n";
5811
5812 outs() << " vtable " << format(Fmt: "0x%" PRIx32, Vals: c.vtable);
5813 name = get_symbol_32(sect_offset: offset + offsetof(struct class32_t, vtable), S, info,
5814 ReferenceValue: c.vtable);
5815 if (name != nullptr)
5816 outs() << " " << name;
5817 outs() << "\n";
5818
5819 name =
5820 get_symbol_32(sect_offset: offset + offsetof(struct class32_t, data), S, info, ReferenceValue: c.data);
5821 outs() << " data " << format(Fmt: "0x%" PRIx32, Vals: c.data)
5822 << " (struct class_ro_t *)";
5823
5824 // This is a Swift class if some of the low bits of the pointer are set.
5825 if (c.data & 0x3)
5826 outs() << " Swift class";
5827 outs() << "\n";
5828 bool is_meta_class;
5829 if (!print_class_ro32_t(p: c.data & ~0x3, info, is_meta_class))
5830 return;
5831
5832 if (!is_meta_class) {
5833 outs() << "Meta Class\n";
5834 print_class32_t(p: c.isa, info);
5835 }
5836}
5837
5838static void print_objc_class_t(struct objc_class_t *objc_class,
5839 struct DisassembleInfo *info) {
5840 uint32_t offset, left, xleft;
5841 const char *name, *p, *ivar_list;
5842 SectionRef S;
5843 int32_t i;
5844 struct objc_ivar_list_t objc_ivar_list;
5845 struct objc_ivar_t ivar;
5846
5847 outs() << "\t\t isa " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->isa);
5848 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)) {
5849 name = get_pointer_32(Address: objc_class->isa, offset, left, S, info, objc_only: true);
5850 if (name != nullptr)
5851 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5852 else
5853 outs() << " (not in an __OBJC section)";
5854 }
5855 outs() << "\n";
5856
5857 outs() << "\t super_class "
5858 << format(Fmt: "0x%08" PRIx32, Vals: objc_class->super_class);
5859 if (info->verbose) {
5860 name = get_pointer_32(Address: objc_class->super_class, offset, left, S, info, objc_only: true);
5861 if (name != nullptr)
5862 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5863 else
5864 outs() << " (not in an __OBJC section)";
5865 }
5866 outs() << "\n";
5867
5868 outs() << "\t\t name " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->name);
5869 if (info->verbose) {
5870 name = get_pointer_32(Address: objc_class->name, offset, left, S, info, objc_only: true);
5871 if (name != nullptr)
5872 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5873 else
5874 outs() << " (not in an __OBJC section)";
5875 }
5876 outs() << "\n";
5877
5878 outs() << "\t\t version " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->version)
5879 << "\n";
5880
5881 outs() << "\t\t info " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->info);
5882 if (info->verbose) {
5883 if (CLS_GETINFO(objc_class, CLS_CLASS))
5884 outs() << " CLS_CLASS";
5885 else if (CLS_GETINFO(objc_class, CLS_META))
5886 outs() << " CLS_META";
5887 }
5888 outs() << "\n";
5889
5890 outs() << "\t instance_size "
5891 << format(Fmt: "0x%08" PRIx32, Vals: objc_class->instance_size) << "\n";
5892
5893 p = get_pointer_32(Address: objc_class->ivars, offset, left, S, info, objc_only: true);
5894 outs() << "\t\t ivars " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->ivars);
5895 if (p != nullptr) {
5896 if (left > sizeof(struct objc_ivar_list_t)) {
5897 outs() << "\n";
5898 memcpy(dest: &objc_ivar_list, src: p, n: sizeof(struct objc_ivar_list_t));
5899 } else {
5900 outs() << " (entends past the end of the section)\n";
5901 memset(s: &objc_ivar_list, c: '\0', n: sizeof(struct objc_ivar_list_t));
5902 memcpy(dest: &objc_ivar_list, src: p, n: left);
5903 }
5904 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5905 swapStruct(objc_ivar_list);
5906 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
5907 ivar_list = p + sizeof(struct objc_ivar_list_t);
5908 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
5909 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
5910 outs() << "\t\t remaining ivar's extend past the of the section\n";
5911 break;
5912 }
5913 memcpy(dest: &ivar, src: ivar_list + i * sizeof(struct objc_ivar_t),
5914 n: sizeof(struct objc_ivar_t));
5915 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5916 swapStruct(objc_ivar&: ivar);
5917
5918 outs() << "\t\t\tivar_name " << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_name);
5919 if (info->verbose) {
5920 name = get_pointer_32(Address: ivar.ivar_name, offset, left&: xleft, S, info, objc_only: true);
5921 if (name != nullptr)
5922 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5923 else
5924 outs() << " (not in an __OBJC section)";
5925 }
5926 outs() << "\n";
5927
5928 outs() << "\t\t\tivar_type " << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_type);
5929 if (info->verbose) {
5930 name = get_pointer_32(Address: ivar.ivar_type, offset, left&: xleft, S, info, objc_only: true);
5931 if (name != nullptr)
5932 outs() << format(Fmt: " %.*s", Vals: xleft, Vals: name);
5933 else
5934 outs() << " (not in an __OBJC section)";
5935 }
5936 outs() << "\n";
5937
5938 outs() << "\t\t ivar_offset "
5939 << format(Fmt: "0x%08" PRIx32, Vals: ivar.ivar_offset) << "\n";
5940 }
5941 } else {
5942 outs() << " (not in an __OBJC section)\n";
5943 }
5944
5945 outs() << "\t\t methods " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->methodLists);
5946 if (print_method_list(p: objc_class->methodLists, info))
5947 outs() << " (not in an __OBJC section)\n";
5948
5949 outs() << "\t\t cache " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->cache)
5950 << "\n";
5951
5952 outs() << "\t\tprotocols " << format(Fmt: "0x%08" PRIx32, Vals: objc_class->protocols);
5953 if (print_protocol_list(p: objc_class->protocols, indent: 16, info))
5954 outs() << " (not in an __OBJC section)\n";
5955}
5956
5957static void print_objc_objc_category_t(struct objc_category_t *objc_category,
5958 struct DisassembleInfo *info) {
5959 uint32_t offset, left;
5960 const char *name;
5961 SectionRef S;
5962
5963 outs() << "\t category name "
5964 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->category_name);
5965 if (info->verbose) {
5966 name = get_pointer_32(Address: objc_category->category_name, offset, left, S, info,
5967 objc_only: true);
5968 if (name != nullptr)
5969 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5970 else
5971 outs() << " (not in an __OBJC section)";
5972 }
5973 outs() << "\n";
5974
5975 outs() << "\t\t class name "
5976 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->class_name);
5977 if (info->verbose) {
5978 name =
5979 get_pointer_32(Address: objc_category->class_name, offset, left, S, info, objc_only: true);
5980 if (name != nullptr)
5981 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
5982 else
5983 outs() << " (not in an __OBJC section)";
5984 }
5985 outs() << "\n";
5986
5987 outs() << "\t instance methods "
5988 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->instance_methods);
5989 if (print_method_list(p: objc_category->instance_methods, info))
5990 outs() << " (not in an __OBJC section)\n";
5991
5992 outs() << "\t class methods "
5993 << format(Fmt: "0x%08" PRIx32, Vals: objc_category->class_methods);
5994 if (print_method_list(p: objc_category->class_methods, info))
5995 outs() << " (not in an __OBJC section)\n";
5996}
5997
5998static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
5999 struct category64_t c;
6000 const char *r;
6001 uint32_t offset, xoffset, left;
6002 SectionRef S, xS;
6003 const char *name, *sym_name;
6004 uint64_t n_value;
6005
6006 r = get_pointer_64(Address: p, offset, left, S, info);
6007 if (r == nullptr)
6008 return;
6009 memset(s: &c, c: '\0', n: sizeof(struct category64_t));
6010 if (left < sizeof(struct category64_t)) {
6011 memcpy(dest: &c, src: r, n: left);
6012 outs() << " (category_t entends past the end of the section)\n";
6013 } else
6014 memcpy(dest: &c, src: r, n: sizeof(struct category64_t));
6015 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6016 swapStruct(c);
6017
6018 outs() << " name ";
6019 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, name), S,
6020 info, n_value, ReferenceValue: c.name);
6021 if (n_value != 0) {
6022 if (info->verbose && sym_name != nullptr)
6023 outs() << sym_name;
6024 else
6025 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6026 if (c.name != 0)
6027 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.name);
6028 } else
6029 outs() << format(Fmt: "0x%" PRIx64, Vals: c.name);
6030 name = get_pointer_64(Address: c.name + n_value, offset&: xoffset, left, S&: xS, info);
6031 if (name != nullptr)
6032 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6033 outs() << "\n";
6034
6035 outs() << " cls ";
6036 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, cls), S, info,
6037 n_value, ReferenceValue: c.cls);
6038 if (n_value != 0) {
6039 if (info->verbose && sym_name != nullptr)
6040 outs() << sym_name;
6041 else
6042 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6043 if (c.cls != 0)
6044 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.cls);
6045 } else
6046 outs() << format(Fmt: "0x%" PRIx64, Vals: c.cls);
6047 outs() << "\n";
6048 if (c.cls + n_value != 0)
6049 print_class64_t(p: c.cls + n_value, info);
6050
6051 outs() << " instanceMethods ";
6052 sym_name =
6053 get_symbol_64(sect_offset: offset + offsetof(struct category64_t, instanceMethods), S,
6054 info, n_value, ReferenceValue: c.instanceMethods);
6055 if (n_value != 0) {
6056 if (info->verbose && sym_name != nullptr)
6057 outs() << sym_name;
6058 else
6059 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6060 if (c.instanceMethods != 0)
6061 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.instanceMethods);
6062 } else
6063 outs() << format(Fmt: "0x%" PRIx64, Vals: c.instanceMethods);
6064 outs() << "\n";
6065 if (c.instanceMethods + n_value != 0)
6066 print_method_list64_t(p: c.instanceMethods + n_value, info, indent: "");
6067
6068 outs() << " classMethods ";
6069 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, classMethods),
6070 S, info, n_value, ReferenceValue: c.classMethods);
6071 if (n_value != 0) {
6072 if (info->verbose && sym_name != nullptr)
6073 outs() << sym_name;
6074 else
6075 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6076 if (c.classMethods != 0)
6077 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.classMethods);
6078 } else
6079 outs() << format(Fmt: "0x%" PRIx64, Vals: c.classMethods);
6080 outs() << "\n";
6081 if (c.classMethods + n_value != 0)
6082 print_method_list64_t(p: c.classMethods + n_value, info, indent: "");
6083
6084 outs() << " protocols ";
6085 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct category64_t, protocols), S,
6086 info, n_value, ReferenceValue: c.protocols);
6087 if (n_value != 0) {
6088 if (info->verbose && sym_name != nullptr)
6089 outs() << sym_name;
6090 else
6091 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6092 if (c.protocols != 0)
6093 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.protocols);
6094 } else
6095 outs() << format(Fmt: "0x%" PRIx64, Vals: c.protocols);
6096 outs() << "\n";
6097 if (c.protocols + n_value != 0)
6098 print_protocol_list64_t(p: c.protocols + n_value, info);
6099
6100 outs() << "instanceProperties ";
6101 sym_name =
6102 get_symbol_64(sect_offset: offset + offsetof(struct category64_t, instanceProperties),
6103 S, info, n_value, ReferenceValue: c.instanceProperties);
6104 if (n_value != 0) {
6105 if (info->verbose && sym_name != nullptr)
6106 outs() << sym_name;
6107 else
6108 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6109 if (c.instanceProperties != 0)
6110 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: c.instanceProperties);
6111 } else
6112 outs() << format(Fmt: "0x%" PRIx64, Vals: c.instanceProperties);
6113 outs() << "\n";
6114 if (c.instanceProperties + n_value != 0)
6115 print_objc_property_list64(p: c.instanceProperties + n_value, info);
6116}
6117
6118static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
6119 struct category32_t c;
6120 const char *r;
6121 uint32_t offset, left;
6122 SectionRef S, xS;
6123 const char *name;
6124
6125 r = get_pointer_32(Address: p, offset, left, S, info);
6126 if (r == nullptr)
6127 return;
6128 memset(s: &c, c: '\0', n: sizeof(struct category32_t));
6129 if (left < sizeof(struct category32_t)) {
6130 memcpy(dest: &c, src: r, n: left);
6131 outs() << " (category_t entends past the end of the section)\n";
6132 } else
6133 memcpy(dest: &c, src: r, n: sizeof(struct category32_t));
6134 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6135 swapStruct(c);
6136
6137 outs() << " name " << format(Fmt: "0x%" PRIx32, Vals: c.name);
6138 name = get_symbol_32(sect_offset: offset + offsetof(struct category32_t, name), S, info,
6139 ReferenceValue: c.name);
6140 if (name)
6141 outs() << " " << name;
6142 outs() << "\n";
6143
6144 outs() << " cls " << format(Fmt: "0x%" PRIx32, Vals: c.cls) << "\n";
6145 if (c.cls != 0)
6146 print_class32_t(p: c.cls, info);
6147 outs() << " instanceMethods " << format(Fmt: "0x%" PRIx32, Vals: c.instanceMethods)
6148 << "\n";
6149 if (c.instanceMethods != 0)
6150 print_method_list32_t(p: c.instanceMethods, info, indent: "");
6151 outs() << " classMethods " << format(Fmt: "0x%" PRIx32, Vals: c.classMethods)
6152 << "\n";
6153 if (c.classMethods != 0)
6154 print_method_list32_t(p: c.classMethods, info, indent: "");
6155 outs() << " protocols " << format(Fmt: "0x%" PRIx32, Vals: c.protocols) << "\n";
6156 if (c.protocols != 0)
6157 print_protocol_list32_t(p: c.protocols, info);
6158 outs() << "instanceProperties " << format(Fmt: "0x%" PRIx32, Vals: c.instanceProperties)
6159 << "\n";
6160 if (c.instanceProperties != 0)
6161 print_objc_property_list32(p: c.instanceProperties, info);
6162}
6163
6164static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
6165 uint32_t i, left, offset, xoffset;
6166 uint64_t p, n_value;
6167 struct message_ref64 mr;
6168 const char *name, *sym_name;
6169 const char *r;
6170 SectionRef xS;
6171
6172 if (S == SectionRef())
6173 return;
6174
6175 StringRef SectName;
6176 Expected<StringRef> SecNameOrErr = S.getName();
6177 if (SecNameOrErr)
6178 SectName = *SecNameOrErr;
6179 else
6180 consumeError(Err: SecNameOrErr.takeError());
6181
6182 DataRefImpl Ref = S.getRawDataRefImpl();
6183 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6184 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6185 offset = 0;
6186 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6187 p = S.getAddress() + i;
6188 r = get_pointer_64(Address: p, offset, left, S, info);
6189 if (r == nullptr)
6190 return;
6191 memset(s: &mr, c: '\0', n: sizeof(struct message_ref64));
6192 if (left < sizeof(struct message_ref64)) {
6193 memcpy(dest: &mr, src: r, n: left);
6194 outs() << " (message_ref entends past the end of the section)\n";
6195 } else
6196 memcpy(dest: &mr, src: r, n: sizeof(struct message_ref64));
6197 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6198 swapStruct(mr);
6199
6200 outs() << " imp ";
6201 name = get_symbol_64(sect_offset: offset + offsetof(struct message_ref64, imp), S, info,
6202 n_value, ReferenceValue: mr.imp);
6203 if (n_value != 0) {
6204 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value) << " ";
6205 if (mr.imp != 0)
6206 outs() << "+ " << format(Fmt: "0x%" PRIx64, Vals: mr.imp) << " ";
6207 } else
6208 outs() << format(Fmt: "0x%" PRIx64, Vals: mr.imp) << " ";
6209 if (name != nullptr)
6210 outs() << " " << name;
6211 outs() << "\n";
6212
6213 outs() << " sel ";
6214 sym_name = get_symbol_64(sect_offset: offset + offsetof(struct message_ref64, sel), S,
6215 info, n_value, ReferenceValue: mr.sel);
6216 if (n_value != 0) {
6217 if (info->verbose && sym_name != nullptr)
6218 outs() << sym_name;
6219 else
6220 outs() << format(Fmt: "0x%" PRIx64, Vals: n_value);
6221 if (mr.sel != 0)
6222 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: mr.sel);
6223 } else
6224 outs() << format(Fmt: "0x%" PRIx64, Vals: mr.sel);
6225 name = get_pointer_64(Address: mr.sel + n_value, offset&: xoffset, left, S&: xS, info);
6226 if (name != nullptr)
6227 outs() << format(Fmt: " %.*s", Vals: left, Vals: name);
6228 outs() << "\n";
6229
6230 offset += sizeof(struct message_ref64);
6231 }
6232}
6233
6234static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
6235 uint32_t i, left, offset, xoffset, p;
6236 struct message_ref32 mr;
6237 const char *name, *r;
6238 SectionRef xS;
6239
6240 if (S == SectionRef())
6241 return;
6242
6243 StringRef SectName;
6244 Expected<StringRef> SecNameOrErr = S.getName();
6245 if (SecNameOrErr)
6246 SectName = *SecNameOrErr;
6247 else
6248 consumeError(Err: SecNameOrErr.takeError());
6249
6250 DataRefImpl Ref = S.getRawDataRefImpl();
6251 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6252 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6253 offset = 0;
6254 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
6255 p = S.getAddress() + i;
6256 r = get_pointer_32(Address: p, offset, left, S, info);
6257 if (r == nullptr)
6258 return;
6259 memset(s: &mr, c: '\0', n: sizeof(struct message_ref32));
6260 if (left < sizeof(struct message_ref32)) {
6261 memcpy(dest: &mr, src: r, n: left);
6262 outs() << " (message_ref entends past the end of the section)\n";
6263 } else
6264 memcpy(dest: &mr, src: r, n: sizeof(struct message_ref32));
6265 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6266 swapStruct(mr);
6267
6268 outs() << " imp " << format(Fmt: "0x%" PRIx32, Vals: mr.imp);
6269 name = get_symbol_32(sect_offset: offset + offsetof(struct message_ref32, imp), S, info,
6270 ReferenceValue: mr.imp);
6271 if (name != nullptr)
6272 outs() << " " << name;
6273 outs() << "\n";
6274
6275 outs() << " sel " << format(Fmt: "0x%" PRIx32, Vals: mr.sel);
6276 name = get_pointer_32(Address: mr.sel, offset&: xoffset, left, S&: xS, info);
6277 if (name != nullptr)
6278 outs() << " " << name;
6279 outs() << "\n";
6280
6281 offset += sizeof(struct message_ref32);
6282 }
6283}
6284
6285static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
6286 uint32_t left, offset, swift_version;
6287 uint64_t p;
6288 struct objc_image_info64 o;
6289 const char *r;
6290
6291 if (S == SectionRef())
6292 return;
6293
6294 StringRef SectName;
6295 Expected<StringRef> SecNameOrErr = S.getName();
6296 if (SecNameOrErr)
6297 SectName = *SecNameOrErr;
6298 else
6299 consumeError(Err: SecNameOrErr.takeError());
6300
6301 DataRefImpl Ref = S.getRawDataRefImpl();
6302 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6303 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6304 p = S.getAddress();
6305 r = get_pointer_64(Address: p, offset, left, S, info);
6306 if (r == nullptr)
6307 return;
6308 memset(s: &o, c: '\0', n: sizeof(struct objc_image_info64));
6309 if (left < sizeof(struct objc_image_info64)) {
6310 memcpy(dest: &o, src: r, n: left);
6311 outs() << " (objc_image_info entends past the end of the section)\n";
6312 } else
6313 memcpy(dest: &o, src: r, n: sizeof(struct objc_image_info64));
6314 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6315 swapStruct(o);
6316 outs() << " version " << o.version << "\n";
6317 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6318 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6319 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6320 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6321 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6322 if (o.flags & OBJC_IMAGE_IS_SIMULATED)
6323 outs() << " OBJC_IMAGE_IS_SIMULATED";
6324 if (o.flags & OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES)
6325 outs() << " OBJC_IMAGE_HAS_CATEGORY_CLASS_PROPERTIES";
6326 swift_version = (o.flags >> 8) & 0xff;
6327 if (swift_version != 0) {
6328 if (swift_version == 1)
6329 outs() << " Swift 1.0";
6330 else if (swift_version == 2)
6331 outs() << " Swift 1.1";
6332 else if(swift_version == 3)
6333 outs() << " Swift 2.0";
6334 else if(swift_version == 4)
6335 outs() << " Swift 3.0";
6336 else if(swift_version == 5)
6337 outs() << " Swift 4.0";
6338 else if(swift_version == 6)
6339 outs() << " Swift 4.1/Swift 4.2";
6340 else if(swift_version == 7)
6341 outs() << " Swift 5 or later";
6342 else
6343 outs() << " unknown future Swift version (" << swift_version << ")";
6344 }
6345 outs() << "\n";
6346}
6347
6348static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
6349 uint32_t left, offset, swift_version, p;
6350 struct objc_image_info32 o;
6351 const char *r;
6352
6353 if (S == SectionRef())
6354 return;
6355
6356 StringRef SectName;
6357 Expected<StringRef> SecNameOrErr = S.getName();
6358 if (SecNameOrErr)
6359 SectName = *SecNameOrErr;
6360 else
6361 consumeError(Err: SecNameOrErr.takeError());
6362
6363 DataRefImpl Ref = S.getRawDataRefImpl();
6364 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6365 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6366 p = S.getAddress();
6367 r = get_pointer_32(Address: p, offset, left, S, info);
6368 if (r == nullptr)
6369 return;
6370 memset(s: &o, c: '\0', n: sizeof(struct objc_image_info32));
6371 if (left < sizeof(struct objc_image_info32)) {
6372 memcpy(dest: &o, src: r, n: left);
6373 outs() << " (objc_image_info entends past the end of the section)\n";
6374 } else
6375 memcpy(dest: &o, src: r, n: sizeof(struct objc_image_info32));
6376 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6377 swapStruct(o);
6378 outs() << " version " << o.version << "\n";
6379 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6380 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT)
6381 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
6382 if (o.flags & OBJC_IMAGE_SUPPORTS_GC)
6383 outs() << " OBJC_IMAGE_SUPPORTS_GC";
6384 swift_version = (o.flags >> 8) & 0xff;
6385 if (swift_version != 0) {
6386 if (swift_version == 1)
6387 outs() << " Swift 1.0";
6388 else if (swift_version == 2)
6389 outs() << " Swift 1.1";
6390 else if(swift_version == 3)
6391 outs() << " Swift 2.0";
6392 else if(swift_version == 4)
6393 outs() << " Swift 3.0";
6394 else if(swift_version == 5)
6395 outs() << " Swift 4.0";
6396 else if(swift_version == 6)
6397 outs() << " Swift 4.1/Swift 4.2";
6398 else if(swift_version == 7)
6399 outs() << " Swift 5 or later";
6400 else
6401 outs() << " unknown future Swift version (" << swift_version << ")";
6402 }
6403 outs() << "\n";
6404}
6405
6406static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
6407 uint32_t left, offset, p;
6408 struct imageInfo_t o;
6409 const char *r;
6410
6411 StringRef SectName;
6412 Expected<StringRef> SecNameOrErr = S.getName();
6413 if (SecNameOrErr)
6414 SectName = *SecNameOrErr;
6415 else
6416 consumeError(Err: SecNameOrErr.takeError());
6417
6418 DataRefImpl Ref = S.getRawDataRefImpl();
6419 StringRef SegName = info->O->getSectionFinalSegmentName(Sec: Ref);
6420 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
6421 p = S.getAddress();
6422 r = get_pointer_32(Address: p, offset, left, S, info);
6423 if (r == nullptr)
6424 return;
6425 memset(s: &o, c: '\0', n: sizeof(struct imageInfo_t));
6426 if (left < sizeof(struct imageInfo_t)) {
6427 memcpy(dest: &o, src: r, n: left);
6428 outs() << " (imageInfo entends past the end of the section)\n";
6429 } else
6430 memcpy(dest: &o, src: r, n: sizeof(struct imageInfo_t));
6431 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
6432 swapStruct(o);
6433 outs() << " version " << o.version << "\n";
6434 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: o.flags);
6435 if (o.flags & 0x1)
6436 outs() << " F&C";
6437 if (o.flags & 0x2)
6438 outs() << " GC";
6439 if (o.flags & 0x4)
6440 outs() << " GC-only";
6441 else
6442 outs() << " RR";
6443 outs() << "\n";
6444}
6445
6446static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
6447 SymbolAddressMap AddrMap;
6448 if (verbose)
6449 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6450
6451 std::vector<SectionRef> Sections;
6452 append_range(C&: Sections, R: O->sections());
6453
6454 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6455
6456 SectionRef CL = get_section(O, segname: "__OBJC2", sectname: "__class_list");
6457 if (CL == SectionRef())
6458 CL = get_section(O, segname: "__DATA", sectname: "__objc_classlist");
6459 if (CL == SectionRef())
6460 CL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classlist");
6461 if (CL == SectionRef())
6462 CL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classlist");
6463 info.S = CL;
6464 walk_pointer_list_64(listname: "class", S: CL, O, info: &info, func: print_class64_t);
6465
6466 SectionRef CR = get_section(O, segname: "__OBJC2", sectname: "__class_refs");
6467 if (CR == SectionRef())
6468 CR = get_section(O, segname: "__DATA", sectname: "__objc_classrefs");
6469 if (CR == SectionRef())
6470 CR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classrefs");
6471 if (CR == SectionRef())
6472 CR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classrefs");
6473 info.S = CR;
6474 walk_pointer_list_64(listname: "class refs", S: CR, O, info: &info, func: nullptr);
6475
6476 SectionRef SR = get_section(O, segname: "__OBJC2", sectname: "__super_refs");
6477 if (SR == SectionRef())
6478 SR = get_section(O, segname: "__DATA", sectname: "__objc_superrefs");
6479 if (SR == SectionRef())
6480 SR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_superrefs");
6481 if (SR == SectionRef())
6482 SR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_superrefs");
6483 info.S = SR;
6484 walk_pointer_list_64(listname: "super refs", S: SR, O, info: &info, func: nullptr);
6485
6486 SectionRef CA = get_section(O, segname: "__OBJC2", sectname: "__category_list");
6487 if (CA == SectionRef())
6488 CA = get_section(O, segname: "__DATA", sectname: "__objc_catlist");
6489 if (CA == SectionRef())
6490 CA = get_section(O, segname: "__DATA_CONST", sectname: "__objc_catlist");
6491 if (CA == SectionRef())
6492 CA = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_catlist");
6493 info.S = CA;
6494 walk_pointer_list_64(listname: "category", S: CA, O, info: &info, func: print_category64_t);
6495
6496 SectionRef PL = get_section(O, segname: "__OBJC2", sectname: "__protocol_list");
6497 if (PL == SectionRef())
6498 PL = get_section(O, segname: "__DATA", sectname: "__objc_protolist");
6499 if (PL == SectionRef())
6500 PL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_protolist");
6501 if (PL == SectionRef())
6502 PL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_protolist");
6503 info.S = PL;
6504 walk_pointer_list_64(listname: "protocol", S: PL, O, info: &info, func: nullptr);
6505
6506 SectionRef MR = get_section(O, segname: "__OBJC2", sectname: "__message_refs");
6507 if (MR == SectionRef())
6508 MR = get_section(O, segname: "__DATA", sectname: "__objc_msgrefs");
6509 if (MR == SectionRef())
6510 MR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_msgrefs");
6511 if (MR == SectionRef())
6512 MR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_msgrefs");
6513 info.S = MR;
6514 print_message_refs64(S: MR, info: &info);
6515
6516 SectionRef II = get_section(O, segname: "__OBJC2", sectname: "__image_info");
6517 if (II == SectionRef())
6518 II = get_section(O, segname: "__DATA", sectname: "__objc_imageinfo");
6519 if (II == SectionRef())
6520 II = get_section(O, segname: "__DATA_CONST", sectname: "__objc_imageinfo");
6521 if (II == SectionRef())
6522 II = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_imageinfo");
6523 info.S = II;
6524 print_image_info64(S: II, info: &info);
6525}
6526
6527static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6528 SymbolAddressMap AddrMap;
6529 if (verbose)
6530 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6531
6532 std::vector<SectionRef> Sections;
6533 append_range(C&: Sections, R: O->sections());
6534
6535 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6536
6537 SectionRef CL = get_section(O, segname: "__OBJC2", sectname: "__class_list");
6538 if (CL == SectionRef())
6539 CL = get_section(O, segname: "__DATA", sectname: "__objc_classlist");
6540 if (CL == SectionRef())
6541 CL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classlist");
6542 if (CL == SectionRef())
6543 CL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classlist");
6544 info.S = CL;
6545 walk_pointer_list_32(listname: "class", S: CL, O, info: &info, func: print_class32_t);
6546
6547 SectionRef CR = get_section(O, segname: "__OBJC2", sectname: "__class_refs");
6548 if (CR == SectionRef())
6549 CR = get_section(O, segname: "__DATA", sectname: "__objc_classrefs");
6550 if (CR == SectionRef())
6551 CR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_classrefs");
6552 if (CR == SectionRef())
6553 CR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_classrefs");
6554 info.S = CR;
6555 walk_pointer_list_32(listname: "class refs", S: CR, O, info: &info, func: nullptr);
6556
6557 SectionRef SR = get_section(O, segname: "__OBJC2", sectname: "__super_refs");
6558 if (SR == SectionRef())
6559 SR = get_section(O, segname: "__DATA", sectname: "__objc_superrefs");
6560 if (SR == SectionRef())
6561 SR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_superrefs");
6562 if (SR == SectionRef())
6563 SR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_superrefs");
6564 info.S = SR;
6565 walk_pointer_list_32(listname: "super refs", S: SR, O, info: &info, func: nullptr);
6566
6567 SectionRef CA = get_section(O, segname: "__OBJC2", sectname: "__category_list");
6568 if (CA == SectionRef())
6569 CA = get_section(O, segname: "__DATA", sectname: "__objc_catlist");
6570 if (CA == SectionRef())
6571 CA = get_section(O, segname: "__DATA_CONST", sectname: "__objc_catlist");
6572 if (CA == SectionRef())
6573 CA = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_catlist");
6574 info.S = CA;
6575 walk_pointer_list_32(listname: "category", S: CA, O, info: &info, func: print_category32_t);
6576
6577 SectionRef PL = get_section(O, segname: "__OBJC2", sectname: "__protocol_list");
6578 if (PL == SectionRef())
6579 PL = get_section(O, segname: "__DATA", sectname: "__objc_protolist");
6580 if (PL == SectionRef())
6581 PL = get_section(O, segname: "__DATA_CONST", sectname: "__objc_protolist");
6582 if (PL == SectionRef())
6583 PL = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_protolist");
6584 info.S = PL;
6585 walk_pointer_list_32(listname: "protocol", S: PL, O, info: &info, func: nullptr);
6586
6587 SectionRef MR = get_section(O, segname: "__OBJC2", sectname: "__message_refs");
6588 if (MR == SectionRef())
6589 MR = get_section(O, segname: "__DATA", sectname: "__objc_msgrefs");
6590 if (MR == SectionRef())
6591 MR = get_section(O, segname: "__DATA_CONST", sectname: "__objc_msgrefs");
6592 if (MR == SectionRef())
6593 MR = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_msgrefs");
6594 info.S = MR;
6595 print_message_refs32(S: MR, info: &info);
6596
6597 SectionRef II = get_section(O, segname: "__OBJC2", sectname: "__image_info");
6598 if (II == SectionRef())
6599 II = get_section(O, segname: "__DATA", sectname: "__objc_imageinfo");
6600 if (II == SectionRef())
6601 II = get_section(O, segname: "__DATA_CONST", sectname: "__objc_imageinfo");
6602 if (II == SectionRef())
6603 II = get_section(O, segname: "__DATA_DIRTY", sectname: "__objc_imageinfo");
6604 info.S = II;
6605 print_image_info32(S: II, info: &info);
6606}
6607
6608static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
6609 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
6610 const char *r, *name, *defs;
6611 struct objc_module_t module;
6612 SectionRef S, xS;
6613 struct objc_symtab_t symtab;
6614 struct objc_class_t objc_class;
6615 struct objc_category_t objc_category;
6616
6617 outs() << "Objective-C segment\n";
6618 S = get_section(O, segname: "__OBJC", sectname: "__module_info");
6619 if (S == SectionRef())
6620 return false;
6621
6622 SymbolAddressMap AddrMap;
6623 if (verbose)
6624 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6625
6626 std::vector<SectionRef> Sections;
6627 append_range(C&: Sections, R: O->sections());
6628
6629 struct DisassembleInfo info(O, &AddrMap, &Sections, verbose);
6630
6631 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
6632 p = S.getAddress() + i;
6633 r = get_pointer_32(Address: p, offset, left, S, info: &info, objc_only: true);
6634 if (r == nullptr)
6635 return true;
6636 memset(s: &module, c: '\0', n: sizeof(struct objc_module_t));
6637 if (left < sizeof(struct objc_module_t)) {
6638 memcpy(dest: &module, src: r, n: left);
6639 outs() << " (module extends past end of __module_info section)\n";
6640 } else
6641 memcpy(dest: &module, src: r, n: sizeof(struct objc_module_t));
6642 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6643 swapStruct(module);
6644
6645 outs() << "Module " << format(Fmt: "0x%" PRIx32, Vals: p) << "\n";
6646 outs() << " version " << module.version << "\n";
6647 outs() << " size " << module.size << "\n";
6648 outs() << " name ";
6649 name = get_pointer_32(Address: module.name, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6650 if (name != nullptr)
6651 outs() << format(Fmt: "%.*s", Vals: left, Vals: name);
6652 else
6653 outs() << format(Fmt: "0x%08" PRIx32, Vals: module.name)
6654 << "(not in an __OBJC section)";
6655 outs() << "\n";
6656
6657 r = get_pointer_32(Address: module.symtab, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6658 if (module.symtab == 0 || r == nullptr) {
6659 outs() << " symtab " << format(Fmt: "0x%08" PRIx32, Vals: module.symtab)
6660 << " (not in an __OBJC section)\n";
6661 continue;
6662 }
6663 outs() << " symtab " << format(Fmt: "0x%08" PRIx32, Vals: module.symtab) << "\n";
6664 memset(s: &symtab, c: '\0', n: sizeof(struct objc_symtab_t));
6665 defs_left = 0;
6666 defs = nullptr;
6667 if (left < sizeof(struct objc_symtab_t)) {
6668 memcpy(dest: &symtab, src: r, n: left);
6669 outs() << "\tsymtab extends past end of an __OBJC section)\n";
6670 } else {
6671 memcpy(dest: &symtab, src: r, n: sizeof(struct objc_symtab_t));
6672 if (left > sizeof(struct objc_symtab_t)) {
6673 defs_left = left - sizeof(struct objc_symtab_t);
6674 defs = r + sizeof(struct objc_symtab_t);
6675 }
6676 }
6677 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6678 swapStruct(symtab);
6679
6680 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
6681 r = get_pointer_32(Address: symtab.refs, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6682 outs() << "\trefs " << format(Fmt: "0x%08" PRIx32, Vals: symtab.refs);
6683 if (r == nullptr)
6684 outs() << " (not in an __OBJC section)";
6685 outs() << "\n";
6686 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
6687 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
6688 if (symtab.cls_def_cnt > 0)
6689 outs() << "\tClass Definitions\n";
6690 for (j = 0; j < symtab.cls_def_cnt; j++) {
6691 if ((j + 1) * sizeof(uint32_t) > defs_left) {
6692 outs() << "\t(remaining class defs entries entends past the end of the "
6693 << "section)\n";
6694 break;
6695 }
6696 memcpy(dest: &def, src: defs + j * sizeof(uint32_t), n: sizeof(uint32_t));
6697 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6698 sys::swapByteOrder(Value&: def);
6699
6700 r = get_pointer_32(Address: def, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6701 outs() << "\tdefs[" << j << "] " << format(Fmt: "0x%08" PRIx32, Vals: def);
6702 if (r != nullptr) {
6703 if (left > sizeof(struct objc_class_t)) {
6704 outs() << "\n";
6705 memcpy(dest: &objc_class, src: r, n: sizeof(struct objc_class_t));
6706 } else {
6707 outs() << " (entends past the end of the section)\n";
6708 memset(s: &objc_class, c: '\0', n: sizeof(struct objc_class_t));
6709 memcpy(dest: &objc_class, src: r, n: left);
6710 }
6711 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6712 swapStruct(objc_class);
6713 print_objc_class_t(objc_class: &objc_class, info: &info);
6714 } else {
6715 outs() << "(not in an __OBJC section)\n";
6716 }
6717
6718 if (CLS_GETINFO(&objc_class, CLS_CLASS)) {
6719 outs() << "\tMeta Class";
6720 r = get_pointer_32(Address: objc_class.isa, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6721 if (r != nullptr) {
6722 if (left > sizeof(struct objc_class_t)) {
6723 outs() << "\n";
6724 memcpy(dest: &objc_class, src: r, n: sizeof(struct objc_class_t));
6725 } else {
6726 outs() << " (entends past the end of the section)\n";
6727 memset(s: &objc_class, c: '\0', n: sizeof(struct objc_class_t));
6728 memcpy(dest: &objc_class, src: r, n: left);
6729 }
6730 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6731 swapStruct(objc_class);
6732 print_objc_class_t(objc_class: &objc_class, info: &info);
6733 } else {
6734 outs() << "(not in an __OBJC section)\n";
6735 }
6736 }
6737 }
6738 if (symtab.cat_def_cnt > 0)
6739 outs() << "\tCategory Definitions\n";
6740 for (j = 0; j < symtab.cat_def_cnt; j++) {
6741 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
6742 outs() << "\t(remaining category defs entries entends past the end of "
6743 << "the section)\n";
6744 break;
6745 }
6746 memcpy(dest: &def, src: defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
6747 n: sizeof(uint32_t));
6748 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6749 sys::swapByteOrder(Value&: def);
6750
6751 r = get_pointer_32(Address: def, offset&: xoffset, left, S&: xS, info: &info, objc_only: true);
6752 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
6753 << format(Fmt: "0x%08" PRIx32, Vals: def);
6754 if (r != nullptr) {
6755 if (left > sizeof(struct objc_category_t)) {
6756 outs() << "\n";
6757 memcpy(dest: &objc_category, src: r, n: sizeof(struct objc_category_t));
6758 } else {
6759 outs() << " (entends past the end of the section)\n";
6760 memset(s: &objc_category, c: '\0', n: sizeof(struct objc_category_t));
6761 memcpy(dest: &objc_category, src: r, n: left);
6762 }
6763 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6764 swapStruct(objc_category);
6765 print_objc_objc_category_t(objc_category: &objc_category, info: &info);
6766 } else {
6767 outs() << "(not in an __OBJC section)\n";
6768 }
6769 }
6770 }
6771 const SectionRef II = get_section(O, segname: "__OBJC", sectname: "__image_info");
6772 if (II != SectionRef())
6773 print_image_info(S: II, info: &info);
6774
6775 return true;
6776}
6777
6778static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
6779 uint32_t size, uint32_t addr) {
6780 SymbolAddressMap AddrMap;
6781 CreateSymbolAddressMap(O, AddrMap: &AddrMap);
6782
6783 std::vector<SectionRef> Sections;
6784 append_range(C&: Sections, R: O->sections());
6785
6786 struct DisassembleInfo info(O, &AddrMap, &Sections, true);
6787
6788 const char *p;
6789 struct objc_protocol_t protocol;
6790 uint32_t left, paddr;
6791 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
6792 memset(s: &protocol, c: '\0', n: sizeof(struct objc_protocol_t));
6793 left = size - (p - sect);
6794 if (left < sizeof(struct objc_protocol_t)) {
6795 outs() << "Protocol extends past end of __protocol section\n";
6796 memcpy(dest: &protocol, src: p, n: left);
6797 } else
6798 memcpy(dest: &protocol, src: p, n: sizeof(struct objc_protocol_t));
6799 if (O->isLittleEndian() != sys::IsLittleEndianHost)
6800 swapStruct(protocol);
6801 paddr = addr + (p - sect);
6802 outs() << "Protocol " << format(Fmt: "0x%" PRIx32, Vals: paddr);
6803 if (print_protocol(p: paddr, indent: 0, info: &info))
6804 outs() << "(not in an __OBJC section)\n";
6805 }
6806}
6807
6808static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6809 if (O->is64Bit())
6810 printObjc2_64bit_MetaData(O, verbose);
6811 else {
6812 MachO::mach_header H;
6813 H = O->getHeader();
6814 if (H.cputype == MachO::CPU_TYPE_ARM)
6815 printObjc2_32bit_MetaData(O, verbose);
6816 else {
6817 // This is the 32-bit non-arm cputype case. Which is normally
6818 // the first Objective-C ABI. But it may be the case of a
6819 // binary for the iOS simulator which is the second Objective-C
6820 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6821 // and return false.
6822 if (!printObjc1_32bit_MetaData(O, verbose))
6823 printObjc2_32bit_MetaData(O, verbose);
6824 }
6825 }
6826}
6827
6828// GuessLiteralPointer returns a string which for the item in the Mach-O file
6829// for the address passed in as ReferenceValue for printing as a comment with
6830// the instruction and also returns the corresponding type of that item
6831// indirectly through ReferenceType.
6832//
6833// If ReferenceValue is an address of literal cstring then a pointer to the
6834// cstring is returned and ReferenceType is set to
6835// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6836//
6837// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6838// Class ref that name is returned and the ReferenceType is set accordingly.
6839//
6840// Lastly, literals which are Symbol address in a literal pool are looked for
6841// and if found the symbol name is returned and ReferenceType is set to
6842// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6843//
6844// If there is no item in the Mach-O file for the address passed in as
6845// ReferenceValue nullptr is returned and ReferenceType is unchanged.
6846static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6847 uint64_t ReferencePC,
6848 uint64_t *ReferenceType,
6849 struct DisassembleInfo *info) {
6850 // First see if there is an external relocation entry at the ReferencePC.
6851 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6852 uint64_t sect_addr = info->S.getAddress();
6853 uint64_t sect_offset = ReferencePC - sect_addr;
6854 bool reloc_found = false;
6855 DataRefImpl Rel;
6856 MachO::any_relocation_info RE;
6857 bool isExtern = false;
6858 SymbolRef Symbol;
6859 for (const RelocationRef &Reloc : info->S.relocations()) {
6860 uint64_t RelocOffset = Reloc.getOffset();
6861 if (RelocOffset == sect_offset) {
6862 Rel = Reloc.getRawDataRefImpl();
6863 RE = info->O->getRelocation(Rel);
6864 if (info->O->isRelocationScattered(RE))
6865 continue;
6866 isExtern = info->O->getPlainRelocationExternal(RE);
6867 if (isExtern) {
6868 symbol_iterator RelocSym = Reloc.getSymbol();
6869 Symbol = *RelocSym;
6870 }
6871 reloc_found = true;
6872 break;
6873 }
6874 }
6875 // If there is an external relocation entry for a symbol in a section
6876 // then used that symbol's value for the value of the reference.
6877 if (reloc_found && isExtern) {
6878 if (info->O->getAnyRelocationPCRel(RE)) {
6879 unsigned Type = info->O->getAnyRelocationType(RE);
6880 if (Type == MachO::X86_64_RELOC_SIGNED) {
6881 ReferenceValue = cantFail(ValOrErr: Symbol.getValue());
6882 }
6883 }
6884 }
6885 }
6886
6887 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6888 // Message refs and Class refs.
6889 bool classref, selref, msgref, cfstring;
6890 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6891 selref, msgref, cfstring);
6892 if (classref && pointer_value == 0) {
6893 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6894 // And the pointer_value in that section is typically zero as it will be
6895 // set by dyld as part of the "bind information".
6896 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6897 if (name != nullptr) {
6898 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6899 const char *class_name = strrchr(s: name, c: '$');
6900 if (class_name != nullptr && class_name[1] == '_' &&
6901 class_name[2] != '\0') {
6902 info->class_name = class_name + 2;
6903 return name;
6904 }
6905 }
6906 }
6907
6908 if (classref) {
6909 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref;
6910 const char *name =
6911 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6912 if (name != nullptr)
6913 info->class_name = name;
6914 else
6915 name = "bad class ref";
6916 return name;
6917 }
6918
6919 if (cfstring) {
6920 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref;
6921 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6922 return name;
6923 }
6924
6925 if (selref && pointer_value == 0)
6926 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6927
6928 if (pointer_value != 0)
6929 ReferenceValue = pointer_value;
6930
6931 const char *name = GuessCstringPointer(ReferenceValue, info);
6932 if (name) {
6933 if (pointer_value != 0 && selref) {
6934 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref;
6935 info->selector_name = name;
6936 } else if (pointer_value != 0 && msgref) {
6937 info->class_name = nullptr;
6938 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref;
6939 info->selector_name = name;
6940 } else
6941 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr;
6942 return name;
6943 }
6944
6945 // Lastly look for an indirect symbol with this ReferenceValue which is in
6946 // a literal pool. If found return that symbol name.
6947 name = GuessIndirectSymbol(ReferenceValue, info);
6948 if (name) {
6949 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr;
6950 return name;
6951 }
6952
6953 return nullptr;
6954}
6955
6956// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6957// the Symbolizer. It looks up the ReferenceValue using the info passed via the
6958// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6959// is created and returns the symbol name that matches the ReferenceValue or
6960// nullptr if none. The ReferenceType is passed in for the IN type of
6961// reference the instruction is making from the values in defined in the header
6962// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6963// Out type and the ReferenceName will also be set which is added as a comment
6964// to the disassembled instruction.
6965//
6966// If the symbol name is a C++ mangled name then the demangled name is
6967// returned through ReferenceName and ReferenceType is set to
6968// LLVMDisassembler_ReferenceType_DeMangled_Name .
6969//
6970// When this is called to get a symbol name for a branch target then the
6971// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6972// SymbolValue will be looked for in the indirect symbol table to determine if
6973// it is an address for a symbol stub. If so then the symbol name for that
6974// stub is returned indirectly through ReferenceName and then ReferenceType is
6975// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6976//
6977// When this is called with an value loaded via a PC relative load then
6978// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6979// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6980// or an Objective-C meta data reference. If so the output ReferenceType is
6981// set to correspond to that as well as setting the ReferenceName.
6982static const char *SymbolizerSymbolLookUp(void *DisInfo,
6983 uint64_t ReferenceValue,
6984 uint64_t *ReferenceType,
6985 uint64_t ReferencePC,
6986 const char **ReferenceName) {
6987 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
6988 // If no verbose symbolic information is wanted then just return nullptr.
6989 if (!info->verbose) {
6990 *ReferenceName = nullptr;
6991 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
6992 return nullptr;
6993 }
6994
6995 const char *SymbolName = GuessSymbolName(value: ReferenceValue, AddrMap: info->AddrMap);
6996
6997 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch) {
6998 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
6999 if (*ReferenceName != nullptr) {
7000 method_reference(info, ReferenceType, ReferenceName);
7001 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message)
7002 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub;
7003 } else if (SymbolName != nullptr && strncmp(s1: SymbolName, s2: "__Z", n: 3) == 0) {
7004 if (info->demangled_name != nullptr)
7005 free(ptr: info->demangled_name);
7006 info->demangled_name = itaniumDemangle(mangled_name: SymbolName + 1);
7007 if (info->demangled_name != nullptr) {
7008 *ReferenceName = info->demangled_name;
7009 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7010 } else
7011 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7012 } else
7013 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7014 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load) {
7015 *ReferenceName =
7016 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7017 if (*ReferenceName)
7018 method_reference(info, ReferenceType, ReferenceName);
7019 else
7020 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7021 // If this is arm64 and the reference is an adrp instruction save the
7022 // instruction, passed in ReferenceValue and the address of the instruction
7023 // for use later if we see and add immediate instruction.
7024 } else if ((info->O->getArch() == Triple::aarch64 ||
7025 info->O->getArch() == Triple::aarch64_32) &&
7026 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP) {
7027 info->adrp_inst = ReferenceValue;
7028 info->adrp_addr = ReferencePC;
7029 SymbolName = nullptr;
7030 *ReferenceName = nullptr;
7031 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7032 // If this is arm64 and reference is an add immediate instruction and we
7033 // have
7034 // seen an adrp instruction just before it and the adrp's Xd register
7035 // matches
7036 // this add's Xn register reconstruct the value being referenced and look to
7037 // see if it is a literal pointer. Note the add immediate instruction is
7038 // passed in ReferenceValue.
7039 } else if ((info->O->getArch() == Triple::aarch64 ||
7040 info->O->getArch() == Triple::aarch64_32) &&
7041 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri &&
7042 ReferencePC - 4 == info->adrp_addr &&
7043 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7044 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7045 uint32_t addxri_inst;
7046 uint64_t adrp_imm, addxri_imm;
7047
7048 adrp_imm =
7049 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7050 if (info->adrp_inst & 0x0200000)
7051 adrp_imm |= 0xfffffffffc000000LL;
7052
7053 addxri_inst = ReferenceValue;
7054 addxri_imm = (addxri_inst >> 10) & 0xfff;
7055 if (((addxri_inst >> 22) & 0x3) == 1)
7056 addxri_imm <<= 12;
7057
7058 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7059 (adrp_imm << 12) + addxri_imm;
7060
7061 *ReferenceName =
7062 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7063 if (*ReferenceName == nullptr)
7064 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7065 // If this is arm64 and the reference is a load register instruction and we
7066 // have seen an adrp instruction just before it and the adrp's Xd register
7067 // matches this add's Xn register reconstruct the value being referenced and
7068 // look to see if it is a literal pointer. Note the load register
7069 // instruction is passed in ReferenceValue.
7070 } else if ((info->O->getArch() == Triple::aarch64 ||
7071 info->O->getArch() == Triple::aarch64_32) &&
7072 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui &&
7073 ReferencePC - 4 == info->adrp_addr &&
7074 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
7075 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
7076 uint32_t ldrxui_inst;
7077 uint64_t adrp_imm, ldrxui_imm;
7078
7079 adrp_imm =
7080 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
7081 if (info->adrp_inst & 0x0200000)
7082 adrp_imm |= 0xfffffffffc000000LL;
7083
7084 ldrxui_inst = ReferenceValue;
7085 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
7086
7087 // The size field (bits [31:30]) determines the scaling.
7088 unsigned Scale = (ldrxui_inst >> 30) & 0x3;
7089 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
7090 (adrp_imm << 12) + (ldrxui_imm << Scale);
7091
7092 *ReferenceName =
7093 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7094 if (*ReferenceName == nullptr)
7095 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7096 }
7097 // If this arm64 and is an load register (PC-relative) instruction the
7098 // ReferenceValue is the PC plus the immediate value.
7099 else if ((info->O->getArch() == Triple::aarch64 ||
7100 info->O->getArch() == Triple::aarch64_32) &&
7101 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl ||
7102 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR)) {
7103 *ReferenceName =
7104 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
7105 if (*ReferenceName == nullptr)
7106 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7107 } else if (SymbolName != nullptr && strncmp(s1: SymbolName, s2: "__Z", n: 3) == 0) {
7108 if (info->demangled_name != nullptr)
7109 free(ptr: info->demangled_name);
7110 info->demangled_name = itaniumDemangle(mangled_name: SymbolName + 1);
7111 if (info->demangled_name != nullptr) {
7112 *ReferenceName = info->demangled_name;
7113 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name;
7114 }
7115 } else {
7116 *ReferenceName = nullptr;
7117 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
7118 }
7119
7120 return SymbolName;
7121}
7122
7123/// Emits the comments that are stored in the CommentStream.
7124/// Each comment in the CommentStream must end with a newline.
7125static void emitComments(raw_svector_ostream &CommentStream,
7126 SmallString<128> &CommentsToEmit,
7127 formatted_raw_ostream &FormattedOS,
7128 const MCAsmInfo &MAI) {
7129 // Flush the stream before taking its content.
7130 StringRef Comments = CommentsToEmit.str();
7131 // Get the default information for printing a comment.
7132 StringRef CommentBegin = MAI.getCommentString();
7133 unsigned CommentColumn = MAI.getCommentColumn();
7134 ListSeparator LS("\n");
7135 while (!Comments.empty()) {
7136 FormattedOS << LS;
7137 // Emit a line of comments.
7138 FormattedOS.PadToColumn(NewCol: CommentColumn);
7139 size_t Position = Comments.find(C: '\n');
7140 FormattedOS << CommentBegin << ' ' << Comments.substr(Start: 0, N: Position);
7141 // Move after the newline character.
7142 Comments = Comments.substr(Start: Position + 1);
7143 }
7144 FormattedOS.flush();
7145
7146 // Tell the comment stream that the vector changed underneath it.
7147 CommentsToEmit.clear();
7148}
7149
7150const MachOObjectFile *
7151objdump::getMachODSymObject(const MachOObjectFile *MachOOF, StringRef Filename,
7152 std::unique_ptr<Binary> &DSYMBinary,
7153 std::unique_ptr<MemoryBuffer> &DSYMBuf) {
7154 const MachOObjectFile *DbgObj = MachOOF;
7155 std::string DSYMPath;
7156
7157 // Auto-detect w/o --dsym.
7158 if (DSYMFile.empty()) {
7159 sys::fs::file_status DSYMStatus;
7160 Twine FilenameDSYM = Filename + ".dSYM";
7161 if (!status(path: FilenameDSYM, result&: DSYMStatus)) {
7162 if (sys::fs::is_directory(status: DSYMStatus)) {
7163 SmallString<1024> Path;
7164 FilenameDSYM.toVector(Out&: Path);
7165 sys::path::append(path&: Path, a: "Contents", b: "Resources", c: "DWARF",
7166 d: sys::path::filename(path: Filename));
7167 DSYMPath = std::string(Path);
7168 } else if (sys::fs::is_regular_file(status: DSYMStatus)) {
7169 DSYMPath = FilenameDSYM.str();
7170 }
7171 }
7172 }
7173
7174 if (DSYMPath.empty() && !DSYMFile.empty()) {
7175 // If DSYMPath is a .dSYM directory, append the Mach-O file.
7176 if (sys::fs::is_directory(Path: DSYMFile) &&
7177 sys::path::extension(path: DSYMFile) == ".dSYM") {
7178 SmallString<128> ShortName(sys::path::filename(path: DSYMFile));
7179 sys::path::replace_extension(path&: ShortName, extension: "");
7180 SmallString<1024> FullPath(DSYMFile);
7181 sys::path::append(path&: FullPath, a: "Contents", b: "Resources", c: "DWARF", d: ShortName);
7182 DSYMPath = FullPath.str();
7183 } else {
7184 DSYMPath = DSYMFile;
7185 }
7186 }
7187
7188 if (!DSYMPath.empty()) {
7189 // Load the file.
7190 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
7191 MemoryBuffer::getFileOrSTDIN(Filename: DSYMPath);
7192 if (std::error_code EC = BufOrErr.getError()) {
7193 reportError(E: errorCodeToError(EC), FileName: DSYMPath);
7194 return nullptr;
7195 }
7196
7197 // We need to keep the file alive, because we're replacing DbgObj with it.
7198 DSYMBuf = std::move(BufOrErr.get());
7199
7200 Expected<std::unique_ptr<Binary>> BinaryOrErr =
7201 createBinary(Source: DSYMBuf->getMemBufferRef());
7202 if (!BinaryOrErr) {
7203 reportError(E: BinaryOrErr.takeError(), FileName: DSYMPath);
7204 return nullptr;
7205 }
7206
7207 // We need to keep the Binary alive with the buffer
7208 DSYMBinary = std::move(BinaryOrErr.get());
7209 if (ObjectFile *O = dyn_cast<ObjectFile>(Val: DSYMBinary.get())) {
7210 // this is a Mach-O object file, use it
7211 if (MachOObjectFile *MachDSYM = dyn_cast<MachOObjectFile>(Val: &*O)) {
7212 DbgObj = MachDSYM;
7213 } else {
7214 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
7215 << DSYMPath << " is not a Mach-O file type.\n";
7216 return nullptr;
7217 }
7218 } else if (auto *UB = dyn_cast<MachOUniversalBinary>(Val: DSYMBinary.get())) {
7219 // this is a Universal Binary, find a Mach-O for this architecture
7220 uint32_t CPUType, CPUSubType;
7221 const char *ArchFlag;
7222 if (MachOOF->is64Bit()) {
7223 const MachO::mach_header_64 H_64 = MachOOF->getHeader64();
7224 CPUType = H_64.cputype;
7225 CPUSubType = H_64.cpusubtype;
7226 } else {
7227 const MachO::mach_header H = MachOOF->getHeader();
7228 CPUType = H.cputype;
7229 CPUSubType = H.cpusubtype;
7230 }
7231 Triple T = MachOObjectFile::getArchTriple(CPUType, CPUSubType, McpuDefault: nullptr,
7232 ArchFlag: &ArchFlag);
7233 Expected<std::unique_ptr<MachOObjectFile>> MachDSYM =
7234 UB->getMachOObjectForArch(ArchName: ArchFlag);
7235 if (!MachDSYM) {
7236 reportError(E: MachDSYM.takeError(), FileName: DSYMPath);
7237 return nullptr;
7238 }
7239
7240 // We need to keep the Binary alive with the buffer
7241 DbgObj = &*MachDSYM.get();
7242 DSYMBinary = std::move(*MachDSYM);
7243 } else {
7244 WithColor::error(OS&: errs(), Prefix: "llvm-objdump")
7245 << DSYMPath << " is not a Mach-O or Universal file type.\n";
7246 return nullptr;
7247 }
7248 }
7249 return DbgObj;
7250}
7251
7252static bool shouldInstPrinterUseColor() {
7253 switch (DisassemblyColor) {
7254 case ColorOutput::Enable:
7255 return true;
7256 case ColorOutput::Auto:
7257 return outs().has_colors();
7258 case ColorOutput::Disable:
7259 case ColorOutput::Invalid:
7260 return false;
7261 }
7262 return false;
7263}
7264
7265static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
7266 StringRef DisSegName, StringRef DisSectName) {
7267 const char *McpuDefault = nullptr;
7268 const Target *ThumbTarget = nullptr;
7269 Triple ThumbTriple;
7270 const Target *TheTarget =
7271 GetTarget(MachOObj: MachOOF, McpuDefault: &McpuDefault, ThumbTarget: &ThumbTarget, ThumbTriple);
7272 if (!TheTarget) {
7273 // GetTarget prints out stuff.
7274 return;
7275 }
7276 std::string MachOMCPU;
7277 if (MCPU.empty() && McpuDefault)
7278 MachOMCPU = McpuDefault;
7279 else
7280 MachOMCPU = MCPU;
7281
7282#define CHECK_TARGET_INFO_CREATION(NAME) \
7283 do { \
7284 if (!NAME) { \
7285 WithColor::error(errs(), "llvm-objdump") \
7286 << "couldn't initialize disassembler for target " << TripleName \
7287 << '\n'; \
7288 return; \
7289 } \
7290 } while (false)
7291#define CHECK_THUMB_TARGET_INFO_CREATION(NAME) \
7292 do { \
7293 if (!NAME) { \
7294 WithColor::error(errs(), "llvm-objdump") \
7295 << "couldn't initialize disassembler for target " << ThumbTripleName \
7296 << '\n'; \
7297 return; \
7298 } \
7299 } while (false)
7300
7301 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
7302 CHECK_TARGET_INFO_CREATION(InstrInfo);
7303 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
7304 if (ThumbTarget) {
7305 ThumbInstrInfo.reset(p: ThumbTarget->createMCInstrInfo());
7306 CHECK_THUMB_TARGET_INFO_CREATION(ThumbInstrInfo);
7307 }
7308
7309 // Package up features to be passed to target/subtarget
7310 std::string FeaturesStr;
7311 if (!MAttrs.empty()) {
7312 SubtargetFeatures Features;
7313 for (unsigned i = 0; i != MAttrs.size(); ++i)
7314 Features.AddFeature(String: MAttrs[i]);
7315 FeaturesStr = Features.getString();
7316 }
7317
7318 Triple TheTriple(TripleName);
7319
7320 MCTargetOptions MCOptions;
7321 // Set up disassembler.
7322 std::unique_ptr<const MCRegisterInfo> MRI(
7323 TheTarget->createMCRegInfo(TT: TheTriple));
7324 CHECK_TARGET_INFO_CREATION(MRI);
7325 std::unique_ptr<const MCAsmInfo> AsmInfo(
7326 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
7327 CHECK_TARGET_INFO_CREATION(AsmInfo);
7328 std::unique_ptr<const MCSubtargetInfo> STI(
7329 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MachOMCPU, Features: FeaturesStr));
7330 CHECK_TARGET_INFO_CREATION(STI);
7331 MCContext Ctx(TheTriple, AsmInfo.get(), MRI.get(), STI.get());
7332 std::unique_ptr<MCDisassembler> DisAsm(
7333 TheTarget->createMCDisassembler(STI: *STI, Ctx));
7334 CHECK_TARGET_INFO_CREATION(DisAsm);
7335 std::unique_ptr<MCSymbolizer> Symbolizer;
7336 struct DisassembleInfo SymbolizerInfo(nullptr, nullptr, nullptr, false);
7337 std::unique_ptr<MCRelocationInfo> RelInfo(
7338 TheTarget->createMCRelocationInfo(TT: TheTriple, Ctx));
7339 if (RelInfo) {
7340 Symbolizer.reset(p: TheTarget->createMCSymbolizer(
7341 TT: TheTriple, GetOpInfo: SymbolizerGetOpInfo, SymbolLookUp: SymbolizerSymbolLookUp, DisInfo: &SymbolizerInfo,
7342 Ctx: &Ctx, RelInfo: std::move(RelInfo)));
7343 DisAsm->setSymbolizer(std::move(Symbolizer));
7344 }
7345 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
7346 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
7347 T: TheTriple, SyntaxVariant: AsmPrinterVariant, MAI: *AsmInfo, MII: *InstrInfo, MRI: *MRI));
7348 CHECK_TARGET_INFO_CREATION(IP);
7349 IP->setPrintImmHex(PrintImmHex);
7350 IP->setUseColor(shouldInstPrinterUseColor());
7351
7352 // Comment stream and backing vector.
7353 SmallString<128> CommentsToEmit;
7354 raw_svector_ostream CommentStream(CommentsToEmit);
7355 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
7356 // if it is done then arm64 comments for string literals don't get printed
7357 // and some constant get printed instead and not setting it causes intel
7358 // (32-bit and 64-bit) comments printed with different spacing before the
7359 // comment causing different diffs with the 'C' disassembler library API.
7360 // IP->setCommentStream(CommentStream);
7361
7362 for (StringRef Opt : DisassemblerOptions)
7363 if (!IP->applyTargetSpecificCLOption(Opt))
7364 reportError(File: Filename, Message: "unrecognized disassembler option: " + Opt);
7365
7366 // Set up separate thumb disassembler if needed.
7367 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
7368 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
7369 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
7370 std::unique_ptr<MCDisassembler> ThumbDisAsm;
7371 std::unique_ptr<MCInstPrinter> ThumbIP;
7372 std::unique_ptr<MCContext> ThumbCtx;
7373 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
7374 struct DisassembleInfo ThumbSymbolizerInfo(nullptr, nullptr, nullptr, false);
7375 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
7376 if (ThumbTarget) {
7377 ThumbMRI.reset(p: ThumbTarget->createMCRegInfo(TT: ThumbTriple));
7378 CHECK_THUMB_TARGET_INFO_CREATION(ThumbMRI);
7379 ThumbAsmInfo.reset(
7380 p: ThumbTarget->createMCAsmInfo(MRI: *ThumbMRI, TheTriple: ThumbTriple, Options: MCOptions));
7381 CHECK_THUMB_TARGET_INFO_CREATION(ThumbAsmInfo);
7382 ThumbSTI.reset(p: ThumbTarget->createMCSubtargetInfo(TheTriple: ThumbTriple, CPU: MachOMCPU,
7383 Features: FeaturesStr));
7384 CHECK_THUMB_TARGET_INFO_CREATION(ThumbSTI);
7385 ThumbCtx.reset(p: new MCContext(ThumbTriple, ThumbAsmInfo.get(),
7386 ThumbMRI.get(), ThumbSTI.get()));
7387 ThumbDisAsm.reset(p: ThumbTarget->createMCDisassembler(STI: *ThumbSTI, Ctx&: *ThumbCtx));
7388 CHECK_THUMB_TARGET_INFO_CREATION(ThumbDisAsm);
7389 MCContext *PtrThumbCtx = ThumbCtx.get();
7390 ThumbRelInfo.reset(
7391 p: ThumbTarget->createMCRelocationInfo(TT: ThumbTriple, Ctx&: *PtrThumbCtx));
7392 if (ThumbRelInfo) {
7393 ThumbSymbolizer.reset(p: ThumbTarget->createMCSymbolizer(
7394 TT: ThumbTriple, GetOpInfo: SymbolizerGetOpInfo, SymbolLookUp: SymbolizerSymbolLookUp,
7395 DisInfo: &ThumbSymbolizerInfo, Ctx: PtrThumbCtx, RelInfo: std::move(ThumbRelInfo)));
7396 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
7397 }
7398 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
7399 ThumbIP.reset(p: ThumbTarget->createMCInstPrinter(
7400 T: ThumbTriple, SyntaxVariant: ThumbAsmPrinterVariant, MAI: *ThumbAsmInfo, MII: *ThumbInstrInfo,
7401 MRI: *ThumbMRI));
7402 CHECK_THUMB_TARGET_INFO_CREATION(ThumbIP);
7403 ThumbIP->setPrintImmHex(PrintImmHex);
7404 ThumbIP->setUseColor(shouldInstPrinterUseColor());
7405 }
7406
7407#undef CHECK_TARGET_INFO_CREATION
7408#undef CHECK_THUMB_TARGET_INFO_CREATION
7409
7410 MachO::mach_header Header = MachOOF->getHeader();
7411
7412 // FIXME: Using the -cfg command line option, this code used to be able to
7413 // annotate relocations with the referenced symbol's name, and if this was
7414 // inside a __[cf]string section, the data it points to. This is now replaced
7415 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
7416 std::vector<SectionRef> Sections;
7417 std::vector<SymbolRef> Symbols;
7418 SmallVector<uint64_t, 8> FoundFns;
7419 uint64_t BaseSegmentAddress = 0;
7420
7421 getSectionsAndSymbols(MachOObj: MachOOF, Sections, Symbols, FoundFns,
7422 BaseSegmentAddress);
7423
7424 // Sort the symbols by address, just in case they didn't come in that way.
7425 llvm::stable_sort(Range&: Symbols, C: SymbolSorter());
7426
7427 // Build a data in code table that is sorted on by the address of each entry.
7428 uint64_t BaseAddress = 0;
7429 if (Header.filetype == MachO::MH_OBJECT)
7430 BaseAddress = Sections[0].getAddress();
7431 else
7432 BaseAddress = BaseSegmentAddress;
7433 DiceTable Dices;
7434 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
7435 DI != DE; ++DI) {
7436 uint32_t Offset;
7437 DI->getOffset(Result&: Offset);
7438 Dices.push_back(x: std::make_pair(x: BaseAddress + Offset, y: *DI));
7439 }
7440 array_pod_sort(Start: Dices.begin(), End: Dices.end());
7441
7442 // Try to find debug info and set up the DIContext for it.
7443 std::unique_ptr<DIContext> diContext;
7444 std::unique_ptr<Binary> DSYMBinary;
7445 std::unique_ptr<MemoryBuffer> DSYMBuf;
7446 const ObjectFile *DbgObj = MachOOF;
7447 if (UseDbg || PrintSource || PrintLines) {
7448 // Look for debug info in external dSYM file or embedded in the object.
7449 // getMachODSymObject returns MachOOF by default if no external dSYM found.
7450 const ObjectFile *DSym =
7451 getMachODSymObject(MachOOF, Filename, DSYMBinary, DSYMBuf);
7452 if (!DSym)
7453 return;
7454 DbgObj = DSym;
7455 if (UseDbg || PrintLines) {
7456 // Setup the DIContext
7457 diContext = DWARFContext::create(Obj: *DbgObj);
7458 }
7459 }
7460
7461 std::optional<SourcePrinter> SP;
7462 std::optional<LiveElementPrinter> LEP;
7463 if (PrintSource || PrintLines) {
7464 SP.emplace(args&: DbgObj, args: TheTarget->getName());
7465 LEP.emplace(args: *MRI, args: *STI);
7466 }
7467
7468 if (FilterSections.empty())
7469 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
7470
7471 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
7472 Expected<StringRef> SecNameOrErr = Sections[SectIdx].getName();
7473 if (!SecNameOrErr) {
7474 consumeError(Err: SecNameOrErr.takeError());
7475 continue;
7476 }
7477 if (*SecNameOrErr != DisSectName)
7478 continue;
7479
7480 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
7481
7482 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(Sec: DR);
7483 if (SegmentName != DisSegName)
7484 continue;
7485
7486 StringRef BytesStr =
7487 unwrapOrError(EO: Sections[SectIdx].getContents(), Args&: Filename);
7488 ArrayRef<uint8_t> Bytes = arrayRefFromStringRef(Input: BytesStr);
7489 uint64_t SectAddress = Sections[SectIdx].getAddress();
7490
7491 bool symbolTableWorked = false;
7492
7493 // Create a map of symbol addresses to symbol names for use by
7494 // the SymbolizerSymbolLookUp() routine.
7495 SymbolAddressMap AddrMap;
7496 bool DisSymNameFound = false;
7497 for (const SymbolRef &Symbol : MachOOF->symbols()) {
7498 SymbolRef::Type ST =
7499 unwrapOrError(EO: Symbol.getType(), Args: MachOOF->getFileName());
7500 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
7501 ST == SymbolRef::ST_Other) {
7502 uint64_t Address = cantFail(ValOrErr: Symbol.getValue());
7503 StringRef SymName =
7504 unwrapOrError(EO: Symbol.getName(), Args: MachOOF->getFileName());
7505 AddrMap[Address] = SymName;
7506 if (!DisSymName.empty() && DisSymName == SymName)
7507 DisSymNameFound = true;
7508 }
7509 }
7510 if (!DisSymName.empty() && !DisSymNameFound) {
7511 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
7512 return;
7513 }
7514 // Set up the block of info used by the Symbolizer call backs.
7515 SymbolizerInfo.verbose = SymbolicOperands;
7516 SymbolizerInfo.O = MachOOF;
7517 SymbolizerInfo.S = Sections[SectIdx];
7518 SymbolizerInfo.AddrMap = &AddrMap;
7519 SymbolizerInfo.Sections = &Sections;
7520 // Same for the ThumbSymbolizer
7521 ThumbSymbolizerInfo.verbose = SymbolicOperands;
7522 ThumbSymbolizerInfo.O = MachOOF;
7523 ThumbSymbolizerInfo.S = Sections[SectIdx];
7524 ThumbSymbolizerInfo.AddrMap = &AddrMap;
7525 ThumbSymbolizerInfo.Sections = &Sections;
7526
7527 unsigned int Arch = MachOOF->getArch();
7528
7529 // Skip all symbols if this is a stubs file.
7530 if (Bytes.empty())
7531 return;
7532
7533 // If the section has symbols but no symbol at the start of the section
7534 // these are used to make sure the bytes before the first symbol are
7535 // disassembled.
7536 bool FirstSymbol = true;
7537 bool FirstSymbolAtSectionStart = true;
7538
7539 // Disassemble symbol by symbol.
7540 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
7541 StringRef SymName =
7542 unwrapOrError(EO: Symbols[SymIdx].getName(), Args: MachOOF->getFileName());
7543 SymbolRef::Type ST =
7544 unwrapOrError(EO: Symbols[SymIdx].getType(), Args: MachOOF->getFileName());
7545 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
7546 continue;
7547
7548 // Make sure the symbol is defined in this section.
7549 bool containsSym = Sections[SectIdx].containsSymbol(S: Symbols[SymIdx]);
7550 if (!containsSym) {
7551 if (!DisSymName.empty() && DisSymName == SymName) {
7552 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
7553 return;
7554 }
7555 continue;
7556 }
7557 // The __mh_execute_header is special and we need to deal with that fact
7558 // this symbol is before the start of the (__TEXT,__text) section and at the
7559 // address of the start of the __TEXT segment. This is because this symbol
7560 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
7561 // start of the section in a standard MH_EXECUTE filetype.
7562 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
7563 outs() << "-dis-symname: __mh_execute_header not in any section\n";
7564 return;
7565 }
7566 // When this code is trying to disassemble a symbol at a time and in the
7567 // case there is only the __mh_execute_header symbol left as in a stripped
7568 // executable, we need to deal with this by ignoring this symbol so the
7569 // whole section is disassembled and this symbol is then not displayed.
7570 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
7571 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
7572 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
7573 continue;
7574
7575 // If we are only disassembling one symbol see if this is that symbol.
7576 if (!DisSymName.empty() && DisSymName != SymName)
7577 continue;
7578
7579 // Start at the address of the symbol relative to the section's address.
7580 uint64_t SectSize = Sections[SectIdx].getSize();
7581 uint64_t Start = cantFail(ValOrErr: Symbols[SymIdx].getValue());
7582 uint64_t SectionAddress = Sections[SectIdx].getAddress();
7583 Start -= SectionAddress;
7584
7585 if (Start > SectSize) {
7586 outs() << "section data ends, " << SymName
7587 << " lies outside valid range\n";
7588 return;
7589 }
7590
7591 // Stop disassembling either at the beginning of the next symbol or at
7592 // the end of the section.
7593 bool containsNextSym = false;
7594 uint64_t NextSym = 0;
7595 uint64_t NextSymIdx = SymIdx + 1;
7596 while (Symbols.size() > NextSymIdx) {
7597 SymbolRef::Type NextSymType = unwrapOrError(
7598 EO: Symbols[NextSymIdx].getType(), Args: MachOOF->getFileName());
7599 if (NextSymType == SymbolRef::ST_Function) {
7600 containsNextSym =
7601 Sections[SectIdx].containsSymbol(S: Symbols[NextSymIdx]);
7602 NextSym = cantFail(ValOrErr: Symbols[NextSymIdx].getValue());
7603 NextSym -= SectionAddress;
7604 break;
7605 }
7606 ++NextSymIdx;
7607 }
7608
7609 uint64_t End = containsNextSym ? std::min(a: NextSym, b: SectSize) : SectSize;
7610 uint64_t Size;
7611
7612 symbolTableWorked = true;
7613
7614 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
7615 uint32_t SymbolFlags = cantFail(ValOrErr: MachOOF->getSymbolFlags(Symb));
7616 bool IsThumb = SymbolFlags & SymbolRef::SF_Thumb;
7617
7618 // We only need the dedicated Thumb target if there's a real choice
7619 // (i.e. we're not targeting M-class) and the function is Thumb.
7620 bool UseThumbTarget = IsThumb && ThumbTarget;
7621
7622 // If we are not specifying a symbol to start disassembly with and this
7623 // is the first symbol in the section but not at the start of the section
7624 // then move the disassembly index to the start of the section and
7625 // don't print the symbol name just yet. This is so the bytes before the
7626 // first symbol are disassembled.
7627 uint64_t SymbolStart = Start;
7628 if (DisSymName.empty() && FirstSymbol && Start != 0) {
7629 FirstSymbolAtSectionStart = false;
7630 Start = 0;
7631 }
7632 else
7633 outs() << SymName << ":\n";
7634
7635 DILineInfo lastLine;
7636 for (uint64_t Index = Start; Index < End; Index += Size) {
7637 MCInst Inst;
7638
7639 // If this is the first symbol in the section and it was not at the
7640 // start of the section, see if we are at its Index now and if so print
7641 // the symbol name.
7642 if (FirstSymbol && !FirstSymbolAtSectionStart && Index == SymbolStart)
7643 outs() << SymName << ":\n";
7644
7645 uint64_t PC = SectAddress + Index;
7646
7647 if (PrintSource || PrintLines) {
7648 formatted_raw_ostream FOS(outs());
7649 SP->printSourceLine(OS&: FOS, Address: {.Address: PC, .SectionIndex: SectIdx}, ObjectFilename: Filename, LEP&: *LEP);
7650 }
7651
7652 if (LeadingAddr) {
7653 if (FullLeadingAddr) {
7654 if (MachOOF->is64Bit())
7655 outs() << format(Fmt: "%016" PRIx64, Vals: PC);
7656 else
7657 outs() << format(Fmt: "%08" PRIx64, Vals: PC);
7658 } else {
7659 outs() << format(Fmt: "%8" PRIx64 ":", Vals: PC);
7660 }
7661 }
7662 if (ShowRawInsn || Arch == Triple::arm)
7663 outs() << "\t";
7664
7665 if (DumpAndSkipDataInCode(PC, bytes: Bytes.data() + Index, Dices, InstSize&: Size))
7666 continue;
7667
7668 SmallVector<char, 64> AnnotationsBytes;
7669 raw_svector_ostream Annotations(AnnotationsBytes);
7670
7671 bool gotInst;
7672 if (UseThumbTarget)
7673 gotInst = ThumbDisAsm->getInstruction(Instr&: Inst, Size, Bytes: Bytes.slice(N: Index),
7674 Address: PC, CStream&: Annotations);
7675 else
7676 gotInst = DisAsm->getInstruction(Instr&: Inst, Size, Bytes: Bytes.slice(N: Index), Address: PC,
7677 CStream&: Annotations);
7678 if (gotInst) {
7679 if (ShowRawInsn || Arch == Triple::arm) {
7680 dumpBytes(Bytes: ArrayRef(Bytes.data() + Index, Size), OS&: outs());
7681 }
7682 formatted_raw_ostream FormattedOS(outs());
7683 StringRef AnnotationsStr = Annotations.str();
7684 if (UseThumbTarget)
7685 ThumbIP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *ThumbSTI,
7686 OS&: FormattedOS);
7687 else
7688 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *STI, OS&: FormattedOS);
7689 emitComments(CommentStream, CommentsToEmit, FormattedOS, MAI: *AsmInfo);
7690
7691 // Print debug info.
7692 if (diContext) {
7693 DILineInfo dli = diContext->getLineInfoForAddress(Address: {.Address: PC, .SectionIndex: SectIdx})
7694 .value_or(u: DILineInfo());
7695 // Print valid line info if it changed.
7696 if (dli != lastLine && dli.Line != 0)
7697 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
7698 << dli.Column;
7699 lastLine = dli;
7700 }
7701 outs() << "\n";
7702 } else {
7703 if (MachOOF->getArchTriple().isX86()) {
7704 outs() << format(Fmt: "\t.byte 0x%02x #bad opcode\n",
7705 Vals: *(Bytes.data() + Index) & 0xff);
7706 Size = 1; // skip exactly one illegible byte and move on.
7707 } else if (Arch == Triple::aarch64 || Arch == Triple::aarch64_32 ||
7708 (Arch == Triple::arm && !IsThumb)) {
7709 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7710 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
7711 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
7712 (*(Bytes.data() + Index + 3) & 0xff) << 24;
7713 outs() << format(Fmt: "\t.long\t0x%08x\n", Vals: opcode);
7714 Size = 4;
7715 } else if (Arch == Triple::arm) {
7716 assert(IsThumb && "ARM mode should have been dealt with above");
7717 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
7718 (*(Bytes.data() + Index + 1) & 0xff) << 8;
7719 outs() << format(Fmt: "\t.short\t0x%04x\n", Vals: opcode);
7720 Size = 2;
7721 } else {
7722 WithColor::warning(OS&: errs(), Prefix: "llvm-objdump")
7723 << "invalid instruction encoding\n";
7724 if (Size == 0)
7725 Size = 1; // skip illegible bytes
7726 }
7727 }
7728 }
7729 // Now that we are done disassembled the first symbol set the bool that
7730 // were doing this to false.
7731 FirstSymbol = false;
7732 }
7733 if (!symbolTableWorked) {
7734 // Reading the symbol table didn't work, disassemble the whole section.
7735 uint64_t SectAddress = Sections[SectIdx].getAddress();
7736 uint64_t SectSize = Sections[SectIdx].getSize();
7737 uint64_t InstSize;
7738 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
7739 MCInst Inst;
7740
7741 uint64_t PC = SectAddress + Index;
7742
7743 if (PrintSource || PrintLines) {
7744 formatted_raw_ostream FOS(outs());
7745 SP->printSourceLine(OS&: FOS, Address: {.Address: PC, .SectionIndex: SectIdx}, ObjectFilename: Filename, LEP&: *LEP);
7746 }
7747
7748 if (DumpAndSkipDataInCode(PC, bytes: Bytes.data() + Index, Dices, InstSize))
7749 continue;
7750
7751 SmallVector<char, 64> AnnotationsBytes;
7752 raw_svector_ostream Annotations(AnnotationsBytes);
7753 if (DisAsm->getInstruction(Instr&: Inst, Size&: InstSize, Bytes: Bytes.slice(N: Index), Address: PC,
7754 CStream&: Annotations)) {
7755 if (LeadingAddr) {
7756 if (FullLeadingAddr) {
7757 if (MachOOF->is64Bit())
7758 outs() << format(Fmt: "%016" PRIx64, Vals: PC);
7759 else
7760 outs() << format(Fmt: "%08" PRIx64, Vals: PC);
7761 } else {
7762 outs() << format(Fmt: "%8" PRIx64 ":", Vals: PC);
7763 }
7764 }
7765 if (ShowRawInsn || Arch == Triple::arm) {
7766 outs() << "\t";
7767 dumpBytes(Bytes: ArrayRef(Bytes.data() + Index, InstSize), OS&: outs());
7768 }
7769 StringRef AnnotationsStr = Annotations.str();
7770 IP->printInst(MI: &Inst, Address: PC, Annot: AnnotationsStr, STI: *STI, OS&: outs());
7771 outs() << "\n";
7772 } else {
7773 if (MachOOF->getArchTriple().isX86()) {
7774 outs() << format(Fmt: "\t.byte 0x%02x #bad opcode\n",
7775 Vals: *(Bytes.data() + Index) & 0xff);
7776 InstSize = 1; // skip exactly one illegible byte and move on.
7777 } else {
7778 WithColor::warning(OS&: errs(), Prefix: "llvm-objdump")
7779 << "invalid instruction encoding\n";
7780 if (InstSize == 0)
7781 InstSize = 1; // skip illegible bytes
7782 }
7783 }
7784 }
7785 }
7786 // The TripleName's need to be reset if we are called again for a different
7787 // architecture.
7788 TripleName = "";
7789 ThumbTripleName = "";
7790
7791 if (SymbolizerInfo.demangled_name != nullptr)
7792 free(ptr: SymbolizerInfo.demangled_name);
7793 if (ThumbSymbolizerInfo.demangled_name != nullptr)
7794 free(ptr: ThumbSymbolizerInfo.demangled_name);
7795 }
7796}
7797
7798//===----------------------------------------------------------------------===//
7799// __compact_unwind section dumping
7800//===----------------------------------------------------------------------===//
7801
7802namespace {
7803
7804template <typename T>
7805static uint64_t read(StringRef Contents, ptrdiff_t Offset) {
7806 if (Offset + sizeof(T) > Contents.size()) {
7807 outs() << "warning: attempt to read past end of buffer\n";
7808 return T();
7809 }
7810
7811 uint64_t Val = support::endian::read<T, llvm::endianness::little>(
7812 Contents.data() + Offset);
7813 return Val;
7814}
7815
7816template <typename T>
7817static uint64_t readNext(StringRef Contents, ptrdiff_t &Offset) {
7818 T Val = read<T>(Contents, Offset);
7819 Offset += sizeof(T);
7820 return Val;
7821}
7822
7823struct CompactUnwindEntry {
7824 uint32_t OffsetInSection;
7825
7826 uint64_t FunctionAddr;
7827 uint32_t Length;
7828 uint32_t CompactEncoding;
7829 uint64_t PersonalityAddr;
7830 uint64_t LSDAAddr;
7831
7832 RelocationRef FunctionReloc;
7833 RelocationRef PersonalityReloc;
7834 RelocationRef LSDAReloc;
7835
7836 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
7837 : OffsetInSection(Offset) {
7838 if (Is64)
7839 read<uint64_t>(Contents, Offset);
7840 else
7841 read<uint32_t>(Contents, Offset);
7842 }
7843
7844private:
7845 template <typename UIntPtr> void read(StringRef Contents, ptrdiff_t Offset) {
7846 FunctionAddr = readNext<UIntPtr>(Contents, Offset);
7847 Length = readNext<uint32_t>(Contents, Offset);
7848 CompactEncoding = readNext<uint32_t>(Contents, Offset);
7849 PersonalityAddr = readNext<UIntPtr>(Contents, Offset);
7850 LSDAAddr = readNext<UIntPtr>(Contents, Offset);
7851 }
7852};
7853}
7854
7855/// Given a relocation from __compact_unwind, consisting of the RelocationRef
7856/// and data being relocated, determine the best base Name and Addend to use for
7857/// display purposes.
7858///
7859/// 1. An Extern relocation will directly reference a symbol (and the data is
7860/// then already an addend), so use that.
7861/// 2. Otherwise the data is an offset in the object file's layout; try to find
7862// a symbol before it in the same section, and use the offset from there.
7863/// 3. Finally, if all that fails, fall back to an offset from the start of the
7864/// referenced section.
7865static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
7866 std::map<uint64_t, SymbolRef> &Symbols,
7867 const RelocationRef &Reloc, uint64_t Addr,
7868 StringRef &Name, uint64_t &Addend) {
7869 if (Reloc.getSymbol() != Obj->symbol_end()) {
7870 Name = unwrapOrError(EO: Reloc.getSymbol()->getName(), Args: Obj->getFileName());
7871 Addend = Addr;
7872 return;
7873 }
7874
7875 auto RE = Obj->getRelocation(Rel: Reloc.getRawDataRefImpl());
7876 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7877
7878 uint64_t SectionAddr = RelocSection.getAddress();
7879
7880 auto Sym = Symbols.upper_bound(x: Addr);
7881 if (Sym == Symbols.begin()) {
7882 // The first symbol in the object is after this reference, the best we can
7883 // do is section-relative notation.
7884 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7885 Name = *NameOrErr;
7886 else
7887 consumeError(Err: NameOrErr.takeError());
7888
7889 Addend = Addr - SectionAddr;
7890 return;
7891 }
7892
7893 // Go back one so that SymbolAddress <= Addr.
7894 --Sym;
7895
7896 section_iterator SymSection =
7897 unwrapOrError(EO: Sym->second.getSection(), Args: Obj->getFileName());
7898 if (RelocSection == *SymSection) {
7899 // There's a valid symbol in the same section before this reference.
7900 Name = unwrapOrError(EO: Sym->second.getName(), Args: Obj->getFileName());
7901 Addend = Addr - Sym->first;
7902 return;
7903 }
7904
7905 // There is a symbol before this reference, but it's in a different
7906 // section. Probably not helpful to mention it, so use the section name.
7907 if (Expected<StringRef> NameOrErr = RelocSection.getName())
7908 Name = *NameOrErr;
7909 else
7910 consumeError(Err: NameOrErr.takeError());
7911
7912 Addend = Addr - SectionAddr;
7913}
7914
7915static void printUnwindRelocDest(const MachOObjectFile *Obj,
7916 std::map<uint64_t, SymbolRef> &Symbols,
7917 const RelocationRef &Reloc, uint64_t Addr) {
7918 StringRef Name;
7919 uint64_t Addend;
7920
7921 if (!Reloc.getObject())
7922 return;
7923
7924 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7925
7926 outs() << Name;
7927 if (Addend)
7928 outs() << " + " << format(Fmt: "0x%" PRIx64, Vals: Addend);
7929}
7930
7931static void
7932printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7933 std::map<uint64_t, SymbolRef> &Symbols,
7934 const SectionRef &CompactUnwind) {
7935
7936 if (!Obj->isLittleEndian()) {
7937 outs() << "Skipping big-endian __compact_unwind section\n";
7938 return;
7939 }
7940
7941 bool Is64 = Obj->is64Bit();
7942 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7943 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7944
7945 StringRef Contents =
7946 unwrapOrError(EO: CompactUnwind.getContents(), Args: Obj->getFileName());
7947 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7948
7949 // First populate the initial raw offsets, encodings and so on from the entry.
7950 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7951 CompactUnwindEntry Entry(Contents, Offset, Is64);
7952 CompactUnwinds.push_back(Elt: Entry);
7953 }
7954
7955 // Next we need to look at the relocations to find out what objects are
7956 // actually being referred to.
7957 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7958 uint64_t RelocAddress = Reloc.getOffset();
7959
7960 uint32_t EntryIdx = RelocAddress / EntrySize;
7961 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7962 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7963
7964 if (OffsetInEntry == 0)
7965 Entry.FunctionReloc = Reloc;
7966 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7967 Entry.PersonalityReloc = Reloc;
7968 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7969 Entry.LSDAReloc = Reloc;
7970 else {
7971 outs() << "Invalid relocation in __compact_unwind section\n";
7972 return;
7973 }
7974 }
7975
7976 // Finally, we're ready to print the data we've gathered.
7977 outs() << "Contents of __compact_unwind section:\n";
7978 for (auto &Entry : CompactUnwinds) {
7979 outs() << " Entry at offset "
7980 << format(Fmt: "0x%" PRIx32, Vals: Entry.OffsetInSection) << ":\n";
7981
7982 // 1. Start of the region this entry applies to.
7983 outs() << " start: " << format(Fmt: "0x%" PRIx64,
7984 Vals: Entry.FunctionAddr) << ' ';
7985 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.FunctionReloc, Addr: Entry.FunctionAddr);
7986 outs() << '\n';
7987
7988 // 2. Length of the region this entry applies to.
7989 outs() << " length: " << format(Fmt: "0x%" PRIx32, Vals: Entry.Length)
7990 << '\n';
7991 // 3. The 32-bit compact encoding.
7992 outs() << " compact encoding: "
7993 << format(Fmt: "0x%08" PRIx32, Vals: Entry.CompactEncoding) << '\n';
7994
7995 // 4. The personality function, if present.
7996 if (Entry.PersonalityReloc.getObject()) {
7997 outs() << " personality function: "
7998 << format(Fmt: "0x%" PRIx64, Vals: Entry.PersonalityAddr) << ' ';
7999 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.PersonalityReloc,
8000 Addr: Entry.PersonalityAddr);
8001 outs() << '\n';
8002 }
8003
8004 // 5. This entry's language-specific data area.
8005 if (Entry.LSDAReloc.getObject()) {
8006 outs() << " LSDA: " << format(Fmt: "0x%" PRIx64,
8007 Vals: Entry.LSDAAddr) << ' ';
8008 printUnwindRelocDest(Obj, Symbols, Reloc: Entry.LSDAReloc, Addr: Entry.LSDAAddr);
8009 outs() << '\n';
8010 }
8011 }
8012}
8013
8014//===----------------------------------------------------------------------===//
8015// __unwind_info section dumping
8016//===----------------------------------------------------------------------===//
8017
8018static void printRegularSecondLevelUnwindPage(StringRef PageData) {
8019 ptrdiff_t Pos = 0;
8020 uint32_t Kind = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8021 (void)Kind;
8022 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
8023
8024 uint16_t EntriesStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8025 uint16_t NumEntries = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8026
8027 Pos = EntriesStart;
8028 for (unsigned i = 0; i < NumEntries; ++i) {
8029 uint32_t FunctionOffset = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8030 uint32_t Encoding = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8031
8032 outs() << " [" << i << "]: "
8033 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8034 << ", "
8035 << "encoding=" << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8036 }
8037}
8038
8039static void printCompressedSecondLevelUnwindPage(
8040 StringRef PageData, uint32_t FunctionBase,
8041 const SmallVectorImpl<uint32_t> &CommonEncodings) {
8042 ptrdiff_t Pos = 0;
8043 uint32_t Kind = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8044 (void)Kind;
8045 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
8046
8047 uint32_t NumCommonEncodings = CommonEncodings.size();
8048 uint16_t EntriesStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8049 uint16_t NumEntries = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8050
8051 uint16_t PageEncodingsStart = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8052 uint16_t NumPageEncodings = readNext<uint16_t>(Contents: PageData, Offset&: Pos);
8053 SmallVector<uint32_t, 64> PageEncodings;
8054 if (NumPageEncodings) {
8055 outs() << " Page encodings: (count = " << NumPageEncodings << ")\n";
8056 Pos = PageEncodingsStart;
8057 for (unsigned i = 0; i < NumPageEncodings; ++i) {
8058 uint32_t Encoding = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8059 PageEncodings.push_back(Elt: Encoding);
8060 outs() << " encoding[" << (i + NumCommonEncodings)
8061 << "]: " << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8062 }
8063 }
8064
8065 Pos = EntriesStart;
8066 for (unsigned i = 0; i < NumEntries; ++i) {
8067 uint32_t Entry = readNext<uint32_t>(Contents: PageData, Offset&: Pos);
8068 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
8069 uint32_t EncodingIdx = Entry >> 24;
8070
8071 uint32_t Encoding;
8072 if (EncodingIdx < NumCommonEncodings)
8073 Encoding = CommonEncodings[EncodingIdx];
8074 else
8075 Encoding = PageEncodings[EncodingIdx - NumCommonEncodings];
8076
8077 outs() << " [" << i << "]: "
8078 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8079 << ", "
8080 << "encoding[" << EncodingIdx
8081 << "]=" << format(Fmt: "0x%08" PRIx32, Vals: Encoding) << '\n';
8082 }
8083}
8084
8085static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
8086 std::map<uint64_t, SymbolRef> &Symbols,
8087 const SectionRef &UnwindInfo) {
8088
8089 if (!Obj->isLittleEndian()) {
8090 outs() << "Skipping big-endian __unwind_info section\n";
8091 return;
8092 }
8093
8094 outs() << "Contents of __unwind_info section:\n";
8095
8096 StringRef Contents =
8097 unwrapOrError(EO: UnwindInfo.getContents(), Args: Obj->getFileName());
8098 ptrdiff_t Pos = 0;
8099
8100 //===----------------------------------
8101 // Section header
8102 //===----------------------------------
8103
8104 uint32_t Version = readNext<uint32_t>(Contents, Offset&: Pos);
8105 outs() << " Version: "
8106 << format(Fmt: "0x%" PRIx32, Vals: Version) << '\n';
8107 if (Version != 1) {
8108 outs() << " Skipping section with unknown version\n";
8109 return;
8110 }
8111
8112 uint32_t CommonEncodingsStart = readNext<uint32_t>(Contents, Offset&: Pos);
8113 outs() << " Common encodings array section offset: "
8114 << format(Fmt: "0x%" PRIx32, Vals: CommonEncodingsStart) << '\n';
8115 uint32_t NumCommonEncodings = readNext<uint32_t>(Contents, Offset&: Pos);
8116 outs() << " Number of common encodings in array: "
8117 << format(Fmt: "0x%" PRIx32, Vals: NumCommonEncodings) << '\n';
8118
8119 uint32_t PersonalitiesStart = readNext<uint32_t>(Contents, Offset&: Pos);
8120 outs() << " Personality function array section offset: "
8121 << format(Fmt: "0x%" PRIx32, Vals: PersonalitiesStart) << '\n';
8122 uint32_t NumPersonalities = readNext<uint32_t>(Contents, Offset&: Pos);
8123 outs() << " Number of personality functions in array: "
8124 << format(Fmt: "0x%" PRIx32, Vals: NumPersonalities) << '\n';
8125
8126 uint32_t IndicesStart = readNext<uint32_t>(Contents, Offset&: Pos);
8127 outs() << " Index array section offset: "
8128 << format(Fmt: "0x%" PRIx32, Vals: IndicesStart) << '\n';
8129 uint32_t NumIndices = readNext<uint32_t>(Contents, Offset&: Pos);
8130 outs() << " Number of indices in array: "
8131 << format(Fmt: "0x%" PRIx32, Vals: NumIndices) << '\n';
8132
8133 //===----------------------------------
8134 // A shared list of common encodings
8135 //===----------------------------------
8136
8137 // These occupy indices in the range [0, N] whenever an encoding is referenced
8138 // from a compressed 2nd level index table. In practice the linker only
8139 // creates ~128 of these, so that indices are available to embed encodings in
8140 // the 2nd level index.
8141
8142 SmallVector<uint32_t, 64> CommonEncodings;
8143 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
8144 Pos = CommonEncodingsStart;
8145 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
8146 uint32_t Encoding = readNext<uint32_t>(Contents, Offset&: Pos);
8147 CommonEncodings.push_back(Elt: Encoding);
8148
8149 outs() << " encoding[" << i << "]: " << format(Fmt: "0x%08" PRIx32, Vals: Encoding)
8150 << '\n';
8151 }
8152
8153 //===----------------------------------
8154 // Personality functions used in this executable
8155 //===----------------------------------
8156
8157 // There should be only a handful of these (one per source language,
8158 // roughly). Particularly since they only get 2 bits in the compact encoding.
8159
8160 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
8161 Pos = PersonalitiesStart;
8162 for (unsigned i = 0; i < NumPersonalities; ++i) {
8163 uint32_t PersonalityFn = readNext<uint32_t>(Contents, Offset&: Pos);
8164 outs() << " personality[" << i + 1
8165 << "]: " << format(Fmt: "0x%08" PRIx32, Vals: PersonalityFn) << '\n';
8166 }
8167
8168 //===----------------------------------
8169 // The level 1 index entries
8170 //===----------------------------------
8171
8172 // These specify an approximate place to start searching for the more detailed
8173 // information, sorted by PC.
8174
8175 struct IndexEntry {
8176 uint32_t FunctionOffset;
8177 uint32_t SecondLevelPageStart;
8178 uint32_t LSDAStart;
8179 };
8180
8181 SmallVector<IndexEntry, 4> IndexEntries;
8182
8183 outs() << " Top level indices: (count = " << NumIndices << ")\n";
8184 Pos = IndicesStart;
8185 for (unsigned i = 0; i < NumIndices; ++i) {
8186 IndexEntry Entry;
8187
8188 Entry.FunctionOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8189 Entry.SecondLevelPageStart = readNext<uint32_t>(Contents, Offset&: Pos);
8190 Entry.LSDAStart = readNext<uint32_t>(Contents, Offset&: Pos);
8191 IndexEntries.push_back(Elt: Entry);
8192
8193 outs() << " [" << i << "]: "
8194 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: Entry.FunctionOffset)
8195 << ", "
8196 << "2nd level page offset="
8197 << format(Fmt: "0x%08" PRIx32, Vals: Entry.SecondLevelPageStart) << ", "
8198 << "LSDA offset=" << format(Fmt: "0x%08" PRIx32, Vals: Entry.LSDAStart) << '\n';
8199 }
8200
8201 //===----------------------------------
8202 // Next come the LSDA tables
8203 //===----------------------------------
8204
8205 // The LSDA layout is rather implicit: it's a contiguous array of entries from
8206 // the first top-level index's LSDAOffset to the last (sentinel).
8207
8208 outs() << " LSDA descriptors:\n";
8209 Pos = IndexEntries[0].LSDAStart;
8210 const uint32_t LSDASize = 2 * sizeof(uint32_t);
8211 int NumLSDAs =
8212 (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) / LSDASize;
8213
8214 for (int i = 0; i < NumLSDAs; ++i) {
8215 uint32_t FunctionOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8216 uint32_t LSDAOffset = readNext<uint32_t>(Contents, Offset&: Pos);
8217 outs() << " [" << i << "]: "
8218 << "function offset=" << format(Fmt: "0x%08" PRIx32, Vals: FunctionOffset)
8219 << ", "
8220 << "LSDA offset=" << format(Fmt: "0x%08" PRIx32, Vals: LSDAOffset) << '\n';
8221 }
8222
8223 //===----------------------------------
8224 // Finally, the 2nd level indices
8225 //===----------------------------------
8226
8227 // Generally these are 4K in size, and have 2 possible forms:
8228 // + Regular stores up to 511 entries with disparate encodings
8229 // + Compressed stores up to 1021 entries if few enough compact encoding
8230 // values are used.
8231 outs() << " Second level indices:\n";
8232 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
8233 // The final sentinel top-level index has no associated 2nd level page
8234 if (IndexEntries[i].SecondLevelPageStart == 0)
8235 break;
8236
8237 outs() << " Second level index[" << i << "]: "
8238 << "offset in section="
8239 << format(Fmt: "0x%08" PRIx32, Vals: IndexEntries[i].SecondLevelPageStart)
8240 << ", "
8241 << "base function offset="
8242 << format(Fmt: "0x%08" PRIx32, Vals: IndexEntries[i].FunctionOffset) << '\n';
8243
8244 Pos = IndexEntries[i].SecondLevelPageStart;
8245 if (Pos + sizeof(uint32_t) > Contents.size()) {
8246 outs() << "warning: invalid offset for second level page: " << Pos << '\n';
8247 continue;
8248 }
8249
8250 uint32_t Kind =
8251 *reinterpret_cast<const support::ulittle32_t *>(Contents.data() + Pos);
8252 if (Kind == 2)
8253 printRegularSecondLevelUnwindPage(PageData: Contents.substr(Start: Pos, N: 4096));
8254 else if (Kind == 3)
8255 printCompressedSecondLevelUnwindPage(PageData: Contents.substr(Start: Pos, N: 4096),
8256 FunctionBase: IndexEntries[i].FunctionOffset,
8257 CommonEncodings);
8258 else
8259 outs() << " Skipping 2nd level page with unknown kind " << Kind
8260 << '\n';
8261 }
8262}
8263
8264void objdump::printMachOUnwindInfo(const MachOObjectFile *Obj) {
8265 std::map<uint64_t, SymbolRef> Symbols;
8266 for (const SymbolRef &SymRef : Obj->symbols()) {
8267 // Discard any undefined or absolute symbols. They're not going to take part
8268 // in the convenience lookup for unwind info and just take up resources.
8269 auto SectOrErr = SymRef.getSection();
8270 if (!SectOrErr) {
8271 // TODO: Actually report errors helpfully.
8272 consumeError(Err: SectOrErr.takeError());
8273 continue;
8274 }
8275 section_iterator Section = *SectOrErr;
8276 if (Section == Obj->section_end())
8277 continue;
8278
8279 uint64_t Addr = cantFail(ValOrErr: SymRef.getValue());
8280 Symbols.insert(x: std::make_pair(x&: Addr, y: SymRef));
8281 }
8282
8283 for (const SectionRef &Section : Obj->sections()) {
8284 StringRef SectName;
8285 if (Expected<StringRef> NameOrErr = Section.getName())
8286 SectName = *NameOrErr;
8287 else
8288 consumeError(Err: NameOrErr.takeError());
8289
8290 if (SectName == "__compact_unwind")
8291 printMachOCompactUnwindSection(Obj, Symbols, CompactUnwind: Section);
8292 else if (SectName == "__unwind_info")
8293 printMachOUnwindInfoSection(Obj, Symbols, UnwindInfo: Section);
8294 }
8295}
8296
8297static void PrintMachHeader(uint32_t magic, uint32_t cputype,
8298 uint32_t cpusubtype, uint32_t filetype,
8299 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
8300 bool verbose) {
8301 outs() << "Mach header\n";
8302 outs() << " magic cputype cpusubtype caps filetype ncmds "
8303 "sizeofcmds flags\n";
8304 if (verbose) {
8305 if (magic == MachO::MH_MAGIC)
8306 outs() << " MH_MAGIC";
8307 else if (magic == MachO::MH_MAGIC_64)
8308 outs() << "MH_MAGIC_64";
8309 else
8310 outs() << format(Fmt: " 0x%08" PRIx32, Vals: magic);
8311 switch (cputype) {
8312 case MachO::CPU_TYPE_I386:
8313 outs() << " I386";
8314 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8315 case MachO::CPU_SUBTYPE_I386_ALL:
8316 outs() << " ALL";
8317 break;
8318 default:
8319 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8320 break;
8321 }
8322 break;
8323 case MachO::CPU_TYPE_X86_64:
8324 outs() << " X86_64";
8325 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8326 case MachO::CPU_SUBTYPE_X86_64_ALL:
8327 outs() << " ALL";
8328 break;
8329 case MachO::CPU_SUBTYPE_X86_64_H:
8330 outs() << " Haswell";
8331 break;
8332 default:
8333 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8334 break;
8335 }
8336 break;
8337 case MachO::CPU_TYPE_ARM:
8338 outs() << " ARM";
8339 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8340 case MachO::CPU_SUBTYPE_ARM_ALL:
8341 outs() << " ALL";
8342 break;
8343 case MachO::CPU_SUBTYPE_ARM_V4T:
8344 outs() << " V4T";
8345 break;
8346 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
8347 outs() << " V5TEJ";
8348 break;
8349 case MachO::CPU_SUBTYPE_ARM_XSCALE:
8350 outs() << " XSCALE";
8351 break;
8352 case MachO::CPU_SUBTYPE_ARM_V6:
8353 outs() << " V6";
8354 break;
8355 case MachO::CPU_SUBTYPE_ARM_V6M:
8356 outs() << " V6M";
8357 break;
8358 case MachO::CPU_SUBTYPE_ARM_V7:
8359 outs() << " V7";
8360 break;
8361 case MachO::CPU_SUBTYPE_ARM_V7EM:
8362 outs() << " V7EM";
8363 break;
8364 case MachO::CPU_SUBTYPE_ARM_V7K:
8365 outs() << " V7K";
8366 break;
8367 case MachO::CPU_SUBTYPE_ARM_V7M:
8368 outs() << " V7M";
8369 break;
8370 case MachO::CPU_SUBTYPE_ARM_V7S:
8371 outs() << " V7S";
8372 break;
8373 default:
8374 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8375 break;
8376 }
8377 break;
8378 case MachO::CPU_TYPE_ARM64:
8379 outs() << " ARM64";
8380 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8381 case MachO::CPU_SUBTYPE_ARM64_ALL:
8382 outs() << " ALL";
8383 break;
8384 case MachO::CPU_SUBTYPE_ARM64_V8:
8385 outs() << " V8";
8386 break;
8387 case MachO::CPU_SUBTYPE_ARM64E:
8388 outs() << " E";
8389 break;
8390 default:
8391 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8392 break;
8393 }
8394 break;
8395 case MachO::CPU_TYPE_ARM64_32:
8396 outs() << " ARM64_32";
8397 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8398 case MachO::CPU_SUBTYPE_ARM64_32_V8:
8399 outs() << " V8";
8400 break;
8401 default:
8402 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8403 break;
8404 }
8405 break;
8406 case MachO::CPU_TYPE_POWERPC:
8407 outs() << " PPC";
8408 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8409 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8410 outs() << " ALL";
8411 break;
8412 default:
8413 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8414 break;
8415 }
8416 break;
8417 case MachO::CPU_TYPE_POWERPC64:
8418 outs() << " PPC64";
8419 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
8420 case MachO::CPU_SUBTYPE_POWERPC_ALL:
8421 outs() << " ALL";
8422 break;
8423 default:
8424 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8425 break;
8426 }
8427 break;
8428 default:
8429 outs() << format(Fmt: " %7d", Vals: cputype);
8430 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8431 break;
8432 }
8433
8434 if (cputype == MachO::CPU_TYPE_ARM64 &&
8435 MachO::CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(ST: cpusubtype)) {
8436 const char *Format =
8437 MachO::CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(ST: cpusubtype)
8438 ? " PAK%02d"
8439 : " PAC%02d";
8440 outs() << format(Fmt: Format,
8441 Vals: MachO::CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(ST: cpusubtype));
8442 } else if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) ==
8443 MachO::CPU_SUBTYPE_LIB64) {
8444 outs() << " LIB64";
8445 } else {
8446 outs() << format(Fmt: " 0x%02" PRIx32,
8447 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8448 }
8449 switch (filetype) {
8450 case MachO::MH_OBJECT:
8451 outs() << " OBJECT";
8452 break;
8453 case MachO::MH_EXECUTE:
8454 outs() << " EXECUTE";
8455 break;
8456 case MachO::MH_FVMLIB:
8457 outs() << " FVMLIB";
8458 break;
8459 case MachO::MH_CORE:
8460 outs() << " CORE";
8461 break;
8462 case MachO::MH_PRELOAD:
8463 outs() << " PRELOAD";
8464 break;
8465 case MachO::MH_DYLIB:
8466 outs() << " DYLIB";
8467 break;
8468 case MachO::MH_DYLIB_STUB:
8469 outs() << " DYLIB_STUB";
8470 break;
8471 case MachO::MH_DYLINKER:
8472 outs() << " DYLINKER";
8473 break;
8474 case MachO::MH_BUNDLE:
8475 outs() << " BUNDLE";
8476 break;
8477 case MachO::MH_DSYM:
8478 outs() << " DSYM";
8479 break;
8480 case MachO::MH_KEXT_BUNDLE:
8481 outs() << " KEXTBUNDLE";
8482 break;
8483 case MachO::MH_FILESET:
8484 outs() << " FILESET";
8485 break;
8486 default:
8487 outs() << format(Fmt: " %10u", Vals: filetype);
8488 break;
8489 }
8490 outs() << format(Fmt: " %5u", Vals: ncmds);
8491 outs() << format(Fmt: " %10u", Vals: sizeofcmds);
8492 uint32_t f = flags;
8493 if (f & MachO::MH_NOUNDEFS) {
8494 outs() << " NOUNDEFS";
8495 f &= ~MachO::MH_NOUNDEFS;
8496 }
8497 if (f & MachO::MH_INCRLINK) {
8498 outs() << " INCRLINK";
8499 f &= ~MachO::MH_INCRLINK;
8500 }
8501 if (f & MachO::MH_DYLDLINK) {
8502 outs() << " DYLDLINK";
8503 f &= ~MachO::MH_DYLDLINK;
8504 }
8505 if (f & MachO::MH_BINDATLOAD) {
8506 outs() << " BINDATLOAD";
8507 f &= ~MachO::MH_BINDATLOAD;
8508 }
8509 if (f & MachO::MH_PREBOUND) {
8510 outs() << " PREBOUND";
8511 f &= ~MachO::MH_PREBOUND;
8512 }
8513 if (f & MachO::MH_SPLIT_SEGS) {
8514 outs() << " SPLIT_SEGS";
8515 f &= ~MachO::MH_SPLIT_SEGS;
8516 }
8517 if (f & MachO::MH_LAZY_INIT) {
8518 outs() << " LAZY_INIT";
8519 f &= ~MachO::MH_LAZY_INIT;
8520 }
8521 if (f & MachO::MH_TWOLEVEL) {
8522 outs() << " TWOLEVEL";
8523 f &= ~MachO::MH_TWOLEVEL;
8524 }
8525 if (f & MachO::MH_FORCE_FLAT) {
8526 outs() << " FORCE_FLAT";
8527 f &= ~MachO::MH_FORCE_FLAT;
8528 }
8529 if (f & MachO::MH_NOMULTIDEFS) {
8530 outs() << " NOMULTIDEFS";
8531 f &= ~MachO::MH_NOMULTIDEFS;
8532 }
8533 if (f & MachO::MH_NOFIXPREBINDING) {
8534 outs() << " NOFIXPREBINDING";
8535 f &= ~MachO::MH_NOFIXPREBINDING;
8536 }
8537 if (f & MachO::MH_PREBINDABLE) {
8538 outs() << " PREBINDABLE";
8539 f &= ~MachO::MH_PREBINDABLE;
8540 }
8541 if (f & MachO::MH_ALLMODSBOUND) {
8542 outs() << " ALLMODSBOUND";
8543 f &= ~MachO::MH_ALLMODSBOUND;
8544 }
8545 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
8546 outs() << " SUBSECTIONS_VIA_SYMBOLS";
8547 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
8548 }
8549 if (f & MachO::MH_CANONICAL) {
8550 outs() << " CANONICAL";
8551 f &= ~MachO::MH_CANONICAL;
8552 }
8553 if (f & MachO::MH_WEAK_DEFINES) {
8554 outs() << " WEAK_DEFINES";
8555 f &= ~MachO::MH_WEAK_DEFINES;
8556 }
8557 if (f & MachO::MH_BINDS_TO_WEAK) {
8558 outs() << " BINDS_TO_WEAK";
8559 f &= ~MachO::MH_BINDS_TO_WEAK;
8560 }
8561 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
8562 outs() << " ALLOW_STACK_EXECUTION";
8563 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
8564 }
8565 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
8566 outs() << " DEAD_STRIPPABLE_DYLIB";
8567 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
8568 }
8569 if (f & MachO::MH_PIE) {
8570 outs() << " PIE";
8571 f &= ~MachO::MH_PIE;
8572 }
8573 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
8574 outs() << " NO_REEXPORTED_DYLIBS";
8575 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
8576 }
8577 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
8578 outs() << " MH_HAS_TLV_DESCRIPTORS";
8579 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
8580 }
8581 if (f & MachO::MH_NO_HEAP_EXECUTION) {
8582 outs() << " MH_NO_HEAP_EXECUTION";
8583 f &= ~MachO::MH_NO_HEAP_EXECUTION;
8584 }
8585 if (f & MachO::MH_APP_EXTENSION_SAFE) {
8586 outs() << " APP_EXTENSION_SAFE";
8587 f &= ~MachO::MH_APP_EXTENSION_SAFE;
8588 }
8589 if (f & MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO) {
8590 outs() << " NLIST_OUTOFSYNC_WITH_DYLDINFO";
8591 f &= ~MachO::MH_NLIST_OUTOFSYNC_WITH_DYLDINFO;
8592 }
8593 if (f != 0 || flags == 0)
8594 outs() << format(Fmt: " 0x%08" PRIx32, Vals: f);
8595 } else {
8596 outs() << format(Fmt: " 0x%08" PRIx32, Vals: magic);
8597 outs() << format(Fmt: " %7d", Vals: cputype);
8598 outs() << format(Fmt: " %10d", Vals: cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
8599 outs() << format(Fmt: " 0x%02" PRIx32,
8600 Vals: (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
8601 outs() << format(Fmt: " %10u", Vals: filetype);
8602 outs() << format(Fmt: " %5u", Vals: ncmds);
8603 outs() << format(Fmt: " %10u", Vals: sizeofcmds);
8604 outs() << format(Fmt: " 0x%08" PRIx32, Vals: flags);
8605 }
8606 outs() << "\n";
8607}
8608
8609static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
8610 StringRef SegName, uint64_t vmaddr,
8611 uint64_t vmsize, uint64_t fileoff,
8612 uint64_t filesize, uint32_t maxprot,
8613 uint32_t initprot, uint32_t nsects,
8614 uint32_t flags, uint32_t object_size,
8615 bool verbose) {
8616 uint64_t expected_cmdsize;
8617 if (cmd == MachO::LC_SEGMENT) {
8618 outs() << " cmd LC_SEGMENT\n";
8619 expected_cmdsize = nsects;
8620 expected_cmdsize *= sizeof(struct MachO::section);
8621 expected_cmdsize += sizeof(struct MachO::segment_command);
8622 } else {
8623 outs() << " cmd LC_SEGMENT_64\n";
8624 expected_cmdsize = nsects;
8625 expected_cmdsize *= sizeof(struct MachO::section_64);
8626 expected_cmdsize += sizeof(struct MachO::segment_command_64);
8627 }
8628 outs() << " cmdsize " << cmdsize;
8629 if (cmdsize != expected_cmdsize)
8630 outs() << " Inconsistent size\n";
8631 else
8632 outs() << "\n";
8633 outs() << " segname " << SegName << "\n";
8634 if (cmd == MachO::LC_SEGMENT_64) {
8635 outs() << " vmaddr " << format(Fmt: "0x%016" PRIx64, Vals: vmaddr) << "\n";
8636 outs() << " vmsize " << format(Fmt: "0x%016" PRIx64, Vals: vmsize) << "\n";
8637 } else {
8638 outs() << " vmaddr " << format(Fmt: "0x%08" PRIx64, Vals: vmaddr) << "\n";
8639 outs() << " vmsize " << format(Fmt: "0x%08" PRIx64, Vals: vmsize) << "\n";
8640 }
8641 outs() << " fileoff " << fileoff;
8642 if (fileoff > object_size)
8643 outs() << " (past end of file)\n";
8644 else
8645 outs() << "\n";
8646 outs() << " filesize " << filesize;
8647 if (fileoff + filesize > object_size)
8648 outs() << " (past end of file)\n";
8649 else
8650 outs() << "\n";
8651 if (verbose) {
8652 if ((maxprot &
8653 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8654 MachO::VM_PROT_EXECUTE)) != 0)
8655 outs() << " maxprot ?" << format(Fmt: "0x%08" PRIx32, Vals: maxprot) << "\n";
8656 else {
8657 outs() << " maxprot ";
8658 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
8659 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8660 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8661 }
8662 if ((initprot &
8663 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
8664 MachO::VM_PROT_EXECUTE)) != 0)
8665 outs() << " initprot ?" << format(Fmt: "0x%08" PRIx32, Vals: initprot) << "\n";
8666 else {
8667 outs() << " initprot ";
8668 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
8669 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
8670 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
8671 }
8672 } else {
8673 outs() << " maxprot " << format(Fmt: "0x%08" PRIx32, Vals: maxprot) << "\n";
8674 outs() << " initprot " << format(Fmt: "0x%08" PRIx32, Vals: initprot) << "\n";
8675 }
8676 outs() << " nsects " << nsects << "\n";
8677 if (verbose) {
8678 outs() << " flags";
8679 if (flags == 0)
8680 outs() << " (none)\n";
8681 else {
8682 if (flags & MachO::SG_HIGHVM) {
8683 outs() << " HIGHVM";
8684 flags &= ~MachO::SG_HIGHVM;
8685 }
8686 if (flags & MachO::SG_FVMLIB) {
8687 outs() << " FVMLIB";
8688 flags &= ~MachO::SG_FVMLIB;
8689 }
8690 if (flags & MachO::SG_NORELOC) {
8691 outs() << " NORELOC";
8692 flags &= ~MachO::SG_NORELOC;
8693 }
8694 if (flags & MachO::SG_PROTECTED_VERSION_1) {
8695 outs() << " PROTECTED_VERSION_1";
8696 flags &= ~MachO::SG_PROTECTED_VERSION_1;
8697 }
8698 if (flags & MachO::SG_READ_ONLY) {
8699 // Apple's otool prints the SG_ prefix for this flag, but not for the
8700 // others.
8701 outs() << " SG_READ_ONLY";
8702 flags &= ~MachO::SG_READ_ONLY;
8703 }
8704 if (flags)
8705 outs() << format(Fmt: " 0x%08" PRIx32, Vals: flags) << " (unknown flags)\n";
8706 else
8707 outs() << "\n";
8708 }
8709 } else {
8710 outs() << " flags " << format(Fmt: "0x%" PRIx32, Vals: flags) << "\n";
8711 }
8712}
8713
8714static void PrintSection(const char *sectname, const char *segname,
8715 uint64_t addr, uint64_t size, uint32_t offset,
8716 uint32_t align, uint32_t reloff, uint32_t nreloc,
8717 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
8718 uint32_t cmd, const char *sg_segname,
8719 uint32_t filetype, uint32_t object_size,
8720 bool verbose) {
8721 outs() << "Section\n";
8722 outs() << " sectname " << format(Fmt: "%.16s\n", Vals: sectname);
8723 outs() << " segname " << format(Fmt: "%.16s", Vals: segname);
8724 if (filetype != MachO::MH_OBJECT && strncmp(s1: sg_segname, s2: segname, n: 16) != 0)
8725 outs() << " (does not match segment)\n";
8726 else
8727 outs() << "\n";
8728 if (cmd == MachO::LC_SEGMENT_64) {
8729 outs() << " addr " << format(Fmt: "0x%016" PRIx64, Vals: addr) << "\n";
8730 outs() << " size " << format(Fmt: "0x%016" PRIx64, Vals: size);
8731 } else {
8732 outs() << " addr " << format(Fmt: "0x%08" PRIx64, Vals: addr) << "\n";
8733 outs() << " size " << format(Fmt: "0x%08" PRIx64, Vals: size);
8734 }
8735 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
8736 outs() << " (past end of file)\n";
8737 else
8738 outs() << "\n";
8739 outs() << " offset " << offset;
8740 if (offset > object_size)
8741 outs() << " (past end of file)\n";
8742 else
8743 outs() << "\n";
8744 uint32_t align_shifted = 1 << align;
8745 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
8746 outs() << " reloff " << reloff;
8747 if (reloff > object_size)
8748 outs() << " (past end of file)\n";
8749 else
8750 outs() << "\n";
8751 outs() << " nreloc " << nreloc;
8752 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
8753 outs() << " (past end of file)\n";
8754 else
8755 outs() << "\n";
8756 uint32_t section_type = flags & MachO::SECTION_TYPE;
8757 if (verbose) {
8758 outs() << " type";
8759 if (section_type == MachO::S_REGULAR)
8760 outs() << " S_REGULAR\n";
8761 else if (section_type == MachO::S_ZEROFILL)
8762 outs() << " S_ZEROFILL\n";
8763 else if (section_type == MachO::S_CSTRING_LITERALS)
8764 outs() << " S_CSTRING_LITERALS\n";
8765 else if (section_type == MachO::S_4BYTE_LITERALS)
8766 outs() << " S_4BYTE_LITERALS\n";
8767 else if (section_type == MachO::S_8BYTE_LITERALS)
8768 outs() << " S_8BYTE_LITERALS\n";
8769 else if (section_type == MachO::S_16BYTE_LITERALS)
8770 outs() << " S_16BYTE_LITERALS\n";
8771 else if (section_type == MachO::S_LITERAL_POINTERS)
8772 outs() << " S_LITERAL_POINTERS\n";
8773 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
8774 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
8775 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
8776 outs() << " S_LAZY_SYMBOL_POINTERS\n";
8777 else if (section_type == MachO::S_SYMBOL_STUBS)
8778 outs() << " S_SYMBOL_STUBS\n";
8779 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
8780 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
8781 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
8782 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
8783 else if (section_type == MachO::S_COALESCED)
8784 outs() << " S_COALESCED\n";
8785 else if (section_type == MachO::S_INTERPOSING)
8786 outs() << " S_INTERPOSING\n";
8787 else if (section_type == MachO::S_DTRACE_DOF)
8788 outs() << " S_DTRACE_DOF\n";
8789 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
8790 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
8791 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
8792 outs() << " S_THREAD_LOCAL_REGULAR\n";
8793 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
8794 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
8795 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
8796 outs() << " S_THREAD_LOCAL_VARIABLES\n";
8797 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8798 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
8799 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
8800 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
8801 else if (section_type == MachO::S_INIT_FUNC_OFFSETS)
8802 outs() << " S_INIT_FUNC_OFFSETS\n";
8803 else
8804 outs() << format(Fmt: "0x%08" PRIx32, Vals: section_type) << "\n";
8805 outs() << "attributes";
8806 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
8807 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
8808 outs() << " PURE_INSTRUCTIONS";
8809 if (section_attributes & MachO::S_ATTR_NO_TOC)
8810 outs() << " NO_TOC";
8811 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
8812 outs() << " STRIP_STATIC_SYMS";
8813 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
8814 outs() << " NO_DEAD_STRIP";
8815 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
8816 outs() << " LIVE_SUPPORT";
8817 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
8818 outs() << " SELF_MODIFYING_CODE";
8819 if (section_attributes & MachO::S_ATTR_DEBUG)
8820 outs() << " DEBUG";
8821 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
8822 outs() << " SOME_INSTRUCTIONS";
8823 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
8824 outs() << " EXT_RELOC";
8825 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
8826 outs() << " LOC_RELOC";
8827 if (section_attributes == 0)
8828 outs() << " (none)";
8829 outs() << "\n";
8830 } else
8831 outs() << " flags " << format(Fmt: "0x%08" PRIx32, Vals: flags) << "\n";
8832 outs() << " reserved1 " << reserved1;
8833 if (section_type == MachO::S_SYMBOL_STUBS ||
8834 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
8835 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
8836 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
8837 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
8838 outs() << " (index into indirect symbol table)\n";
8839 else
8840 outs() << "\n";
8841 outs() << " reserved2 " << reserved2;
8842 if (section_type == MachO::S_SYMBOL_STUBS)
8843 outs() << " (size of stubs)\n";
8844 else
8845 outs() << "\n";
8846}
8847
8848static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
8849 uint32_t object_size) {
8850 outs() << " cmd LC_SYMTAB\n";
8851 outs() << " cmdsize " << st.cmdsize;
8852 if (st.cmdsize != sizeof(struct MachO::symtab_command))
8853 outs() << " Incorrect size\n";
8854 else
8855 outs() << "\n";
8856 outs() << " symoff " << st.symoff;
8857 if (st.symoff > object_size)
8858 outs() << " (past end of file)\n";
8859 else
8860 outs() << "\n";
8861 outs() << " nsyms " << st.nsyms;
8862 uint64_t big_size;
8863 if (Is64Bit) {
8864 big_size = st.nsyms;
8865 big_size *= sizeof(struct MachO::nlist_64);
8866 big_size += st.symoff;
8867 if (big_size > object_size)
8868 outs() << " (past end of file)\n";
8869 else
8870 outs() << "\n";
8871 } else {
8872 big_size = st.nsyms;
8873 big_size *= sizeof(struct MachO::nlist);
8874 big_size += st.symoff;
8875 if (big_size > object_size)
8876 outs() << " (past end of file)\n";
8877 else
8878 outs() << "\n";
8879 }
8880 outs() << " stroff " << st.stroff;
8881 if (st.stroff > object_size)
8882 outs() << " (past end of file)\n";
8883 else
8884 outs() << "\n";
8885 outs() << " strsize " << st.strsize;
8886 big_size = st.stroff;
8887 big_size += st.strsize;
8888 if (big_size > object_size)
8889 outs() << " (past end of file)\n";
8890 else
8891 outs() << "\n";
8892}
8893
8894static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
8895 uint32_t nsyms, uint32_t object_size,
8896 bool Is64Bit) {
8897 outs() << " cmd LC_DYSYMTAB\n";
8898 outs() << " cmdsize " << dyst.cmdsize;
8899 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
8900 outs() << " Incorrect size\n";
8901 else
8902 outs() << "\n";
8903 outs() << " ilocalsym " << dyst.ilocalsym;
8904 if (dyst.ilocalsym > nsyms)
8905 outs() << " (greater than the number of symbols)\n";
8906 else
8907 outs() << "\n";
8908 outs() << " nlocalsym " << dyst.nlocalsym;
8909 uint64_t big_size;
8910 big_size = dyst.ilocalsym;
8911 big_size += dyst.nlocalsym;
8912 if (big_size > nsyms)
8913 outs() << " (past the end of the symbol table)\n";
8914 else
8915 outs() << "\n";
8916 outs() << " iextdefsym " << dyst.iextdefsym;
8917 if (dyst.iextdefsym > nsyms)
8918 outs() << " (greater than the number of symbols)\n";
8919 else
8920 outs() << "\n";
8921 outs() << " nextdefsym " << dyst.nextdefsym;
8922 big_size = dyst.iextdefsym;
8923 big_size += dyst.nextdefsym;
8924 if (big_size > nsyms)
8925 outs() << " (past the end of the symbol table)\n";
8926 else
8927 outs() << "\n";
8928 outs() << " iundefsym " << dyst.iundefsym;
8929 if (dyst.iundefsym > nsyms)
8930 outs() << " (greater than the number of symbols)\n";
8931 else
8932 outs() << "\n";
8933 outs() << " nundefsym " << dyst.nundefsym;
8934 big_size = dyst.iundefsym;
8935 big_size += dyst.nundefsym;
8936 if (big_size > nsyms)
8937 outs() << " (past the end of the symbol table)\n";
8938 else
8939 outs() << "\n";
8940 outs() << " tocoff " << dyst.tocoff;
8941 if (dyst.tocoff > object_size)
8942 outs() << " (past end of file)\n";
8943 else
8944 outs() << "\n";
8945 outs() << " ntoc " << dyst.ntoc;
8946 big_size = dyst.ntoc;
8947 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8948 big_size += dyst.tocoff;
8949 if (big_size > object_size)
8950 outs() << " (past end of file)\n";
8951 else
8952 outs() << "\n";
8953 outs() << " modtaboff " << dyst.modtaboff;
8954 if (dyst.modtaboff > object_size)
8955 outs() << " (past end of file)\n";
8956 else
8957 outs() << "\n";
8958 outs() << " nmodtab " << dyst.nmodtab;
8959 uint64_t modtabend;
8960 if (Is64Bit) {
8961 modtabend = dyst.nmodtab;
8962 modtabend *= sizeof(struct MachO::dylib_module_64);
8963 modtabend += dyst.modtaboff;
8964 } else {
8965 modtabend = dyst.nmodtab;
8966 modtabend *= sizeof(struct MachO::dylib_module);
8967 modtabend += dyst.modtaboff;
8968 }
8969 if (modtabend > object_size)
8970 outs() << " (past end of file)\n";
8971 else
8972 outs() << "\n";
8973 outs() << " extrefsymoff " << dyst.extrefsymoff;
8974 if (dyst.extrefsymoff > object_size)
8975 outs() << " (past end of file)\n";
8976 else
8977 outs() << "\n";
8978 outs() << " nextrefsyms " << dyst.nextrefsyms;
8979 big_size = dyst.nextrefsyms;
8980 big_size *= sizeof(struct MachO::dylib_reference);
8981 big_size += dyst.extrefsymoff;
8982 if (big_size > object_size)
8983 outs() << " (past end of file)\n";
8984 else
8985 outs() << "\n";
8986 outs() << " indirectsymoff " << dyst.indirectsymoff;
8987 if (dyst.indirectsymoff > object_size)
8988 outs() << " (past end of file)\n";
8989 else
8990 outs() << "\n";
8991 outs() << " nindirectsyms " << dyst.nindirectsyms;
8992 big_size = dyst.nindirectsyms;
8993 big_size *= sizeof(uint32_t);
8994 big_size += dyst.indirectsymoff;
8995 if (big_size > object_size)
8996 outs() << " (past end of file)\n";
8997 else
8998 outs() << "\n";
8999 outs() << " extreloff " << dyst.extreloff;
9000 if (dyst.extreloff > object_size)
9001 outs() << " (past end of file)\n";
9002 else
9003 outs() << "\n";
9004 outs() << " nextrel " << dyst.nextrel;
9005 big_size = dyst.nextrel;
9006 big_size *= sizeof(struct MachO::relocation_info);
9007 big_size += dyst.extreloff;
9008 if (big_size > object_size)
9009 outs() << " (past end of file)\n";
9010 else
9011 outs() << "\n";
9012 outs() << " locreloff " << dyst.locreloff;
9013 if (dyst.locreloff > object_size)
9014 outs() << " (past end of file)\n";
9015 else
9016 outs() << "\n";
9017 outs() << " nlocrel " << dyst.nlocrel;
9018 big_size = dyst.nlocrel;
9019 big_size *= sizeof(struct MachO::relocation_info);
9020 big_size += dyst.locreloff;
9021 if (big_size > object_size)
9022 outs() << " (past end of file)\n";
9023 else
9024 outs() << "\n";
9025}
9026
9027static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
9028 uint32_t object_size) {
9029 if (dc.cmd == MachO::LC_DYLD_INFO)
9030 outs() << " cmd LC_DYLD_INFO\n";
9031 else
9032 outs() << " cmd LC_DYLD_INFO_ONLY\n";
9033 outs() << " cmdsize " << dc.cmdsize;
9034 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
9035 outs() << " Incorrect size\n";
9036 else
9037 outs() << "\n";
9038 outs() << " rebase_off " << dc.rebase_off;
9039 if (dc.rebase_off > object_size)
9040 outs() << " (past end of file)\n";
9041 else
9042 outs() << "\n";
9043 outs() << " rebase_size " << dc.rebase_size;
9044 uint64_t big_size;
9045 big_size = dc.rebase_off;
9046 big_size += dc.rebase_size;
9047 if (big_size > object_size)
9048 outs() << " (past end of file)\n";
9049 else
9050 outs() << "\n";
9051 outs() << " bind_off " << dc.bind_off;
9052 if (dc.bind_off > object_size)
9053 outs() << " (past end of file)\n";
9054 else
9055 outs() << "\n";
9056 outs() << " bind_size " << dc.bind_size;
9057 big_size = dc.bind_off;
9058 big_size += dc.bind_size;
9059 if (big_size > object_size)
9060 outs() << " (past end of file)\n";
9061 else
9062 outs() << "\n";
9063 outs() << " weak_bind_off " << dc.weak_bind_off;
9064 if (dc.weak_bind_off > object_size)
9065 outs() << " (past end of file)\n";
9066 else
9067 outs() << "\n";
9068 outs() << " weak_bind_size " << dc.weak_bind_size;
9069 big_size = dc.weak_bind_off;
9070 big_size += dc.weak_bind_size;
9071 if (big_size > object_size)
9072 outs() << " (past end of file)\n";
9073 else
9074 outs() << "\n";
9075 outs() << " lazy_bind_off " << dc.lazy_bind_off;
9076 if (dc.lazy_bind_off > object_size)
9077 outs() << " (past end of file)\n";
9078 else
9079 outs() << "\n";
9080 outs() << " lazy_bind_size " << dc.lazy_bind_size;
9081 big_size = dc.lazy_bind_off;
9082 big_size += dc.lazy_bind_size;
9083 if (big_size > object_size)
9084 outs() << " (past end of file)\n";
9085 else
9086 outs() << "\n";
9087 outs() << " export_off " << dc.export_off;
9088 if (dc.export_off > object_size)
9089 outs() << " (past end of file)\n";
9090 else
9091 outs() << "\n";
9092 outs() << " export_size " << dc.export_size;
9093 big_size = dc.export_off;
9094 big_size += dc.export_size;
9095 if (big_size > object_size)
9096 outs() << " (past end of file)\n";
9097 else
9098 outs() << "\n";
9099}
9100
9101static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
9102 const char *Ptr) {
9103 if (dyld.cmd == MachO::LC_ID_DYLINKER)
9104 outs() << " cmd LC_ID_DYLINKER\n";
9105 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
9106 outs() << " cmd LC_LOAD_DYLINKER\n";
9107 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
9108 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
9109 else
9110 outs() << " cmd ?(" << dyld.cmd << ")\n";
9111 outs() << " cmdsize " << dyld.cmdsize;
9112 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
9113 outs() << " Incorrect size\n";
9114 else
9115 outs() << "\n";
9116 if (dyld.name >= dyld.cmdsize)
9117 outs() << " name ?(bad offset " << dyld.name << ")\n";
9118 else {
9119 const char *P = Ptr + dyld.name;
9120 outs() << " name " << P << " (offset " << dyld.name << ")\n";
9121 }
9122}
9123
9124static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
9125 outs() << " cmd LC_UUID\n";
9126 outs() << " cmdsize " << uuid.cmdsize;
9127 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
9128 outs() << " Incorrect size\n";
9129 else
9130 outs() << "\n";
9131 outs() << " uuid ";
9132 for (int i = 0; i < 16; ++i) {
9133 outs() << format(Fmt: "%02" PRIX32, Vals: uuid.uuid[i]);
9134 if (i == 3 || i == 5 || i == 7 || i == 9)
9135 outs() << "-";
9136 }
9137 outs() << "\n";
9138}
9139
9140static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
9141 outs() << " cmd LC_RPATH\n";
9142 outs() << " cmdsize " << rpath.cmdsize;
9143 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
9144 outs() << " Incorrect size\n";
9145 else
9146 outs() << "\n";
9147 if (rpath.path >= rpath.cmdsize)
9148 outs() << " path ?(bad offset " << rpath.path << ")\n";
9149 else {
9150 const char *P = Ptr + rpath.path;
9151 outs() << " path " << P << " (offset " << rpath.path << ")\n";
9152 }
9153}
9154
9155static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
9156 StringRef LoadCmdName;
9157 switch (vd.cmd) {
9158 case MachO::LC_VERSION_MIN_MACOSX:
9159 LoadCmdName = "LC_VERSION_MIN_MACOSX";
9160 break;
9161 case MachO::LC_VERSION_MIN_IPHONEOS:
9162 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
9163 break;
9164 case MachO::LC_VERSION_MIN_TVOS:
9165 LoadCmdName = "LC_VERSION_MIN_TVOS";
9166 break;
9167 case MachO::LC_VERSION_MIN_WATCHOS:
9168 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
9169 break;
9170 default:
9171 llvm_unreachable("Unknown version min load command");
9172 }
9173
9174 outs() << " cmd " << LoadCmdName << '\n';
9175 outs() << " cmdsize " << vd.cmdsize;
9176 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
9177 outs() << " Incorrect size\n";
9178 else
9179 outs() << "\n";
9180 outs() << " version "
9181 << MachOObjectFile::getVersionMinMajor(C&: vd, SDK: false) << "."
9182 << MachOObjectFile::getVersionMinMinor(C&: vd, SDK: false);
9183 uint32_t Update = MachOObjectFile::getVersionMinUpdate(C&: vd, SDK: false);
9184 if (Update != 0)
9185 outs() << "." << Update;
9186 outs() << "\n";
9187 if (vd.sdk == 0)
9188 outs() << " sdk n/a";
9189 else {
9190 outs() << " sdk "
9191 << MachOObjectFile::getVersionMinMajor(C&: vd, SDK: true) << "."
9192 << MachOObjectFile::getVersionMinMinor(C&: vd, SDK: true);
9193 }
9194 Update = MachOObjectFile::getVersionMinUpdate(C&: vd, SDK: true);
9195 if (Update != 0)
9196 outs() << "." << Update;
9197 outs() << "\n";
9198}
9199
9200static void PrintNoteLoadCommand(MachO::note_command Nt) {
9201 outs() << " cmd LC_NOTE\n";
9202 outs() << " cmdsize " << Nt.cmdsize;
9203 if (Nt.cmdsize != sizeof(struct MachO::note_command))
9204 outs() << " Incorrect size\n";
9205 else
9206 outs() << "\n";
9207 const char *d = Nt.data_owner;
9208 outs() << "data_owner " << format(Fmt: "%.16s\n", Vals: d);
9209 outs() << " offset " << Nt.offset << "\n";
9210 outs() << " size " << Nt.size << "\n";
9211}
9212
9213static void PrintBuildToolVersion(MachO::build_tool_version bv, bool verbose) {
9214 outs() << " tool ";
9215 if (verbose)
9216 outs() << MachOObjectFile::getBuildTool(tools: bv.tool);
9217 else
9218 outs() << bv.tool;
9219 outs() << "\n";
9220 outs() << " version " << MachOObjectFile::getVersionString(version: bv.version)
9221 << "\n";
9222}
9223
9224static void PrintBuildVersionLoadCommand(const MachOObjectFile *obj,
9225 MachO::build_version_command bd,
9226 bool verbose) {
9227 outs() << " cmd LC_BUILD_VERSION\n";
9228 outs() << " cmdsize " << bd.cmdsize;
9229 if (bd.cmdsize !=
9230 sizeof(struct MachO::build_version_command) +
9231 bd.ntools * sizeof(struct MachO::build_tool_version))
9232 outs() << " Incorrect size\n";
9233 else
9234 outs() << "\n";
9235 outs() << " platform ";
9236 if (verbose)
9237 outs() << MachOObjectFile::getBuildPlatform(platform: bd.platform);
9238 else
9239 outs() << bd.platform;
9240 outs() << "\n";
9241 if (bd.sdk)
9242 outs() << " sdk " << MachOObjectFile::getVersionString(version: bd.sdk)
9243 << "\n";
9244 else
9245 outs() << " sdk n/a\n";
9246 outs() << " minos " << MachOObjectFile::getVersionString(version: bd.minos)
9247 << "\n";
9248 outs() << " ntools " << bd.ntools << "\n";
9249 for (unsigned i = 0; i < bd.ntools; ++i) {
9250 MachO::build_tool_version bv = obj->getBuildToolVersion(index: i);
9251 PrintBuildToolVersion(bv, verbose);
9252 }
9253}
9254
9255static void PrintSourceVersionCommand(MachO::source_version_command sd) {
9256 outs() << " cmd LC_SOURCE_VERSION\n";
9257 outs() << " cmdsize " << sd.cmdsize;
9258 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
9259 outs() << " Incorrect size\n";
9260 else
9261 outs() << "\n";
9262 uint64_t a = (sd.version >> 40) & 0xffffff;
9263 uint64_t b = (sd.version >> 30) & 0x3ff;
9264 uint64_t c = (sd.version >> 20) & 0x3ff;
9265 uint64_t d = (sd.version >> 10) & 0x3ff;
9266 uint64_t e = sd.version & 0x3ff;
9267 outs() << " version " << a << "." << b;
9268 if (e != 0)
9269 outs() << "." << c << "." << d << "." << e;
9270 else if (d != 0)
9271 outs() << "." << c << "." << d;
9272 else if (c != 0)
9273 outs() << "." << c;
9274 outs() << "\n";
9275}
9276
9277static void PrintEntryPointCommand(MachO::entry_point_command ep) {
9278 outs() << " cmd LC_MAIN\n";
9279 outs() << " cmdsize " << ep.cmdsize;
9280 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
9281 outs() << " Incorrect size\n";
9282 else
9283 outs() << "\n";
9284 outs() << " entryoff " << ep.entryoff << "\n";
9285 outs() << " stacksize " << ep.stacksize << "\n";
9286}
9287
9288static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
9289 uint32_t object_size) {
9290 outs() << " cmd LC_ENCRYPTION_INFO\n";
9291 outs() << " cmdsize " << ec.cmdsize;
9292 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
9293 outs() << " Incorrect size\n";
9294 else
9295 outs() << "\n";
9296 outs() << " cryptoff " << ec.cryptoff;
9297 if (ec.cryptoff > object_size)
9298 outs() << " (past end of file)\n";
9299 else
9300 outs() << "\n";
9301 outs() << " cryptsize " << ec.cryptsize;
9302 if (ec.cryptsize > object_size)
9303 outs() << " (past end of file)\n";
9304 else
9305 outs() << "\n";
9306 outs() << " cryptid " << ec.cryptid << "\n";
9307}
9308
9309static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
9310 uint32_t object_size) {
9311 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
9312 outs() << " cmdsize " << ec.cmdsize;
9313 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
9314 outs() << " Incorrect size\n";
9315 else
9316 outs() << "\n";
9317 outs() << " cryptoff " << ec.cryptoff;
9318 if (ec.cryptoff > object_size)
9319 outs() << " (past end of file)\n";
9320 else
9321 outs() << "\n";
9322 outs() << " cryptsize " << ec.cryptsize;
9323 if (ec.cryptsize > object_size)
9324 outs() << " (past end of file)\n";
9325 else
9326 outs() << "\n";
9327 outs() << " cryptid " << ec.cryptid << "\n";
9328 outs() << " pad " << ec.pad << "\n";
9329}
9330
9331static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
9332 const char *Ptr) {
9333 outs() << " cmd LC_LINKER_OPTION\n";
9334 outs() << " cmdsize " << lo.cmdsize;
9335 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
9336 outs() << " Incorrect size\n";
9337 else
9338 outs() << "\n";
9339 outs() << " count " << lo.count << "\n";
9340 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
9341 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
9342 uint32_t i = 0;
9343 while (left > 0) {
9344 while (*string == '\0' && left > 0) {
9345 string++;
9346 left--;
9347 }
9348 if (left > 0) {
9349 i++;
9350 outs() << " string #" << i << " " << format(Fmt: "%.*s\n", Vals: left, Vals: string);
9351 uint32_t NullPos = StringRef(string, left).find(C: '\0');
9352 uint32_t len = std::min(a: NullPos, b: left) + 1;
9353 string += len;
9354 left -= len;
9355 }
9356 }
9357 if (lo.count != i)
9358 outs() << " count " << lo.count << " does not match number of strings "
9359 << i << "\n";
9360}
9361
9362static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
9363 const char *Ptr) {
9364 outs() << " cmd LC_SUB_FRAMEWORK\n";
9365 outs() << " cmdsize " << sub.cmdsize;
9366 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
9367 outs() << " Incorrect size\n";
9368 else
9369 outs() << "\n";
9370 if (sub.umbrella < sub.cmdsize) {
9371 const char *P = Ptr + sub.umbrella;
9372 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
9373 } else {
9374 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
9375 }
9376}
9377
9378static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
9379 const char *Ptr) {
9380 outs() << " cmd LC_SUB_UMBRELLA\n";
9381 outs() << " cmdsize " << sub.cmdsize;
9382 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
9383 outs() << " Incorrect size\n";
9384 else
9385 outs() << "\n";
9386 if (sub.sub_umbrella < sub.cmdsize) {
9387 const char *P = Ptr + sub.sub_umbrella;
9388 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
9389 } else {
9390 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
9391 }
9392}
9393
9394static void PrintSubLibraryCommand(MachO::sub_library_command sub,
9395 const char *Ptr) {
9396 outs() << " cmd LC_SUB_LIBRARY\n";
9397 outs() << " cmdsize " << sub.cmdsize;
9398 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
9399 outs() << " Incorrect size\n";
9400 else
9401 outs() << "\n";
9402 if (sub.sub_library < sub.cmdsize) {
9403 const char *P = Ptr + sub.sub_library;
9404 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
9405 } else {
9406 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
9407 }
9408}
9409
9410static void PrintSubClientCommand(MachO::sub_client_command sub,
9411 const char *Ptr) {
9412 outs() << " cmd LC_SUB_CLIENT\n";
9413 outs() << " cmdsize " << sub.cmdsize;
9414 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
9415 outs() << " Incorrect size\n";
9416 else
9417 outs() << "\n";
9418 if (sub.client < sub.cmdsize) {
9419 const char *P = Ptr + sub.client;
9420 outs() << " client " << P << " (offset " << sub.client << ")\n";
9421 } else {
9422 outs() << " client ?(bad offset " << sub.client << ")\n";
9423 }
9424}
9425
9426static void PrintRoutinesCommand(MachO::routines_command r) {
9427 outs() << " cmd LC_ROUTINES\n";
9428 outs() << " cmdsize " << r.cmdsize;
9429 if (r.cmdsize != sizeof(struct MachO::routines_command))
9430 outs() << " Incorrect size\n";
9431 else
9432 outs() << "\n";
9433 outs() << " init_address " << format(Fmt: "0x%08" PRIx32, Vals: r.init_address) << "\n";
9434 outs() << " init_module " << r.init_module << "\n";
9435 outs() << " reserved1 " << r.reserved1 << "\n";
9436 outs() << " reserved2 " << r.reserved2 << "\n";
9437 outs() << " reserved3 " << r.reserved3 << "\n";
9438 outs() << " reserved4 " << r.reserved4 << "\n";
9439 outs() << " reserved5 " << r.reserved5 << "\n";
9440 outs() << " reserved6 " << r.reserved6 << "\n";
9441}
9442
9443static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
9444 outs() << " cmd LC_ROUTINES_64\n";
9445 outs() << " cmdsize " << r.cmdsize;
9446 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
9447 outs() << " Incorrect size\n";
9448 else
9449 outs() << "\n";
9450 outs() << " init_address " << format(Fmt: "0x%016" PRIx64, Vals: r.init_address) << "\n";
9451 outs() << " init_module " << r.init_module << "\n";
9452 outs() << " reserved1 " << r.reserved1 << "\n";
9453 outs() << " reserved2 " << r.reserved2 << "\n";
9454 outs() << " reserved3 " << r.reserved3 << "\n";
9455 outs() << " reserved4 " << r.reserved4 << "\n";
9456 outs() << " reserved5 " << r.reserved5 << "\n";
9457 outs() << " reserved6 " << r.reserved6 << "\n";
9458}
9459
9460static void Print_x86_thread_state32_t(MachO::x86_thread_state32_t &cpu32) {
9461 outs() << "\t eax " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eax);
9462 outs() << " ebx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ebx);
9463 outs() << " ecx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ecx);
9464 outs() << " edx " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.edx) << "\n";
9465 outs() << "\t edi " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.edi);
9466 outs() << " esi " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.esi);
9467 outs() << " ebp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ebp);
9468 outs() << " esp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.esp) << "\n";
9469 outs() << "\t ss " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ss);
9470 outs() << " eflags " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eflags);
9471 outs() << " eip " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.eip);
9472 outs() << " cs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.cs) << "\n";
9473 outs() << "\t ds " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.ds);
9474 outs() << " es " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.es);
9475 outs() << " fs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.fs);
9476 outs() << " gs " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.gs) << "\n";
9477}
9478
9479static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
9480 outs() << " rax " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rax);
9481 outs() << " rbx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rbx);
9482 outs() << " rcx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rcx) << "\n";
9483 outs() << " rdx " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rdx);
9484 outs() << " rdi " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rdi);
9485 outs() << " rsi " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rsi) << "\n";
9486 outs() << " rbp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rbp);
9487 outs() << " rsp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rsp);
9488 outs() << " r8 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r8) << "\n";
9489 outs() << " r9 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r9);
9490 outs() << " r10 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r10);
9491 outs() << " r11 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r11) << "\n";
9492 outs() << " r12 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r12);
9493 outs() << " r13 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r13);
9494 outs() << " r14 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r14) << "\n";
9495 outs() << " r15 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.r15);
9496 outs() << " rip " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rip) << "\n";
9497 outs() << "rflags " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.rflags);
9498 outs() << " cs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.cs);
9499 outs() << " fs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.fs) << "\n";
9500 outs() << " gs " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.gs) << "\n";
9501}
9502
9503static void Print_mmst_reg(MachO::mmst_reg_t &r) {
9504 uint32_t f;
9505 outs() << "\t mmst_reg ";
9506 for (f = 0; f < 10; f++)
9507 outs() << format(Fmt: "%02" PRIx32, Vals: (r.mmst_reg[f] & 0xff)) << " ";
9508 outs() << "\n";
9509 outs() << "\t mmst_rsrv ";
9510 for (f = 0; f < 6; f++)
9511 outs() << format(Fmt: "%02" PRIx32, Vals: (r.mmst_rsrv[f] & 0xff)) << " ";
9512 outs() << "\n";
9513}
9514
9515static void Print_xmm_reg(MachO::xmm_reg_t &r) {
9516 uint32_t f;
9517 outs() << "\t xmm_reg ";
9518 for (f = 0; f < 16; f++)
9519 outs() << format(Fmt: "%02" PRIx32, Vals: (r.xmm_reg[f] & 0xff)) << " ";
9520 outs() << "\n";
9521}
9522
9523static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
9524 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
9525 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
9526 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
9527 outs() << " denorm " << fpu.fpu_fcw.denorm;
9528 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
9529 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
9530 outs() << " undfl " << fpu.fpu_fcw.undfl;
9531 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
9532 outs() << "\t\t pc ";
9533 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
9534 outs() << "FP_PREC_24B ";
9535 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
9536 outs() << "FP_PREC_53B ";
9537 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
9538 outs() << "FP_PREC_64B ";
9539 else
9540 outs() << fpu.fpu_fcw.pc << " ";
9541 outs() << "rc ";
9542 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
9543 outs() << "FP_RND_NEAR ";
9544 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
9545 outs() << "FP_RND_DOWN ";
9546 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
9547 outs() << "FP_RND_UP ";
9548 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
9549 outs() << "FP_CHOP ";
9550 outs() << "\n";
9551 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
9552 outs() << " denorm " << fpu.fpu_fsw.denorm;
9553 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
9554 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
9555 outs() << " undfl " << fpu.fpu_fsw.undfl;
9556 outs() << " precis " << fpu.fpu_fsw.precis;
9557 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
9558 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
9559 outs() << " c0 " << fpu.fpu_fsw.c0;
9560 outs() << " c1 " << fpu.fpu_fsw.c1;
9561 outs() << " c2 " << fpu.fpu_fsw.c2;
9562 outs() << " tos " << fpu.fpu_fsw.tos;
9563 outs() << " c3 " << fpu.fpu_fsw.c3;
9564 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
9565 outs() << "\t fpu_ftw " << format(Fmt: "0x%02" PRIx32, Vals: fpu.fpu_ftw);
9566 outs() << " fpu_rsrv1 " << format(Fmt: "0x%02" PRIx32, Vals: fpu.fpu_rsrv1);
9567 outs() << " fpu_fop " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_fop);
9568 outs() << " fpu_ip " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_ip) << "\n";
9569 outs() << "\t fpu_cs " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_cs);
9570 outs() << " fpu_rsrv2 " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_rsrv2);
9571 outs() << " fpu_dp " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_dp);
9572 outs() << " fpu_ds " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_ds) << "\n";
9573 outs() << "\t fpu_rsrv3 " << format(Fmt: "0x%04" PRIx32, Vals: fpu.fpu_rsrv3);
9574 outs() << " fpu_mxcsr " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_mxcsr);
9575 outs() << " fpu_mxcsrmask " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_mxcsrmask);
9576 outs() << "\n";
9577 outs() << "\t fpu_stmm0:\n";
9578 Print_mmst_reg(r&: fpu.fpu_stmm0);
9579 outs() << "\t fpu_stmm1:\n";
9580 Print_mmst_reg(r&: fpu.fpu_stmm1);
9581 outs() << "\t fpu_stmm2:\n";
9582 Print_mmst_reg(r&: fpu.fpu_stmm2);
9583 outs() << "\t fpu_stmm3:\n";
9584 Print_mmst_reg(r&: fpu.fpu_stmm3);
9585 outs() << "\t fpu_stmm4:\n";
9586 Print_mmst_reg(r&: fpu.fpu_stmm4);
9587 outs() << "\t fpu_stmm5:\n";
9588 Print_mmst_reg(r&: fpu.fpu_stmm5);
9589 outs() << "\t fpu_stmm6:\n";
9590 Print_mmst_reg(r&: fpu.fpu_stmm6);
9591 outs() << "\t fpu_stmm7:\n";
9592 Print_mmst_reg(r&: fpu.fpu_stmm7);
9593 outs() << "\t fpu_xmm0:\n";
9594 Print_xmm_reg(r&: fpu.fpu_xmm0);
9595 outs() << "\t fpu_xmm1:\n";
9596 Print_xmm_reg(r&: fpu.fpu_xmm1);
9597 outs() << "\t fpu_xmm2:\n";
9598 Print_xmm_reg(r&: fpu.fpu_xmm2);
9599 outs() << "\t fpu_xmm3:\n";
9600 Print_xmm_reg(r&: fpu.fpu_xmm3);
9601 outs() << "\t fpu_xmm4:\n";
9602 Print_xmm_reg(r&: fpu.fpu_xmm4);
9603 outs() << "\t fpu_xmm5:\n";
9604 Print_xmm_reg(r&: fpu.fpu_xmm5);
9605 outs() << "\t fpu_xmm6:\n";
9606 Print_xmm_reg(r&: fpu.fpu_xmm6);
9607 outs() << "\t fpu_xmm7:\n";
9608 Print_xmm_reg(r&: fpu.fpu_xmm7);
9609 outs() << "\t fpu_xmm8:\n";
9610 Print_xmm_reg(r&: fpu.fpu_xmm8);
9611 outs() << "\t fpu_xmm9:\n";
9612 Print_xmm_reg(r&: fpu.fpu_xmm9);
9613 outs() << "\t fpu_xmm10:\n";
9614 Print_xmm_reg(r&: fpu.fpu_xmm10);
9615 outs() << "\t fpu_xmm11:\n";
9616 Print_xmm_reg(r&: fpu.fpu_xmm11);
9617 outs() << "\t fpu_xmm12:\n";
9618 Print_xmm_reg(r&: fpu.fpu_xmm12);
9619 outs() << "\t fpu_xmm13:\n";
9620 Print_xmm_reg(r&: fpu.fpu_xmm13);
9621 outs() << "\t fpu_xmm14:\n";
9622 Print_xmm_reg(r&: fpu.fpu_xmm14);
9623 outs() << "\t fpu_xmm15:\n";
9624 Print_xmm_reg(r&: fpu.fpu_xmm15);
9625 outs() << "\t fpu_rsrv4:\n";
9626 for (uint32_t f = 0; f < 6; f++) {
9627 outs() << "\t ";
9628 for (uint32_t g = 0; g < 16; g++)
9629 outs() << format(Fmt: "%02" PRIx32, Vals: fpu.fpu_rsrv4[f * g]) << " ";
9630 outs() << "\n";
9631 }
9632 outs() << "\t fpu_reserved1 " << format(Fmt: "0x%08" PRIx32, Vals: fpu.fpu_reserved1);
9633 outs() << "\n";
9634}
9635
9636static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
9637 outs() << "\t trapno " << format(Fmt: "0x%08" PRIx32, Vals: exc64.trapno);
9638 outs() << " err " << format(Fmt: "0x%08" PRIx32, Vals: exc64.err);
9639 outs() << " faultvaddr " << format(Fmt: "0x%016" PRIx64, Vals: exc64.faultvaddr) << "\n";
9640}
9641
9642static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
9643 outs() << "\t r0 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[0]);
9644 outs() << " r1 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[1]);
9645 outs() << " r2 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[2]);
9646 outs() << " r3 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[3]) << "\n";
9647 outs() << "\t r4 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[4]);
9648 outs() << " r5 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[5]);
9649 outs() << " r6 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[6]);
9650 outs() << " r7 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[7]) << "\n";
9651 outs() << "\t r8 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[8]);
9652 outs() << " r9 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[9]);
9653 outs() << " r10 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[10]);
9654 outs() << " r11 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[11]) << "\n";
9655 outs() << "\t r12 " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.r[12]);
9656 outs() << " sp " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.sp);
9657 outs() << " lr " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.lr);
9658 outs() << " pc " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.pc) << "\n";
9659 outs() << "\t cpsr " << format(Fmt: "0x%08" PRIx32, Vals: cpu32.cpsr) << "\n";
9660}
9661
9662static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
9663 outs() << "\t x0 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[0]);
9664 outs() << " x1 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[1]);
9665 outs() << " x2 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[2]) << "\n";
9666 outs() << "\t x3 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[3]);
9667 outs() << " x4 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[4]);
9668 outs() << " x5 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[5]) << "\n";
9669 outs() << "\t x6 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[6]);
9670 outs() << " x7 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[7]);
9671 outs() << " x8 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[8]) << "\n";
9672 outs() << "\t x9 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[9]);
9673 outs() << " x10 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[10]);
9674 outs() << " x11 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[11]) << "\n";
9675 outs() << "\t x12 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[12]);
9676 outs() << " x13 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[13]);
9677 outs() << " x14 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[14]) << "\n";
9678 outs() << "\t x15 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[15]);
9679 outs() << " x16 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[16]);
9680 outs() << " x17 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[17]) << "\n";
9681 outs() << "\t x18 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[18]);
9682 outs() << " x19 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[19]);
9683 outs() << " x20 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[20]) << "\n";
9684 outs() << "\t x21 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[21]);
9685 outs() << " x22 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[22]);
9686 outs() << " x23 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[23]) << "\n";
9687 outs() << "\t x24 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[24]);
9688 outs() << " x25 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[25]);
9689 outs() << " x26 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[26]) << "\n";
9690 outs() << "\t x27 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[27]);
9691 outs() << " x28 " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.x[28]);
9692 outs() << " fp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.fp) << "\n";
9693 outs() << "\t lr " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.lr);
9694 outs() << " sp " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.sp);
9695 outs() << " pc " << format(Fmt: "0x%016" PRIx64, Vals: cpu64.pc) << "\n";
9696 outs() << "\t cpsr " << format(Fmt: "0x%08" PRIx32, Vals: cpu64.cpsr) << "\n";
9697}
9698
9699static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
9700 bool isLittleEndian, uint32_t cputype) {
9701 if (t.cmd == MachO::LC_THREAD)
9702 outs() << " cmd LC_THREAD\n";
9703 else if (t.cmd == MachO::LC_UNIXTHREAD)
9704 outs() << " cmd LC_UNIXTHREAD\n";
9705 else
9706 outs() << " cmd " << t.cmd << " (unknown)\n";
9707 outs() << " cmdsize " << t.cmdsize;
9708 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
9709 outs() << " Incorrect size\n";
9710 else
9711 outs() << "\n";
9712
9713 const char *begin = Ptr + sizeof(struct MachO::thread_command);
9714 const char *end = Ptr + t.cmdsize;
9715 uint32_t flavor, count, left;
9716 if (cputype == MachO::CPU_TYPE_I386) {
9717 while (begin < end) {
9718 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9719 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9720 begin += sizeof(uint32_t);
9721 } else {
9722 flavor = 0;
9723 begin = end;
9724 }
9725 if (isLittleEndian != sys::IsLittleEndianHost)
9726 sys::swapByteOrder(Value&: flavor);
9727 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9728 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9729 begin += sizeof(uint32_t);
9730 } else {
9731 count = 0;
9732 begin = end;
9733 }
9734 if (isLittleEndian != sys::IsLittleEndianHost)
9735 sys::swapByteOrder(Value&: count);
9736 if (flavor == MachO::x86_THREAD_STATE32) {
9737 outs() << " flavor i386_THREAD_STATE\n";
9738 if (count == MachO::x86_THREAD_STATE32_COUNT)
9739 outs() << " count i386_THREAD_STATE_COUNT\n";
9740 else
9741 outs() << " count " << count
9742 << " (not x86_THREAD_STATE32_COUNT)\n";
9743 MachO::x86_thread_state32_t cpu32;
9744 left = end - begin;
9745 if (left >= sizeof(MachO::x86_thread_state32_t)) {
9746 memcpy(dest: &cpu32, src: begin, n: sizeof(MachO::x86_thread_state32_t));
9747 begin += sizeof(MachO::x86_thread_state32_t);
9748 } else {
9749 memset(s: &cpu32, c: '\0', n: sizeof(MachO::x86_thread_state32_t));
9750 memcpy(dest: &cpu32, src: begin, n: left);
9751 begin += left;
9752 }
9753 if (isLittleEndian != sys::IsLittleEndianHost)
9754 swapStruct(x&: cpu32);
9755 Print_x86_thread_state32_t(cpu32);
9756 } else if (flavor == MachO::x86_THREAD_STATE) {
9757 outs() << " flavor x86_THREAD_STATE\n";
9758 if (count == MachO::x86_THREAD_STATE_COUNT)
9759 outs() << " count x86_THREAD_STATE_COUNT\n";
9760 else
9761 outs() << " count " << count
9762 << " (not x86_THREAD_STATE_COUNT)\n";
9763 struct MachO::x86_thread_state_t ts;
9764 left = end - begin;
9765 if (left >= sizeof(MachO::x86_thread_state_t)) {
9766 memcpy(dest: &ts, src: begin, n: sizeof(MachO::x86_thread_state_t));
9767 begin += sizeof(MachO::x86_thread_state_t);
9768 } else {
9769 memset(s: &ts, c: '\0', n: sizeof(MachO::x86_thread_state_t));
9770 memcpy(dest: &ts, src: begin, n: left);
9771 begin += left;
9772 }
9773 if (isLittleEndian != sys::IsLittleEndianHost)
9774 swapStruct(x&: ts);
9775 if (ts.tsh.flavor == MachO::x86_THREAD_STATE32) {
9776 outs() << "\t tsh.flavor x86_THREAD_STATE32 ";
9777 if (ts.tsh.count == MachO::x86_THREAD_STATE32_COUNT)
9778 outs() << "tsh.count x86_THREAD_STATE32_COUNT\n";
9779 else
9780 outs() << "tsh.count " << ts.tsh.count
9781 << " (not x86_THREAD_STATE32_COUNT\n";
9782 Print_x86_thread_state32_t(cpu32&: ts.uts.ts32);
9783 } else {
9784 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9785 << ts.tsh.count << "\n";
9786 }
9787 } else {
9788 outs() << " flavor " << flavor << " (unknown)\n";
9789 outs() << " count " << count << "\n";
9790 outs() << " state (unknown)\n";
9791 begin += count * sizeof(uint32_t);
9792 }
9793 }
9794 } else if (cputype == MachO::CPU_TYPE_X86_64) {
9795 while (begin < end) {
9796 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9797 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9798 begin += sizeof(uint32_t);
9799 } else {
9800 flavor = 0;
9801 begin = end;
9802 }
9803 if (isLittleEndian != sys::IsLittleEndianHost)
9804 sys::swapByteOrder(Value&: flavor);
9805 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9806 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9807 begin += sizeof(uint32_t);
9808 } else {
9809 count = 0;
9810 begin = end;
9811 }
9812 if (isLittleEndian != sys::IsLittleEndianHost)
9813 sys::swapByteOrder(Value&: count);
9814 if (flavor == MachO::x86_THREAD_STATE64) {
9815 outs() << " flavor x86_THREAD_STATE64\n";
9816 if (count == MachO::x86_THREAD_STATE64_COUNT)
9817 outs() << " count x86_THREAD_STATE64_COUNT\n";
9818 else
9819 outs() << " count " << count
9820 << " (not x86_THREAD_STATE64_COUNT)\n";
9821 MachO::x86_thread_state64_t cpu64;
9822 left = end - begin;
9823 if (left >= sizeof(MachO::x86_thread_state64_t)) {
9824 memcpy(dest: &cpu64, src: begin, n: sizeof(MachO::x86_thread_state64_t));
9825 begin += sizeof(MachO::x86_thread_state64_t);
9826 } else {
9827 memset(s: &cpu64, c: '\0', n: sizeof(MachO::x86_thread_state64_t));
9828 memcpy(dest: &cpu64, src: begin, n: left);
9829 begin += left;
9830 }
9831 if (isLittleEndian != sys::IsLittleEndianHost)
9832 swapStruct(x&: cpu64);
9833 Print_x86_thread_state64_t(cpu64);
9834 } else if (flavor == MachO::x86_THREAD_STATE) {
9835 outs() << " flavor x86_THREAD_STATE\n";
9836 if (count == MachO::x86_THREAD_STATE_COUNT)
9837 outs() << " count x86_THREAD_STATE_COUNT\n";
9838 else
9839 outs() << " count " << count
9840 << " (not x86_THREAD_STATE_COUNT)\n";
9841 struct MachO::x86_thread_state_t ts;
9842 left = end - begin;
9843 if (left >= sizeof(MachO::x86_thread_state_t)) {
9844 memcpy(dest: &ts, src: begin, n: sizeof(MachO::x86_thread_state_t));
9845 begin += sizeof(MachO::x86_thread_state_t);
9846 } else {
9847 memset(s: &ts, c: '\0', n: sizeof(MachO::x86_thread_state_t));
9848 memcpy(dest: &ts, src: begin, n: left);
9849 begin += left;
9850 }
9851 if (isLittleEndian != sys::IsLittleEndianHost)
9852 swapStruct(x&: ts);
9853 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
9854 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
9855 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
9856 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
9857 else
9858 outs() << "tsh.count " << ts.tsh.count
9859 << " (not x86_THREAD_STATE64_COUNT\n";
9860 Print_x86_thread_state64_t(cpu64&: ts.uts.ts64);
9861 } else {
9862 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
9863 << ts.tsh.count << "\n";
9864 }
9865 } else if (flavor == MachO::x86_FLOAT_STATE) {
9866 outs() << " flavor x86_FLOAT_STATE\n";
9867 if (count == MachO::x86_FLOAT_STATE_COUNT)
9868 outs() << " count x86_FLOAT_STATE_COUNT\n";
9869 else
9870 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
9871 struct MachO::x86_float_state_t fs;
9872 left = end - begin;
9873 if (left >= sizeof(MachO::x86_float_state_t)) {
9874 memcpy(dest: &fs, src: begin, n: sizeof(MachO::x86_float_state_t));
9875 begin += sizeof(MachO::x86_float_state_t);
9876 } else {
9877 memset(s: &fs, c: '\0', n: sizeof(MachO::x86_float_state_t));
9878 memcpy(dest: &fs, src: begin, n: left);
9879 begin += left;
9880 }
9881 if (isLittleEndian != sys::IsLittleEndianHost)
9882 swapStruct(x&: fs);
9883 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
9884 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
9885 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
9886 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
9887 else
9888 outs() << "fsh.count " << fs.fsh.count
9889 << " (not x86_FLOAT_STATE64_COUNT\n";
9890 Print_x86_float_state_t(fpu&: fs.ufs.fs64);
9891 } else {
9892 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
9893 << fs.fsh.count << "\n";
9894 }
9895 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
9896 outs() << " flavor x86_EXCEPTION_STATE\n";
9897 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
9898 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
9899 else
9900 outs() << " count " << count
9901 << " (not x86_EXCEPTION_STATE_COUNT)\n";
9902 struct MachO::x86_exception_state_t es;
9903 left = end - begin;
9904 if (left >= sizeof(MachO::x86_exception_state_t)) {
9905 memcpy(dest: &es, src: begin, n: sizeof(MachO::x86_exception_state_t));
9906 begin += sizeof(MachO::x86_exception_state_t);
9907 } else {
9908 memset(s: &es, c: '\0', n: sizeof(MachO::x86_exception_state_t));
9909 memcpy(dest: &es, src: begin, n: left);
9910 begin += left;
9911 }
9912 if (isLittleEndian != sys::IsLittleEndianHost)
9913 swapStruct(x&: es);
9914 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
9915 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
9916 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
9917 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
9918 else
9919 outs() << "\t esh.count " << es.esh.count
9920 << " (not x86_EXCEPTION_STATE64_COUNT\n";
9921 Print_x86_exception_state_t(exc64&: es.ues.es64);
9922 } else {
9923 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
9924 << es.esh.count << "\n";
9925 }
9926 } else if (flavor == MachO::x86_EXCEPTION_STATE64) {
9927 outs() << " flavor x86_EXCEPTION_STATE64\n";
9928 if (count == MachO::x86_EXCEPTION_STATE64_COUNT)
9929 outs() << " count x86_EXCEPTION_STATE64_COUNT\n";
9930 else
9931 outs() << " count " << count
9932 << " (not x86_EXCEPTION_STATE64_COUNT)\n";
9933 struct MachO::x86_exception_state64_t es64;
9934 left = end - begin;
9935 if (left >= sizeof(MachO::x86_exception_state64_t)) {
9936 memcpy(dest: &es64, src: begin, n: sizeof(MachO::x86_exception_state64_t));
9937 begin += sizeof(MachO::x86_exception_state64_t);
9938 } else {
9939 memset(s: &es64, c: '\0', n: sizeof(MachO::x86_exception_state64_t));
9940 memcpy(dest: &es64, src: begin, n: left);
9941 begin += left;
9942 }
9943 if (isLittleEndian != sys::IsLittleEndianHost)
9944 swapStruct(x&: es64);
9945 Print_x86_exception_state_t(exc64&: es64);
9946 } else {
9947 outs() << " flavor " << flavor << " (unknown)\n";
9948 outs() << " count " << count << "\n";
9949 outs() << " state (unknown)\n";
9950 begin += count * sizeof(uint32_t);
9951 }
9952 }
9953 } else if (cputype == MachO::CPU_TYPE_ARM) {
9954 while (begin < end) {
9955 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9956 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
9957 begin += sizeof(uint32_t);
9958 } else {
9959 flavor = 0;
9960 begin = end;
9961 }
9962 if (isLittleEndian != sys::IsLittleEndianHost)
9963 sys::swapByteOrder(Value&: flavor);
9964 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
9965 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
9966 begin += sizeof(uint32_t);
9967 } else {
9968 count = 0;
9969 begin = end;
9970 }
9971 if (isLittleEndian != sys::IsLittleEndianHost)
9972 sys::swapByteOrder(Value&: count);
9973 if (flavor == MachO::ARM_THREAD_STATE) {
9974 outs() << " flavor ARM_THREAD_STATE\n";
9975 if (count == MachO::ARM_THREAD_STATE_COUNT)
9976 outs() << " count ARM_THREAD_STATE_COUNT\n";
9977 else
9978 outs() << " count " << count
9979 << " (not ARM_THREAD_STATE_COUNT)\n";
9980 MachO::arm_thread_state32_t cpu32;
9981 left = end - begin;
9982 if (left >= sizeof(MachO::arm_thread_state32_t)) {
9983 memcpy(dest: &cpu32, src: begin, n: sizeof(MachO::arm_thread_state32_t));
9984 begin += sizeof(MachO::arm_thread_state32_t);
9985 } else {
9986 memset(s: &cpu32, c: '\0', n: sizeof(MachO::arm_thread_state32_t));
9987 memcpy(dest: &cpu32, src: begin, n: left);
9988 begin += left;
9989 }
9990 if (isLittleEndian != sys::IsLittleEndianHost)
9991 swapStruct(x&: cpu32);
9992 Print_arm_thread_state32_t(cpu32);
9993 } else {
9994 outs() << " flavor " << flavor << " (unknown)\n";
9995 outs() << " count " << count << "\n";
9996 outs() << " state (unknown)\n";
9997 begin += count * sizeof(uint32_t);
9998 }
9999 }
10000 } else if (cputype == MachO::CPU_TYPE_ARM64 ||
10001 cputype == MachO::CPU_TYPE_ARM64_32) {
10002 while (begin < end) {
10003 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10004 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
10005 begin += sizeof(uint32_t);
10006 } else {
10007 flavor = 0;
10008 begin = end;
10009 }
10010 if (isLittleEndian != sys::IsLittleEndianHost)
10011 sys::swapByteOrder(Value&: flavor);
10012 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10013 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10014 begin += sizeof(uint32_t);
10015 } else {
10016 count = 0;
10017 begin = end;
10018 }
10019 if (isLittleEndian != sys::IsLittleEndianHost)
10020 sys::swapByteOrder(Value&: count);
10021 if (flavor == MachO::ARM_THREAD_STATE64) {
10022 outs() << " flavor ARM_THREAD_STATE64\n";
10023 if (count == MachO::ARM_THREAD_STATE64_COUNT)
10024 outs() << " count ARM_THREAD_STATE64_COUNT\n";
10025 else
10026 outs() << " count " << count
10027 << " (not ARM_THREAD_STATE64_COUNT)\n";
10028 MachO::arm_thread_state64_t cpu64;
10029 left = end - begin;
10030 if (left >= sizeof(MachO::arm_thread_state64_t)) {
10031 memcpy(dest: &cpu64, src: begin, n: sizeof(MachO::arm_thread_state64_t));
10032 begin += sizeof(MachO::arm_thread_state64_t);
10033 } else {
10034 memset(s: &cpu64, c: '\0', n: sizeof(MachO::arm_thread_state64_t));
10035 memcpy(dest: &cpu64, src: begin, n: left);
10036 begin += left;
10037 }
10038 if (isLittleEndian != sys::IsLittleEndianHost)
10039 swapStruct(x&: cpu64);
10040 Print_arm_thread_state64_t(cpu64);
10041 } else {
10042 outs() << " flavor " << flavor << " (unknown)\n";
10043 outs() << " count " << count << "\n";
10044 outs() << " state (unknown)\n";
10045 begin += count * sizeof(uint32_t);
10046 }
10047 }
10048 } else {
10049 while (begin < end) {
10050 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10051 memcpy(dest: (char *)&flavor, src: begin, n: sizeof(uint32_t));
10052 begin += sizeof(uint32_t);
10053 } else {
10054 flavor = 0;
10055 begin = end;
10056 }
10057 if (isLittleEndian != sys::IsLittleEndianHost)
10058 sys::swapByteOrder(Value&: flavor);
10059 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
10060 memcpy(dest: (char *)&count, src: begin, n: sizeof(uint32_t));
10061 begin += sizeof(uint32_t);
10062 } else {
10063 count = 0;
10064 begin = end;
10065 }
10066 if (isLittleEndian != sys::IsLittleEndianHost)
10067 sys::swapByteOrder(Value&: count);
10068 outs() << " flavor " << flavor << "\n";
10069 outs() << " count " << count << "\n";
10070 outs() << " state (Unknown cputype/cpusubtype)\n";
10071 begin += count * sizeof(uint32_t);
10072 }
10073 }
10074}
10075
10076static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
10077 if (dl.cmd == MachO::LC_ID_DYLIB)
10078 outs() << " cmd LC_ID_DYLIB\n";
10079 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
10080 outs() << " cmd LC_LOAD_DYLIB\n";
10081 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
10082 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
10083 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
10084 outs() << " cmd LC_REEXPORT_DYLIB\n";
10085 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
10086 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
10087 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
10088 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
10089 else
10090 outs() << " cmd " << dl.cmd << " (unknown)\n";
10091 outs() << " cmdsize " << dl.cmdsize;
10092 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
10093 outs() << " Incorrect size\n";
10094 else
10095 outs() << "\n";
10096 if (dl.dylib.name < dl.cmdsize) {
10097 const char *P = Ptr + dl.dylib.name;
10098 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
10099 } else {
10100 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
10101 }
10102 outs() << " time stamp " << dl.dylib.timestamp << " ";
10103 time_t t = dl.dylib.timestamp;
10104 outs() << ctime(timer: &t);
10105 outs() << " current version ";
10106 if (dl.dylib.current_version == 0xffffffff)
10107 outs() << "n/a\n";
10108 else
10109 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
10110 << ((dl.dylib.current_version >> 8) & 0xff) << "."
10111 << (dl.dylib.current_version & 0xff) << "\n";
10112 outs() << "compatibility version ";
10113 if (dl.dylib.compatibility_version == 0xffffffff)
10114 outs() << "n/a\n";
10115 else
10116 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
10117 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
10118 << (dl.dylib.compatibility_version & 0xff) << "\n";
10119}
10120
10121static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
10122 uint32_t object_size) {
10123 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
10124 outs() << " cmd LC_CODE_SIGNATURE\n";
10125 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
10126 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
10127 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
10128 outs() << " cmd LC_FUNCTION_STARTS\n";
10129 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
10130 outs() << " cmd LC_DATA_IN_CODE\n";
10131 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
10132 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
10133 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
10134 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
10135 else if (ld.cmd == MachO::LC_DYLD_EXPORTS_TRIE)
10136 outs() << " cmd LC_DYLD_EXPORTS_TRIE\n";
10137 else if (ld.cmd == MachO::LC_DYLD_CHAINED_FIXUPS)
10138 outs() << " cmd LC_DYLD_CHAINED_FIXUPS\n";
10139 else if (ld.cmd == MachO::LC_ATOM_INFO)
10140 outs() << " cmd LC_ATOM_INFO\n";
10141 else
10142 outs() << " cmd " << ld.cmd << " (?)\n";
10143 outs() << " cmdsize " << ld.cmdsize;
10144 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
10145 outs() << " Incorrect size\n";
10146 else
10147 outs() << "\n";
10148 outs() << " dataoff " << ld.dataoff;
10149 if (ld.dataoff > object_size)
10150 outs() << " (past end of file)\n";
10151 else
10152 outs() << "\n";
10153 outs() << " datasize " << ld.datasize;
10154 uint64_t big_size = ld.dataoff;
10155 big_size += ld.datasize;
10156 if (big_size > object_size)
10157 outs() << " (past end of file)\n";
10158 else
10159 outs() << "\n";
10160}
10161
10162static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
10163 uint32_t cputype, bool verbose) {
10164 StringRef Buf = Obj->getData();
10165 unsigned Index = 0;
10166 for (const auto &Command : Obj->load_commands()) {
10167 outs() << "Load command " << Index++ << "\n";
10168 if (Command.C.cmd == MachO::LC_SEGMENT) {
10169 MachO::segment_command SLC = Obj->getSegmentLoadCommand(L: Command);
10170 const char *sg_segname = SLC.segname;
10171 PrintSegmentCommand(cmd: SLC.cmd, cmdsize: SLC.cmdsize, SegName: SLC.segname, vmaddr: SLC.vmaddr,
10172 vmsize: SLC.vmsize, fileoff: SLC.fileoff, filesize: SLC.filesize, maxprot: SLC.maxprot,
10173 initprot: SLC.initprot, nsects: SLC.nsects, flags: SLC.flags, object_size: Buf.size(),
10174 verbose);
10175 for (unsigned j = 0; j < SLC.nsects; j++) {
10176 MachO::section S = Obj->getSection(L: Command, Index: j);
10177 PrintSection(sectname: S.sectname, segname: S.segname, addr: S.addr, size: S.size, offset: S.offset, align: S.align,
10178 reloff: S.reloff, nreloc: S.nreloc, flags: S.flags, reserved1: S.reserved1, reserved2: S.reserved2,
10179 cmd: SLC.cmd, sg_segname, filetype, object_size: Buf.size(), verbose);
10180 }
10181 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10182 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(L: Command);
10183 const char *sg_segname = SLC_64.segname;
10184 PrintSegmentCommand(cmd: SLC_64.cmd, cmdsize: SLC_64.cmdsize, SegName: SLC_64.segname,
10185 vmaddr: SLC_64.vmaddr, vmsize: SLC_64.vmsize, fileoff: SLC_64.fileoff,
10186 filesize: SLC_64.filesize, maxprot: SLC_64.maxprot, initprot: SLC_64.initprot,
10187 nsects: SLC_64.nsects, flags: SLC_64.flags, object_size: Buf.size(), verbose);
10188 for (unsigned j = 0; j < SLC_64.nsects; j++) {
10189 MachO::section_64 S_64 = Obj->getSection64(L: Command, Index: j);
10190 PrintSection(sectname: S_64.sectname, segname: S_64.segname, addr: S_64.addr, size: S_64.size,
10191 offset: S_64.offset, align: S_64.align, reloff: S_64.reloff, nreloc: S_64.nreloc,
10192 flags: S_64.flags, reserved1: S_64.reserved1, reserved2: S_64.reserved2, cmd: SLC_64.cmd,
10193 sg_segname, filetype, object_size: Buf.size(), verbose);
10194 }
10195 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
10196 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10197 PrintSymtabLoadCommand(st: Symtab, Is64Bit: Obj->is64Bit(), object_size: Buf.size());
10198 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
10199 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
10200 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
10201 PrintDysymtabLoadCommand(dyst: Dysymtab, nsyms: Symtab.nsyms, object_size: Buf.size(),
10202 Is64Bit: Obj->is64Bit());
10203 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
10204 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
10205 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(L: Command);
10206 PrintDyldInfoLoadCommand(dc: DyldInfo, object_size: Buf.size());
10207 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
10208 Command.C.cmd == MachO::LC_ID_DYLINKER ||
10209 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
10210 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(L: Command);
10211 PrintDyldLoadCommand(dyld: Dyld, Ptr: Command.Ptr);
10212 } else if (Command.C.cmd == MachO::LC_UUID) {
10213 MachO::uuid_command Uuid = Obj->getUuidCommand(L: Command);
10214 PrintUuidLoadCommand(uuid: Uuid);
10215 } else if (Command.C.cmd == MachO::LC_RPATH) {
10216 MachO::rpath_command Rpath = Obj->getRpathCommand(L: Command);
10217 PrintRpathLoadCommand(rpath: Rpath, Ptr: Command.Ptr);
10218 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
10219 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
10220 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
10221 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
10222 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(L: Command);
10223 PrintVersionMinLoadCommand(vd: Vd);
10224 } else if (Command.C.cmd == MachO::LC_NOTE) {
10225 MachO::note_command Nt = Obj->getNoteLoadCommand(L: Command);
10226 PrintNoteLoadCommand(Nt);
10227 } else if (Command.C.cmd == MachO::LC_BUILD_VERSION) {
10228 MachO::build_version_command Bv =
10229 Obj->getBuildVersionLoadCommand(L: Command);
10230 PrintBuildVersionLoadCommand(obj: Obj, bd: Bv, verbose);
10231 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
10232 MachO::source_version_command Sd = Obj->getSourceVersionCommand(L: Command);
10233 PrintSourceVersionCommand(sd: Sd);
10234 } else if (Command.C.cmd == MachO::LC_MAIN) {
10235 MachO::entry_point_command Ep = Obj->getEntryPointCommand(L: Command);
10236 PrintEntryPointCommand(ep: Ep);
10237 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
10238 MachO::encryption_info_command Ei =
10239 Obj->getEncryptionInfoCommand(L: Command);
10240 PrintEncryptionInfoCommand(ec: Ei, object_size: Buf.size());
10241 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
10242 MachO::encryption_info_command_64 Ei =
10243 Obj->getEncryptionInfoCommand64(L: Command);
10244 PrintEncryptionInfoCommand64(ec: Ei, object_size: Buf.size());
10245 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
10246 MachO::linker_option_command Lo =
10247 Obj->getLinkerOptionLoadCommand(L: Command);
10248 PrintLinkerOptionCommand(lo: Lo, Ptr: Command.Ptr);
10249 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
10250 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(L: Command);
10251 PrintSubFrameworkCommand(sub: Sf, Ptr: Command.Ptr);
10252 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
10253 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(L: Command);
10254 PrintSubUmbrellaCommand(sub: Sf, Ptr: Command.Ptr);
10255 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
10256 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(L: Command);
10257 PrintSubLibraryCommand(sub: Sl, Ptr: Command.Ptr);
10258 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
10259 MachO::sub_client_command Sc = Obj->getSubClientCommand(L: Command);
10260 PrintSubClientCommand(sub: Sc, Ptr: Command.Ptr);
10261 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
10262 MachO::routines_command Rc = Obj->getRoutinesCommand(L: Command);
10263 PrintRoutinesCommand(r: Rc);
10264 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
10265 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(L: Command);
10266 PrintRoutinesCommand64(r: Rc);
10267 } else if (Command.C.cmd == MachO::LC_THREAD ||
10268 Command.C.cmd == MachO::LC_UNIXTHREAD) {
10269 MachO::thread_command Tc = Obj->getThreadCommand(L: Command);
10270 PrintThreadCommand(t: Tc, Ptr: Command.Ptr, isLittleEndian: Obj->isLittleEndian(), cputype);
10271 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
10272 Command.C.cmd == MachO::LC_ID_DYLIB ||
10273 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
10274 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
10275 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
10276 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
10277 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(L: Command);
10278 PrintDylibCommand(dl: Dl, Ptr: Command.Ptr);
10279 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
10280 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
10281 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
10282 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
10283 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
10284 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT ||
10285 Command.C.cmd == MachO::LC_DYLD_EXPORTS_TRIE ||
10286 Command.C.cmd == MachO::LC_DYLD_CHAINED_FIXUPS ||
10287 Command.C.cmd == MachO::LC_ATOM_INFO) {
10288 MachO::linkedit_data_command Ld =
10289 Obj->getLinkeditDataLoadCommand(L: Command);
10290 PrintLinkEditDataCommand(ld: Ld, object_size: Buf.size());
10291 } else {
10292 outs() << " cmd ?(" << format(Fmt: "0x%08" PRIx32, Vals: Command.C.cmd)
10293 << ")\n";
10294 outs() << " cmdsize " << Command.C.cmdsize << "\n";
10295 // TODO: get and print the raw bytes of the load command.
10296 }
10297 // TODO: print all the other kinds of load commands.
10298 }
10299}
10300
10301static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
10302 if (Obj->is64Bit()) {
10303 MachO::mach_header_64 H_64;
10304 H_64 = Obj->getHeader64();
10305 PrintMachHeader(magic: H_64.magic, cputype: H_64.cputype, cpusubtype: H_64.cpusubtype, filetype: H_64.filetype,
10306 ncmds: H_64.ncmds, sizeofcmds: H_64.sizeofcmds, flags: H_64.flags, verbose);
10307 } else {
10308 MachO::mach_header H;
10309 H = Obj->getHeader();
10310 PrintMachHeader(magic: H.magic, cputype: H.cputype, cpusubtype: H.cpusubtype, filetype: H.filetype, ncmds: H.ncmds,
10311 sizeofcmds: H.sizeofcmds, flags: H.flags, verbose);
10312 }
10313}
10314
10315void objdump::printMachOFileHeader(const object::ObjectFile *Obj) {
10316 const MachOObjectFile *file = cast<const MachOObjectFile>(Val: Obj);
10317 PrintMachHeader(Obj: file, verbose: Verbose);
10318}
10319
10320void MachODumper::printPrivateHeaders() {
10321 printMachOFileHeader(Obj: &Obj);
10322 if (!FirstPrivateHeader)
10323 printMachOLoadCommands(O: &Obj);
10324}
10325
10326void objdump::printMachOLoadCommands(const object::ObjectFile *Obj) {
10327 const MachOObjectFile *file = cast<const MachOObjectFile>(Val: Obj);
10328 uint32_t filetype = 0;
10329 uint32_t cputype = 0;
10330 if (file->is64Bit()) {
10331 MachO::mach_header_64 H_64;
10332 H_64 = file->getHeader64();
10333 filetype = H_64.filetype;
10334 cputype = H_64.cputype;
10335 } else {
10336 MachO::mach_header H;
10337 H = file->getHeader();
10338 filetype = H.filetype;
10339 cputype = H.cputype;
10340 }
10341 PrintLoadCommands(Obj: file, filetype, cputype, verbose: Verbose);
10342}
10343
10344//===----------------------------------------------------------------------===//
10345// export trie dumping
10346//===----------------------------------------------------------------------===//
10347
10348static void printMachOExportsTrie(const object::MachOObjectFile *Obj) {
10349 uint64_t BaseSegmentAddress = 0;
10350 for (const auto &Command : Obj->load_commands()) {
10351 if (Command.C.cmd == MachO::LC_SEGMENT) {
10352 MachO::segment_command Seg = Obj->getSegmentLoadCommand(L: Command);
10353 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10354 BaseSegmentAddress = Seg.vmaddr;
10355 break;
10356 }
10357 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
10358 MachO::segment_command_64 Seg = Obj->getSegment64LoadCommand(L: Command);
10359 if (Seg.fileoff == 0 && Seg.filesize != 0) {
10360 BaseSegmentAddress = Seg.vmaddr;
10361 break;
10362 }
10363 }
10364 }
10365 Error Err = Error::success();
10366 for (const object::ExportEntry &Entry : Obj->exports(Err)) {
10367 uint64_t Flags = Entry.flags();
10368 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
10369 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
10370 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10371 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
10372 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
10373 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
10374 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
10375 if (ReExport)
10376 outs() << "[re-export] ";
10377 else
10378 outs() << format(Fmt: "0x%08llX ",
10379 Vals: Entry.address() + BaseSegmentAddress);
10380 outs() << Entry.name();
10381 if (WeakDef || ThreadLocal || Resolver || Abs) {
10382 ListSeparator LS;
10383 outs() << " [";
10384 if (WeakDef)
10385 outs() << LS << "weak_def";
10386 if (ThreadLocal)
10387 outs() << LS << "per-thread";
10388 if (Abs)
10389 outs() << LS << "absolute";
10390 if (Resolver)
10391 outs() << LS << format(Fmt: "resolver=0x%08llX", Vals: Entry.other());
10392 outs() << "]";
10393 }
10394 if (ReExport) {
10395 StringRef DylibName = "unknown";
10396 int Ordinal = Entry.other() - 1;
10397 Obj->getLibraryShortNameByIndex(Index: Ordinal, DylibName);
10398 if (Entry.otherName().empty())
10399 outs() << " (from " << DylibName << ")";
10400 else
10401 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
10402 }
10403 outs() << "\n";
10404 }
10405 if (Err)
10406 reportError(E: std::move(Err), FileName: Obj->getFileName());
10407}
10408
10409//===----------------------------------------------------------------------===//
10410// rebase table dumping
10411//===----------------------------------------------------------------------===//
10412
10413static void printMachORebaseTable(object::MachOObjectFile *Obj) {
10414 outs() << "segment section address type\n";
10415 Error Err = Error::success();
10416 for (const object::MachORebaseEntry &Entry : Obj->rebaseTable(Err)) {
10417 StringRef SegmentName = Entry.segmentName();
10418 StringRef SectionName = Entry.sectionName();
10419 uint64_t Address = Entry.address();
10420
10421 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
10422 outs() << format(Fmt: "%-8s %-18s 0x%08" PRIX64 " %s\n",
10423 Vals: SegmentName.str().c_str(), Vals: SectionName.str().c_str(),
10424 Vals: Address, Vals: Entry.typeName().str().c_str());
10425 }
10426 if (Err)
10427 reportError(E: std::move(Err), FileName: Obj->getFileName());
10428}
10429
10430static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
10431 StringRef DylibName;
10432 switch (Ordinal) {
10433 case MachO::BIND_SPECIAL_DYLIB_SELF:
10434 return "this-image";
10435 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
10436 return "main-executable";
10437 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
10438 return "flat-namespace";
10439 case MachO::BIND_SPECIAL_DYLIB_WEAK_LOOKUP:
10440 return "weak";
10441 default:
10442 if (Ordinal > 0) {
10443 std::error_code EC =
10444 Obj->getLibraryShortNameByIndex(Index: Ordinal - 1, DylibName);
10445 if (EC)
10446 return "<<bad library ordinal>>";
10447 return DylibName;
10448 }
10449 }
10450 return "<<unknown special ordinal>>";
10451}
10452
10453//===----------------------------------------------------------------------===//
10454// bind table dumping
10455//===----------------------------------------------------------------------===//
10456
10457static void printMachOBindTable(object::MachOObjectFile *Obj) {
10458 // Build table of sections so names can used in final output.
10459 outs() << "segment section address type "
10460 "addend dylib symbol\n";
10461 Error Err = Error::success();
10462 for (const object::MachOBindEntry &Entry : Obj->bindTable(Err)) {
10463 StringRef SegmentName = Entry.segmentName();
10464 StringRef SectionName = Entry.sectionName();
10465 uint64_t Address = Entry.address();
10466
10467 // Table lines look like:
10468 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
10469 StringRef Attr;
10470 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
10471 Attr = " (weak_import)";
10472 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10473 << left_justify(Str: SectionName, Width: 18) << " "
10474 << format_hex(N: Address, Width: 10, Upper: true) << " "
10475 << left_justify(Str: Entry.typeName(), Width: 8) << " "
10476 << format_decimal(N: Entry.addend(), Width: 8) << " "
10477 << left_justify(Str: ordinalName(Obj, Ordinal: Entry.ordinal()), Width: 16) << " "
10478 << Entry.symbolName() << Attr << "\n";
10479 }
10480 if (Err)
10481 reportError(E: std::move(Err), FileName: Obj->getFileName());
10482}
10483
10484//===----------------------------------------------------------------------===//
10485// lazy bind table dumping
10486//===----------------------------------------------------------------------===//
10487
10488static void printMachOLazyBindTable(object::MachOObjectFile *Obj) {
10489 outs() << "segment section address "
10490 "dylib symbol\n";
10491 Error Err = Error::success();
10492 for (const object::MachOBindEntry &Entry : Obj->lazyBindTable(Err)) {
10493 StringRef SegmentName = Entry.segmentName();
10494 StringRef SectionName = Entry.sectionName();
10495 uint64_t Address = Entry.address();
10496
10497 // Table lines look like:
10498 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
10499 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10500 << left_justify(Str: SectionName, Width: 18) << " "
10501 << format_hex(N: Address, Width: 10, Upper: true) << " "
10502 << left_justify(Str: ordinalName(Obj, Ordinal: Entry.ordinal()), Width: 16) << " "
10503 << Entry.symbolName() << "\n";
10504 }
10505 if (Err)
10506 reportError(E: std::move(Err), FileName: Obj->getFileName());
10507}
10508
10509//===----------------------------------------------------------------------===//
10510// weak bind table dumping
10511//===----------------------------------------------------------------------===//
10512
10513static void printMachOWeakBindTable(object::MachOObjectFile *Obj) {
10514 outs() << "segment section address "
10515 "type addend symbol\n";
10516 Error Err = Error::success();
10517 for (const object::MachOBindEntry &Entry : Obj->weakBindTable(Err)) {
10518 // Strong symbols don't have a location to update.
10519 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
10520 outs() << " strong "
10521 << Entry.symbolName() << "\n";
10522 continue;
10523 }
10524 StringRef SegmentName = Entry.segmentName();
10525 StringRef SectionName = Entry.sectionName();
10526 uint64_t Address = Entry.address();
10527
10528 // Table lines look like:
10529 // __DATA __data 0x00001000 pointer 0 _foo
10530 outs() << left_justify(Str: SegmentName, Width: 8) << " "
10531 << left_justify(Str: SectionName, Width: 18) << " "
10532 << format_hex(N: Address, Width: 10, Upper: true) << " "
10533 << left_justify(Str: Entry.typeName(), Width: 8) << " "
10534 << format_decimal(N: Entry.addend(), Width: 8) << " " << Entry.symbolName()
10535 << "\n";
10536 }
10537 if (Err)
10538 reportError(E: std::move(Err), FileName: Obj->getFileName());
10539}
10540
10541// get_dyld_bind_info_symbolname() is used for disassembly and passed an
10542// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
10543// information for that address. If the address is found its binding symbol
10544// name is returned. If not nullptr is returned.
10545static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
10546 struct DisassembleInfo *info) {
10547 if (info->bindtable == nullptr) {
10548 info->bindtable = std::make_unique<SymbolAddressMap>();
10549 Error Err = Error::success();
10550 for (const object::MachOBindEntry &Entry : info->O->bindTable(Err)) {
10551 uint64_t Address = Entry.address();
10552 StringRef name = Entry.symbolName();
10553 if (!name.empty())
10554 (*info->bindtable)[Address] = name;
10555 }
10556 if (Err)
10557 reportError(E: std::move(Err), FileName: info->O->getFileName());
10558 }
10559 auto name = info->bindtable->lookup(Val: ReferenceValue);
10560 return !name.empty() ? name.data() : nullptr;
10561}
10562
10563void objdump::printLazyBindTable(ObjectFile *o) {
10564 outs() << "\nLazy bind table:\n";
10565 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10566 printMachOLazyBindTable(Obj: MachO);
10567 else
10568 WithColor::error()
10569 << "This operation is only currently supported "
10570 "for Mach-O executable files.\n";
10571}
10572
10573void objdump::printWeakBindTable(ObjectFile *o) {
10574 outs() << "\nWeak bind table:\n";
10575 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10576 printMachOWeakBindTable(Obj: MachO);
10577 else
10578 WithColor::error()
10579 << "This operation is only currently supported "
10580 "for Mach-O executable files.\n";
10581}
10582
10583void objdump::printExportsTrie(const ObjectFile *o) {
10584 outs() << "\nExports trie:\n";
10585 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10586 printMachOExportsTrie(Obj: MachO);
10587 else
10588 WithColor::error()
10589 << "This operation is only currently supported "
10590 "for Mach-O executable files.\n";
10591}
10592
10593void objdump::printRebaseTable(ObjectFile *o) {
10594 outs() << "\nRebase table:\n";
10595 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10596 printMachORebaseTable(Obj: MachO);
10597 else
10598 WithColor::error()
10599 << "This operation is only currently supported "
10600 "for Mach-O executable files.\n";
10601}
10602
10603void objdump::printBindTable(ObjectFile *o) {
10604 outs() << "\nBind table:\n";
10605 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: o))
10606 printMachOBindTable(Obj: MachO);
10607 else
10608 WithColor::error()
10609 << "This operation is only currently supported "
10610 "for Mach-O executable files.\n";
10611}
10612