Bug Summary

File:tools/llvm-objdump/MachODump.cpp
Warning:line 2124, column 25
Function call argument is an uninitialized value

Annotated Source Code

1//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Object/MachO.h"
15#include "llvm-objdump.h"
16#include "llvm-c/Disassembler.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/ADT/Triple.h"
20#include "llvm/Config/config.h"
21#include "llvm/DebugInfo/DIContext.h"
22#include "llvm/DebugInfo/DWARF/DWARFContext.h"
23#include "llvm/Demangle/Demangle.h"
24#include "llvm/MC/MCAsmInfo.h"
25#include "llvm/MC/MCContext.h"
26#include "llvm/MC/MCDisassembler/MCDisassembler.h"
27#include "llvm/MC/MCInst.h"
28#include "llvm/MC/MCInstPrinter.h"
29#include "llvm/MC/MCInstrDesc.h"
30#include "llvm/MC/MCInstrInfo.h"
31#include "llvm/MC/MCRegisterInfo.h"
32#include "llvm/MC/MCSubtargetInfo.h"
33#include "llvm/Object/MachOUniversal.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/CommandLine.h"
36#include "llvm/Support/Debug.h"
37#include "llvm/Support/Endian.h"
38#include "llvm/Support/Format.h"
39#include "llvm/Support/FormattedStream.h"
40#include "llvm/Support/GraphWriter.h"
41#include "llvm/Support/LEB128.h"
42#include "llvm/Support/MachO.h"
43#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/TargetRegistry.h"
45#include "llvm/Support/TargetSelect.h"
46#include "llvm/Support/ToolOutputFile.h"
47#include "llvm/Support/raw_ostream.h"
48#include <algorithm>
49#include <cstring>
50#include <system_error>
51
52#ifdef HAVE_LIBXAR
53extern "C" {
54#include <xar/xar.h>
55}
56#endif
57
58using namespace llvm;
59using namespace object;
60
61static cl::opt<bool>
62 UseDbg("g",
63 cl::desc("Print line information from debug info if available"));
64
65static cl::opt<std::string> DSYMFile("dsym",
66 cl::desc("Use .dSYM file for debug info"));
67
68static cl::opt<bool> FullLeadingAddr("full-leading-addr",
69 cl::desc("Print full leading address"));
70
71static cl::opt<bool> NoLeadingAddr("no-leading-addr",
72 cl::desc("Print no leading address"));
73
74cl::opt<bool> llvm::UniversalHeaders("universal-headers",
75 cl::desc("Print Mach-O universal headers "
76 "(requires -macho)"));
77
78cl::opt<bool>
79 llvm::ArchiveHeaders("archive-headers",
80 cl::desc("Print archive headers for Mach-O archives "
81 "(requires -macho)"));
82
83cl::opt<bool>
84 ArchiveMemberOffsets("archive-member-offsets",
85 cl::desc("Print the offset to each archive member for "
86 "Mach-O archives (requires -macho and "
87 "-archive-headers)"));
88
89cl::opt<bool>
90 llvm::IndirectSymbols("indirect-symbols",
91 cl::desc("Print indirect symbol table for Mach-O "
92 "objects (requires -macho)"));
93
94cl::opt<bool>
95 llvm::DataInCode("data-in-code",
96 cl::desc("Print the data in code table for Mach-O objects "
97 "(requires -macho)"));
98
99cl::opt<bool>
100 llvm::LinkOptHints("link-opt-hints",
101 cl::desc("Print the linker optimization hints for "
102 "Mach-O objects (requires -macho)"));
103
104cl::opt<bool>
105 llvm::InfoPlist("info-plist",
106 cl::desc("Print the info plist section as strings for "
107 "Mach-O objects (requires -macho)"));
108
109cl::opt<bool>
110 llvm::DylibsUsed("dylibs-used",
111 cl::desc("Print the shared libraries used for linked "
112 "Mach-O files (requires -macho)"));
113
114cl::opt<bool>
115 llvm::DylibId("dylib-id",
116 cl::desc("Print the shared library's id for the dylib Mach-O "
117 "file (requires -macho)"));
118
119cl::opt<bool>
120 llvm::NonVerbose("non-verbose",
121 cl::desc("Print the info for Mach-O objects in "
122 "non-verbose or numeric form (requires -macho)"));
123
124cl::opt<bool>
125 llvm::ObjcMetaData("objc-meta-data",
126 cl::desc("Print the Objective-C runtime meta data for "
127 "Mach-O files (requires -macho)"));
128
129cl::opt<std::string> llvm::DisSymName(
130 "dis-symname",
131 cl::desc("disassemble just this symbol's instructions (requires -macho)"));
132
133static cl::opt<bool> NoSymbolicOperands(
134 "no-symbolic-operands",
135 cl::desc("do not symbolic operands when disassembling (requires -macho)"));
136
137static cl::list<std::string>
138 ArchFlags("arch", cl::desc("architecture(s) from a Mach-O file to dump"),
139 cl::ZeroOrMore);
140
141bool ArchAll = false;
142
143static std::string ThumbTripleName;
144
145static const Target *GetTarget(const MachOObjectFile *MachOObj,
146 const char **McpuDefault,
147 const Target **ThumbTarget) {
148 // Figure out the target triple.
149 llvm::Triple TT(TripleName);
150 if (TripleName.empty()) {
151 TT = MachOObj->getArchTriple(McpuDefault);
152 TripleName = TT.str();
153 }
154
155 if (TT.getArch() == Triple::arm) {
156 // We've inferred a 32-bit ARM target from the object file. All MachO CPUs
157 // that support ARM are also capable of Thumb mode.
158 llvm::Triple ThumbTriple = TT;
159 std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
160 ThumbTriple.setArchName(ThumbName);
161 ThumbTripleName = ThumbTriple.str();
162 }
163
164 // Get the target specific parser.
165 std::string Error;
166 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
167 if (TheTarget && ThumbTripleName.empty())
168 return TheTarget;
169
170 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
171 if (*ThumbTarget)
172 return TheTarget;
173
174 errs() << "llvm-objdump: error: unable to get target for '";
175 if (!TheTarget)
176 errs() << TripleName;
177 else
178 errs() << ThumbTripleName;
179 errs() << "', see --version and --triple.\n";
180 return nullptr;
181}
182
183struct SymbolSorter {
184 bool operator()(const SymbolRef &A, const SymbolRef &B) {
185 Expected<SymbolRef::Type> ATypeOrErr = A.getType();
186 if (!ATypeOrErr) {
187 std::string Buf;
188 raw_string_ostream OS(Buf);
189 logAllUnhandledErrors(ATypeOrErr.takeError(), OS, "");
190 OS.flush();
191 report_fatal_error(Buf);
192 }
193 SymbolRef::Type AType = *ATypeOrErr;
194 Expected<SymbolRef::Type> BTypeOrErr = B.getType();
195 if (!BTypeOrErr) {
196 std::string Buf;
197 raw_string_ostream OS(Buf);
198 logAllUnhandledErrors(BTypeOrErr.takeError(), OS, "");
199 OS.flush();
200 report_fatal_error(Buf);
201 }
202 SymbolRef::Type BType = *BTypeOrErr;
203 uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : A.getValue();
204 uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : B.getValue();
205 return AAddr < BAddr;
206 }
207};
208
209// Types for the storted data in code table that is built before disassembly
210// and the predicate function to sort them.
211typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
212typedef std::vector<DiceTableEntry> DiceTable;
213typedef DiceTable::iterator dice_table_iterator;
214
215// This is used to search for a data in code table entry for the PC being
216// disassembled. The j parameter has the PC in j.first. A single data in code
217// table entry can cover many bytes for each of its Kind's. So if the offset,
218// aka the i.first value, of the data in code table entry plus its Length
219// covers the PC being searched for this will return true. If not it will
220// return false.
221static bool compareDiceTableEntries(const DiceTableEntry &i,
222 const DiceTableEntry &j) {
223 uint16_t Length;
224 i.second.getLength(Length);
225
226 return j.first >= i.first && j.first < i.first + Length;
227}
228
229static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
230 unsigned short Kind) {
231 uint32_t Value, Size = 1;
232
233 switch (Kind) {
234 default:
235 case MachO::DICE_KIND_DATA:
236 if (Length >= 4) {
237 if (!NoShowRawInsn)
238 dumpBytes(makeArrayRef(bytes, 4), outs());
239 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
240 outs() << "\t.long " << Value;
241 Size = 4;
242 } else if (Length >= 2) {
243 if (!NoShowRawInsn)
244 dumpBytes(makeArrayRef(bytes, 2), outs());
245 Value = bytes[1] << 8 | bytes[0];
246 outs() << "\t.short " << Value;
247 Size = 2;
248 } else {
249 if (!NoShowRawInsn)
250 dumpBytes(makeArrayRef(bytes, 2), outs());
251 Value = bytes[0];
252 outs() << "\t.byte " << Value;
253 Size = 1;
254 }
255 if (Kind == MachO::DICE_KIND_DATA)
256 outs() << "\t@ KIND_DATA\n";
257 else
258 outs() << "\t@ data in code kind = " << Kind << "\n";
259 break;
260 case MachO::DICE_KIND_JUMP_TABLE8:
261 if (!NoShowRawInsn)
262 dumpBytes(makeArrayRef(bytes, 1), outs());
263 Value = bytes[0];
264 outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
265 Size = 1;
266 break;
267 case MachO::DICE_KIND_JUMP_TABLE16:
268 if (!NoShowRawInsn)
269 dumpBytes(makeArrayRef(bytes, 2), outs());
270 Value = bytes[1] << 8 | bytes[0];
271 outs() << "\t.short " << format("%5u", Value & 0xffff)
272 << "\t@ KIND_JUMP_TABLE16\n";
273 Size = 2;
274 break;
275 case MachO::DICE_KIND_JUMP_TABLE32:
276 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
277 if (!NoShowRawInsn)
278 dumpBytes(makeArrayRef(bytes, 4), outs());
279 Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
280 outs() << "\t.long " << Value;
281 if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
282 outs() << "\t@ KIND_JUMP_TABLE32\n";
283 else
284 outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
285 Size = 4;
286 break;
287 }
288 return Size;
289}
290
291static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
292 std::vector<SectionRef> &Sections,
293 std::vector<SymbolRef> &Symbols,
294 SmallVectorImpl<uint64_t> &FoundFns,
295 uint64_t &BaseSegmentAddress) {
296 for (const SymbolRef &Symbol : MachOObj->symbols()) {
297 Expected<StringRef> SymName = Symbol.getName();
298 if (!SymName) {
299 std::string Buf;
300 raw_string_ostream OS(Buf);
301 logAllUnhandledErrors(SymName.takeError(), OS, "");
302 OS.flush();
303 report_fatal_error(Buf);
304 }
305 if (!SymName->startswith("ltmp"))
306 Symbols.push_back(Symbol);
307 }
308
309 for (const SectionRef &Section : MachOObj->sections()) {
310 StringRef SectName;
311 Section.getName(SectName);
312 Sections.push_back(Section);
313 }
314
315 bool BaseSegmentAddressSet = false;
316 for (const auto &Command : MachOObj->load_commands()) {
317 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
318 // We found a function starts segment, parse the addresses for later
319 // consumption.
320 MachO::linkedit_data_command LLC =
321 MachOObj->getLinkeditDataLoadCommand(Command);
322
323 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
324 } else if (Command.C.cmd == MachO::LC_SEGMENT) {
325 MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
326 StringRef SegName = SLC.segname;
327 if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
328 BaseSegmentAddressSet = true;
329 BaseSegmentAddress = SLC.vmaddr;
330 }
331 }
332 }
333}
334
335static void PrintIndirectSymbolTable(MachOObjectFile *O, bool verbose,
336 uint32_t n, uint32_t count,
337 uint32_t stride, uint64_t addr) {
338 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
339 uint32_t nindirectsyms = Dysymtab.nindirectsyms;
340 if (n > nindirectsyms)
341 outs() << " (entries start past the end of the indirect symbol "
342 "table) (reserved1 field greater than the table size)";
343 else if (n + count > nindirectsyms)
344 outs() << " (entries extends past the end of the indirect symbol "
345 "table)";
346 outs() << "\n";
347 uint32_t cputype = O->getHeader().cputype;
348 if (cputype & MachO::CPU_ARCH_ABI64)
349 outs() << "address index";
350 else
351 outs() << "address index";
352 if (verbose)
353 outs() << " name\n";
354 else
355 outs() << "\n";
356 for (uint32_t j = 0; j < count && n + j < nindirectsyms; j++) {
357 if (cputype & MachO::CPU_ARCH_ABI64)
358 outs() << format("0x%016" PRIx64"l" "x", addr + j * stride) << " ";
359 else
360 outs() << format("0x%08" PRIx32"x", (uint32_t)addr + j * stride) << " ";
361 MachO::dysymtab_command Dysymtab = O->getDysymtabLoadCommand();
362 uint32_t indirect_symbol = O->getIndirectSymbolTableEntry(Dysymtab, n + j);
363 if (indirect_symbol == MachO::INDIRECT_SYMBOL_LOCAL) {
364 outs() << "LOCAL\n";
365 continue;
366 }
367 if (indirect_symbol ==
368 (MachO::INDIRECT_SYMBOL_LOCAL | MachO::INDIRECT_SYMBOL_ABS)) {
369 outs() << "LOCAL ABSOLUTE\n";
370 continue;
371 }
372 if (indirect_symbol == MachO::INDIRECT_SYMBOL_ABS) {
373 outs() << "ABSOLUTE\n";
374 continue;
375 }
376 outs() << format("%5u ", indirect_symbol);
377 if (verbose) {
378 MachO::symtab_command Symtab = O->getSymtabLoadCommand();
379 if (indirect_symbol < Symtab.nsyms) {
380 symbol_iterator Sym = O->getSymbolByIndex(indirect_symbol);
381 SymbolRef Symbol = *Sym;
382 Expected<StringRef> SymName = Symbol.getName();
383 if (!SymName) {
384 std::string Buf;
385 raw_string_ostream OS(Buf);
386 logAllUnhandledErrors(SymName.takeError(), OS, "");
387 OS.flush();
388 report_fatal_error(Buf);
389 }
390 outs() << *SymName;
391 } else {
392 outs() << "?";
393 }
394 }
395 outs() << "\n";
396 }
397}
398
399static void PrintIndirectSymbols(MachOObjectFile *O, bool verbose) {
400 for (const auto &Load : O->load_commands()) {
401 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
402 MachO::segment_command_64 Seg = O->getSegment64LoadCommand(Load);
403 for (unsigned J = 0; J < Seg.nsects; ++J) {
404 MachO::section_64 Sec = O->getSection64(Load, J);
405 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
406 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
407 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
408 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
409 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
410 section_type == MachO::S_SYMBOL_STUBS) {
411 uint32_t stride;
412 if (section_type == MachO::S_SYMBOL_STUBS)
413 stride = Sec.reserved2;
414 else
415 stride = 8;
416 if (stride == 0) {
417 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
418 << Sec.sectname << ") "
419 << "(size of stubs in reserved2 field is zero)\n";
420 continue;
421 }
422 uint32_t count = Sec.size / stride;
423 outs() << "Indirect symbols for (" << Sec.segname << ","
424 << Sec.sectname << ") " << count << " entries";
425 uint32_t n = Sec.reserved1;
426 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
427 }
428 }
429 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
430 MachO::segment_command Seg = O->getSegmentLoadCommand(Load);
431 for (unsigned J = 0; J < Seg.nsects; ++J) {
432 MachO::section Sec = O->getSection(Load, J);
433 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
434 if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
435 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
436 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
437 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
438 section_type == MachO::S_SYMBOL_STUBS) {
439 uint32_t stride;
440 if (section_type == MachO::S_SYMBOL_STUBS)
441 stride = Sec.reserved2;
442 else
443 stride = 4;
444 if (stride == 0) {
445 outs() << "Can't print indirect symbols for (" << Sec.segname << ","
446 << Sec.sectname << ") "
447 << "(size of stubs in reserved2 field is zero)\n";
448 continue;
449 }
450 uint32_t count = Sec.size / stride;
451 outs() << "Indirect symbols for (" << Sec.segname << ","
452 << Sec.sectname << ") " << count << " entries";
453 uint32_t n = Sec.reserved1;
454 PrintIndirectSymbolTable(O, verbose, n, count, stride, Sec.addr);
455 }
456 }
457 }
458 }
459}
460
461static void PrintDataInCodeTable(MachOObjectFile *O, bool verbose) {
462 MachO::linkedit_data_command DIC = O->getDataInCodeLoadCommand();
463 uint32_t nentries = DIC.datasize / sizeof(struct MachO::data_in_code_entry);
464 outs() << "Data in code table (" << nentries << " entries)\n";
465 outs() << "offset length kind\n";
466 for (dice_iterator DI = O->begin_dices(), DE = O->end_dices(); DI != DE;
467 ++DI) {
468 uint32_t Offset;
469 DI->getOffset(Offset);
470 outs() << format("0x%08" PRIx32"x", Offset) << " ";
471 uint16_t Length;
472 DI->getLength(Length);
473 outs() << format("%6u", Length) << " ";
474 uint16_t Kind;
475 DI->getKind(Kind);
476 if (verbose) {
477 switch (Kind) {
478 case MachO::DICE_KIND_DATA:
479 outs() << "DATA";
480 break;
481 case MachO::DICE_KIND_JUMP_TABLE8:
482 outs() << "JUMP_TABLE8";
483 break;
484 case MachO::DICE_KIND_JUMP_TABLE16:
485 outs() << "JUMP_TABLE16";
486 break;
487 case MachO::DICE_KIND_JUMP_TABLE32:
488 outs() << "JUMP_TABLE32";
489 break;
490 case MachO::DICE_KIND_ABS_JUMP_TABLE32:
491 outs() << "ABS_JUMP_TABLE32";
492 break;
493 default:
494 outs() << format("0x%04" PRIx32"x", Kind);
495 break;
496 }
497 } else
498 outs() << format("0x%04" PRIx32"x", Kind);
499 outs() << "\n";
500 }
501}
502
503static void PrintLinkOptHints(MachOObjectFile *O) {
504 MachO::linkedit_data_command LohLC = O->getLinkOptHintsLoadCommand();
505 const char *loh = O->getData().substr(LohLC.dataoff, 1).data();
506 uint32_t nloh = LohLC.datasize;
507 outs() << "Linker optimiztion hints (" << nloh << " total bytes)\n";
508 for (uint32_t i = 0; i < nloh;) {
509 unsigned n;
510 uint64_t identifier = decodeULEB128((const uint8_t *)(loh + i), &n);
511 i += n;
512 outs() << " identifier " << identifier << " ";
513 if (i >= nloh)
514 return;
515 switch (identifier) {
516 case 1:
517 outs() << "AdrpAdrp\n";
518 break;
519 case 2:
520 outs() << "AdrpLdr\n";
521 break;
522 case 3:
523 outs() << "AdrpAddLdr\n";
524 break;
525 case 4:
526 outs() << "AdrpLdrGotLdr\n";
527 break;
528 case 5:
529 outs() << "AdrpAddStr\n";
530 break;
531 case 6:
532 outs() << "AdrpLdrGotStr\n";
533 break;
534 case 7:
535 outs() << "AdrpAdd\n";
536 break;
537 case 8:
538 outs() << "AdrpLdrGot\n";
539 break;
540 default:
541 outs() << "Unknown identifier value\n";
542 break;
543 }
544 uint64_t narguments = decodeULEB128((const uint8_t *)(loh + i), &n);
545 i += n;
546 outs() << " narguments " << narguments << "\n";
547 if (i >= nloh)
548 return;
549
550 for (uint32_t j = 0; j < narguments; j++) {
551 uint64_t value = decodeULEB128((const uint8_t *)(loh + i), &n);
552 i += n;
553 outs() << "\tvalue " << format("0x%" PRIx64"l" "x", value) << "\n";
554 if (i >= nloh)
555 return;
556 }
557 }
558}
559
560static void PrintDylibs(MachOObjectFile *O, bool JustId) {
561 unsigned Index = 0;
562 for (const auto &Load : O->load_commands()) {
563 if ((JustId && Load.C.cmd == MachO::LC_ID_DYLIB) ||
564 (!JustId && (Load.C.cmd == MachO::LC_ID_DYLIB ||
565 Load.C.cmd == MachO::LC_LOAD_DYLIB ||
566 Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
567 Load.C.cmd == MachO::LC_REEXPORT_DYLIB ||
568 Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
569 Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB))) {
570 MachO::dylib_command dl = O->getDylibIDLoadCommand(Load);
571 if (dl.dylib.name < dl.cmdsize) {
572 const char *p = (const char *)(Load.Ptr) + dl.dylib.name;
573 if (JustId)
574 outs() << p << "\n";
575 else {
576 outs() << "\t" << p;
577 outs() << " (compatibility version "
578 << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
579 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
580 << (dl.dylib.compatibility_version & 0xff) << ",";
581 outs() << " current version "
582 << ((dl.dylib.current_version >> 16) & 0xffff) << "."
583 << ((dl.dylib.current_version >> 8) & 0xff) << "."
584 << (dl.dylib.current_version & 0xff) << ")\n";
585 }
586 } else {
587 outs() << "\tBad offset (" << dl.dylib.name << ") for name of ";
588 if (Load.C.cmd == MachO::LC_ID_DYLIB)
589 outs() << "LC_ID_DYLIB ";
590 else if (Load.C.cmd == MachO::LC_LOAD_DYLIB)
591 outs() << "LC_LOAD_DYLIB ";
592 else if (Load.C.cmd == MachO::LC_LOAD_WEAK_DYLIB)
593 outs() << "LC_LOAD_WEAK_DYLIB ";
594 else if (Load.C.cmd == MachO::LC_LAZY_LOAD_DYLIB)
595 outs() << "LC_LAZY_LOAD_DYLIB ";
596 else if (Load.C.cmd == MachO::LC_REEXPORT_DYLIB)
597 outs() << "LC_REEXPORT_DYLIB ";
598 else if (Load.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
599 outs() << "LC_LOAD_UPWARD_DYLIB ";
600 else
601 outs() << "LC_??? ";
602 outs() << "command " << Index++ << "\n";
603 }
604 }
605 }
606}
607
608typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
609
610static void CreateSymbolAddressMap(MachOObjectFile *O,
611 SymbolAddressMap *AddrMap) {
612 // Create a map of symbol addresses to symbol names.
613 for (const SymbolRef &Symbol : O->symbols()) {
614 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
615 if (!STOrErr) {
616 std::string Buf;
617 raw_string_ostream OS(Buf);
618 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
619 OS.flush();
620 report_fatal_error(Buf);
621 }
622 SymbolRef::Type ST = *STOrErr;
623 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
624 ST == SymbolRef::ST_Other) {
625 uint64_t Address = Symbol.getValue();
626 Expected<StringRef> SymNameOrErr = Symbol.getName();
627 if (!SymNameOrErr) {
628 std::string Buf;
629 raw_string_ostream OS(Buf);
630 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
631 OS.flush();
632 report_fatal_error(Buf);
633 }
634 StringRef SymName = *SymNameOrErr;
635 if (!SymName.startswith(".objc"))
636 (*AddrMap)[Address] = SymName;
637 }
638 }
639}
640
641// GuessSymbolName is passed the address of what might be a symbol and a
642// pointer to the SymbolAddressMap. It returns the name of a symbol
643// with that address or nullptr if no symbol is found with that address.
644static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
645 const char *SymbolName = nullptr;
646 // A DenseMap can't lookup up some values.
647 if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
648 StringRef name = AddrMap->lookup(value);
649 if (!name.empty())
650 SymbolName = name.data();
651 }
652 return SymbolName;
653}
654
655static void DumpCstringChar(const char c) {
656 char p[2];
657 p[0] = c;
658 p[1] = '\0';
659 outs().write_escaped(p);
660}
661
662static void DumpCstringSection(MachOObjectFile *O, const char *sect,
663 uint32_t sect_size, uint64_t sect_addr,
664 bool print_addresses) {
665 for (uint32_t i = 0; i < sect_size; i++) {
666 if (print_addresses) {
667 if (O->is64Bit())
668 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
669 else
670 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
671 }
672 for (; i < sect_size && sect[i] != '\0'; i++)
673 DumpCstringChar(sect[i]);
674 if (i < sect_size && sect[i] == '\0')
675 outs() << "\n";
676 }
677}
678
679static void DumpLiteral4(uint32_t l, float f) {
680 outs() << format("0x%08" PRIx32"x", l);
681 if ((l & 0x7f800000) != 0x7f800000)
682 outs() << format(" (%.16e)\n", f);
683 else {
684 if (l == 0x7f800000)
685 outs() << " (+Infinity)\n";
686 else if (l == 0xff800000)
687 outs() << " (-Infinity)\n";
688 else if ((l & 0x00400000) == 0x00400000)
689 outs() << " (non-signaling Not-a-Number)\n";
690 else
691 outs() << " (signaling Not-a-Number)\n";
692 }
693}
694
695static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
696 uint32_t sect_size, uint64_t sect_addr,
697 bool print_addresses) {
698 for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
699 if (print_addresses) {
700 if (O->is64Bit())
701 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
702 else
703 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
704 }
705 float f;
706 memcpy(&f, sect + i, sizeof(float));
707 if (O->isLittleEndian() != sys::IsLittleEndianHost)
708 sys::swapByteOrder(f);
709 uint32_t l;
710 memcpy(&l, sect + i, sizeof(uint32_t));
711 if (O->isLittleEndian() != sys::IsLittleEndianHost)
712 sys::swapByteOrder(l);
713 DumpLiteral4(l, f);
714 }
715}
716
717static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
718 double d) {
719 outs() << format("0x%08" PRIx32"x", l0) << " " << format("0x%08" PRIx32"x", l1);
720 uint32_t Hi, Lo;
721 Hi = (O->isLittleEndian()) ? l1 : l0;
722 Lo = (O->isLittleEndian()) ? l0 : l1;
723
724 // Hi is the high word, so this is equivalent to if(isfinite(d))
725 if ((Hi & 0x7ff00000) != 0x7ff00000)
726 outs() << format(" (%.16e)\n", d);
727 else {
728 if (Hi == 0x7ff00000 && Lo == 0)
729 outs() << " (+Infinity)\n";
730 else if (Hi == 0xfff00000 && Lo == 0)
731 outs() << " (-Infinity)\n";
732 else if ((Hi & 0x00080000) == 0x00080000)
733 outs() << " (non-signaling Not-a-Number)\n";
734 else
735 outs() << " (signaling Not-a-Number)\n";
736 }
737}
738
739static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
740 uint32_t sect_size, uint64_t sect_addr,
741 bool print_addresses) {
742 for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
743 if (print_addresses) {
744 if (O->is64Bit())
745 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
746 else
747 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
748 }
749 double d;
750 memcpy(&d, sect + i, sizeof(double));
751 if (O->isLittleEndian() != sys::IsLittleEndianHost)
752 sys::swapByteOrder(d);
753 uint32_t l0, l1;
754 memcpy(&l0, sect + i, sizeof(uint32_t));
755 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
756 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
757 sys::swapByteOrder(l0);
758 sys::swapByteOrder(l1);
759 }
760 DumpLiteral8(O, l0, l1, d);
761 }
762}
763
764static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
765 outs() << format("0x%08" PRIx32"x", l0) << " ";
766 outs() << format("0x%08" PRIx32"x", l1) << " ";
767 outs() << format("0x%08" PRIx32"x", l2) << " ";
768 outs() << format("0x%08" PRIx32"x", l3) << "\n";
769}
770
771static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
772 uint32_t sect_size, uint64_t sect_addr,
773 bool print_addresses) {
774 for (uint32_t i = 0; i < sect_size; i += 16) {
775 if (print_addresses) {
776 if (O->is64Bit())
777 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
778 else
779 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
780 }
781 uint32_t l0, l1, l2, l3;
782 memcpy(&l0, sect + i, sizeof(uint32_t));
783 memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
784 memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
785 memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
786 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
787 sys::swapByteOrder(l0);
788 sys::swapByteOrder(l1);
789 sys::swapByteOrder(l2);
790 sys::swapByteOrder(l3);
791 }
792 DumpLiteral16(l0, l1, l2, l3);
793 }
794}
795
796static void DumpLiteralPointerSection(MachOObjectFile *O,
797 const SectionRef &Section,
798 const char *sect, uint32_t sect_size,
799 uint64_t sect_addr,
800 bool print_addresses) {
801 // Collect the literal sections in this Mach-O file.
802 std::vector<SectionRef> LiteralSections;
803 for (const SectionRef &Section : O->sections()) {
804 DataRefImpl Ref = Section.getRawDataRefImpl();
805 uint32_t section_type;
806 if (O->is64Bit()) {
807 const MachO::section_64 Sec = O->getSection64(Ref);
808 section_type = Sec.flags & MachO::SECTION_TYPE;
809 } else {
810 const MachO::section Sec = O->getSection(Ref);
811 section_type = Sec.flags & MachO::SECTION_TYPE;
812 }
813 if (section_type == MachO::S_CSTRING_LITERALS ||
814 section_type == MachO::S_4BYTE_LITERALS ||
815 section_type == MachO::S_8BYTE_LITERALS ||
816 section_type == MachO::S_16BYTE_LITERALS)
817 LiteralSections.push_back(Section);
818 }
819
820 // Set the size of the literal pointer.
821 uint32_t lp_size = O->is64Bit() ? 8 : 4;
822
823 // Collect the external relocation symbols for the literal pointers.
824 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
825 for (const RelocationRef &Reloc : Section.relocations()) {
826 DataRefImpl Rel;
827 MachO::any_relocation_info RE;
828 bool isExtern = false;
829 Rel = Reloc.getRawDataRefImpl();
830 RE = O->getRelocation(Rel);
831 isExtern = O->getPlainRelocationExternal(RE);
832 if (isExtern) {
833 uint64_t RelocOffset = Reloc.getOffset();
834 symbol_iterator RelocSym = Reloc.getSymbol();
835 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
836 }
837 }
838 array_pod_sort(Relocs.begin(), Relocs.end());
839
840 // Dump each literal pointer.
841 for (uint32_t i = 0; i < sect_size; i += lp_size) {
842 if (print_addresses) {
843 if (O->is64Bit())
844 outs() << format("%016" PRIx64"l" "x", sect_addr + i) << " ";
845 else
846 outs() << format("%08" PRIx64"l" "x", sect_addr + i) << " ";
847 }
848 uint64_t lp;
849 if (O->is64Bit()) {
850 memcpy(&lp, sect + i, sizeof(uint64_t));
851 if (O->isLittleEndian() != sys::IsLittleEndianHost)
852 sys::swapByteOrder(lp);
853 } else {
854 uint32_t li;
855 memcpy(&li, sect + i, sizeof(uint32_t));
856 if (O->isLittleEndian() != sys::IsLittleEndianHost)
857 sys::swapByteOrder(li);
858 lp = li;
859 }
860
861 // First look for an external relocation entry for this literal pointer.
862 auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
863 return P.first == i;
864 });
865 if (Reloc != Relocs.end()) {
866 symbol_iterator RelocSym = Reloc->second;
867 Expected<StringRef> SymName = RelocSym->getName();
868 if (!SymName) {
869 std::string Buf;
870 raw_string_ostream OS(Buf);
871 logAllUnhandledErrors(SymName.takeError(), OS, "");
872 OS.flush();
873 report_fatal_error(Buf);
874 }
875 outs() << "external relocation entry for symbol:" << *SymName << "\n";
876 continue;
877 }
878
879 // For local references see what the section the literal pointer points to.
880 auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
881 return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
882 });
883 if (Sect == LiteralSections.end()) {
884 outs() << format("0x%" PRIx64"l" "x", lp) << " (not in a literal section)\n";
885 continue;
886 }
887
888 uint64_t SectAddress = Sect->getAddress();
889 uint64_t SectSize = Sect->getSize();
890
891 StringRef SectName;
892 Sect->getName(SectName);
893 DataRefImpl Ref = Sect->getRawDataRefImpl();
894 StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
895 outs() << SegmentName << ":" << SectName << ":";
896
897 uint32_t section_type;
898 if (O->is64Bit()) {
899 const MachO::section_64 Sec = O->getSection64(Ref);
900 section_type = Sec.flags & MachO::SECTION_TYPE;
901 } else {
902 const MachO::section Sec = O->getSection(Ref);
903 section_type = Sec.flags & MachO::SECTION_TYPE;
904 }
905
906 StringRef BytesStr;
907 Sect->getContents(BytesStr);
908 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
909
910 switch (section_type) {
911 case MachO::S_CSTRING_LITERALS:
912 for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
913 i++) {
914 DumpCstringChar(Contents[i]);
915 }
916 outs() << "\n";
917 break;
918 case MachO::S_4BYTE_LITERALS:
919 float f;
920 memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
921 uint32_t l;
922 memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
923 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
924 sys::swapByteOrder(f);
925 sys::swapByteOrder(l);
926 }
927 DumpLiteral4(l, f);
928 break;
929 case MachO::S_8BYTE_LITERALS: {
930 double d;
931 memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
932 uint32_t l0, l1;
933 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
934 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
935 sizeof(uint32_t));
936 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
937 sys::swapByteOrder(f);
938 sys::swapByteOrder(l0);
939 sys::swapByteOrder(l1);
940 }
941 DumpLiteral8(O, l0, l1, d);
942 break;
943 }
944 case MachO::S_16BYTE_LITERALS: {
945 uint32_t l0, l1, l2, l3;
946 memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
947 memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
948 sizeof(uint32_t));
949 memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
950 sizeof(uint32_t));
951 memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
952 sizeof(uint32_t));
953 if (O->isLittleEndian() != sys::IsLittleEndianHost) {
954 sys::swapByteOrder(l0);
955 sys::swapByteOrder(l1);
956 sys::swapByteOrder(l2);
957 sys::swapByteOrder(l3);
958 }
959 DumpLiteral16(l0, l1, l2, l3);
960 break;
961 }
962 }
963 }
964}
965
966static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
967 uint32_t sect_size, uint64_t sect_addr,
968 SymbolAddressMap *AddrMap,
969 bool verbose) {
970 uint32_t stride;
971 stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
972 for (uint32_t i = 0; i < sect_size; i += stride) {
973 const char *SymbolName = nullptr;
974 if (O->is64Bit()) {
975 outs() << format("0x%016" PRIx64"l" "x", sect_addr + i * stride) << " ";
976 uint64_t pointer_value;
977 memcpy(&pointer_value, sect + i, stride);
978 if (O->isLittleEndian() != sys::IsLittleEndianHost)
979 sys::swapByteOrder(pointer_value);
980 outs() << format("0x%016" PRIx64"l" "x", pointer_value);
981 if (verbose)
982 SymbolName = GuessSymbolName(pointer_value, AddrMap);
983 } else {
984 outs() << format("0x%08" PRIx64"l" "x", sect_addr + i * stride) << " ";
985 uint32_t pointer_value;
986 memcpy(&pointer_value, sect + i, stride);
987 if (O->isLittleEndian() != sys::IsLittleEndianHost)
988 sys::swapByteOrder(pointer_value);
989 outs() << format("0x%08" PRIx32"x", pointer_value);
990 if (verbose)
991 SymbolName = GuessSymbolName(pointer_value, AddrMap);
992 }
993 if (SymbolName)
994 outs() << " " << SymbolName;
995 outs() << "\n";
996 }
997}
998
999static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
1000 uint32_t size, uint64_t addr) {
1001 uint32_t cputype = O->getHeader().cputype;
1002 if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
1003 uint32_t j;
1004 for (uint32_t i = 0; i < size; i += j, addr += j) {
1005 if (O->is64Bit())
1006 outs() << format("%016" PRIx64"l" "x", addr) << "\t";
1007 else
1008 outs() << format("%08" PRIx64"l" "x", addr) << "\t";
1009 for (j = 0; j < 16 && i + j < size; j++) {
1010 uint8_t byte_word = *(sect + i + j);
1011 outs() << format("%02" PRIx32"x", (uint32_t)byte_word) << " ";
1012 }
1013 outs() << "\n";
1014 }
1015 } else {
1016 uint32_t j;
1017 for (uint32_t i = 0; i < size; i += j, addr += j) {
1018 if (O->is64Bit())
1019 outs() << format("%016" PRIx64"l" "x", addr) << "\t";
1020 else
1021 outs() << format("%08" PRIx64"l" "x", addr) << "\t";
1022 for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
1023 j += sizeof(int32_t)) {
1024 if (i + j + sizeof(int32_t) <= size) {
1025 uint32_t long_word;
1026 memcpy(&long_word, sect + i + j, sizeof(int32_t));
1027 if (O->isLittleEndian() != sys::IsLittleEndianHost)
1028 sys::swapByteOrder(long_word);
1029 outs() << format("%08" PRIx32"x", long_word) << " ";
1030 } else {
1031 for (uint32_t k = 0; i + j + k < size; k++) {
1032 uint8_t byte_word = *(sect + i + j + k);
1033 outs() << format("%02" PRIx32"x", (uint32_t)byte_word) << " ";
1034 }
1035 }
1036 }
1037 outs() << "\n";
1038 }
1039 }
1040}
1041
1042static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
1043 StringRef DisSegName, StringRef DisSectName);
1044static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
1045 uint32_t size, uint32_t addr);
1046#ifdef HAVE_LIBXAR
1047static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
1048 uint32_t size, bool verbose,
1049 bool PrintXarHeader, bool PrintXarFileHeaders,
1050 std::string XarMemberName);
1051#endif // defined(HAVE_LIBXAR)
1052
1053static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
1054 bool verbose) {
1055 SymbolAddressMap AddrMap;
1056 if (verbose)
1057 CreateSymbolAddressMap(O, &AddrMap);
1058
1059 for (unsigned i = 0; i < FilterSections.size(); ++i) {
1060 StringRef DumpSection = FilterSections[i];
1061 std::pair<StringRef, StringRef> DumpSegSectName;
1062 DumpSegSectName = DumpSection.split(',');
1063 StringRef DumpSegName, DumpSectName;
1064 if (DumpSegSectName.second.size()) {
1065 DumpSegName = DumpSegSectName.first;
1066 DumpSectName = DumpSegSectName.second;
1067 } else {
1068 DumpSegName = "";
1069 DumpSectName = DumpSegSectName.first;
1070 }
1071 for (const SectionRef &Section : O->sections()) {
1072 StringRef SectName;
1073 Section.getName(SectName);
1074 DataRefImpl Ref = Section.getRawDataRefImpl();
1075 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1076 if ((DumpSegName.empty() || SegName == DumpSegName) &&
1077 (SectName == DumpSectName)) {
1078
1079 uint32_t section_flags;
1080 if (O->is64Bit()) {
1081 const MachO::section_64 Sec = O->getSection64(Ref);
1082 section_flags = Sec.flags;
1083
1084 } else {
1085 const MachO::section Sec = O->getSection(Ref);
1086 section_flags = Sec.flags;
1087 }
1088 uint32_t section_type = section_flags & MachO::SECTION_TYPE;
1089
1090 StringRef BytesStr;
1091 Section.getContents(BytesStr);
1092 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1093 uint32_t sect_size = BytesStr.size();
1094 uint64_t sect_addr = Section.getAddress();
1095
1096 outs() << "Contents of (" << SegName << "," << SectName
1097 << ") section\n";
1098
1099 if (verbose) {
1100 if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
1101 (section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
1102 DisassembleMachO(Filename, O, SegName, SectName);
1103 continue;
1104 }
1105 if (SegName == "__TEXT" && SectName == "__info_plist") {
1106 outs() << sect;
1107 continue;
1108 }
1109 if (SegName == "__OBJC" && SectName == "__protocol") {
1110 DumpProtocolSection(O, sect, sect_size, sect_addr);
1111 continue;
1112 }
1113#ifdef HAVE_LIBXAR
1114 if (SegName == "__LLVM" && SectName == "__bundle") {
1115 DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
1116 ArchiveHeaders, "");
1117 continue;
1118 }
1119#endif // defined(HAVE_LIBXAR)
1120 switch (section_type) {
1121 case MachO::S_REGULAR:
1122 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1123 break;
1124 case MachO::S_ZEROFILL:
1125 outs() << "zerofill section and has no contents in the file\n";
1126 break;
1127 case MachO::S_CSTRING_LITERALS:
1128 DumpCstringSection(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1129 break;
1130 case MachO::S_4BYTE_LITERALS:
1131 DumpLiteral4Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1132 break;
1133 case MachO::S_8BYTE_LITERALS:
1134 DumpLiteral8Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1135 break;
1136 case MachO::S_16BYTE_LITERALS:
1137 DumpLiteral16Section(O, sect, sect_size, sect_addr, !NoLeadingAddr);
1138 break;
1139 case MachO::S_LITERAL_POINTERS:
1140 DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
1141 !NoLeadingAddr);
1142 break;
1143 case MachO::S_MOD_INIT_FUNC_POINTERS:
1144 case MachO::S_MOD_TERM_FUNC_POINTERS:
1145 DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
1146 verbose);
1147 break;
1148 default:
1149 outs() << "Unknown section type ("
1150 << format("0x%08" PRIx32"x", section_type) << ")\n";
1151 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1152 break;
1153 }
1154 } else {
1155 if (section_type == MachO::S_ZEROFILL)
1156 outs() << "zerofill section and has no contents in the file\n";
1157 else
1158 DumpRawSectionContents(O, sect, sect_size, sect_addr);
1159 }
1160 }
1161 }
1162 }
1163}
1164
1165static void DumpInfoPlistSectionContents(StringRef Filename,
1166 MachOObjectFile *O) {
1167 for (const SectionRef &Section : O->sections()) {
1168 StringRef SectName;
1169 Section.getName(SectName);
1170 DataRefImpl Ref = Section.getRawDataRefImpl();
1171 StringRef SegName = O->getSectionFinalSegmentName(Ref);
1172 if (SegName == "__TEXT" && SectName == "__info_plist") {
1173 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
1174 StringRef BytesStr;
1175 Section.getContents(BytesStr);
1176 const char *sect = reinterpret_cast<const char *>(BytesStr.data());
1177 outs() << sect;
1178 return;
1179 }
1180 }
1181}
1182
1183// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
1184// and if it is and there is a list of architecture flags is specified then
1185// check to make sure this Mach-O file is one of those architectures or all
1186// architectures were specified. If not then an error is generated and this
1187// routine returns false. Else it returns true.
1188static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
1189 auto *MachO = dyn_cast<MachOObjectFile>(O);
1190
1191 if (!MachO || ArchAll || ArchFlags.empty())
1192 return true;
1193
1194 MachO::mach_header H;
1195 MachO::mach_header_64 H_64;
1196 Triple T;
1197 if (MachO->is64Bit()) {
1198 H_64 = MachO->MachOObjectFile::getHeader64();
1199 T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype);
1200 } else {
1201 H = MachO->MachOObjectFile::getHeader();
1202 T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype);
1203 }
1204 if (none_of(ArchFlags, [&](const std::string &Name) {
1205 return Name == T.getArchName();
1206 })) {
1207 errs() << "llvm-objdump: " + Filename + ": No architecture specified.\n";
1208 return false;
1209 }
1210 return true;
1211}
1212
1213static void printObjcMetaData(MachOObjectFile *O, bool verbose);
1214
1215// ProcessMachO() is passed a single opened Mach-O file, which may be an
1216// archive member and or in a slice of a universal file. It prints the
1217// the file name and header info and then processes it according to the
1218// command line options.
1219static void ProcessMachO(StringRef Filename, MachOObjectFile *MachOOF,
1220 StringRef ArchiveMemberName = StringRef(),
1221 StringRef ArchitectureName = StringRef()) {
1222 // If we are doing some processing here on the Mach-O file print the header
1223 // info. And don't print it otherwise like in the case of printing the
1224 // UniversalHeaders or ArchiveHeaders.
1225 if (Disassemble || PrivateHeaders || ExportsTrie || Rebase || Bind || SymbolTable ||
1226 LazyBind || WeakBind || IndirectSymbols || DataInCode || LinkOptHints ||
1227 DylibsUsed || DylibId || ObjcMetaData || (FilterSections.size() != 0)) {
1228 outs() << Filename;
1229 if (!ArchiveMemberName.empty())
1230 outs() << '(' << ArchiveMemberName << ')';
1231 if (!ArchitectureName.empty())
1232 outs() << " (architecture " << ArchitectureName << ")";
1233 outs() << ":\n";
1234 }
1235
1236 if (Disassemble)
1237 DisassembleMachO(Filename, MachOOF, "__TEXT", "__text");
1238 if (IndirectSymbols)
1239 PrintIndirectSymbols(MachOOF, !NonVerbose);
1240 if (DataInCode)
1241 PrintDataInCodeTable(MachOOF, !NonVerbose);
1242 if (LinkOptHints)
1243 PrintLinkOptHints(MachOOF);
1244 if (Relocations)
1245 PrintRelocations(MachOOF);
1246 if (SectionHeaders)
1247 PrintSectionHeaders(MachOOF);
1248 if (SectionContents)
1249 PrintSectionContents(MachOOF);
1250 if (FilterSections.size() != 0)
1251 DumpSectionContents(Filename, MachOOF, !NonVerbose);
1252 if (InfoPlist)
1253 DumpInfoPlistSectionContents(Filename, MachOOF);
1254 if (DylibsUsed)
1255 PrintDylibs(MachOOF, false);
1256 if (DylibId)
1257 PrintDylibs(MachOOF, true);
1258 if (SymbolTable) {
1259 StringRef ArchiveName = ArchiveMemberName == StringRef() ? "" : Filename;
1260 PrintSymbolTable(MachOOF, ArchiveName, ArchitectureName);
1261 }
1262 if (UnwindInfo)
1263 printMachOUnwindInfo(MachOOF);
1264 if (PrivateHeaders) {
1265 printMachOFileHeader(MachOOF);
1266 printMachOLoadCommands(MachOOF);
1267 }
1268 if (FirstPrivateHeader)
1269 printMachOFileHeader(MachOOF);
1270 if (ObjcMetaData)
1271 printObjcMetaData(MachOOF, !NonVerbose);
1272 if (ExportsTrie)
1273 printExportsTrie(MachOOF);
1274 if (Rebase)
1275 printRebaseTable(MachOOF);
1276 if (Bind)
1277 printBindTable(MachOOF);
1278 if (LazyBind)
1279 printLazyBindTable(MachOOF);
1280 if (WeakBind)
1281 printWeakBindTable(MachOOF);
1282
1283 if (DwarfDumpType != DIDT_Null) {
1284 std::unique_ptr<DIContext> DICtx(new DWARFContextInMemory(*MachOOF));
1285 // Dump the complete DWARF structure.
1286 DICtx->dump(outs(), DwarfDumpType, true /* DumpEH */);
1287 }
1288}
1289
1290// printUnknownCPUType() helps print_fat_headers for unknown CPU's.
1291static void printUnknownCPUType(uint32_t cputype, uint32_t cpusubtype) {
1292 outs() << " cputype (" << cputype << ")\n";
1293 outs() << " cpusubtype (" << cpusubtype << ")\n";
1294}
1295
1296// printCPUType() helps print_fat_headers by printing the cputype and
1297// pusubtype (symbolically for the one's it knows about).
1298static void printCPUType(uint32_t cputype, uint32_t cpusubtype) {
1299 switch (cputype) {
1300 case MachO::CPU_TYPE_I386:
1301 switch (cpusubtype) {
1302 case MachO::CPU_SUBTYPE_I386_ALL:
1303 outs() << " cputype CPU_TYPE_I386\n";
1304 outs() << " cpusubtype CPU_SUBTYPE_I386_ALL\n";
1305 break;
1306 default:
1307 printUnknownCPUType(cputype, cpusubtype);
1308 break;
1309 }
1310 break;
1311 case MachO::CPU_TYPE_X86_64:
1312 switch (cpusubtype) {
1313 case MachO::CPU_SUBTYPE_X86_64_ALL:
1314 outs() << " cputype CPU_TYPE_X86_64\n";
1315 outs() << " cpusubtype CPU_SUBTYPE_X86_64_ALL\n";
1316 break;
1317 case MachO::CPU_SUBTYPE_X86_64_H:
1318 outs() << " cputype CPU_TYPE_X86_64\n";
1319 outs() << " cpusubtype CPU_SUBTYPE_X86_64_H\n";
1320 break;
1321 default:
1322 printUnknownCPUType(cputype, cpusubtype);
1323 break;
1324 }
1325 break;
1326 case MachO::CPU_TYPE_ARM:
1327 switch (cpusubtype) {
1328 case MachO::CPU_SUBTYPE_ARM_ALL:
1329 outs() << " cputype CPU_TYPE_ARM\n";
1330 outs() << " cpusubtype CPU_SUBTYPE_ARM_ALL\n";
1331 break;
1332 case MachO::CPU_SUBTYPE_ARM_V4T:
1333 outs() << " cputype CPU_TYPE_ARM\n";
1334 outs() << " cpusubtype CPU_SUBTYPE_ARM_V4T\n";
1335 break;
1336 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
1337 outs() << " cputype CPU_TYPE_ARM\n";
1338 outs() << " cpusubtype CPU_SUBTYPE_ARM_V5TEJ\n";
1339 break;
1340 case MachO::CPU_SUBTYPE_ARM_XSCALE:
1341 outs() << " cputype CPU_TYPE_ARM\n";
1342 outs() << " cpusubtype CPU_SUBTYPE_ARM_XSCALE\n";
1343 break;
1344 case MachO::CPU_SUBTYPE_ARM_V6:
1345 outs() << " cputype CPU_TYPE_ARM\n";
1346 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6\n";
1347 break;
1348 case MachO::CPU_SUBTYPE_ARM_V6M:
1349 outs() << " cputype CPU_TYPE_ARM\n";
1350 outs() << " cpusubtype CPU_SUBTYPE_ARM_V6M\n";
1351 break;
1352 case MachO::CPU_SUBTYPE_ARM_V7:
1353 outs() << " cputype CPU_TYPE_ARM\n";
1354 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7\n";
1355 break;
1356 case MachO::CPU_SUBTYPE_ARM_V7EM:
1357 outs() << " cputype CPU_TYPE_ARM\n";
1358 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7EM\n";
1359 break;
1360 case MachO::CPU_SUBTYPE_ARM_V7K:
1361 outs() << " cputype CPU_TYPE_ARM\n";
1362 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7K\n";
1363 break;
1364 case MachO::CPU_SUBTYPE_ARM_V7M:
1365 outs() << " cputype CPU_TYPE_ARM\n";
1366 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7M\n";
1367 break;
1368 case MachO::CPU_SUBTYPE_ARM_V7S:
1369 outs() << " cputype CPU_TYPE_ARM\n";
1370 outs() << " cpusubtype CPU_SUBTYPE_ARM_V7S\n";
1371 break;
1372 default:
1373 printUnknownCPUType(cputype, cpusubtype);
1374 break;
1375 }
1376 break;
1377 case MachO::CPU_TYPE_ARM64:
1378 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
1379 case MachO::CPU_SUBTYPE_ARM64_ALL:
1380 outs() << " cputype CPU_TYPE_ARM64\n";
1381 outs() << " cpusubtype CPU_SUBTYPE_ARM64_ALL\n";
1382 break;
1383 default:
1384 printUnknownCPUType(cputype, cpusubtype);
1385 break;
1386 }
1387 break;
1388 default:
1389 printUnknownCPUType(cputype, cpusubtype);
1390 break;
1391 }
1392}
1393
1394static void printMachOUniversalHeaders(const object::MachOUniversalBinary *UB,
1395 bool verbose) {
1396 outs() << "Fat headers\n";
1397 if (verbose) {
1398 if (UB->getMagic() == MachO::FAT_MAGIC)
1399 outs() << "fat_magic FAT_MAGIC\n";
1400 else // UB->getMagic() == MachO::FAT_MAGIC_64
1401 outs() << "fat_magic FAT_MAGIC_64\n";
1402 } else
1403 outs() << "fat_magic " << format("0x%" PRIx32"x", MachO::FAT_MAGIC) << "\n";
1404
1405 uint32_t nfat_arch = UB->getNumberOfObjects();
1406 StringRef Buf = UB->getData();
1407 uint64_t size = Buf.size();
1408 uint64_t big_size = sizeof(struct MachO::fat_header) +
1409 nfat_arch * sizeof(struct MachO::fat_arch);
1410 outs() << "nfat_arch " << UB->getNumberOfObjects();
1411 if (nfat_arch == 0)
1412 outs() << " (malformed, contains zero architecture types)\n";
1413 else if (big_size > size)
1414 outs() << " (malformed, architectures past end of file)\n";
1415 else
1416 outs() << "\n";
1417
1418 for (uint32_t i = 0; i < nfat_arch; ++i) {
1419 MachOUniversalBinary::ObjectForArch OFA(UB, i);
1420 uint32_t cputype = OFA.getCPUType();
1421 uint32_t cpusubtype = OFA.getCPUSubType();
1422 outs() << "architecture ";
1423 for (uint32_t j = 0; i != 0 && j <= i - 1; j++) {
1424 MachOUniversalBinary::ObjectForArch other_OFA(UB, j);
1425 uint32_t other_cputype = other_OFA.getCPUType();
1426 uint32_t other_cpusubtype = other_OFA.getCPUSubType();
1427 if (cputype != 0 && cpusubtype != 0 && cputype == other_cputype &&
1428 (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) ==
1429 (other_cpusubtype & ~MachO::CPU_SUBTYPE_MASK)) {
1430 outs() << "(illegal duplicate architecture) ";
1431 break;
1432 }
1433 }
1434 if (verbose) {
1435 outs() << OFA.getArchTypeName() << "\n";
1436 printCPUType(cputype, cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
1437 } else {
1438 outs() << i << "\n";
1439 outs() << " cputype " << cputype << "\n";
1440 outs() << " cpusubtype " << (cpusubtype & ~MachO::CPU_SUBTYPE_MASK)
1441 << "\n";
1442 }
1443 if (verbose &&
1444 (cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64)
1445 outs() << " capabilities CPU_SUBTYPE_LIB64\n";
1446 else
1447 outs() << " capabilities "
1448 << format("0x%" PRIx32"x",
1449 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24) << "\n";
1450 outs() << " offset " << OFA.getOffset();
1451 if (OFA.getOffset() > size)
1452 outs() << " (past end of file)";
1453 if (OFA.getOffset() % (1 << OFA.getAlign()) != 0)
1454 outs() << " (not aligned on it's alignment (2^" << OFA.getAlign() << ")";
1455 outs() << "\n";
1456 outs() << " size " << OFA.getSize();
1457 big_size = OFA.getOffset() + OFA.getSize();
1458 if (big_size > size)
1459 outs() << " (past end of file)";
1460 outs() << "\n";
1461 outs() << " align 2^" << OFA.getAlign() << " (" << (1 << OFA.getAlign())
1462 << ")\n";
1463 }
1464}
1465
1466static void printArchiveChild(StringRef Filename, const Archive::Child &C,
1467 bool verbose, bool print_offset,
1468 StringRef ArchitectureName = StringRef()) {
1469 if (print_offset)
1470 outs() << C.getChildOffset() << "\t";
1471 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
1472 if (!ModeOrErr)
1473 report_error(Filename, C, ModeOrErr.takeError(), ArchitectureName);
1474 sys::fs::perms Mode = ModeOrErr.get();
1475 if (verbose) {
1476 // FIXME: this first dash, "-", is for (Mode & S_IFMT) == S_IFREG.
1477 // But there is nothing in sys::fs::perms for S_IFMT or S_IFREG.
1478 outs() << "-";
1479 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
1480 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
1481 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
1482 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
1483 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
1484 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
1485 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
1486 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
1487 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
1488 } else {
1489 outs() << format("0%o ", Mode);
1490 }
1491
1492 Expected<unsigned> UIDOrErr = C.getUID();
1493 if (!UIDOrErr)
1494 report_error(Filename, C, UIDOrErr.takeError(), ArchitectureName);
1495 unsigned UID = UIDOrErr.get();
1496 outs() << format("%3d/", UID);
1497 Expected<unsigned> GIDOrErr = C.getGID();
1498 if (!GIDOrErr)
1499 report_error(Filename, C, GIDOrErr.takeError(), ArchitectureName);
1500 unsigned GID = GIDOrErr.get();
1501 outs() << format("%-3d ", GID);
1502 Expected<uint64_t> Size = C.getRawSize();
1503 if (!Size)
1504 report_error(Filename, C, Size.takeError(), ArchitectureName);
1505 outs() << format("%5" PRId64"l" "d", Size.get()) << " ";
1506
1507 StringRef RawLastModified = C.getRawLastModified();
1508 if (verbose) {
1509 unsigned Seconds;
1510 if (RawLastModified.getAsInteger(10, Seconds))
1511 outs() << "(date: \"" << RawLastModified
1512 << "\" contains non-decimal chars) ";
1513 else {
1514 // Since cime(3) returns a 26 character string of the form:
1515 // "Sun Sep 16 01:03:52 1973\n\0"
1516 // just print 24 characters.
1517 time_t t = Seconds;
1518 outs() << format("%.24s ", ctime(&t));
1519 }
1520 } else {
1521 outs() << RawLastModified << " ";
1522 }
1523
1524 if (verbose) {
1525 Expected<StringRef> NameOrErr = C.getName();
1526 if (!NameOrErr) {
1527 consumeError(NameOrErr.takeError());
1528 Expected<StringRef> NameOrErr = C.getRawName();
1529 if (!NameOrErr)
1530 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1531 StringRef RawName = NameOrErr.get();
1532 outs() << RawName << "\n";
1533 } else {
1534 StringRef Name = NameOrErr.get();
1535 outs() << Name << "\n";
1536 }
1537 } else {
1538 Expected<StringRef> NameOrErr = C.getRawName();
1539 if (!NameOrErr)
1540 report_error(Filename, C, NameOrErr.takeError(), ArchitectureName);
1541 StringRef RawName = NameOrErr.get();
1542 outs() << RawName << "\n";
1543 }
1544}
1545
1546static void printArchiveHeaders(StringRef Filename, Archive *A, bool verbose,
1547 bool print_offset,
1548 StringRef ArchitectureName = StringRef()) {
1549 Error Err;
1550 for (const auto &C : A->children(Err, false))
1551 printArchiveChild(Filename, C, verbose, print_offset, ArchitectureName);
1552
1553 if (Err)
1554 report_error(Filename, std::move(Err));
1555}
1556
1557// ParseInputMachO() parses the named Mach-O file in Filename and handles the
1558// -arch flags selecting just those slices as specified by them and also parses
1559// archive files. Then for each individual Mach-O file ProcessMachO() is
1560// called to process the file based on the command line options.
1561void llvm::ParseInputMachO(StringRef Filename) {
1562 // Check for -arch all and verifiy the -arch flags are valid.
1563 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1564 if (ArchFlags[i] == "all") {
1565 ArchAll = true;
1566 } else {
1567 if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
1568 errs() << "llvm-objdump: Unknown architecture named '" + ArchFlags[i] +
1569 "'for the -arch option\n";
1570 return;
1571 }
1572 }
1573 }
1574
1575 // Attempt to open the binary.
1576 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
1577 if (!BinaryOrErr)
1578 report_error(Filename, BinaryOrErr.takeError());
1579 Binary &Bin = *BinaryOrErr.get().getBinary();
1580
1581 if (Archive *A = dyn_cast<Archive>(&Bin)) {
1582 outs() << "Archive : " << Filename << "\n";
1583 if (ArchiveHeaders)
1584 printArchiveHeaders(Filename, A, !NonVerbose, ArchiveMemberOffsets);
1585
1586 Error Err;
1587 for (auto &C : A->children(Err)) {
1588 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1589 if (!ChildOrErr) {
1590 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1591 report_error(Filename, C, std::move(E));
1592 continue;
1593 }
1594 if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1595 if (!checkMachOAndArchFlags(O, Filename))
1596 return;
1597 ProcessMachO(Filename, O, O->getFileName());
1598 }
1599 }
1600 if (Err)
1601 report_error(Filename, std::move(Err));
1602 return;
1603 }
1604 if (UniversalHeaders) {
1605 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin))
1606 printMachOUniversalHeaders(UB, !NonVerbose);
1607 }
1608 if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
1609 // If we have a list of architecture flags specified dump only those.
1610 if (!ArchAll && ArchFlags.size() != 0) {
1611 // Look for a slice in the universal binary that matches each ArchFlag.
1612 bool ArchFound;
1613 for (unsigned i = 0; i < ArchFlags.size(); ++i) {
1614 ArchFound = false;
1615 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1616 E = UB->end_objects();
1617 I != E; ++I) {
1618 if (ArchFlags[i] == I->getArchTypeName()) {
1619 ArchFound = true;
1620 Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
1621 I->getAsObjectFile();
1622 std::string ArchitectureName = "";
1623 if (ArchFlags.size() > 1)
1624 ArchitectureName = I->getArchTypeName();
1625 if (ObjOrErr) {
1626 ObjectFile &O = *ObjOrErr.get();
1627 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1628 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1629 } else if (auto E = isNotObjectErrorInvalidFileType(
1630 ObjOrErr.takeError())) {
1631 report_error(Filename, StringRef(), std::move(E),
1632 ArchitectureName);
1633 continue;
1634 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1635 I->getAsArchive()) {
1636 std::unique_ptr<Archive> &A = *AOrErr;
1637 outs() << "Archive : " << Filename;
1638 if (!ArchitectureName.empty())
1639 outs() << " (architecture " << ArchitectureName << ")";
1640 outs() << "\n";
1641 if (ArchiveHeaders)
1642 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1643 ArchiveMemberOffsets, ArchitectureName);
1644 Error Err;
1645 for (auto &C : A->children(Err)) {
1646 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1647 if (!ChildOrErr) {
1648 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1649 report_error(Filename, C, std::move(E), ArchitectureName);
1650 continue;
1651 }
1652 if (MachOObjectFile *O =
1653 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1654 ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
1655 }
1656 if (Err)
1657 report_error(Filename, std::move(Err));
1658 } else {
1659 consumeError(AOrErr.takeError());
1660 error("Mach-O universal file: " + Filename + " for " +
1661 "architecture " + StringRef(I->getArchTypeName()) +
1662 " is not a Mach-O file or an archive file");
1663 }
1664 }
1665 }
1666 if (!ArchFound) {
1667 errs() << "llvm-objdump: file: " + Filename + " does not contain "
1668 << "architecture: " + ArchFlags[i] + "\n";
1669 return;
1670 }
1671 }
1672 return;
1673 }
1674 // No architecture flags were specified so if this contains a slice that
1675 // matches the host architecture dump only that.
1676 if (!ArchAll) {
1677 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1678 E = UB->end_objects();
1679 I != E; ++I) {
1680 if (MachOObjectFile::getHostArch().getArchName() ==
1681 I->getArchTypeName()) {
1682 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1683 std::string ArchiveName;
1684 ArchiveName.clear();
1685 if (ObjOrErr) {
1686 ObjectFile &O = *ObjOrErr.get();
1687 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
1688 ProcessMachO(Filename, MachOOF);
1689 } else if (auto E = isNotObjectErrorInvalidFileType(
1690 ObjOrErr.takeError())) {
1691 report_error(Filename, std::move(E));
1692 continue;
1693 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1694 I->getAsArchive()) {
1695 std::unique_ptr<Archive> &A = *AOrErr;
1696 outs() << "Archive : " << Filename << "\n";
1697 if (ArchiveHeaders)
1698 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1699 ArchiveMemberOffsets);
1700 Error Err;
1701 for (auto &C : A->children(Err)) {
1702 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1703 if (!ChildOrErr) {
1704 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1705 report_error(Filename, C, std::move(E));
1706 continue;
1707 }
1708 if (MachOObjectFile *O =
1709 dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
1710 ProcessMachO(Filename, O, O->getFileName());
1711 }
1712 if (Err)
1713 report_error(Filename, std::move(Err));
1714 } else {
1715 consumeError(AOrErr.takeError());
1716 error("Mach-O universal file: " + Filename + " for architecture " +
1717 StringRef(I->getArchTypeName()) +
1718 " is not a Mach-O file or an archive file");
1719 }
1720 return;
1721 }
1722 }
1723 }
1724 // Either all architectures have been specified or none have been specified
1725 // and this does not contain the host architecture so dump all the slices.
1726 bool moreThanOneArch = UB->getNumberOfObjects() > 1;
1727 for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
1728 E = UB->end_objects();
1729 I != E; ++I) {
1730 Expected<std::unique_ptr<ObjectFile>> ObjOrErr = I->getAsObjectFile();
1731 std::string ArchitectureName = "";
1732 if (moreThanOneArch)
1733 ArchitectureName = I->getArchTypeName();
1734 if (ObjOrErr) {
1735 ObjectFile &Obj = *ObjOrErr.get();
1736 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&Obj))
1737 ProcessMachO(Filename, MachOOF, "", ArchitectureName);
1738 } else if (auto E = isNotObjectErrorInvalidFileType(
1739 ObjOrErr.takeError())) {
1740 report_error(StringRef(), Filename, std::move(E), ArchitectureName);
1741 continue;
1742 } else if (Expected<std::unique_ptr<Archive>> AOrErr =
1743 I->getAsArchive()) {
1744 std::unique_ptr<Archive> &A = *AOrErr;
1745 outs() << "Archive : " << Filename;
1746 if (!ArchitectureName.empty())
1747 outs() << " (architecture " << ArchitectureName << ")";
1748 outs() << "\n";
1749 if (ArchiveHeaders)
1750 printArchiveHeaders(Filename, A.get(), !NonVerbose,
1751 ArchiveMemberOffsets, ArchitectureName);
1752 Error Err;
1753 for (auto &C : A->children(Err)) {
1754 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
1755 if (!ChildOrErr) {
1756 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
1757 report_error(Filename, C, std::move(E), ArchitectureName);
1758 continue;
1759 }
1760 if (MachOObjectFile *O =
1761 dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
1762 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(O))
1763 ProcessMachO(Filename, MachOOF, MachOOF->getFileName(),
1764 ArchitectureName);
1765 }
1766 }
1767 if (Err)
1768 report_error(Filename, std::move(Err));
1769 } else {
1770 consumeError(AOrErr.takeError());
1771 error("Mach-O universal file: " + Filename + " for architecture " +
1772 StringRef(I->getArchTypeName()) +
1773 " is not a Mach-O file or an archive file");
1774 }
1775 }
1776 return;
1777 }
1778 if (ObjectFile *O = dyn_cast<ObjectFile>(&Bin)) {
1779 if (!checkMachOAndArchFlags(O, Filename))
1780 return;
1781 if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&*O)) {
1782 ProcessMachO(Filename, MachOOF);
1783 } else
1784 errs() << "llvm-objdump: '" << Filename << "': "
1785 << "Object is not a Mach-O file type.\n";
1786 return;
1787 }
1788 llvm_unreachable("Input object can't be invalid at this point")::llvm::llvm_unreachable_internal("Input object can't be invalid at this point"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 1788)
;
1789}
1790
1791typedef std::pair<uint64_t, const char *> BindInfoEntry;
1792typedef std::vector<BindInfoEntry> BindTable;
1793typedef BindTable::iterator bind_table_iterator;
1794
1795// The block of info used by the Symbolizer call backs.
1796struct DisassembleInfo {
1797 bool verbose;
1798 MachOObjectFile *O;
1799 SectionRef S;
1800 SymbolAddressMap *AddrMap;
1801 std::vector<SectionRef> *Sections;
1802 const char *class_name;
1803 const char *selector_name;
1804 char *method;
1805 char *demangled_name;
1806 uint64_t adrp_addr;
1807 uint32_t adrp_inst;
1808 BindTable *bindtable;
1809 uint32_t depth;
1810};
1811
1812// SymbolizerGetOpInfo() is the operand information call back function.
1813// This is called to get the symbolic information for operand(s) of an
1814// instruction when it is being done. This routine does this from
1815// the relocation information, symbol table, etc. That block of information
1816// is a pointer to the struct DisassembleInfo that was passed when the
1817// disassembler context was created and passed to back to here when
1818// called back by the disassembler for instruction operands that could have
1819// relocation information. The address of the instruction containing operand is
1820// at the Pc parameter. The immediate value the operand has is passed in
1821// op_info->Value and is at Offset past the start of the instruction and has a
1822// byte Size of 1, 2 or 4. The symbolc information is returned in TagBuf is the
1823// LLVMOpInfo1 struct defined in the header "llvm-c/Disassembler.h" as symbol
1824// names and addends of the symbolic expression to add for the operand. The
1825// value of TagType is currently 1 (for the LLVMOpInfo1 struct). If symbolic
1826// information is returned then this function returns 1 else it returns 0.
1827static int SymbolizerGetOpInfo(void *DisInfo, uint64_t Pc, uint64_t Offset,
1828 uint64_t Size, int TagType, void *TagBuf) {
1829 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
1830 struct LLVMOpInfo1 *op_info = (struct LLVMOpInfo1 *)TagBuf;
1831 uint64_t value = op_info->Value;
1832
1833 // Make sure all fields returned are zero if we don't set them.
1834 memset((void *)op_info, '\0', sizeof(struct LLVMOpInfo1));
1835 op_info->Value = value;
1836
1837 // If the TagType is not the value 1 which it code knows about or if no
1838 // verbose symbolic information is wanted then just return 0, indicating no
1839 // information is being returned.
1840 if (TagType != 1 || !info->verbose)
1
Assuming 'TagType' is equal to 1
2
Assuming the condition is false
3
Taking false branch
1841 return 0;
1842
1843 unsigned int Arch = info->O->getArch();
1844 if (Arch == Triple::x86) {
4
Assuming 'Arch' is not equal to x86
5
Taking false branch
1845 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1846 return 0;
1847 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1848 // TODO:
1849 // Search the external relocation entries of a fully linked image
1850 // (if any) for an entry that matches this segment offset.
1851 // uint32_t seg_offset = (Pc + Offset);
1852 return 0;
1853 }
1854 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1855 // for an entry for this section offset.
1856 uint32_t sect_addr = info->S.getAddress();
1857 uint32_t sect_offset = (Pc + Offset) - sect_addr;
1858 bool reloc_found = false;
1859 DataRefImpl Rel;
1860 MachO::any_relocation_info RE;
1861 bool isExtern = false;
1862 SymbolRef Symbol;
1863 bool r_scattered = false;
1864 uint32_t r_value, pair_r_value, r_type;
1865 for (const RelocationRef &Reloc : info->S.relocations()) {
1866 uint64_t RelocOffset = Reloc.getOffset();
1867 if (RelocOffset == sect_offset) {
1868 Rel = Reloc.getRawDataRefImpl();
1869 RE = info->O->getRelocation(Rel);
1870 r_type = info->O->getAnyRelocationType(RE);
1871 r_scattered = info->O->isRelocationScattered(RE);
1872 if (r_scattered) {
1873 r_value = info->O->getScatteredRelocationValue(RE);
1874 if (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1875 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF) {
1876 DataRefImpl RelNext = Rel;
1877 info->O->moveRelocationNext(RelNext);
1878 MachO::any_relocation_info RENext;
1879 RENext = info->O->getRelocation(RelNext);
1880 if (info->O->isRelocationScattered(RENext))
1881 pair_r_value = info->O->getScatteredRelocationValue(RENext);
1882 else
1883 return 0;
1884 }
1885 } else {
1886 isExtern = info->O->getPlainRelocationExternal(RE);
1887 if (isExtern) {
1888 symbol_iterator RelocSym = Reloc.getSymbol();
1889 Symbol = *RelocSym;
1890 }
1891 }
1892 reloc_found = true;
1893 break;
1894 }
1895 }
1896 if (reloc_found && isExtern) {
1897 Expected<StringRef> SymName = Symbol.getName();
1898 if (!SymName) {
1899 std::string Buf;
1900 raw_string_ostream OS(Buf);
1901 logAllUnhandledErrors(SymName.takeError(), OS, "");
1902 OS.flush();
1903 report_fatal_error(Buf);
1904 }
1905 const char *name = SymName->data();
1906 op_info->AddSymbol.Present = 1;
1907 op_info->AddSymbol.Name = name;
1908 // For i386 extern relocation entries the value in the instruction is
1909 // the offset from the symbol, and value is already set in op_info->Value.
1910 return 1;
1911 }
1912 if (reloc_found && (r_type == MachO::GENERIC_RELOC_SECTDIFF ||
1913 r_type == MachO::GENERIC_RELOC_LOCAL_SECTDIFF)) {
1914 const char *add = GuessSymbolName(r_value, info->AddrMap);
1915 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
1916 uint32_t offset = value - (r_value - pair_r_value);
1917 op_info->AddSymbol.Present = 1;
1918 if (add != nullptr)
1919 op_info->AddSymbol.Name = add;
1920 else
1921 op_info->AddSymbol.Value = r_value;
1922 op_info->SubtractSymbol.Present = 1;
1923 if (sub != nullptr)
1924 op_info->SubtractSymbol.Name = sub;
1925 else
1926 op_info->SubtractSymbol.Value = pair_r_value;
1927 op_info->Value = offset;
1928 return 1;
1929 }
1930 return 0;
1931 }
1932 if (Arch == Triple::x86_64) {
6
Assuming 'Arch' is not equal to x86_64
7
Taking false branch
1933 if (Size != 1 && Size != 2 && Size != 4 && Size != 0)
1934 return 0;
1935 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
1936 // TODO:
1937 // Search the external relocation entries of a fully linked image
1938 // (if any) for an entry that matches this segment offset.
1939 // uint64_t seg_offset = (Pc + Offset);
1940 return 0;
1941 }
1942 // In MH_OBJECT filetypes search the section's relocation entries (if any)
1943 // for an entry for this section offset.
1944 uint64_t sect_addr = info->S.getAddress();
1945 uint64_t sect_offset = (Pc + Offset) - sect_addr;
1946 bool reloc_found = false;
1947 DataRefImpl Rel;
1948 MachO::any_relocation_info RE;
1949 bool isExtern = false;
1950 SymbolRef Symbol;
1951 for (const RelocationRef &Reloc : info->S.relocations()) {
1952 uint64_t RelocOffset = Reloc.getOffset();
1953 if (RelocOffset == sect_offset) {
1954 Rel = Reloc.getRawDataRefImpl();
1955 RE = info->O->getRelocation(Rel);
1956 // NOTE: Scattered relocations don't exist on x86_64.
1957 isExtern = info->O->getPlainRelocationExternal(RE);
1958 if (isExtern) {
1959 symbol_iterator RelocSym = Reloc.getSymbol();
1960 Symbol = *RelocSym;
1961 }
1962 reloc_found = true;
1963 break;
1964 }
1965 }
1966 if (reloc_found && isExtern) {
1967 // The Value passed in will be adjusted by the Pc if the instruction
1968 // adds the Pc. But for x86_64 external relocation entries the Value
1969 // is the offset from the external symbol.
1970 if (info->O->getAnyRelocationPCRel(RE))
1971 op_info->Value -= Pc + Offset + Size;
1972 Expected<StringRef> SymName = Symbol.getName();
1973 if (!SymName) {
1974 std::string Buf;
1975 raw_string_ostream OS(Buf);
1976 logAllUnhandledErrors(SymName.takeError(), OS, "");
1977 OS.flush();
1978 report_fatal_error(Buf);
1979 }
1980 const char *name = SymName->data();
1981 unsigned Type = info->O->getAnyRelocationType(RE);
1982 if (Type == MachO::X86_64_RELOC_SUBTRACTOR) {
1983 DataRefImpl RelNext = Rel;
1984 info->O->moveRelocationNext(RelNext);
1985 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
1986 unsigned TypeNext = info->O->getAnyRelocationType(RENext);
1987 bool isExternNext = info->O->getPlainRelocationExternal(RENext);
1988 unsigned SymbolNum = info->O->getPlainRelocationSymbolNum(RENext);
1989 if (TypeNext == MachO::X86_64_RELOC_UNSIGNED && isExternNext) {
1990 op_info->SubtractSymbol.Present = 1;
1991 op_info->SubtractSymbol.Name = name;
1992 symbol_iterator RelocSymNext = info->O->getSymbolByIndex(SymbolNum);
1993 Symbol = *RelocSymNext;
1994 Expected<StringRef> SymNameNext = Symbol.getName();
1995 if (!SymNameNext) {
1996 std::string Buf;
1997 raw_string_ostream OS(Buf);
1998 logAllUnhandledErrors(SymNameNext.takeError(), OS, "");
1999 OS.flush();
2000 report_fatal_error(Buf);
2001 }
2002 name = SymNameNext->data();
2003 }
2004 }
2005 // TODO: add the VariantKinds to op_info->VariantKind for relocation types
2006 // like: X86_64_RELOC_TLV, X86_64_RELOC_GOT_LOAD and X86_64_RELOC_GOT.
2007 op_info->AddSymbol.Present = 1;
2008 op_info->AddSymbol.Name = name;
2009 return 1;
2010 }
2011 return 0;
2012 }
2013 if (Arch == Triple::arm) {
8
Assuming 'Arch' is equal to arm
9
Taking true branch
2014 if (Offset != 0 || (Size != 4 && Size != 2))
10
Assuming 'Offset' is equal to 0
11
Assuming 'Size' is equal to 4
2015 return 0;
2016 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
12
Assuming the condition is false
13
Taking false branch
2017 // TODO:
2018 // Search the external relocation entries of a fully linked image
2019 // (if any) for an entry that matches this segment offset.
2020 // uint32_t seg_offset = (Pc + Offset);
2021 return 0;
2022 }
2023 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2024 // for an entry for this section offset.
2025 uint32_t sect_addr = info->S.getAddress();
2026 uint32_t sect_offset = (Pc + Offset) - sect_addr;
2027 DataRefImpl Rel;
2028 MachO::any_relocation_info RE;
2029 bool isExtern = false;
2030 SymbolRef Symbol;
2031 bool r_scattered = false;
2032 uint32_t r_value, pair_r_value, r_type, r_length, other_half;
14
'r_value' declared without an initial value
2033 auto Reloc =
2034 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2035 uint64_t RelocOffset = Reloc.getOffset();
2036 return RelocOffset == sect_offset;
2037 });
2038
2039 if (Reloc == info->S.relocations().end())
15
Assuming the condition is false
16
Taking false branch
2040 return 0;
2041
2042 Rel = Reloc->getRawDataRefImpl();
2043 RE = info->O->getRelocation(Rel);
2044 r_length = info->O->getAnyRelocationLength(RE);
2045 r_scattered = info->O->isRelocationScattered(RE);
2046 if (r_scattered) {
17
Assuming 'r_scattered' is 0
18
Taking false branch
2047 r_value = info->O->getScatteredRelocationValue(RE);
2048 r_type = info->O->getScatteredRelocationType(RE);
2049 } else {
2050 r_type = info->O->getAnyRelocationType(RE);
2051 isExtern = info->O->getPlainRelocationExternal(RE);
2052 if (isExtern) {
19
Assuming 'isExtern' is 0
20
Taking false branch
2053 symbol_iterator RelocSym = Reloc->getSymbol();
2054 Symbol = *RelocSym;
2055 }
2056 }
2057 if (r_type == MachO::ARM_RELOC_HALF ||
21
Assuming 'r_type' is not equal to ARM_RELOC_HALF
25
Taking true branch
2058 r_type == MachO::ARM_RELOC_SECTDIFF ||
22
Assuming 'r_type' is not equal to ARM_RELOC_SECTDIFF
2059 r_type == MachO::ARM_RELOC_LOCAL_SECTDIFF ||
23
Assuming 'r_type' is not equal to ARM_RELOC_LOCAL_SECTDIFF
2060 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
24
Assuming 'r_type' is equal to ARM_RELOC_HALF_SECTDIFF
2061 DataRefImpl RelNext = Rel;
2062 info->O->moveRelocationNext(RelNext);
2063 MachO::any_relocation_info RENext;
2064 RENext = info->O->getRelocation(RelNext);
2065 other_half = info->O->getAnyRelocationAddress(RENext) & 0xffff;
2066 if (info->O->isRelocationScattered(RENext))
26
Assuming the condition is false
27
Taking false branch
2067 pair_r_value = info->O->getScatteredRelocationValue(RENext);
2068 }
2069
2070 if (isExtern) {
28
Taking false branch
2071 Expected<StringRef> SymName = Symbol.getName();
2072 if (!SymName) {
2073 std::string Buf;
2074 raw_string_ostream OS(Buf);
2075 logAllUnhandledErrors(SymName.takeError(), OS, "");
2076 OS.flush();
2077 report_fatal_error(Buf);
2078 }
2079 const char *name = SymName->data();
2080 op_info->AddSymbol.Present = 1;
2081 op_info->AddSymbol.Name = name;
2082 switch (r_type) {
2083 case MachO::ARM_RELOC_HALF:
2084 if ((r_length & 0x1) == 1) {
2085 op_info->Value = value << 16 | other_half;
2086 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI161;
2087 } else {
2088 op_info->Value = other_half << 16 | value;
2089 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO162;
2090 }
2091 break;
2092 default:
2093 break;
2094 }
2095 return 1;
2096 }
2097 // If we have a branch that is not an external relocation entry then
2098 // return 0 so the code in tryAddingSymbolicOperand() can use the
2099 // SymbolLookUp call back with the branch target address to look up the
2100 // symbol and possiblity add an annotation for a symbol stub.
2101 if (isExtern == 0 && (r_type == MachO::ARM_RELOC_BR24 ||
29
Taking false branch
2102 r_type == MachO::ARM_THUMB_RELOC_BR22))
2103 return 0;
2104
2105 uint32_t offset = 0;
2106 if (r_type == MachO::ARM_RELOC_HALF ||
30
Taking true branch
2107 r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
2108 if ((r_length & 0x1) == 1)
31
Assuming the condition is false
32
Taking false branch
2109 value = value << 16 | other_half;
2110 else
2111 value = other_half << 16 | value;
2112 }
2113 if (r_scattered && (r_type != MachO::ARM_RELOC_HALF &&
2114 r_type != MachO::ARM_RELOC_HALF_SECTDIFF)) {
2115 offset = value - r_value;
2116 value = r_value;
2117 }
2118
2119 if (r_type == MachO::ARM_RELOC_HALF_SECTDIFF) {
33
Taking true branch
2120 if ((r_length & 0x1) == 1)
34
Taking false branch
2121 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI161;
2122 else
2123 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO162;
2124 const char *add = GuessSymbolName(r_value, info->AddrMap);
35
Function call argument is an uninitialized value
2125 const char *sub = GuessSymbolName(pair_r_value, info->AddrMap);
2126 int32_t offset = value - (r_value - pair_r_value);
2127 op_info->AddSymbol.Present = 1;
2128 if (add != nullptr)
2129 op_info->AddSymbol.Name = add;
2130 else
2131 op_info->AddSymbol.Value = r_value;
2132 op_info->SubtractSymbol.Present = 1;
2133 if (sub != nullptr)
2134 op_info->SubtractSymbol.Name = sub;
2135 else
2136 op_info->SubtractSymbol.Value = pair_r_value;
2137 op_info->Value = offset;
2138 return 1;
2139 }
2140
2141 op_info->AddSymbol.Present = 1;
2142 op_info->Value = offset;
2143 if (r_type == MachO::ARM_RELOC_HALF) {
2144 if ((r_length & 0x1) == 1)
2145 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_HI161;
2146 else
2147 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM_LO162;
2148 }
2149 const char *add = GuessSymbolName(value, info->AddrMap);
2150 if (add != nullptr) {
2151 op_info->AddSymbol.Name = add;
2152 return 1;
2153 }
2154 op_info->AddSymbol.Value = value;
2155 return 1;
2156 }
2157 if (Arch == Triple::aarch64) {
2158 if (Offset != 0 || Size != 4)
2159 return 0;
2160 if (info->O->getHeader().filetype != MachO::MH_OBJECT) {
2161 // TODO:
2162 // Search the external relocation entries of a fully linked image
2163 // (if any) for an entry that matches this segment offset.
2164 // uint64_t seg_offset = (Pc + Offset);
2165 return 0;
2166 }
2167 // In MH_OBJECT filetypes search the section's relocation entries (if any)
2168 // for an entry for this section offset.
2169 uint64_t sect_addr = info->S.getAddress();
2170 uint64_t sect_offset = (Pc + Offset) - sect_addr;
2171 auto Reloc =
2172 find_if(info->S.relocations(), [&](const RelocationRef &Reloc) {
2173 uint64_t RelocOffset = Reloc.getOffset();
2174 return RelocOffset == sect_offset;
2175 });
2176
2177 if (Reloc == info->S.relocations().end())
2178 return 0;
2179
2180 DataRefImpl Rel = Reloc->getRawDataRefImpl();
2181 MachO::any_relocation_info RE = info->O->getRelocation(Rel);
2182 uint32_t r_type = info->O->getAnyRelocationType(RE);
2183 if (r_type == MachO::ARM64_RELOC_ADDEND) {
2184 DataRefImpl RelNext = Rel;
2185 info->O->moveRelocationNext(RelNext);
2186 MachO::any_relocation_info RENext = info->O->getRelocation(RelNext);
2187 if (value == 0) {
2188 value = info->O->getPlainRelocationSymbolNum(RENext);
2189 op_info->Value = value;
2190 }
2191 }
2192 // NOTE: Scattered relocations don't exist on arm64.
2193 if (!info->O->getPlainRelocationExternal(RE))
2194 return 0;
2195 Expected<StringRef> SymName = Reloc->getSymbol()->getName();
2196 if (!SymName) {
2197 std::string Buf;
2198 raw_string_ostream OS(Buf);
2199 logAllUnhandledErrors(SymName.takeError(), OS, "");
2200 OS.flush();
2201 report_fatal_error(Buf);
2202 }
2203 const char *name = SymName->data();
2204 op_info->AddSymbol.Present = 1;
2205 op_info->AddSymbol.Name = name;
2206
2207 switch (r_type) {
2208 case MachO::ARM64_RELOC_PAGE21:
2209 /* @page */
2210 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGE1;
2211 break;
2212 case MachO::ARM64_RELOC_PAGEOFF12:
2213 /* @pageoff */
2214 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_PAGEOFF2;
2215 break;
2216 case MachO::ARM64_RELOC_GOT_LOAD_PAGE21:
2217 /* @gotpage */
2218 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGE3;
2219 break;
2220 case MachO::ARM64_RELOC_GOT_LOAD_PAGEOFF12:
2221 /* @gotpageoff */
2222 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_GOTPAGEOFF4;
2223 break;
2224 case MachO::ARM64_RELOC_TLVP_LOAD_PAGE21:
2225 /* @tvlppage is not implemented in llvm-mc */
2226 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVP5;
2227 break;
2228 case MachO::ARM64_RELOC_TLVP_LOAD_PAGEOFF12:
2229 /* @tvlppageoff is not implemented in llvm-mc */
2230 op_info->VariantKind = LLVMDisassembler_VariantKind_ARM64_TLVOFF6;
2231 break;
2232 default:
2233 case MachO::ARM64_RELOC_BRANCH26:
2234 op_info->VariantKind = LLVMDisassembler_VariantKind_None0;
2235 break;
2236 }
2237 return 1;
2238 }
2239 return 0;
2240}
2241
2242// GuessCstringPointer is passed the address of what might be a pointer to a
2243// literal string in a cstring section. If that address is in a cstring section
2244// it returns a pointer to that string. Else it returns nullptr.
2245static const char *GuessCstringPointer(uint64_t ReferenceValue,
2246 struct DisassembleInfo *info) {
2247 for (const auto &Load : info->O->load_commands()) {
2248 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2249 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2250 for (unsigned J = 0; J < Seg.nsects; ++J) {
2251 MachO::section_64 Sec = info->O->getSection64(Load, J);
2252 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2253 if (section_type == MachO::S_CSTRING_LITERALS &&
2254 ReferenceValue >= Sec.addr &&
2255 ReferenceValue < Sec.addr + Sec.size) {
2256 uint64_t sect_offset = ReferenceValue - Sec.addr;
2257 uint64_t object_offset = Sec.offset + sect_offset;
2258 StringRef MachOContents = info->O->getData();
2259 uint64_t object_size = MachOContents.size();
2260 const char *object_addr = (const char *)MachOContents.data();
2261 if (object_offset < object_size) {
2262 const char *name = object_addr + object_offset;
2263 return name;
2264 } else {
2265 return nullptr;
2266 }
2267 }
2268 }
2269 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2270 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2271 for (unsigned J = 0; J < Seg.nsects; ++J) {
2272 MachO::section Sec = info->O->getSection(Load, J);
2273 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2274 if (section_type == MachO::S_CSTRING_LITERALS &&
2275 ReferenceValue >= Sec.addr &&
2276 ReferenceValue < Sec.addr + Sec.size) {
2277 uint64_t sect_offset = ReferenceValue - Sec.addr;
2278 uint64_t object_offset = Sec.offset + sect_offset;
2279 StringRef MachOContents = info->O->getData();
2280 uint64_t object_size = MachOContents.size();
2281 const char *object_addr = (const char *)MachOContents.data();
2282 if (object_offset < object_size) {
2283 const char *name = object_addr + object_offset;
2284 return name;
2285 } else {
2286 return nullptr;
2287 }
2288 }
2289 }
2290 }
2291 }
2292 return nullptr;
2293}
2294
2295// GuessIndirectSymbol returns the name of the indirect symbol for the
2296// ReferenceValue passed in or nullptr. This is used when ReferenceValue maybe
2297// an address of a symbol stub or a lazy or non-lazy pointer to associate the
2298// symbol name being referenced by the stub or pointer.
2299static const char *GuessIndirectSymbol(uint64_t ReferenceValue,
2300 struct DisassembleInfo *info) {
2301 MachO::dysymtab_command Dysymtab = info->O->getDysymtabLoadCommand();
2302 MachO::symtab_command Symtab = info->O->getSymtabLoadCommand();
2303 for (const auto &Load : info->O->load_commands()) {
2304 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2305 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2306 for (unsigned J = 0; J < Seg.nsects; ++J) {
2307 MachO::section_64 Sec = info->O->getSection64(Load, J);
2308 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2309 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2310 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2311 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2312 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2313 section_type == MachO::S_SYMBOL_STUBS) &&
2314 ReferenceValue >= Sec.addr &&
2315 ReferenceValue < Sec.addr + Sec.size) {
2316 uint32_t stride;
2317 if (section_type == MachO::S_SYMBOL_STUBS)
2318 stride = Sec.reserved2;
2319 else
2320 stride = 8;
2321 if (stride == 0)
2322 return nullptr;
2323 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2324 if (index < Dysymtab.nindirectsyms) {
2325 uint32_t indirect_symbol =
2326 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2327 if (indirect_symbol < Symtab.nsyms) {
2328 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2329 SymbolRef Symbol = *Sym;
2330 Expected<StringRef> SymName = Symbol.getName();
2331 if (!SymName) {
2332 std::string Buf;
2333 raw_string_ostream OS(Buf);
2334 logAllUnhandledErrors(SymName.takeError(), OS, "");
2335 OS.flush();
2336 report_fatal_error(Buf);
2337 }
2338 const char *name = SymName->data();
2339 return name;
2340 }
2341 }
2342 }
2343 }
2344 } else if (Load.C.cmd == MachO::LC_SEGMENT) {
2345 MachO::segment_command Seg = info->O->getSegmentLoadCommand(Load);
2346 for (unsigned J = 0; J < Seg.nsects; ++J) {
2347 MachO::section Sec = info->O->getSection(Load, J);
2348 uint32_t section_type = Sec.flags & MachO::SECTION_TYPE;
2349 if ((section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
2350 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
2351 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
2352 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS ||
2353 section_type == MachO::S_SYMBOL_STUBS) &&
2354 ReferenceValue >= Sec.addr &&
2355 ReferenceValue < Sec.addr + Sec.size) {
2356 uint32_t stride;
2357 if (section_type == MachO::S_SYMBOL_STUBS)
2358 stride = Sec.reserved2;
2359 else
2360 stride = 4;
2361 if (stride == 0)
2362 return nullptr;
2363 uint32_t index = Sec.reserved1 + (ReferenceValue - Sec.addr) / stride;
2364 if (index < Dysymtab.nindirectsyms) {
2365 uint32_t indirect_symbol =
2366 info->O->getIndirectSymbolTableEntry(Dysymtab, index);
2367 if (indirect_symbol < Symtab.nsyms) {
2368 symbol_iterator Sym = info->O->getSymbolByIndex(indirect_symbol);
2369 SymbolRef Symbol = *Sym;
2370 Expected<StringRef> SymName = Symbol.getName();
2371 if (!SymName) {
2372 std::string Buf;
2373 raw_string_ostream OS(Buf);
2374 logAllUnhandledErrors(SymName.takeError(), OS, "");
2375 OS.flush();
2376 report_fatal_error(Buf);
2377 }
2378 const char *name = SymName->data();
2379 return name;
2380 }
2381 }
2382 }
2383 }
2384 }
2385 }
2386 return nullptr;
2387}
2388
2389// method_reference() is called passing it the ReferenceName that might be
2390// a reference it to an Objective-C method call. If so then it allocates and
2391// assembles a method call string with the values last seen and saved in
2392// the DisassembleInfo's class_name and selector_name fields. This is saved
2393// into the method field of the info and any previous string is free'ed.
2394// Then the class_name field in the info is set to nullptr. The method call
2395// string is set into ReferenceName and ReferenceType is set to
2396// LLVMDisassembler_ReferenceType_Out_Objc_Message. If this not a method call
2397// then both ReferenceType and ReferenceName are left unchanged.
2398static void method_reference(struct DisassembleInfo *info,
2399 uint64_t *ReferenceType,
2400 const char **ReferenceName) {
2401 unsigned int Arch = info->O->getArch();
2402 if (*ReferenceName != nullptr) {
2403 if (strcmp(*ReferenceName, "_objc_msgSend") == 0) {
2404 if (info->selector_name != nullptr) {
2405 if (info->method != nullptr)
2406 free(info->method);
2407 if (info->class_name != nullptr) {
2408 info->method = (char *)malloc(5 + strlen(info->class_name) +
2409 strlen(info->selector_name));
2410 if (info->method != nullptr) {
2411 strcpy(info->method, "+[");
2412 strcat(info->method, info->class_name);
2413 strcat(info->method, " ");
2414 strcat(info->method, info->selector_name);
2415 strcat(info->method, "]");
2416 *ReferenceName = info->method;
2417 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message5;
2418 }
2419 } else {
2420 info->method = (char *)malloc(9 + strlen(info->selector_name));
2421 if (info->method != nullptr) {
2422 if (Arch == Triple::x86_64)
2423 strcpy(info->method, "-[%rdi ");
2424 else if (Arch == Triple::aarch64)
2425 strcpy(info->method, "-[x0 ");
2426 else
2427 strcpy(info->method, "-[r? ");
2428 strcat(info->method, info->selector_name);
2429 strcat(info->method, "]");
2430 *ReferenceName = info->method;
2431 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message5;
2432 }
2433 }
2434 info->class_name = nullptr;
2435 }
2436 } else if (strcmp(*ReferenceName, "_objc_msgSendSuper2") == 0) {
2437 if (info->selector_name != nullptr) {
2438 if (info->method != nullptr)
2439 free(info->method);
2440 info->method = (char *)malloc(17 + strlen(info->selector_name));
2441 if (info->method != nullptr) {
2442 if (Arch == Triple::x86_64)
2443 strcpy(info->method, "-[[%rdi super] ");
2444 else if (Arch == Triple::aarch64)
2445 strcpy(info->method, "-[[x0 super] ");
2446 else
2447 strcpy(info->method, "-[[r? super] ");
2448 strcat(info->method, info->selector_name);
2449 strcat(info->method, "]");
2450 *ReferenceName = info->method;
2451 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message5;
2452 }
2453 info->class_name = nullptr;
2454 }
2455 }
2456 }
2457}
2458
2459// GuessPointerPointer() is passed the address of what might be a pointer to
2460// a reference to an Objective-C class, selector, message ref or cfstring.
2461// If so the value of the pointer is returned and one of the booleans are set
2462// to true. If not zero is returned and all the booleans are set to false.
2463static uint64_t GuessPointerPointer(uint64_t ReferenceValue,
2464 struct DisassembleInfo *info,
2465 bool &classref, bool &selref, bool &msgref,
2466 bool &cfstring) {
2467 classref = false;
2468 selref = false;
2469 msgref = false;
2470 cfstring = false;
2471 for (const auto &Load : info->O->load_commands()) {
2472 if (Load.C.cmd == MachO::LC_SEGMENT_64) {
2473 MachO::segment_command_64 Seg = info->O->getSegment64LoadCommand(Load);
2474 for (unsigned J = 0; J < Seg.nsects; ++J) {
2475 MachO::section_64 Sec = info->O->getSection64(Load, J);
2476 if ((strncmp(Sec.sectname, "__objc_selrefs", 16) == 0 ||
2477 strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2478 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0 ||
2479 strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 ||
2480 strncmp(Sec.sectname, "__cfstring", 16) == 0) &&
2481 ReferenceValue >= Sec.addr &&
2482 ReferenceValue < Sec.addr + Sec.size) {
2483 uint64_t sect_offset = ReferenceValue - Sec.addr;
2484 uint64_t object_offset = Sec.offset + sect_offset;
2485 StringRef MachOContents = info->O->getData();
2486 uint64_t object_size = MachOContents.size();
2487 const char *object_addr = (const char *)MachOContents.data();
2488 if (object_offset < object_size) {
2489 uint64_t pointer_value;
2490 memcpy(&pointer_value, object_addr + object_offset,
2491 sizeof(uint64_t));
2492 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2493 sys::swapByteOrder(pointer_value);
2494 if (strncmp(Sec.sectname, "__objc_selrefs", 16) == 0)
2495 selref = true;
2496 else if (strncmp(Sec.sectname, "__objc_classrefs", 16) == 0 ||
2497 strncmp(Sec.sectname, "__objc_superrefs", 16) == 0)
2498 classref = true;
2499 else if (strncmp(Sec.sectname, "__objc_msgrefs", 16) == 0 &&
2500 ReferenceValue + 8 < Sec.addr + Sec.size) {
2501 msgref = true;
2502 memcpy(&pointer_value, object_addr + object_offset + 8,
2503 sizeof(uint64_t));
2504 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
2505 sys::swapByteOrder(pointer_value);
2506 } else if (strncmp(Sec.sectname, "__cfstring", 16) == 0)
2507 cfstring = true;
2508 return pointer_value;
2509 } else {
2510 return 0;
2511 }
2512 }
2513 }
2514 }
2515 // TODO: Look for LC_SEGMENT for 32-bit Mach-O files.
2516 }
2517 return 0;
2518}
2519
2520// get_pointer_64 returns a pointer to the bytes in the object file at the
2521// Address from a section in the Mach-O file. And indirectly returns the
2522// offset into the section, number of bytes left in the section past the offset
2523// and which section is was being referenced. If the Address is not in a
2524// section nullptr is returned.
2525static const char *get_pointer_64(uint64_t Address, uint32_t &offset,
2526 uint32_t &left, SectionRef &S,
2527 DisassembleInfo *info,
2528 bool objc_only = false) {
2529 offset = 0;
2530 left = 0;
2531 S = SectionRef();
2532 for (unsigned SectIdx = 0; SectIdx != info->Sections->size(); SectIdx++) {
2533 uint64_t SectAddress = ((*(info->Sections))[SectIdx]).getAddress();
2534 uint64_t SectSize = ((*(info->Sections))[SectIdx]).getSize();
2535 if (SectSize == 0)
2536 continue;
2537 if (objc_only) {
2538 StringRef SectName;
2539 ((*(info->Sections))[SectIdx]).getName(SectName);
2540 DataRefImpl Ref = ((*(info->Sections))[SectIdx]).getRawDataRefImpl();
2541 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
2542 if (SegName != "__OBJC" && SectName != "__cstring")
2543 continue;
2544 }
2545 if (Address >= SectAddress && Address < SectAddress + SectSize) {
2546 S = (*(info->Sections))[SectIdx];
2547 offset = Address - SectAddress;
2548 left = SectSize - offset;
2549 StringRef SectContents;
2550 ((*(info->Sections))[SectIdx]).getContents(SectContents);
2551 return SectContents.data() + offset;
2552 }
2553 }
2554 return nullptr;
2555}
2556
2557static const char *get_pointer_32(uint32_t Address, uint32_t &offset,
2558 uint32_t &left, SectionRef &S,
2559 DisassembleInfo *info,
2560 bool objc_only = false) {
2561 return get_pointer_64(Address, offset, left, S, info, objc_only);
2562}
2563
2564// get_symbol_64() returns the name of a symbol (or nullptr) and the address of
2565// the symbol indirectly through n_value. Based on the relocation information
2566// for the specified section offset in the specified section reference.
2567// If no relocation information is found and a non-zero ReferenceValue for the
2568// symbol is passed, look up that address in the info's AddrMap.
2569static const char *get_symbol_64(uint32_t sect_offset, SectionRef S,
2570 DisassembleInfo *info, uint64_t &n_value,
2571 uint64_t ReferenceValue = 0) {
2572 n_value = 0;
2573 if (!info->verbose)
2574 return nullptr;
2575
2576 // See if there is an external relocation entry at the sect_offset.
2577 bool reloc_found = false;
2578 DataRefImpl Rel;
2579 MachO::any_relocation_info RE;
2580 bool isExtern = false;
2581 SymbolRef Symbol;
2582 for (const RelocationRef &Reloc : S.relocations()) {
2583 uint64_t RelocOffset = Reloc.getOffset();
2584 if (RelocOffset == sect_offset) {
2585 Rel = Reloc.getRawDataRefImpl();
2586 RE = info->O->getRelocation(Rel);
2587 if (info->O->isRelocationScattered(RE))
2588 continue;
2589 isExtern = info->O->getPlainRelocationExternal(RE);
2590 if (isExtern) {
2591 symbol_iterator RelocSym = Reloc.getSymbol();
2592 Symbol = *RelocSym;
2593 }
2594 reloc_found = true;
2595 break;
2596 }
2597 }
2598 // If there is an external relocation entry for a symbol in this section
2599 // at this section_offset then use that symbol's value for the n_value
2600 // and return its name.
2601 const char *SymbolName = nullptr;
2602 if (reloc_found && isExtern) {
2603 n_value = Symbol.getValue();
2604 Expected<StringRef> NameOrError = Symbol.getName();
2605 if (!NameOrError) {
2606 std::string Buf;
2607 raw_string_ostream OS(Buf);
2608 logAllUnhandledErrors(NameOrError.takeError(), OS, "");
2609 OS.flush();
2610 report_fatal_error(Buf);
2611 }
2612 StringRef Name = *NameOrError;
2613 if (!Name.empty()) {
2614 SymbolName = Name.data();
2615 return SymbolName;
2616 }
2617 }
2618
2619 // TODO: For fully linked images, look through the external relocation
2620 // entries off the dynamic symtab command. For these the r_offset is from the
2621 // start of the first writeable segment in the Mach-O file. So the offset
2622 // to this section from that segment is passed to this routine by the caller,
2623 // as the database_offset. Which is the difference of the section's starting
2624 // address and the first writable segment.
2625 //
2626 // NOTE: need add passing the database_offset to this routine.
2627
2628 // We did not find an external relocation entry so look up the ReferenceValue
2629 // as an address of a symbol and if found return that symbol's name.
2630 SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
2631
2632 return SymbolName;
2633}
2634
2635static const char *get_symbol_32(uint32_t sect_offset, SectionRef S,
2636 DisassembleInfo *info,
2637 uint32_t ReferenceValue) {
2638 uint64_t n_value64;
2639 return get_symbol_64(sect_offset, S, info, n_value64, ReferenceValue);
2640}
2641
2642// These are structs in the Objective-C meta data and read to produce the
2643// comments for disassembly. While these are part of the ABI they are no
2644// public defintions. So the are here not in include/llvm/Support/MachO.h .
2645
2646// The cfstring object in a 64-bit Mach-O file.
2647struct cfstring64_t {
2648 uint64_t isa; // class64_t * (64-bit pointer)
2649 uint64_t flags; // flag bits
2650 uint64_t characters; // char * (64-bit pointer)
2651 uint64_t length; // number of non-NULL characters in above
2652};
2653
2654// The class object in a 64-bit Mach-O file.
2655struct class64_t {
2656 uint64_t isa; // class64_t * (64-bit pointer)
2657 uint64_t superclass; // class64_t * (64-bit pointer)
2658 uint64_t cache; // Cache (64-bit pointer)
2659 uint64_t vtable; // IMP * (64-bit pointer)
2660 uint64_t data; // class_ro64_t * (64-bit pointer)
2661};
2662
2663struct class32_t {
2664 uint32_t isa; /* class32_t * (32-bit pointer) */
2665 uint32_t superclass; /* class32_t * (32-bit pointer) */
2666 uint32_t cache; /* Cache (32-bit pointer) */
2667 uint32_t vtable; /* IMP * (32-bit pointer) */
2668 uint32_t data; /* class_ro32_t * (32-bit pointer) */
2669};
2670
2671struct class_ro64_t {
2672 uint32_t flags;
2673 uint32_t instanceStart;
2674 uint32_t instanceSize;
2675 uint32_t reserved;
2676 uint64_t ivarLayout; // const uint8_t * (64-bit pointer)
2677 uint64_t name; // const char * (64-bit pointer)
2678 uint64_t baseMethods; // const method_list_t * (64-bit pointer)
2679 uint64_t baseProtocols; // const protocol_list_t * (64-bit pointer)
2680 uint64_t ivars; // const ivar_list_t * (64-bit pointer)
2681 uint64_t weakIvarLayout; // const uint8_t * (64-bit pointer)
2682 uint64_t baseProperties; // const struct objc_property_list (64-bit pointer)
2683};
2684
2685struct class_ro32_t {
2686 uint32_t flags;
2687 uint32_t instanceStart;
2688 uint32_t instanceSize;
2689 uint32_t ivarLayout; /* const uint8_t * (32-bit pointer) */
2690 uint32_t name; /* const char * (32-bit pointer) */
2691 uint32_t baseMethods; /* const method_list_t * (32-bit pointer) */
2692 uint32_t baseProtocols; /* const protocol_list_t * (32-bit pointer) */
2693 uint32_t ivars; /* const ivar_list_t * (32-bit pointer) */
2694 uint32_t weakIvarLayout; /* const uint8_t * (32-bit pointer) */
2695 uint32_t baseProperties; /* const struct objc_property_list *
2696 (32-bit pointer) */
2697};
2698
2699/* Values for class_ro{64,32}_t->flags */
2700#define RO_META(1 << 0) (1 << 0)
2701#define RO_ROOT(1 << 1) (1 << 1)
2702#define RO_HAS_CXX_STRUCTORS(1 << 2) (1 << 2)
2703
2704struct method_list64_t {
2705 uint32_t entsize;
2706 uint32_t count;
2707 /* struct method64_t first; These structures follow inline */
2708};
2709
2710struct method_list32_t {
2711 uint32_t entsize;
2712 uint32_t count;
2713 /* struct method32_t first; These structures follow inline */
2714};
2715
2716struct method64_t {
2717 uint64_t name; /* SEL (64-bit pointer) */
2718 uint64_t types; /* const char * (64-bit pointer) */
2719 uint64_t imp; /* IMP (64-bit pointer) */
2720};
2721
2722struct method32_t {
2723 uint32_t name; /* SEL (32-bit pointer) */
2724 uint32_t types; /* const char * (32-bit pointer) */
2725 uint32_t imp; /* IMP (32-bit pointer) */
2726};
2727
2728struct protocol_list64_t {
2729 uint64_t count; /* uintptr_t (a 64-bit value) */
2730 /* struct protocol64_t * list[0]; These pointers follow inline */
2731};
2732
2733struct protocol_list32_t {
2734 uint32_t count; /* uintptr_t (a 32-bit value) */
2735 /* struct protocol32_t * list[0]; These pointers follow inline */
2736};
2737
2738struct protocol64_t {
2739 uint64_t isa; /* id * (64-bit pointer) */
2740 uint64_t name; /* const char * (64-bit pointer) */
2741 uint64_t protocols; /* struct protocol_list64_t *
2742 (64-bit pointer) */
2743 uint64_t instanceMethods; /* method_list_t * (64-bit pointer) */
2744 uint64_t classMethods; /* method_list_t * (64-bit pointer) */
2745 uint64_t optionalInstanceMethods; /* method_list_t * (64-bit pointer) */
2746 uint64_t optionalClassMethods; /* method_list_t * (64-bit pointer) */
2747 uint64_t instanceProperties; /* struct objc_property_list *
2748 (64-bit pointer) */
2749};
2750
2751struct protocol32_t {
2752 uint32_t isa; /* id * (32-bit pointer) */
2753 uint32_t name; /* const char * (32-bit pointer) */
2754 uint32_t protocols; /* struct protocol_list_t *
2755 (32-bit pointer) */
2756 uint32_t instanceMethods; /* method_list_t * (32-bit pointer) */
2757 uint32_t classMethods; /* method_list_t * (32-bit pointer) */
2758 uint32_t optionalInstanceMethods; /* method_list_t * (32-bit pointer) */
2759 uint32_t optionalClassMethods; /* method_list_t * (32-bit pointer) */
2760 uint32_t instanceProperties; /* struct objc_property_list *
2761 (32-bit pointer) */
2762};
2763
2764struct ivar_list64_t {
2765 uint32_t entsize;
2766 uint32_t count;
2767 /* struct ivar64_t first; These structures follow inline */
2768};
2769
2770struct ivar_list32_t {
2771 uint32_t entsize;
2772 uint32_t count;
2773 /* struct ivar32_t first; These structures follow inline */
2774};
2775
2776struct ivar64_t {
2777 uint64_t offset; /* uintptr_t * (64-bit pointer) */
2778 uint64_t name; /* const char * (64-bit pointer) */
2779 uint64_t type; /* const char * (64-bit pointer) */
2780 uint32_t alignment;
2781 uint32_t size;
2782};
2783
2784struct ivar32_t {
2785 uint32_t offset; /* uintptr_t * (32-bit pointer) */
2786 uint32_t name; /* const char * (32-bit pointer) */
2787 uint32_t type; /* const char * (32-bit pointer) */
2788 uint32_t alignment;
2789 uint32_t size;
2790};
2791
2792struct objc_property_list64 {
2793 uint32_t entsize;
2794 uint32_t count;
2795 /* struct objc_property64 first; These structures follow inline */
2796};
2797
2798struct objc_property_list32 {
2799 uint32_t entsize;
2800 uint32_t count;
2801 /* struct objc_property32 first; These structures follow inline */
2802};
2803
2804struct objc_property64 {
2805 uint64_t name; /* const char * (64-bit pointer) */
2806 uint64_t attributes; /* const char * (64-bit pointer) */
2807};
2808
2809struct objc_property32 {
2810 uint32_t name; /* const char * (32-bit pointer) */
2811 uint32_t attributes; /* const char * (32-bit pointer) */
2812};
2813
2814struct category64_t {
2815 uint64_t name; /* const char * (64-bit pointer) */
2816 uint64_t cls; /* struct class_t * (64-bit pointer) */
2817 uint64_t instanceMethods; /* struct method_list_t * (64-bit pointer) */
2818 uint64_t classMethods; /* struct method_list_t * (64-bit pointer) */
2819 uint64_t protocols; /* struct protocol_list_t * (64-bit pointer) */
2820 uint64_t instanceProperties; /* struct objc_property_list *
2821 (64-bit pointer) */
2822};
2823
2824struct category32_t {
2825 uint32_t name; /* const char * (32-bit pointer) */
2826 uint32_t cls; /* struct class_t * (32-bit pointer) */
2827 uint32_t instanceMethods; /* struct method_list_t * (32-bit pointer) */
2828 uint32_t classMethods; /* struct method_list_t * (32-bit pointer) */
2829 uint32_t protocols; /* struct protocol_list_t * (32-bit pointer) */
2830 uint32_t instanceProperties; /* struct objc_property_list *
2831 (32-bit pointer) */
2832};
2833
2834struct objc_image_info64 {
2835 uint32_t version;
2836 uint32_t flags;
2837};
2838struct objc_image_info32 {
2839 uint32_t version;
2840 uint32_t flags;
2841};
2842struct imageInfo_t {
2843 uint32_t version;
2844 uint32_t flags;
2845};
2846/* masks for objc_image_info.flags */
2847#define OBJC_IMAGE_IS_REPLACEMENT(1 << 0) (1 << 0)
2848#define OBJC_IMAGE_SUPPORTS_GC(1 << 1) (1 << 1)
2849
2850struct message_ref64 {
2851 uint64_t imp; /* IMP (64-bit pointer) */
2852 uint64_t sel; /* SEL (64-bit pointer) */
2853};
2854
2855struct message_ref32 {
2856 uint32_t imp; /* IMP (32-bit pointer) */
2857 uint32_t sel; /* SEL (32-bit pointer) */
2858};
2859
2860// Objective-C 1 (32-bit only) meta data structs.
2861
2862struct objc_module_t {
2863 uint32_t version;
2864 uint32_t size;
2865 uint32_t name; /* char * (32-bit pointer) */
2866 uint32_t symtab; /* struct objc_symtab * (32-bit pointer) */
2867};
2868
2869struct objc_symtab_t {
2870 uint32_t sel_ref_cnt;
2871 uint32_t refs; /* SEL * (32-bit pointer) */
2872 uint16_t cls_def_cnt;
2873 uint16_t cat_def_cnt;
2874 // uint32_t defs[1]; /* void * (32-bit pointer) variable size */
2875};
2876
2877struct objc_class_t {
2878 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2879 uint32_t super_class; /* struct objc_class * (32-bit pointer) */
2880 uint32_t name; /* const char * (32-bit pointer) */
2881 int32_t version;
2882 int32_t info;
2883 int32_t instance_size;
2884 uint32_t ivars; /* struct objc_ivar_list * (32-bit pointer) */
2885 uint32_t methodLists; /* struct objc_method_list ** (32-bit pointer) */
2886 uint32_t cache; /* struct objc_cache * (32-bit pointer) */
2887 uint32_t protocols; /* struct objc_protocol_list * (32-bit pointer) */
2888};
2889
2890#define CLS_GETINFO(cls, infomask)((cls)->info & (infomask)) ((cls)->info & (infomask))
2891// class is not a metaclass
2892#define CLS_CLASS0x1 0x1
2893// class is a metaclass
2894#define CLS_META0x2 0x2
2895
2896struct objc_category_t {
2897 uint32_t category_name; /* char * (32-bit pointer) */
2898 uint32_t class_name; /* char * (32-bit pointer) */
2899 uint32_t instance_methods; /* struct objc_method_list * (32-bit pointer) */
2900 uint32_t class_methods; /* struct objc_method_list * (32-bit pointer) */
2901 uint32_t protocols; /* struct objc_protocol_list * (32-bit ptr) */
2902};
2903
2904struct objc_ivar_t {
2905 uint32_t ivar_name; /* char * (32-bit pointer) */
2906 uint32_t ivar_type; /* char * (32-bit pointer) */
2907 int32_t ivar_offset;
2908};
2909
2910struct objc_ivar_list_t {
2911 int32_t ivar_count;
2912 // struct objc_ivar_t ivar_list[1]; /* variable length structure */
2913};
2914
2915struct objc_method_list_t {
2916 uint32_t obsolete; /* struct objc_method_list * (32-bit pointer) */
2917 int32_t method_count;
2918 // struct objc_method_t method_list[1]; /* variable length structure */
2919};
2920
2921struct objc_method_t {
2922 uint32_t method_name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2923 uint32_t method_types; /* char * (32-bit pointer) */
2924 uint32_t method_imp; /* IMP, aka function pointer, (*IMP)(id, SEL, ...)
2925 (32-bit pointer) */
2926};
2927
2928struct objc_protocol_list_t {
2929 uint32_t next; /* struct objc_protocol_list * (32-bit pointer) */
2930 int32_t count;
2931 // uint32_t list[1]; /* Protocol *, aka struct objc_protocol_t *
2932 // (32-bit pointer) */
2933};
2934
2935struct objc_protocol_t {
2936 uint32_t isa; /* struct objc_class * (32-bit pointer) */
2937 uint32_t protocol_name; /* char * (32-bit pointer) */
2938 uint32_t protocol_list; /* struct objc_protocol_list * (32-bit pointer) */
2939 uint32_t instance_methods; /* struct objc_method_description_list *
2940 (32-bit pointer) */
2941 uint32_t class_methods; /* struct objc_method_description_list *
2942 (32-bit pointer) */
2943};
2944
2945struct objc_method_description_list_t {
2946 int32_t count;
2947 // struct objc_method_description_t list[1];
2948};
2949
2950struct objc_method_description_t {
2951 uint32_t name; /* SEL, aka struct objc_selector * (32-bit pointer) */
2952 uint32_t types; /* char * (32-bit pointer) */
2953};
2954
2955inline void swapStruct(struct cfstring64_t &cfs) {
2956 sys::swapByteOrder(cfs.isa);
2957 sys::swapByteOrder(cfs.flags);
2958 sys::swapByteOrder(cfs.characters);
2959 sys::swapByteOrder(cfs.length);
2960}
2961
2962inline void swapStruct(struct class64_t &c) {
2963 sys::swapByteOrder(c.isa);
2964 sys::swapByteOrder(c.superclass);
2965 sys::swapByteOrder(c.cache);
2966 sys::swapByteOrder(c.vtable);
2967 sys::swapByteOrder(c.data);
2968}
2969
2970inline void swapStruct(struct class32_t &c) {
2971 sys::swapByteOrder(c.isa);
2972 sys::swapByteOrder(c.superclass);
2973 sys::swapByteOrder(c.cache);
2974 sys::swapByteOrder(c.vtable);
2975 sys::swapByteOrder(c.data);
2976}
2977
2978inline void swapStruct(struct class_ro64_t &cro) {
2979 sys::swapByteOrder(cro.flags);
2980 sys::swapByteOrder(cro.instanceStart);
2981 sys::swapByteOrder(cro.instanceSize);
2982 sys::swapByteOrder(cro.reserved);
2983 sys::swapByteOrder(cro.ivarLayout);
2984 sys::swapByteOrder(cro.name);
2985 sys::swapByteOrder(cro.baseMethods);
2986 sys::swapByteOrder(cro.baseProtocols);
2987 sys::swapByteOrder(cro.ivars);
2988 sys::swapByteOrder(cro.weakIvarLayout);
2989 sys::swapByteOrder(cro.baseProperties);
2990}
2991
2992inline void swapStruct(struct class_ro32_t &cro) {
2993 sys::swapByteOrder(cro.flags);
2994 sys::swapByteOrder(cro.instanceStart);
2995 sys::swapByteOrder(cro.instanceSize);
2996 sys::swapByteOrder(cro.ivarLayout);
2997 sys::swapByteOrder(cro.name);
2998 sys::swapByteOrder(cro.baseMethods);
2999 sys::swapByteOrder(cro.baseProtocols);
3000 sys::swapByteOrder(cro.ivars);
3001 sys::swapByteOrder(cro.weakIvarLayout);
3002 sys::swapByteOrder(cro.baseProperties);
3003}
3004
3005inline void swapStruct(struct method_list64_t &ml) {
3006 sys::swapByteOrder(ml.entsize);
3007 sys::swapByteOrder(ml.count);
3008}
3009
3010inline void swapStruct(struct method_list32_t &ml) {
3011 sys::swapByteOrder(ml.entsize);
3012 sys::swapByteOrder(ml.count);
3013}
3014
3015inline void swapStruct(struct method64_t &m) {
3016 sys::swapByteOrder(m.name);
3017 sys::swapByteOrder(m.types);
3018 sys::swapByteOrder(m.imp);
3019}
3020
3021inline void swapStruct(struct method32_t &m) {
3022 sys::swapByteOrder(m.name);
3023 sys::swapByteOrder(m.types);
3024 sys::swapByteOrder(m.imp);
3025}
3026
3027inline void swapStruct(struct protocol_list64_t &pl) {
3028 sys::swapByteOrder(pl.count);
3029}
3030
3031inline void swapStruct(struct protocol_list32_t &pl) {
3032 sys::swapByteOrder(pl.count);
3033}
3034
3035inline void swapStruct(struct protocol64_t &p) {
3036 sys::swapByteOrder(p.isa);
3037 sys::swapByteOrder(p.name);
3038 sys::swapByteOrder(p.protocols);
3039 sys::swapByteOrder(p.instanceMethods);
3040 sys::swapByteOrder(p.classMethods);
3041 sys::swapByteOrder(p.optionalInstanceMethods);
3042 sys::swapByteOrder(p.optionalClassMethods);
3043 sys::swapByteOrder(p.instanceProperties);
3044}
3045
3046inline void swapStruct(struct protocol32_t &p) {
3047 sys::swapByteOrder(p.isa);
3048 sys::swapByteOrder(p.name);
3049 sys::swapByteOrder(p.protocols);
3050 sys::swapByteOrder(p.instanceMethods);
3051 sys::swapByteOrder(p.classMethods);
3052 sys::swapByteOrder(p.optionalInstanceMethods);
3053 sys::swapByteOrder(p.optionalClassMethods);
3054 sys::swapByteOrder(p.instanceProperties);
3055}
3056
3057inline void swapStruct(struct ivar_list64_t &il) {
3058 sys::swapByteOrder(il.entsize);
3059 sys::swapByteOrder(il.count);
3060}
3061
3062inline void swapStruct(struct ivar_list32_t &il) {
3063 sys::swapByteOrder(il.entsize);
3064 sys::swapByteOrder(il.count);
3065}
3066
3067inline void swapStruct(struct ivar64_t &i) {
3068 sys::swapByteOrder(i.offset);
3069 sys::swapByteOrder(i.name);
3070 sys::swapByteOrder(i.type);
3071 sys::swapByteOrder(i.alignment);
3072 sys::swapByteOrder(i.size);
3073}
3074
3075inline void swapStruct(struct ivar32_t &i) {
3076 sys::swapByteOrder(i.offset);
3077 sys::swapByteOrder(i.name);
3078 sys::swapByteOrder(i.type);
3079 sys::swapByteOrder(i.alignment);
3080 sys::swapByteOrder(i.size);
3081}
3082
3083inline void swapStruct(struct objc_property_list64 &pl) {
3084 sys::swapByteOrder(pl.entsize);
3085 sys::swapByteOrder(pl.count);
3086}
3087
3088inline void swapStruct(struct objc_property_list32 &pl) {
3089 sys::swapByteOrder(pl.entsize);
3090 sys::swapByteOrder(pl.count);
3091}
3092
3093inline void swapStruct(struct objc_property64 &op) {
3094 sys::swapByteOrder(op.name);
3095 sys::swapByteOrder(op.attributes);
3096}
3097
3098inline void swapStruct(struct objc_property32 &op) {
3099 sys::swapByteOrder(op.name);
3100 sys::swapByteOrder(op.attributes);
3101}
3102
3103inline void swapStruct(struct category64_t &c) {
3104 sys::swapByteOrder(c.name);
3105 sys::swapByteOrder(c.cls);
3106 sys::swapByteOrder(c.instanceMethods);
3107 sys::swapByteOrder(c.classMethods);
3108 sys::swapByteOrder(c.protocols);
3109 sys::swapByteOrder(c.instanceProperties);
3110}
3111
3112inline void swapStruct(struct category32_t &c) {
3113 sys::swapByteOrder(c.name);
3114 sys::swapByteOrder(c.cls);
3115 sys::swapByteOrder(c.instanceMethods);
3116 sys::swapByteOrder(c.classMethods);
3117 sys::swapByteOrder(c.protocols);
3118 sys::swapByteOrder(c.instanceProperties);
3119}
3120
3121inline void swapStruct(struct objc_image_info64 &o) {
3122 sys::swapByteOrder(o.version);
3123 sys::swapByteOrder(o.flags);
3124}
3125
3126inline void swapStruct(struct objc_image_info32 &o) {
3127 sys::swapByteOrder(o.version);
3128 sys::swapByteOrder(o.flags);
3129}
3130
3131inline void swapStruct(struct imageInfo_t &o) {
3132 sys::swapByteOrder(o.version);
3133 sys::swapByteOrder(o.flags);
3134}
3135
3136inline void swapStruct(struct message_ref64 &mr) {
3137 sys::swapByteOrder(mr.imp);
3138 sys::swapByteOrder(mr.sel);
3139}
3140
3141inline void swapStruct(struct message_ref32 &mr) {
3142 sys::swapByteOrder(mr.imp);
3143 sys::swapByteOrder(mr.sel);
3144}
3145
3146inline void swapStruct(struct objc_module_t &module) {
3147 sys::swapByteOrder(module.version);
3148 sys::swapByteOrder(module.size);
3149 sys::swapByteOrder(module.name);
3150 sys::swapByteOrder(module.symtab);
3151}
3152
3153inline void swapStruct(struct objc_symtab_t &symtab) {
3154 sys::swapByteOrder(symtab.sel_ref_cnt);
3155 sys::swapByteOrder(symtab.refs);
3156 sys::swapByteOrder(symtab.cls_def_cnt);
3157 sys::swapByteOrder(symtab.cat_def_cnt);
3158}
3159
3160inline void swapStruct(struct objc_class_t &objc_class) {
3161 sys::swapByteOrder(objc_class.isa);
3162 sys::swapByteOrder(objc_class.super_class);
3163 sys::swapByteOrder(objc_class.name);
3164 sys::swapByteOrder(objc_class.version);
3165 sys::swapByteOrder(objc_class.info);
3166 sys::swapByteOrder(objc_class.instance_size);
3167 sys::swapByteOrder(objc_class.ivars);
3168 sys::swapByteOrder(objc_class.methodLists);
3169 sys::swapByteOrder(objc_class.cache);
3170 sys::swapByteOrder(objc_class.protocols);
3171}
3172
3173inline void swapStruct(struct objc_category_t &objc_category) {
3174 sys::swapByteOrder(objc_category.category_name);
3175 sys::swapByteOrder(objc_category.class_name);
3176 sys::swapByteOrder(objc_category.instance_methods);
3177 sys::swapByteOrder(objc_category.class_methods);
3178 sys::swapByteOrder(objc_category.protocols);
3179}
3180
3181inline void swapStruct(struct objc_ivar_list_t &objc_ivar_list) {
3182 sys::swapByteOrder(objc_ivar_list.ivar_count);
3183}
3184
3185inline void swapStruct(struct objc_ivar_t &objc_ivar) {
3186 sys::swapByteOrder(objc_ivar.ivar_name);
3187 sys::swapByteOrder(objc_ivar.ivar_type);
3188 sys::swapByteOrder(objc_ivar.ivar_offset);
3189}
3190
3191inline void swapStruct(struct objc_method_list_t &method_list) {
3192 sys::swapByteOrder(method_list.obsolete);
3193 sys::swapByteOrder(method_list.method_count);
3194}
3195
3196inline void swapStruct(struct objc_method_t &method) {
3197 sys::swapByteOrder(method.method_name);
3198 sys::swapByteOrder(method.method_types);
3199 sys::swapByteOrder(method.method_imp);
3200}
3201
3202inline void swapStruct(struct objc_protocol_list_t &protocol_list) {
3203 sys::swapByteOrder(protocol_list.next);
3204 sys::swapByteOrder(protocol_list.count);
3205}
3206
3207inline void swapStruct(struct objc_protocol_t &protocol) {
3208 sys::swapByteOrder(protocol.isa);
3209 sys::swapByteOrder(protocol.protocol_name);
3210 sys::swapByteOrder(protocol.protocol_list);
3211 sys::swapByteOrder(protocol.instance_methods);
3212 sys::swapByteOrder(protocol.class_methods);
3213}
3214
3215inline void swapStruct(struct objc_method_description_list_t &mdl) {
3216 sys::swapByteOrder(mdl.count);
3217}
3218
3219inline void swapStruct(struct objc_method_description_t &md) {
3220 sys::swapByteOrder(md.name);
3221 sys::swapByteOrder(md.types);
3222}
3223
3224static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
3225 struct DisassembleInfo *info);
3226
3227// get_objc2_64bit_class_name() is used for disassembly and is passed a pointer
3228// to an Objective-C class and returns the class name. It is also passed the
3229// address of the pointer, so when the pointer is zero as it can be in an .o
3230// file, that is used to look for an external relocation entry with a symbol
3231// name.
3232static const char *get_objc2_64bit_class_name(uint64_t pointer_value,
3233 uint64_t ReferenceValue,
3234 struct DisassembleInfo *info) {
3235 const char *r;
3236 uint32_t offset, left;
3237 SectionRef S;
3238
3239 // The pointer_value can be 0 in an object file and have a relocation
3240 // entry for the class symbol at the ReferenceValue (the address of the
3241 // pointer).
3242 if (pointer_value == 0) {
3243 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3244 if (r == nullptr || left < sizeof(uint64_t))
3245 return nullptr;
3246 uint64_t n_value;
3247 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3248 if (symbol_name == nullptr)
3249 return nullptr;
3250 const char *class_name = strrchr(symbol_name, '$');
3251 if (class_name != nullptr && class_name[1] == '_' && class_name[2] != '\0')
3252 return class_name + 2;
3253 else
3254 return nullptr;
3255 }
3256
3257 // The case were the pointer_value is non-zero and points to a class defined
3258 // in this Mach-O file.
3259 r = get_pointer_64(pointer_value, offset, left, S, info);
3260 if (r == nullptr || left < sizeof(struct class64_t))
3261 return nullptr;
3262 struct class64_t c;
3263 memcpy(&c, r, sizeof(struct class64_t));
3264 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3265 swapStruct(c);
3266 if (c.data == 0)
3267 return nullptr;
3268 r = get_pointer_64(c.data, offset, left, S, info);
3269 if (r == nullptr || left < sizeof(struct class_ro64_t))
3270 return nullptr;
3271 struct class_ro64_t cro;
3272 memcpy(&cro, r, sizeof(struct class_ro64_t));
3273 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3274 swapStruct(cro);
3275 if (cro.name == 0)
3276 return nullptr;
3277 const char *name = get_pointer_64(cro.name, offset, left, S, info);
3278 return name;
3279}
3280
3281// get_objc2_64bit_cfstring_name is used for disassembly and is passed a
3282// pointer to a cfstring and returns its name or nullptr.
3283static const char *get_objc2_64bit_cfstring_name(uint64_t ReferenceValue,
3284 struct DisassembleInfo *info) {
3285 const char *r, *name;
3286 uint32_t offset, left;
3287 SectionRef S;
3288 struct cfstring64_t cfs;
3289 uint64_t cfs_characters;
3290
3291 r = get_pointer_64(ReferenceValue, offset, left, S, info);
3292 if (r == nullptr || left < sizeof(struct cfstring64_t))
3293 return nullptr;
3294 memcpy(&cfs, r, sizeof(struct cfstring64_t));
3295 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3296 swapStruct(cfs);
3297 if (cfs.characters == 0) {
3298 uint64_t n_value;
3299 const char *symbol_name = get_symbol_64(
3300 offset + offsetof(struct cfstring64_t, characters)__builtin_offsetof(struct cfstring64_t, characters), S, info, n_value);
3301 if (symbol_name == nullptr)
3302 return nullptr;
3303 cfs_characters = n_value;
3304 } else
3305 cfs_characters = cfs.characters;
3306 name = get_pointer_64(cfs_characters, offset, left, S, info);
3307
3308 return name;
3309}
3310
3311// get_objc2_64bit_selref() is used for disassembly and is passed a the address
3312// of a pointer to an Objective-C selector reference when the pointer value is
3313// zero as in a .o file and is likely to have a external relocation entry with
3314// who's symbol's n_value is the real pointer to the selector name. If that is
3315// the case the real pointer to the selector name is returned else 0 is
3316// returned
3317static uint64_t get_objc2_64bit_selref(uint64_t ReferenceValue,
3318 struct DisassembleInfo *info) {
3319 uint32_t offset, left;
3320 SectionRef S;
3321
3322 const char *r = get_pointer_64(ReferenceValue, offset, left, S, info);
3323 if (r == nullptr || left < sizeof(uint64_t))
3324 return 0;
3325 uint64_t n_value;
3326 const char *symbol_name = get_symbol_64(offset, S, info, n_value);
3327 if (symbol_name == nullptr)
3328 return 0;
3329 return n_value;
3330}
3331
3332static const SectionRef get_section(MachOObjectFile *O, const char *segname,
3333 const char *sectname) {
3334 for (const SectionRef &Section : O->sections()) {
3335 StringRef SectName;
3336 Section.getName(SectName);
3337 DataRefImpl Ref = Section.getRawDataRefImpl();
3338 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3339 if (SegName == segname && SectName == sectname)
3340 return Section;
3341 }
3342 return SectionRef();
3343}
3344
3345static void
3346walk_pointer_list_64(const char *listname, const SectionRef S,
3347 MachOObjectFile *O, struct DisassembleInfo *info,
3348 void (*func)(uint64_t, struct DisassembleInfo *info)) {
3349 if (S == SectionRef())
3350 return;
3351
3352 StringRef SectName;
3353 S.getName(SectName);
3354 DataRefImpl Ref = S.getRawDataRefImpl();
3355 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3356 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3357
3358 StringRef BytesStr;
3359 S.getContents(BytesStr);
3360 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3361
3362 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint64_t)) {
3363 uint32_t left = S.getSize() - i;
3364 uint32_t size = left < sizeof(uint64_t) ? left : sizeof(uint64_t);
3365 uint64_t p = 0;
3366 memcpy(&p, Contents + i, size);
3367 if (i + sizeof(uint64_t) > S.getSize())
3368 outs() << listname << " list pointer extends past end of (" << SegName
3369 << "," << SectName << ") section\n";
3370 outs() << format("%016" PRIx64"l" "x", S.getAddress() + i) << " ";
3371
3372 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3373 sys::swapByteOrder(p);
3374
3375 uint64_t n_value = 0;
3376 const char *name = get_symbol_64(i, S, info, n_value, p);
3377 if (name == nullptr)
3378 name = get_dyld_bind_info_symbolname(S.getAddress() + i, info);
3379
3380 if (n_value != 0) {
3381 outs() << format("0x%" PRIx64"l" "x", n_value);
3382 if (p != 0)
3383 outs() << " + " << format("0x%" PRIx64"l" "x", p);
3384 } else
3385 outs() << format("0x%" PRIx64"l" "x", p);
3386 if (name != nullptr)
3387 outs() << " " << name;
3388 outs() << "\n";
3389
3390 p += n_value;
3391 if (func)
3392 func(p, info);
3393 }
3394}
3395
3396static void
3397walk_pointer_list_32(const char *listname, const SectionRef S,
3398 MachOObjectFile *O, struct DisassembleInfo *info,
3399 void (*func)(uint32_t, struct DisassembleInfo *info)) {
3400 if (S == SectionRef())
3401 return;
3402
3403 StringRef SectName;
3404 S.getName(SectName);
3405 DataRefImpl Ref = S.getRawDataRefImpl();
3406 StringRef SegName = O->getSectionFinalSegmentName(Ref);
3407 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
3408
3409 StringRef BytesStr;
3410 S.getContents(BytesStr);
3411 const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
3412
3413 for (uint32_t i = 0; i < S.getSize(); i += sizeof(uint32_t)) {
3414 uint32_t left = S.getSize() - i;
3415 uint32_t size = left < sizeof(uint32_t) ? left : sizeof(uint32_t);
3416 uint32_t p = 0;
3417 memcpy(&p, Contents + i, size);
3418 if (i + sizeof(uint32_t) > S.getSize())
3419 outs() << listname << " list pointer extends past end of (" << SegName
3420 << "," << SectName << ") section\n";
3421 uint32_t Address = S.getAddress() + i;
3422 outs() << format("%08" PRIx32"x", Address) << " ";
3423
3424 if (O->isLittleEndian() != sys::IsLittleEndianHost)
3425 sys::swapByteOrder(p);
3426 outs() << format("0x%" PRIx32"x", p);
3427
3428 const char *name = get_symbol_32(i, S, info, p);
3429 if (name != nullptr)
3430 outs() << " " << name;
3431 outs() << "\n";
3432
3433 if (func)
3434 func(p, info);
3435 }
3436}
3437
3438static void print_layout_map(const char *layout_map, uint32_t left) {
3439 if (layout_map == nullptr)
3440 return;
3441 outs() << " layout map: ";
3442 do {
3443 outs() << format("0x%02" PRIx32"x", (*layout_map) & 0xff) << " ";
3444 left--;
3445 layout_map++;
3446 } while (*layout_map != '\0' && left != 0);
3447 outs() << "\n";
3448}
3449
3450static void print_layout_map64(uint64_t p, struct DisassembleInfo *info) {
3451 uint32_t offset, left;
3452 SectionRef S;
3453 const char *layout_map;
3454
3455 if (p == 0)
3456 return;
3457 layout_map = get_pointer_64(p, offset, left, S, info);
3458 print_layout_map(layout_map, left);
3459}
3460
3461static void print_layout_map32(uint32_t p, struct DisassembleInfo *info) {
3462 uint32_t offset, left;
3463 SectionRef S;
3464 const char *layout_map;
3465
3466 if (p == 0)
3467 return;
3468 layout_map = get_pointer_32(p, offset, left, S, info);
3469 print_layout_map(layout_map, left);
3470}
3471
3472static void print_method_list64_t(uint64_t p, struct DisassembleInfo *info,
3473 const char *indent) {
3474 struct method_list64_t ml;
3475 struct method64_t m;
3476 const char *r;
3477 uint32_t offset, xoffset, left, i;
3478 SectionRef S, xS;
3479 const char *name, *sym_name;
3480 uint64_t n_value;
3481
3482 r = get_pointer_64(p, offset, left, S, info);
3483 if (r == nullptr)
3484 return;
3485 memset(&ml, '\0', sizeof(struct method_list64_t));
3486 if (left < sizeof(struct method_list64_t)) {
3487 memcpy(&ml, r, left);
3488 outs() << " (method_list_t entends past the end of the section)\n";
3489 } else
3490 memcpy(&ml, r, sizeof(struct method_list64_t));
3491 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3492 swapStruct(ml);
3493 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3494 outs() << indent << "\t\t count " << ml.count << "\n";
3495
3496 p += sizeof(struct method_list64_t);
3497 offset += sizeof(struct method_list64_t);
3498 for (i = 0; i < ml.count; i++) {
3499 r = get_pointer_64(p, offset, left, S, info);
3500 if (r == nullptr)
3501 return;
3502 memset(&m, '\0', sizeof(struct method64_t));
3503 if (left < sizeof(struct method64_t)) {
3504 memcpy(&m, r, left);
3505 outs() << indent << " (method_t extends past the end of the section)\n";
3506 } else
3507 memcpy(&m, r, sizeof(struct method64_t));
3508 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3509 swapStruct(m);
3510
3511 outs() << indent << "\t\t name ";
3512 sym_name = get_symbol_64(offset + offsetof(struct method64_t, name)__builtin_offsetof(struct method64_t, name), S,
3513 info, n_value, m.name);
3514 if (n_value != 0) {
3515 if (info->verbose && sym_name != nullptr)
3516 outs() << sym_name;
3517 else
3518 outs() << format("0x%" PRIx64"l" "x", n_value);
3519 if (m.name != 0)
3520 outs() << " + " << format("0x%" PRIx64"l" "x", m.name);
3521 } else
3522 outs() << format("0x%" PRIx64"l" "x", m.name);
3523 name = get_pointer_64(m.name + n_value, xoffset, left, xS, info);
3524 if (name != nullptr)
3525 outs() << format(" %.*s", left, name);
3526 outs() << "\n";
3527
3528 outs() << indent << "\t\t types ";
3529 sym_name = get_symbol_64(offset + offsetof(struct method64_t, types)__builtin_offsetof(struct method64_t, types), S,
3530 info, n_value, m.types);
3531 if (n_value != 0) {
3532 if (info->verbose && sym_name != nullptr)
3533 outs() << sym_name;
3534 else
3535 outs() << format("0x%" PRIx64"l" "x", n_value);
3536 if (m.types != 0)
3537 outs() << " + " << format("0x%" PRIx64"l" "x", m.types);
3538 } else
3539 outs() << format("0x%" PRIx64"l" "x", m.types);
3540 name = get_pointer_64(m.types + n_value, xoffset, left, xS, info);
3541 if (name != nullptr)
3542 outs() << format(" %.*s", left, name);
3543 outs() << "\n";
3544
3545 outs() << indent << "\t\t imp ";
3546 name = get_symbol_64(offset + offsetof(struct method64_t, imp)__builtin_offsetof(struct method64_t, imp), S, info,
3547 n_value, m.imp);
3548 if (info->verbose && name == nullptr) {
3549 if (n_value != 0) {
3550 outs() << format("0x%" PRIx64"l" "x", n_value) << " ";
3551 if (m.imp != 0)
3552 outs() << "+ " << format("0x%" PRIx64"l" "x", m.imp) << " ";
3553 } else
3554 outs() << format("0x%" PRIx64"l" "x", m.imp) << " ";
3555 }
3556 if (name != nullptr)
3557 outs() << name;
3558 outs() << "\n";
3559
3560 p += sizeof(struct method64_t);
3561 offset += sizeof(struct method64_t);
3562 }
3563}
3564
3565static void print_method_list32_t(uint64_t p, struct DisassembleInfo *info,
3566 const char *indent) {
3567 struct method_list32_t ml;
3568 struct method32_t m;
3569 const char *r, *name;
3570 uint32_t offset, xoffset, left, i;
3571 SectionRef S, xS;
3572
3573 r = get_pointer_32(p, offset, left, S, info);
3574 if (r == nullptr)
3575 return;
3576 memset(&ml, '\0', sizeof(struct method_list32_t));
3577 if (left < sizeof(struct method_list32_t)) {
3578 memcpy(&ml, r, left);
3579 outs() << " (method_list_t entends past the end of the section)\n";
3580 } else
3581 memcpy(&ml, r, sizeof(struct method_list32_t));
3582 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3583 swapStruct(ml);
3584 outs() << indent << "\t\t entsize " << ml.entsize << "\n";
3585 outs() << indent << "\t\t count " << ml.count << "\n";
3586
3587 p += sizeof(struct method_list32_t);
3588 offset += sizeof(struct method_list32_t);
3589 for (i = 0; i < ml.count; i++) {
3590 r = get_pointer_32(p, offset, left, S, info);
3591 if (r == nullptr)
3592 return;
3593 memset(&m, '\0', sizeof(struct method32_t));
3594 if (left < sizeof(struct method32_t)) {
3595 memcpy(&ml, r, left);
3596 outs() << indent << " (method_t entends past the end of the section)\n";
3597 } else
3598 memcpy(&m, r, sizeof(struct method32_t));
3599 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3600 swapStruct(m);
3601
3602 outs() << indent << "\t\t name " << format("0x%" PRIx32"x", m.name);
3603 name = get_pointer_32(m.name, xoffset, left, xS, info);
3604 if (name != nullptr)
3605 outs() << format(" %.*s", left, name);
3606 outs() << "\n";
3607
3608 outs() << indent << "\t\t types " << format("0x%" PRIx32"x", m.types);
3609 name = get_pointer_32(m.types, xoffset, left, xS, info);
3610 if (name != nullptr)
3611 outs() << format(" %.*s", left, name);
3612 outs() << "\n";
3613
3614 outs() << indent << "\t\t imp " << format("0x%" PRIx32"x", m.imp);
3615 name = get_symbol_32(offset + offsetof(struct method32_t, imp)__builtin_offsetof(struct method32_t, imp), S, info,
3616 m.imp);
3617 if (name != nullptr)
3618 outs() << " " << name;
3619 outs() << "\n";
3620
3621 p += sizeof(struct method32_t);
3622 offset += sizeof(struct method32_t);
3623 }
3624}
3625
3626static bool print_method_list(uint32_t p, struct DisassembleInfo *info) {
3627 uint32_t offset, left, xleft;
3628 SectionRef S;
3629 struct objc_method_list_t method_list;
3630 struct objc_method_t method;
3631 const char *r, *methods, *name, *SymbolName;
3632 int32_t i;
3633
3634 r = get_pointer_32(p, offset, left, S, info, true);
3635 if (r == nullptr)
3636 return true;
3637
3638 outs() << "\n";
3639 if (left > sizeof(struct objc_method_list_t)) {
3640 memcpy(&method_list, r, sizeof(struct objc_method_list_t));
3641 } else {
3642 outs() << "\t\t objc_method_list extends past end of the section\n";
3643 memset(&method_list, '\0', sizeof(struct objc_method_list_t));
3644 memcpy(&method_list, r, left);
3645 }
3646 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3647 swapStruct(method_list);
3648
3649 outs() << "\t\t obsolete "
3650 << format("0x%08" PRIx32"x", method_list.obsolete) << "\n";
3651 outs() << "\t\t method_count " << method_list.method_count << "\n";
3652
3653 methods = r + sizeof(struct objc_method_list_t);
3654 for (i = 0; i < method_list.method_count; i++) {
3655 if ((i + 1) * sizeof(struct objc_method_t) > left) {
3656 outs() << "\t\t remaining method's extend past the of the section\n";
3657 break;
3658 }
3659 memcpy(&method, methods + i * sizeof(struct objc_method_t),
3660 sizeof(struct objc_method_t));
3661 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3662 swapStruct(method);
3663
3664 outs() << "\t\t method_name "
3665 << format("0x%08" PRIx32"x", method.method_name);
3666 if (info->verbose) {
3667 name = get_pointer_32(method.method_name, offset, xleft, S, info, true);
3668 if (name != nullptr)
3669 outs() << format(" %.*s", xleft, name);
3670 else
3671 outs() << " (not in an __OBJC section)";
3672 }
3673 outs() << "\n";
3674
3675 outs() << "\t\t method_types "
3676 << format("0x%08" PRIx32"x", method.method_types);
3677 if (info->verbose) {
3678 name = get_pointer_32(method.method_types, offset, xleft, S, info, true);
3679 if (name != nullptr)
3680 outs() << format(" %.*s", xleft, name);
3681 else
3682 outs() << " (not in an __OBJC section)";
3683 }
3684 outs() << "\n";
3685
3686 outs() << "\t\t method_imp "
3687 << format("0x%08" PRIx32"x", method.method_imp) << " ";
3688 if (info->verbose) {
3689 SymbolName = GuessSymbolName(method.method_imp, info->AddrMap);
3690 if (SymbolName != nullptr)
3691 outs() << SymbolName;
3692 }
3693 outs() << "\n";
3694 }
3695 return false;
3696}
3697
3698static void print_protocol_list64_t(uint64_t p, struct DisassembleInfo *info) {
3699 struct protocol_list64_t pl;
3700 uint64_t q, n_value;
3701 struct protocol64_t pc;
3702 const char *r;
3703 uint32_t offset, xoffset, left, i;
3704 SectionRef S, xS;
3705 const char *name, *sym_name;
3706
3707 r = get_pointer_64(p, offset, left, S, info);
3708 if (r == nullptr)
3709 return;
3710 memset(&pl, '\0', sizeof(struct protocol_list64_t));
3711 if (left < sizeof(struct protocol_list64_t)) {
3712 memcpy(&pl, r, left);
3713 outs() << " (protocol_list_t entends past the end of the section)\n";
3714 } else
3715 memcpy(&pl, r, sizeof(struct protocol_list64_t));
3716 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3717 swapStruct(pl);
3718 outs() << " count " << pl.count << "\n";
3719
3720 p += sizeof(struct protocol_list64_t);
3721 offset += sizeof(struct protocol_list64_t);
3722 for (i = 0; i < pl.count; i++) {
3723 r = get_pointer_64(p, offset, left, S, info);
3724 if (r == nullptr)
3725 return;
3726 q = 0;
3727 if (left < sizeof(uint64_t)) {
3728 memcpy(&q, r, left);
3729 outs() << " (protocol_t * entends past the end of the section)\n";
3730 } else
3731 memcpy(&q, r, sizeof(uint64_t));
3732 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3733 sys::swapByteOrder(q);
3734
3735 outs() << "\t\t list[" << i << "] ";
3736 sym_name = get_symbol_64(offset, S, info, n_value, q);
3737 if (n_value != 0) {
3738 if (info->verbose && sym_name != nullptr)
3739 outs() << sym_name;
3740 else
3741 outs() << format("0x%" PRIx64"l" "x", n_value);
3742 if (q != 0)
3743 outs() << " + " << format("0x%" PRIx64"l" "x", q);
3744 } else
3745 outs() << format("0x%" PRIx64"l" "x", q);
3746 outs() << " (struct protocol_t *)\n";
3747
3748 r = get_pointer_64(q + n_value, offset, left, S, info);
3749 if (r == nullptr)
3750 return;
3751 memset(&pc, '\0', sizeof(struct protocol64_t));
3752 if (left < sizeof(struct protocol64_t)) {
3753 memcpy(&pc, r, left);
3754 outs() << " (protocol_t entends past the end of the section)\n";
3755 } else
3756 memcpy(&pc, r, sizeof(struct protocol64_t));
3757 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3758 swapStruct(pc);
3759
3760 outs() << "\t\t\t isa " << format("0x%" PRIx64"l" "x", pc.isa) << "\n";
3761
3762 outs() << "\t\t\t name ";
3763 sym_name = get_symbol_64(offset + offsetof(struct protocol64_t, name)__builtin_offsetof(struct protocol64_t, name), S,
3764 info, n_value, pc.name);
3765 if (n_value != 0) {
3766 if (info->verbose && sym_name != nullptr)
3767 outs() << sym_name;
3768 else
3769 outs() << format("0x%" PRIx64"l" "x", n_value);
3770 if (pc.name != 0)
3771 outs() << " + " << format("0x%" PRIx64"l" "x", pc.name);
3772 } else
3773 outs() << format("0x%" PRIx64"l" "x", pc.name);
3774 name = get_pointer_64(pc.name + n_value, xoffset, left, xS, info);
3775 if (name != nullptr)
3776 outs() << format(" %.*s", left, name);
3777 outs() << "\n";
3778
3779 outs() << "\t\t\tprotocols " << format("0x%" PRIx64"l" "x", pc.protocols) << "\n";
3780
3781 outs() << "\t\t instanceMethods ";
3782 sym_name =
3783 get_symbol_64(offset + offsetof(struct protocol64_t, instanceMethods)__builtin_offsetof(struct protocol64_t, instanceMethods),
3784 S, info, n_value, pc.instanceMethods);
3785 if (n_value != 0) {
3786 if (info->verbose && sym_name != nullptr)
3787 outs() << sym_name;
3788 else
3789 outs() << format("0x%" PRIx64"l" "x", n_value);
3790 if (pc.instanceMethods != 0)
3791 outs() << " + " << format("0x%" PRIx64"l" "x", pc.instanceMethods);
3792 } else
3793 outs() << format("0x%" PRIx64"l" "x", pc.instanceMethods);
3794 outs() << " (struct method_list_t *)\n";
3795 if (pc.instanceMethods + n_value != 0)
3796 print_method_list64_t(pc.instanceMethods + n_value, info, "\t");
3797
3798 outs() << "\t\t classMethods ";
3799 sym_name =
3800 get_symbol_64(offset + offsetof(struct protocol64_t, classMethods)__builtin_offsetof(struct protocol64_t, classMethods), S,
3801 info, n_value, pc.classMethods);
3802 if (n_value != 0) {
3803 if (info->verbose && sym_name != nullptr)
3804 outs() << sym_name;
3805 else
3806 outs() << format("0x%" PRIx64"l" "x", n_value);
3807 if (pc.classMethods != 0)
3808 outs() << " + " << format("0x%" PRIx64"l" "x", pc.classMethods);
3809 } else
3810 outs() << format("0x%" PRIx64"l" "x", pc.classMethods);
3811 outs() << " (struct method_list_t *)\n";
3812 if (pc.classMethods + n_value != 0)
3813 print_method_list64_t(pc.classMethods + n_value, info, "\t");
3814
3815 outs() << "\t optionalInstanceMethods "
3816 << format("0x%" PRIx64"l" "x", pc.optionalInstanceMethods) << "\n";
3817 outs() << "\t optionalClassMethods "
3818 << format("0x%" PRIx64"l" "x", pc.optionalClassMethods) << "\n";
3819 outs() << "\t instanceProperties "
3820 << format("0x%" PRIx64"l" "x", pc.instanceProperties) << "\n";
3821
3822 p += sizeof(uint64_t);
3823 offset += sizeof(uint64_t);
3824 }
3825}
3826
3827static void print_protocol_list32_t(uint32_t p, struct DisassembleInfo *info) {
3828 struct protocol_list32_t pl;
3829 uint32_t q;
3830 struct protocol32_t pc;
3831 const char *r;
3832 uint32_t offset, xoffset, left, i;
3833 SectionRef S, xS;
3834 const char *name;
3835
3836 r = get_pointer_32(p, offset, left, S, info);
3837 if (r == nullptr)
3838 return;
3839 memset(&pl, '\0', sizeof(struct protocol_list32_t));
3840 if (left < sizeof(struct protocol_list32_t)) {
3841 memcpy(&pl, r, left);
3842 outs() << " (protocol_list_t entends past the end of the section)\n";
3843 } else
3844 memcpy(&pl, r, sizeof(struct protocol_list32_t));
3845 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3846 swapStruct(pl);
3847 outs() << " count " << pl.count << "\n";
3848
3849 p += sizeof(struct protocol_list32_t);
3850 offset += sizeof(struct protocol_list32_t);
3851 for (i = 0; i < pl.count; i++) {
3852 r = get_pointer_32(p, offset, left, S, info);
3853 if (r == nullptr)
3854 return;
3855 q = 0;
3856 if (left < sizeof(uint32_t)) {
3857 memcpy(&q, r, left);
3858 outs() << " (protocol_t * entends past the end of the section)\n";
3859 } else
3860 memcpy(&q, r, sizeof(uint32_t));
3861 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3862 sys::swapByteOrder(q);
3863 outs() << "\t\t list[" << i << "] " << format("0x%" PRIx32"x", q)
3864 << " (struct protocol_t *)\n";
3865 r = get_pointer_32(q, offset, left, S, info);
3866 if (r == nullptr)
3867 return;
3868 memset(&pc, '\0', sizeof(struct protocol32_t));
3869 if (left < sizeof(struct protocol32_t)) {
3870 memcpy(&pc, r, left);
3871 outs() << " (protocol_t entends past the end of the section)\n";
3872 } else
3873 memcpy(&pc, r, sizeof(struct protocol32_t));
3874 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3875 swapStruct(pc);
3876 outs() << "\t\t\t isa " << format("0x%" PRIx32"x", pc.isa) << "\n";
3877 outs() << "\t\t\t name " << format("0x%" PRIx32"x", pc.name);
3878 name = get_pointer_32(pc.name, xoffset, left, xS, info);
3879 if (name != nullptr)
3880 outs() << format(" %.*s", left, name);
3881 outs() << "\n";
3882 outs() << "\t\t\tprotocols " << format("0x%" PRIx32"x", pc.protocols) << "\n";
3883 outs() << "\t\t instanceMethods "
3884 << format("0x%" PRIx32"x", pc.instanceMethods)
3885 << " (struct method_list_t *)\n";
3886 if (pc.instanceMethods != 0)
3887 print_method_list32_t(pc.instanceMethods, info, "\t");
3888 outs() << "\t\t classMethods " << format("0x%" PRIx32"x", pc.classMethods)
3889 << " (struct method_list_t *)\n";
3890 if (pc.classMethods != 0)
3891 print_method_list32_t(pc.classMethods, info, "\t");
3892 outs() << "\t optionalInstanceMethods "
3893 << format("0x%" PRIx32"x", pc.optionalInstanceMethods) << "\n";
3894 outs() << "\t optionalClassMethods "
3895 << format("0x%" PRIx32"x", pc.optionalClassMethods) << "\n";
3896 outs() << "\t instanceProperties "
3897 << format("0x%" PRIx32"x", pc.instanceProperties) << "\n";
3898 p += sizeof(uint32_t);
3899 offset += sizeof(uint32_t);
3900 }
3901}
3902
3903static void print_indent(uint32_t indent) {
3904 for (uint32_t i = 0; i < indent;) {
3905 if (indent - i >= 8) {
3906 outs() << "\t";
3907 i += 8;
3908 } else {
3909 for (uint32_t j = i; j < indent; j++)
3910 outs() << " ";
3911 return;
3912 }
3913 }
3914}
3915
3916static bool print_method_description_list(uint32_t p, uint32_t indent,
3917 struct DisassembleInfo *info) {
3918 uint32_t offset, left, xleft;
3919 SectionRef S;
3920 struct objc_method_description_list_t mdl;
3921 struct objc_method_description_t md;
3922 const char *r, *list, *name;
3923 int32_t i;
3924
3925 r = get_pointer_32(p, offset, left, S, info, true);
3926 if (r == nullptr)
3927 return true;
3928
3929 outs() << "\n";
3930 if (left > sizeof(struct objc_method_description_list_t)) {
3931 memcpy(&mdl, r, sizeof(struct objc_method_description_list_t));
3932 } else {
3933 print_indent(indent);
3934 outs() << " objc_method_description_list extends past end of the section\n";
3935 memset(&mdl, '\0', sizeof(struct objc_method_description_list_t));
3936 memcpy(&mdl, r, left);
3937 }
3938 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3939 swapStruct(mdl);
3940
3941 print_indent(indent);
3942 outs() << " count " << mdl.count << "\n";
3943
3944 list = r + sizeof(struct objc_method_description_list_t);
3945 for (i = 0; i < mdl.count; i++) {
3946 if ((i + 1) * sizeof(struct objc_method_description_t) > left) {
3947 print_indent(indent);
3948 outs() << " remaining list entries extend past the of the section\n";
3949 break;
3950 }
3951 print_indent(indent);
3952 outs() << " list[" << i << "]\n";
3953 memcpy(&md, list + i * sizeof(struct objc_method_description_t),
3954 sizeof(struct objc_method_description_t));
3955 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
3956 swapStruct(md);
3957
3958 print_indent(indent);
3959 outs() << " name " << format("0x%08" PRIx32"x", md.name);
3960 if (info->verbose) {
3961 name = get_pointer_32(md.name, offset, xleft, S, info, true);
3962 if (name != nullptr)
3963 outs() << format(" %.*s", xleft, name);
3964 else
3965 outs() << " (not in an __OBJC section)";
3966 }
3967 outs() << "\n";
3968
3969 print_indent(indent);
3970 outs() << " types " << format("0x%08" PRIx32"x", md.types);
3971 if (info->verbose) {
3972 name = get_pointer_32(md.types, offset, xleft, S, info, true);
3973 if (name != nullptr)
3974 outs() << format(" %.*s", xleft, name);
3975 else
3976 outs() << " (not in an __OBJC section)";
3977 }
3978 outs() << "\n";
3979 }
3980 return false;
3981}
3982
3983static bool print_protocol_list(uint32_t p, uint32_t indent,
3984 struct DisassembleInfo *info);
3985
3986static bool print_protocol(uint32_t p, uint32_t indent,
3987 struct DisassembleInfo *info) {
3988 uint32_t offset, left;
3989 SectionRef S;
3990 struct objc_protocol_t protocol;
3991 const char *r, *name;
3992
3993 r = get_pointer_32(p, offset, left, S, info, true);
3994 if (r == nullptr)
3995 return true;
3996
3997 outs() << "\n";
3998 if (left >= sizeof(struct objc_protocol_t)) {
3999 memcpy(&protocol, r, sizeof(struct objc_protocol_t));
4000 } else {
4001 print_indent(indent);
4002 outs() << " Protocol extends past end of the section\n";
4003 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
4004 memcpy(&protocol, r, left);
4005 }
4006 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4007 swapStruct(protocol);
4008
4009 print_indent(indent);
4010 outs() << " isa " << format("0x%08" PRIx32"x", protocol.isa)
4011 << "\n";
4012
4013 print_indent(indent);
4014 outs() << " protocol_name "
4015 << format("0x%08" PRIx32"x", protocol.protocol_name);
4016 if (info->verbose) {
4017 name = get_pointer_32(protocol.protocol_name, offset, left, S, info, true);
4018 if (name != nullptr)
4019 outs() << format(" %.*s", left, name);
4020 else
4021 outs() << " (not in an __OBJC section)";
4022 }
4023 outs() << "\n";
4024
4025 print_indent(indent);
4026 outs() << " protocol_list "
4027 << format("0x%08" PRIx32"x", protocol.protocol_list);
4028 if (print_protocol_list(protocol.protocol_list, indent + 4, info))
4029 outs() << " (not in an __OBJC section)\n";
4030
4031 print_indent(indent);
4032 outs() << " instance_methods "
4033 << format("0x%08" PRIx32"x", protocol.instance_methods);
4034 if (print_method_description_list(protocol.instance_methods, indent, info))
4035 outs() << " (not in an __OBJC section)\n";
4036
4037 print_indent(indent);
4038 outs() << " class_methods "
4039 << format("0x%08" PRIx32"x", protocol.class_methods);
4040 if (print_method_description_list(protocol.class_methods, indent, info))
4041 outs() << " (not in an __OBJC section)\n";
4042
4043 return false;
4044}
4045
4046static bool print_protocol_list(uint32_t p, uint32_t indent,
4047 struct DisassembleInfo *info) {
4048 uint32_t offset, left, l;
4049 SectionRef S;
4050 struct objc_protocol_list_t protocol_list;
4051 const char *r, *list;
4052 int32_t i;
4053
4054 r = get_pointer_32(p, offset, left, S, info, true);
4055 if (r == nullptr)
4056 return true;
4057
4058 outs() << "\n";
4059 if (left > sizeof(struct objc_protocol_list_t)) {
4060 memcpy(&protocol_list, r, sizeof(struct objc_protocol_list_t));
4061 } else {
4062 outs() << "\t\t objc_protocol_list_t extends past end of the section\n";
4063 memset(&protocol_list, '\0', sizeof(struct objc_protocol_list_t));
4064 memcpy(&protocol_list, r, left);
4065 }
4066 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4067 swapStruct(protocol_list);
4068
4069 print_indent(indent);
4070 outs() << " next " << format("0x%08" PRIx32"x", protocol_list.next)
4071 << "\n";
4072 print_indent(indent);
4073 outs() << " count " << protocol_list.count << "\n";
4074
4075 list = r + sizeof(struct objc_protocol_list_t);
4076 for (i = 0; i < protocol_list.count; i++) {
4077 if ((i + 1) * sizeof(uint32_t) > left) {
4078 outs() << "\t\t remaining list entries extend past the of the section\n";
4079 break;
4080 }
4081 memcpy(&l, list + i * sizeof(uint32_t), sizeof(uint32_t));
4082 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4083 sys::swapByteOrder(l);
4084
4085 print_indent(indent);
4086 outs() << " list[" << i << "] " << format("0x%08" PRIx32"x", l);
4087 if (print_protocol(l, indent, info))
4088 outs() << "(not in an __OBJC section)\n";
4089 }
4090 return false;
4091}
4092
4093static void print_ivar_list64_t(uint64_t p, struct DisassembleInfo *info) {
4094 struct ivar_list64_t il;
4095 struct ivar64_t i;
4096 const char *r;
4097 uint32_t offset, xoffset, left, j;
4098 SectionRef S, xS;
4099 const char *name, *sym_name, *ivar_offset_p;
4100 uint64_t ivar_offset, n_value;
4101
4102 r = get_pointer_64(p, offset, left, S, info);
4103 if (r == nullptr)
4104 return;
4105 memset(&il, '\0', sizeof(struct ivar_list64_t));
4106 if (left < sizeof(struct ivar_list64_t)) {
4107 memcpy(&il, r, left);
4108 outs() << " (ivar_list_t entends past the end of the section)\n";
4109 } else
4110 memcpy(&il, r, sizeof(struct ivar_list64_t));
4111 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4112 swapStruct(il);
4113 outs() << " entsize " << il.entsize << "\n";
4114 outs() << " count " << il.count << "\n";
4115
4116 p += sizeof(struct ivar_list64_t);
4117 offset += sizeof(struct ivar_list64_t);
4118 for (j = 0; j < il.count; j++) {
4119 r = get_pointer_64(p, offset, left, S, info);
4120 if (r == nullptr)
4121 return;
4122 memset(&i, '\0', sizeof(struct ivar64_t));
4123 if (left < sizeof(struct ivar64_t)) {
4124 memcpy(&i, r, left);
4125 outs() << " (ivar_t entends past the end of the section)\n";
4126 } else
4127 memcpy(&i, r, sizeof(struct ivar64_t));
4128 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4129 swapStruct(i);
4130
4131 outs() << "\t\t\t offset ";
4132 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, offset)__builtin_offsetof(struct ivar64_t, offset), S,
4133 info, n_value, i.offset);
4134 if (n_value != 0) {
4135 if (info->verbose && sym_name != nullptr)
4136 outs() << sym_name;
4137 else
4138 outs() << format("0x%" PRIx64"l" "x", n_value);
4139 if (i.offset != 0)
4140 outs() << " + " << format("0x%" PRIx64"l" "x", i.offset);
4141 } else
4142 outs() << format("0x%" PRIx64"l" "x", i.offset);
4143 ivar_offset_p = get_pointer_64(i.offset + n_value, xoffset, left, xS, info);
4144 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4145 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4146 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4147 sys::swapByteOrder(ivar_offset);
4148 outs() << " " << ivar_offset << "\n";
4149 } else
4150 outs() << "\n";
4151
4152 outs() << "\t\t\t name ";
4153 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, name)__builtin_offsetof(struct ivar64_t, name), S, info,
4154 n_value, i.name);
4155 if (n_value != 0) {
4156 if (info->verbose && sym_name != nullptr)
4157 outs() << sym_name;
4158 else
4159 outs() << format("0x%" PRIx64"l" "x", n_value);
4160 if (i.name != 0)
4161 outs() << " + " << format("0x%" PRIx64"l" "x", i.name);
4162 } else
4163 outs() << format("0x%" PRIx64"l" "x", i.name);
4164 name = get_pointer_64(i.name + n_value, xoffset, left, xS, info);
4165 if (name != nullptr)
4166 outs() << format(" %.*s", left, name);
4167 outs() << "\n";
4168
4169 outs() << "\t\t\t type ";
4170 sym_name = get_symbol_64(offset + offsetof(struct ivar64_t, type)__builtin_offsetof(struct ivar64_t, type), S, info,
4171 n_value, i.name);
4172 name = get_pointer_64(i.type + n_value, xoffset, left, xS, info);
4173 if (n_value != 0) {
4174 if (info->verbose && sym_name != nullptr)
4175 outs() << sym_name;
4176 else
4177 outs() << format("0x%" PRIx64"l" "x", n_value);
4178 if (i.type != 0)
4179 outs() << " + " << format("0x%" PRIx64"l" "x", i.type);
4180 } else
4181 outs() << format("0x%" PRIx64"l" "x", i.type);
4182 if (name != nullptr)
4183 outs() << format(" %.*s", left, name);
4184 outs() << "\n";
4185
4186 outs() << "\t\t\talignment " << i.alignment << "\n";
4187 outs() << "\t\t\t size " << i.size << "\n";
4188
4189 p += sizeof(struct ivar64_t);
4190 offset += sizeof(struct ivar64_t);
4191 }
4192}
4193
4194static void print_ivar_list32_t(uint32_t p, struct DisassembleInfo *info) {
4195 struct ivar_list32_t il;
4196 struct ivar32_t i;
4197 const char *r;
4198 uint32_t offset, xoffset, left, j;
4199 SectionRef S, xS;
4200 const char *name, *ivar_offset_p;
4201 uint32_t ivar_offset;
4202
4203 r = get_pointer_32(p, offset, left, S, info);
4204 if (r == nullptr)
4205 return;
4206 memset(&il, '\0', sizeof(struct ivar_list32_t));
4207 if (left < sizeof(struct ivar_list32_t)) {
4208 memcpy(&il, r, left);
4209 outs() << " (ivar_list_t entends past the end of the section)\n";
4210 } else
4211 memcpy(&il, r, sizeof(struct ivar_list32_t));
4212 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4213 swapStruct(il);
4214 outs() << " entsize " << il.entsize << "\n";
4215 outs() << " count " << il.count << "\n";
4216
4217 p += sizeof(struct ivar_list32_t);
4218 offset += sizeof(struct ivar_list32_t);
4219 for (j = 0; j < il.count; j++) {
4220 r = get_pointer_32(p, offset, left, S, info);
4221 if (r == nullptr)
4222 return;
4223 memset(&i, '\0', sizeof(struct ivar32_t));
4224 if (left < sizeof(struct ivar32_t)) {
4225 memcpy(&i, r, left);
4226 outs() << " (ivar_t entends past the end of the section)\n";
4227 } else
4228 memcpy(&i, r, sizeof(struct ivar32_t));
4229 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4230 swapStruct(i);
4231
4232 outs() << "\t\t\t offset " << format("0x%" PRIx32"x", i.offset);
4233 ivar_offset_p = get_pointer_32(i.offset, xoffset, left, xS, info);
4234 if (ivar_offset_p != nullptr && left >= sizeof(*ivar_offset_p)) {
4235 memcpy(&ivar_offset, ivar_offset_p, sizeof(ivar_offset));
4236 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4237 sys::swapByteOrder(ivar_offset);
4238 outs() << " " << ivar_offset << "\n";
4239 } else
4240 outs() << "\n";
4241
4242 outs() << "\t\t\t name " << format("0x%" PRIx32"x", i.name);
4243 name = get_pointer_32(i.name, xoffset, left, xS, info);
4244 if (name != nullptr)
4245 outs() << format(" %.*s", left, name);
4246 outs() << "\n";
4247
4248 outs() << "\t\t\t type " << format("0x%" PRIx32"x", i.type);
4249 name = get_pointer_32(i.type, xoffset, left, xS, info);
4250 if (name != nullptr)
4251 outs() << format(" %.*s", left, name);
4252 outs() << "\n";
4253
4254 outs() << "\t\t\talignment " << i.alignment << "\n";
4255 outs() << "\t\t\t size " << i.size << "\n";
4256
4257 p += sizeof(struct ivar32_t);
4258 offset += sizeof(struct ivar32_t);
4259 }
4260}
4261
4262static void print_objc_property_list64(uint64_t p,
4263 struct DisassembleInfo *info) {
4264 struct objc_property_list64 opl;
4265 struct objc_property64 op;
4266 const char *r;
4267 uint32_t offset, xoffset, left, j;
4268 SectionRef S, xS;
4269 const char *name, *sym_name;
4270 uint64_t n_value;
4271
4272 r = get_pointer_64(p, offset, left, S, info);
4273 if (r == nullptr)
4274 return;
4275 memset(&opl, '\0', sizeof(struct objc_property_list64));
4276 if (left < sizeof(struct objc_property_list64)) {
4277 memcpy(&opl, r, left);
4278 outs() << " (objc_property_list entends past the end of the section)\n";
4279 } else
4280 memcpy(&opl, r, sizeof(struct objc_property_list64));
4281 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4282 swapStruct(opl);
4283 outs() << " entsize " << opl.entsize << "\n";
4284 outs() << " count " << opl.count << "\n";
4285
4286 p += sizeof(struct objc_property_list64);
4287 offset += sizeof(struct objc_property_list64);
4288 for (j = 0; j < opl.count; j++) {
4289 r = get_pointer_64(p, offset, left, S, info);
4290 if (r == nullptr)
4291 return;
4292 memset(&op, '\0', sizeof(struct objc_property64));
4293 if (left < sizeof(struct objc_property64)) {
4294 memcpy(&op, r, left);
4295 outs() << " (objc_property entends past the end of the section)\n";
4296 } else
4297 memcpy(&op, r, sizeof(struct objc_property64));
4298 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4299 swapStruct(op);
4300
4301 outs() << "\t\t\t name ";
4302 sym_name = get_symbol_64(offset + offsetof(struct objc_property64, name)__builtin_offsetof(struct objc_property64, name), S,
4303 info, n_value, op.name);
4304 if (n_value != 0) {
4305 if (info->verbose && sym_name != nullptr)
4306 outs() << sym_name;
4307 else
4308 outs() << format("0x%" PRIx64"l" "x", n_value);
4309 if (op.name != 0)
4310 outs() << " + " << format("0x%" PRIx64"l" "x", op.name);
4311 } else
4312 outs() << format("0x%" PRIx64"l" "x", op.name);
4313 name = get_pointer_64(op.name + n_value, xoffset, left, xS, info);
4314 if (name != nullptr)
4315 outs() << format(" %.*s", left, name);
4316 outs() << "\n";
4317
4318 outs() << "\t\t\tattributes ";
4319 sym_name =
4320 get_symbol_64(offset + offsetof(struct objc_property64, attributes)__builtin_offsetof(struct objc_property64, attributes), S,
4321 info, n_value, op.attributes);
4322 if (n_value != 0) {
4323 if (info->verbose && sym_name != nullptr)
4324 outs() << sym_name;
4325 else
4326 outs() << format("0x%" PRIx64"l" "x", n_value);
4327 if (op.attributes != 0)
4328 outs() << " + " << format("0x%" PRIx64"l" "x", op.attributes);
4329 } else
4330 outs() << format("0x%" PRIx64"l" "x", op.attributes);
4331 name = get_pointer_64(op.attributes + n_value, xoffset, left, xS, info);
4332 if (name != nullptr)
4333 outs() << format(" %.*s", left, name);
4334 outs() << "\n";
4335
4336 p += sizeof(struct objc_property64);
4337 offset += sizeof(struct objc_property64);
4338 }
4339}
4340
4341static void print_objc_property_list32(uint32_t p,
4342 struct DisassembleInfo *info) {
4343 struct objc_property_list32 opl;
4344 struct objc_property32 op;
4345 const char *r;
4346 uint32_t offset, xoffset, left, j;
4347 SectionRef S, xS;
4348 const char *name;
4349
4350 r = get_pointer_32(p, offset, left, S, info);
4351 if (r == nullptr)
4352 return;
4353 memset(&opl, '\0', sizeof(struct objc_property_list32));
4354 if (left < sizeof(struct objc_property_list32)) {
4355 memcpy(&opl, r, left);
4356 outs() << " (objc_property_list entends past the end of the section)\n";
4357 } else
4358 memcpy(&opl, r, sizeof(struct objc_property_list32));
4359 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4360 swapStruct(opl);
4361 outs() << " entsize " << opl.entsize << "\n";
4362 outs() << " count " << opl.count << "\n";
4363
4364 p += sizeof(struct objc_property_list32);
4365 offset += sizeof(struct objc_property_list32);
4366 for (j = 0; j < opl.count; j++) {
4367 r = get_pointer_32(p, offset, left, S, info);
4368 if (r == nullptr)
4369 return;
4370 memset(&op, '\0', sizeof(struct objc_property32));
4371 if (left < sizeof(struct objc_property32)) {
4372 memcpy(&op, r, left);
4373 outs() << " (objc_property entends past the end of the section)\n";
4374 } else
4375 memcpy(&op, r, sizeof(struct objc_property32));
4376 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4377 swapStruct(op);
4378
4379 outs() << "\t\t\t name " << format("0x%" PRIx32"x", op.name);
4380 name = get_pointer_32(op.name, xoffset, left, xS, info);
4381 if (name != nullptr)
4382 outs() << format(" %.*s", left, name);
4383 outs() << "\n";
4384
4385 outs() << "\t\t\tattributes " << format("0x%" PRIx32"x", op.attributes);
4386 name = get_pointer_32(op.attributes, xoffset, left, xS, info);
4387 if (name != nullptr)
4388 outs() << format(" %.*s", left, name);
4389 outs() << "\n";
4390
4391 p += sizeof(struct objc_property32);
4392 offset += sizeof(struct objc_property32);
4393 }
4394}
4395
4396static bool print_class_ro64_t(uint64_t p, struct DisassembleInfo *info,
4397 bool &is_meta_class) {
4398 struct class_ro64_t cro;
4399 const char *r;
4400 uint32_t offset, xoffset, left;
4401 SectionRef S, xS;
4402 const char *name, *sym_name;
4403 uint64_t n_value;
4404
4405 r = get_pointer_64(p, offset, left, S, info);
4406 if (r == nullptr || left < sizeof(struct class_ro64_t))
4407 return false;
4408 memcpy(&cro, r, sizeof(struct class_ro64_t));
4409 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4410 swapStruct(cro);
4411 outs() << " flags " << format("0x%" PRIx32"x", cro.flags);
4412 if (cro.flags & RO_META(1 << 0))
4413 outs() << " RO_META";
4414 if (cro.flags & RO_ROOT(1 << 1))
4415 outs() << " RO_ROOT";
4416 if (cro.flags & RO_HAS_CXX_STRUCTORS(1 << 2))
4417 outs() << " RO_HAS_CXX_STRUCTORS";
4418 outs() << "\n";
4419 outs() << " instanceStart " << cro.instanceStart << "\n";
4420 outs() << " instanceSize " << cro.instanceSize << "\n";
4421 outs() << " reserved " << format("0x%" PRIx32"x", cro.reserved)
4422 << "\n";
4423 outs() << " ivarLayout " << format("0x%" PRIx64"l" "x", cro.ivarLayout)
4424 << "\n";
4425 print_layout_map64(cro.ivarLayout, info);
4426
4427 outs() << " name ";
4428 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, name)__builtin_offsetof(struct class_ro64_t, name), S,
4429 info, n_value, cro.name);
4430 if (n_value != 0) {
4431 if (info->verbose && sym_name != nullptr)
4432 outs() << sym_name;
4433 else
4434 outs() << format("0x%" PRIx64"l" "x", n_value);
4435 if (cro.name != 0)
4436 outs() << " + " << format("0x%" PRIx64"l" "x", cro.name);
4437 } else
4438 outs() << format("0x%" PRIx64"l" "x", cro.name);
4439 name = get_pointer_64(cro.name + n_value, xoffset, left, xS, info);
4440 if (name != nullptr)
4441 outs() << format(" %.*s", left, name);
4442 outs() << "\n";
4443
4444 outs() << " baseMethods ";
4445 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, baseMethods)__builtin_offsetof(struct class_ro64_t, baseMethods),
4446 S, info, n_value, cro.baseMethods);
4447 if (n_value != 0) {
4448 if (info->verbose && sym_name != nullptr)
4449 outs() << sym_name;
4450 else
4451 outs() << format("0x%" PRIx64"l" "x", n_value);
4452 if (cro.baseMethods != 0)
4453 outs() << " + " << format("0x%" PRIx64"l" "x", cro.baseMethods);
4454 } else
4455 outs() << format("0x%" PRIx64"l" "x", cro.baseMethods);
4456 outs() << " (struct method_list_t *)\n";
4457 if (cro.baseMethods + n_value != 0)
4458 print_method_list64_t(cro.baseMethods + n_value, info, "");
4459
4460 outs() << " baseProtocols ";
4461 sym_name =
4462 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProtocols)__builtin_offsetof(struct class_ro64_t, baseProtocols), S,
4463 info, n_value, cro.baseProtocols);
4464 if (n_value != 0) {
4465 if (info->verbose && sym_name != nullptr)
4466 outs() << sym_name;
4467 else
4468 outs() << format("0x%" PRIx64"l" "x", n_value);
4469 if (cro.baseProtocols != 0)
4470 outs() << " + " << format("0x%" PRIx64"l" "x", cro.baseProtocols);
4471 } else
4472 outs() << format("0x%" PRIx64"l" "x", cro.baseProtocols);
4473 outs() << "\n";
4474 if (cro.baseProtocols + n_value != 0)
4475 print_protocol_list64_t(cro.baseProtocols + n_value, info);
4476
4477 outs() << " ivars ";
4478 sym_name = get_symbol_64(offset + offsetof(struct class_ro64_t, ivars)__builtin_offsetof(struct class_ro64_t, ivars), S,
4479 info, n_value, cro.ivars);
4480 if (n_value != 0) {
4481 if (info->verbose && sym_name != nullptr)
4482 outs() << sym_name;
4483 else
4484 outs() << format("0x%" PRIx64"l" "x", n_value);
4485 if (cro.ivars != 0)
4486 outs() << " + " << format("0x%" PRIx64"l" "x", cro.ivars);
4487 } else
4488 outs() << format("0x%" PRIx64"l" "x", cro.ivars);
4489 outs() << "\n";
4490 if (cro.ivars + n_value != 0)
4491 print_ivar_list64_t(cro.ivars + n_value, info);
4492
4493 outs() << " weakIvarLayout ";
4494 sym_name =
4495 get_symbol_64(offset + offsetof(struct class_ro64_t, weakIvarLayout)__builtin_offsetof(struct class_ro64_t, weakIvarLayout), S,
4496 info, n_value, cro.weakIvarLayout);
4497 if (n_value != 0) {
4498 if (info->verbose && sym_name != nullptr)
4499 outs() << sym_name;
4500 else
4501 outs() << format("0x%" PRIx64"l" "x", n_value);
4502 if (cro.weakIvarLayout != 0)
4503 outs() << " + " << format("0x%" PRIx64"l" "x", cro.weakIvarLayout);
4504 } else
4505 outs() << format("0x%" PRIx64"l" "x", cro.weakIvarLayout);
4506 outs() << "\n";
4507 print_layout_map64(cro.weakIvarLayout + n_value, info);
4508
4509 outs() << " baseProperties ";
4510 sym_name =
4511 get_symbol_64(offset + offsetof(struct class_ro64_t, baseProperties)__builtin_offsetof(struct class_ro64_t, baseProperties), S,
4512 info, n_value, cro.baseProperties);
4513 if (n_value != 0) {
4514 if (info->verbose && sym_name != nullptr)
4515 outs() << sym_name;
4516 else
4517 outs() << format("0x%" PRIx64"l" "x", n_value);
4518 if (cro.baseProperties != 0)
4519 outs() << " + " << format("0x%" PRIx64"l" "x", cro.baseProperties);
4520 } else
4521 outs() << format("0x%" PRIx64"l" "x", cro.baseProperties);
4522 outs() << "\n";
4523 if (cro.baseProperties + n_value != 0)
4524 print_objc_property_list64(cro.baseProperties + n_value, info);
4525
4526 is_meta_class = (cro.flags & RO_META(1 << 0)) != 0;
4527 return true;
4528}
4529
4530static bool print_class_ro32_t(uint32_t p, struct DisassembleInfo *info,
4531 bool &is_meta_class) {
4532 struct class_ro32_t cro;
4533 const char *r;
4534 uint32_t offset, xoffset, left;
4535 SectionRef S, xS;
4536 const char *name;
4537
4538 r = get_pointer_32(p, offset, left, S, info);
4539 if (r == nullptr)
4540 return false;
4541 memset(&cro, '\0', sizeof(struct class_ro32_t));
4542 if (left < sizeof(struct class_ro32_t)) {
4543 memcpy(&cro, r, left);
4544 outs() << " (class_ro_t entends past the end of the section)\n";
4545 } else
4546 memcpy(&cro, r, sizeof(struct class_ro32_t));
4547 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4548 swapStruct(cro);
4549 outs() << " flags " << format("0x%" PRIx32"x", cro.flags);
4550 if (cro.flags & RO_META(1 << 0))
4551 outs() << " RO_META";
4552 if (cro.flags & RO_ROOT(1 << 1))
4553 outs() << " RO_ROOT";
4554 if (cro.flags & RO_HAS_CXX_STRUCTORS(1 << 2))
4555 outs() << " RO_HAS_CXX_STRUCTORS";
4556 outs() << "\n";
4557 outs() << " instanceStart " << cro.instanceStart << "\n";
4558 outs() << " instanceSize " << cro.instanceSize << "\n";
4559 outs() << " ivarLayout " << format("0x%" PRIx32"x", cro.ivarLayout)
4560 << "\n";
4561 print_layout_map32(cro.ivarLayout, info);
4562
4563 outs() << " name " << format("0x%" PRIx32"x", cro.name);
4564 name = get_pointer_32(cro.name, xoffset, left, xS, info);
4565 if (name != nullptr)
4566 outs() << format(" %.*s", left, name);
4567 outs() << "\n";
4568
4569 outs() << " baseMethods "
4570 << format("0x%" PRIx32"x", cro.baseMethods)
4571 << " (struct method_list_t *)\n";
4572 if (cro.baseMethods != 0)
4573 print_method_list32_t(cro.baseMethods, info, "");
4574
4575 outs() << " baseProtocols "
4576 << format("0x%" PRIx32"x", cro.baseProtocols) << "\n";
4577 if (cro.baseProtocols != 0)
4578 print_protocol_list32_t(cro.baseProtocols, info);
4579 outs() << " ivars " << format("0x%" PRIx32"x", cro.ivars)
4580 << "\n";
4581 if (cro.ivars != 0)
4582 print_ivar_list32_t(cro.ivars, info);
4583 outs() << " weakIvarLayout "
4584 << format("0x%" PRIx32"x", cro.weakIvarLayout) << "\n";
4585 print_layout_map32(cro.weakIvarLayout, info);
4586 outs() << " baseProperties "
4587 << format("0x%" PRIx32"x", cro.baseProperties) << "\n";
4588 if (cro.baseProperties != 0)
4589 print_objc_property_list32(cro.baseProperties, info);
4590 is_meta_class = (cro.flags & RO_META(1 << 0)) != 0;
4591 return true;
4592}
4593
4594static void print_class64_t(uint64_t p, struct DisassembleInfo *info) {
4595 struct class64_t c;
4596 const char *r;
4597 uint32_t offset, left;
4598 SectionRef S;
4599 const char *name;
4600 uint64_t isa_n_value, n_value;
4601
4602 r = get_pointer_64(p, offset, left, S, info);
4603 if (r == nullptr || left < sizeof(struct class64_t))
4604 return;
4605 memcpy(&c, r, sizeof(struct class64_t));
4606 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4607 swapStruct(c);
4608
4609 outs() << " isa " << format("0x%" PRIx64"l" "x", c.isa);
4610 name = get_symbol_64(offset + offsetof(struct class64_t, isa)__builtin_offsetof(struct class64_t, isa), S, info,
4611 isa_n_value, c.isa);
4612 if (name != nullptr)
4613 outs() << " " << name;
4614 outs() << "\n";
4615
4616 outs() << " superclass " << format("0x%" PRIx64"l" "x", c.superclass);
4617 name = get_symbol_64(offset + offsetof(struct class64_t, superclass)__builtin_offsetof(struct class64_t, superclass), S, info,
4618 n_value, c.superclass);
4619 if (name != nullptr)
4620 outs() << " " << name;
4621 outs() << "\n";
4622
4623 outs() << " cache " << format("0x%" PRIx64"l" "x", c.cache);
4624 name = get_symbol_64(offset + offsetof(struct class64_t, cache)__builtin_offsetof(struct class64_t, cache), S, info,
4625 n_value, c.cache);
4626 if (name != nullptr)
4627 outs() << " " << name;
4628 outs() << "\n";
4629
4630 outs() << " vtable " << format("0x%" PRIx64"l" "x", c.vtable);
4631 name = get_symbol_64(offset + offsetof(struct class64_t, vtable)__builtin_offsetof(struct class64_t, vtable), S, info,
4632 n_value, c.vtable);
4633 if (name != nullptr)
4634 outs() << " " << name;
4635 outs() << "\n";
4636
4637 name = get_symbol_64(offset + offsetof(struct class64_t, data)__builtin_offsetof(struct class64_t, data), S, info,
4638 n_value, c.data);
4639 outs() << " data ";
4640 if (n_value != 0) {
4641 if (info->verbose && name != nullptr)
4642 outs() << name;
4643 else
4644 outs() << format("0x%" PRIx64"l" "x", n_value);
4645 if (c.data != 0)
4646 outs() << " + " << format("0x%" PRIx64"l" "x", c.data);
4647 } else
4648 outs() << format("0x%" PRIx64"l" "x", c.data);
4649 outs() << " (struct class_ro_t *)";
4650
4651 // This is a Swift class if some of the low bits of the pointer are set.
4652 if ((c.data + n_value) & 0x7)
4653 outs() << " Swift class";
4654 outs() << "\n";
4655 bool is_meta_class;
4656 if (!print_class_ro64_t((c.data + n_value) & ~0x7, info, is_meta_class))
4657 return;
4658
4659 if (!is_meta_class &&
4660 c.isa + isa_n_value != p &&
4661 c.isa + isa_n_value != 0 &&
4662 info->depth < 100) {
4663 info->depth++;
4664 outs() << "Meta Class\n";
4665 print_class64_t(c.isa + isa_n_value, info);
4666 }
4667}
4668
4669static void print_class32_t(uint32_t p, struct DisassembleInfo *info) {
4670 struct class32_t c;
4671 const char *r;
4672 uint32_t offset, left;
4673 SectionRef S;
4674 const char *name;
4675
4676 r = get_pointer_32(p, offset, left, S, info);
4677 if (r == nullptr)
4678 return;
4679 memset(&c, '\0', sizeof(struct class32_t));
4680 if (left < sizeof(struct class32_t)) {
4681 memcpy(&c, r, left);
4682 outs() << " (class_t entends past the end of the section)\n";
4683 } else
4684 memcpy(&c, r, sizeof(struct class32_t));
4685 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4686 swapStruct(c);
4687
4688 outs() << " isa " << format("0x%" PRIx32"x", c.isa);
4689 name =
4690 get_symbol_32(offset + offsetof(struct class32_t, isa)__builtin_offsetof(struct class32_t, isa), S, info, c.isa);
4691 if (name != nullptr)
4692 outs() << " " << name;
4693 outs() << "\n";
4694
4695 outs() << " superclass " << format("0x%" PRIx32"x", c.superclass);
4696 name = get_symbol_32(offset + offsetof(struct class32_t, superclass)__builtin_offsetof(struct class32_t, superclass), S, info,
4697 c.superclass);
4698 if (name != nullptr)
4699 outs() << " " << name;
4700 outs() << "\n";
4701
4702 outs() << " cache " << format("0x%" PRIx32"x", c.cache);
4703 name = get_symbol_32(offset + offsetof(struct class32_t, cache)__builtin_offsetof(struct class32_t, cache), S, info,
4704 c.cache);
4705 if (name != nullptr)
4706 outs() << " " << name;
4707 outs() << "\n";
4708
4709 outs() << " vtable " << format("0x%" PRIx32"x", c.vtable);
4710 name = get_symbol_32(offset + offsetof(struct class32_t, vtable)__builtin_offsetof(struct class32_t, vtable), S, info,
4711 c.vtable);
4712 if (name != nullptr)
4713 outs() << " " << name;
4714 outs() << "\n";
4715
4716 name =
4717 get_symbol_32(offset + offsetof(struct class32_t, data)__builtin_offsetof(struct class32_t, data), S, info, c.data);
4718 outs() << " data " << format("0x%" PRIx32"x", c.data)
4719 << " (struct class_ro_t *)";
4720
4721 // This is a Swift class if some of the low bits of the pointer are set.
4722 if (c.data & 0x3)
4723 outs() << " Swift class";
4724 outs() << "\n";
4725 bool is_meta_class;
4726 if (!print_class_ro32_t(c.data & ~0x3, info, is_meta_class))
4727 return;
4728
4729 if (!is_meta_class) {
4730 outs() << "Meta Class\n";
4731 print_class32_t(c.isa, info);
4732 }
4733}
4734
4735static void print_objc_class_t(struct objc_class_t *objc_class,
4736 struct DisassembleInfo *info) {
4737 uint32_t offset, left, xleft;
4738 const char *name, *p, *ivar_list;
4739 SectionRef S;
4740 int32_t i;
4741 struct objc_ivar_list_t objc_ivar_list;
4742 struct objc_ivar_t ivar;
4743
4744 outs() << "\t\t isa " << format("0x%08" PRIx32"x", objc_class->isa);
4745 if (info->verbose && CLS_GETINFO(objc_class, CLS_META)((objc_class)->info & (0x2))) {
4746 name = get_pointer_32(objc_class->isa, offset, left, S, info, true);
4747 if (name != nullptr)
4748 outs() << format(" %.*s", left, name);
4749 else
4750 outs() << " (not in an __OBJC section)";
4751 }
4752 outs() << "\n";
4753
4754 outs() << "\t super_class "
4755 << format("0x%08" PRIx32"x", objc_class->super_class);
4756 if (info->verbose) {
4757 name = get_pointer_32(objc_class->super_class, offset, left, S, info, true);
4758 if (name != nullptr)
4759 outs() << format(" %.*s", left, name);
4760 else
4761 outs() << " (not in an __OBJC section)";
4762 }
4763 outs() << "\n";
4764
4765 outs() << "\t\t name " << format("0x%08" PRIx32"x", objc_class->name);
4766 if (info->verbose) {
4767 name = get_pointer_32(objc_class->name, offset, left, S, info, true);
4768 if (name != nullptr)
4769 outs() << format(" %.*s", left, name);
4770 else
4771 outs() << " (not in an __OBJC section)";
4772 }
4773 outs() << "\n";
4774
4775 outs() << "\t\t version " << format("0x%08" PRIx32"x", objc_class->version)
4776 << "\n";
4777
4778 outs() << "\t\t info " << format("0x%08" PRIx32"x", objc_class->info);
4779 if (info->verbose) {
4780 if (CLS_GETINFO(objc_class, CLS_CLASS)((objc_class)->info & (0x1)))
4781 outs() << " CLS_CLASS";
4782 else if (CLS_GETINFO(objc_class, CLS_META)((objc_class)->info & (0x2)))
4783 outs() << " CLS_META";
4784 }
4785 outs() << "\n";
4786
4787 outs() << "\t instance_size "
4788 << format("0x%08" PRIx32"x", objc_class->instance_size) << "\n";
4789
4790 p = get_pointer_32(objc_class->ivars, offset, left, S, info, true);
4791 outs() << "\t\t ivars " << format("0x%08" PRIx32"x", objc_class->ivars);
4792 if (p != nullptr) {
4793 if (left > sizeof(struct objc_ivar_list_t)) {
4794 outs() << "\n";
4795 memcpy(&objc_ivar_list, p, sizeof(struct objc_ivar_list_t));
4796 } else {
4797 outs() << " (entends past the end of the section)\n";
4798 memset(&objc_ivar_list, '\0', sizeof(struct objc_ivar_list_t));
4799 memcpy(&objc_ivar_list, p, left);
4800 }
4801 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4802 swapStruct(objc_ivar_list);
4803 outs() << "\t\t ivar_count " << objc_ivar_list.ivar_count << "\n";
4804 ivar_list = p + sizeof(struct objc_ivar_list_t);
4805 for (i = 0; i < objc_ivar_list.ivar_count; i++) {
4806 if ((i + 1) * sizeof(struct objc_ivar_t) > left) {
4807 outs() << "\t\t remaining ivar's extend past the of the section\n";
4808 break;
4809 }
4810 memcpy(&ivar, ivar_list + i * sizeof(struct objc_ivar_t),
4811 sizeof(struct objc_ivar_t));
4812 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4813 swapStruct(ivar);
4814
4815 outs() << "\t\t\tivar_name " << format("0x%08" PRIx32"x", ivar.ivar_name);
4816 if (info->verbose) {
4817 name = get_pointer_32(ivar.ivar_name, offset, xleft, S, info, true);
4818 if (name != nullptr)
4819 outs() << format(" %.*s", xleft, name);
4820 else
4821 outs() << " (not in an __OBJC section)";
4822 }
4823 outs() << "\n";
4824
4825 outs() << "\t\t\tivar_type " << format("0x%08" PRIx32"x", ivar.ivar_type);
4826 if (info->verbose) {
4827 name = get_pointer_32(ivar.ivar_type, offset, xleft, S, info, true);
4828 if (name != nullptr)
4829 outs() << format(" %.*s", xleft, name);
4830 else
4831 outs() << " (not in an __OBJC section)";
4832 }
4833 outs() << "\n";
4834
4835 outs() << "\t\t ivar_offset "
4836 << format("0x%08" PRIx32"x", ivar.ivar_offset) << "\n";
4837 }
4838 } else {
4839 outs() << " (not in an __OBJC section)\n";
4840 }
4841
4842 outs() << "\t\t methods " << format("0x%08" PRIx32"x", objc_class->methodLists);
4843 if (print_method_list(objc_class->methodLists, info))
4844 outs() << " (not in an __OBJC section)\n";
4845
4846 outs() << "\t\t cache " << format("0x%08" PRIx32"x", objc_class->cache)
4847 << "\n";
4848
4849 outs() << "\t\tprotocols " << format("0x%08" PRIx32"x", objc_class->protocols);
4850 if (print_protocol_list(objc_class->protocols, 16, info))
4851 outs() << " (not in an __OBJC section)\n";
4852}
4853
4854static void print_objc_objc_category_t(struct objc_category_t *objc_category,
4855 struct DisassembleInfo *info) {
4856 uint32_t offset, left;
4857 const char *name;
4858 SectionRef S;
4859
4860 outs() << "\t category name "
4861 << format("0x%08" PRIx32"x", objc_category->category_name);
4862 if (info->verbose) {
4863 name = get_pointer_32(objc_category->category_name, offset, left, S, info,
4864 true);
4865 if (name != nullptr)
4866 outs() << format(" %.*s", left, name);
4867 else
4868 outs() << " (not in an __OBJC section)";
4869 }
4870 outs() << "\n";
4871
4872 outs() << "\t\t class name "
4873 << format("0x%08" PRIx32"x", objc_category->class_name);
4874 if (info->verbose) {
4875 name =
4876 get_pointer_32(objc_category->class_name, offset, left, S, info, true);
4877 if (name != nullptr)
4878 outs() << format(" %.*s", left, name);
4879 else
4880 outs() << " (not in an __OBJC section)";
4881 }
4882 outs() << "\n";
4883
4884 outs() << "\t instance methods "
4885 << format("0x%08" PRIx32"x", objc_category->instance_methods);
4886 if (print_method_list(objc_category->instance_methods, info))
4887 outs() << " (not in an __OBJC section)\n";
4888
4889 outs() << "\t class methods "
4890 << format("0x%08" PRIx32"x", objc_category->class_methods);
4891 if (print_method_list(objc_category->class_methods, info))
4892 outs() << " (not in an __OBJC section)\n";
4893}
4894
4895static void print_category64_t(uint64_t p, struct DisassembleInfo *info) {
4896 struct category64_t c;
4897 const char *r;
4898 uint32_t offset, xoffset, left;
4899 SectionRef S, xS;
4900 const char *name, *sym_name;
4901 uint64_t n_value;
4902
4903 r = get_pointer_64(p, offset, left, S, info);
4904 if (r == nullptr)
4905 return;
4906 memset(&c, '\0', sizeof(struct category64_t));
4907 if (left < sizeof(struct category64_t)) {
4908 memcpy(&c, r, left);
4909 outs() << " (category_t entends past the end of the section)\n";
4910 } else
4911 memcpy(&c, r, sizeof(struct category64_t));
4912 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
4913 swapStruct(c);
4914
4915 outs() << " name ";
4916 sym_name = get_symbol_64(offset + offsetof(struct category64_t, name)__builtin_offsetof(struct category64_t, name), S,
4917 info, n_value, c.name);
4918 if (n_value != 0) {
4919 if (info->verbose && sym_name != nullptr)
4920 outs() << sym_name;
4921 else
4922 outs() << format("0x%" PRIx64"l" "x", n_value);
4923 if (c.name != 0)
4924 outs() << " + " << format("0x%" PRIx64"l" "x", c.name);
4925 } else
4926 outs() << format("0x%" PRIx64"l" "x", c.name);
4927 name = get_pointer_64(c.name + n_value, xoffset, left, xS, info);
4928 if (name != nullptr)
4929 outs() << format(" %.*s", left, name);
4930 outs() << "\n";
4931
4932 outs() << " cls ";
4933 sym_name = get_symbol_64(offset + offsetof(struct category64_t, cls)__builtin_offsetof(struct category64_t, cls), S, info,
4934 n_value, c.cls);
4935 if (n_value != 0) {
4936 if (info->verbose && sym_name != nullptr)
4937 outs() << sym_name;
4938 else
4939 outs() << format("0x%" PRIx64"l" "x", n_value);
4940 if (c.cls != 0)
4941 outs() << " + " << format("0x%" PRIx64"l" "x", c.cls);
4942 } else
4943 outs() << format("0x%" PRIx64"l" "x", c.cls);
4944 outs() << "\n";
4945 if (c.cls + n_value != 0)
4946 print_class64_t(c.cls + n_value, info);
4947
4948 outs() << " instanceMethods ";
4949 sym_name =
4950 get_symbol_64(offset + offsetof(struct category64_t, instanceMethods)__builtin_offsetof(struct category64_t, instanceMethods), S,
4951 info, n_value, c.instanceMethods);
4952 if (n_value != 0) {
4953 if (info->verbose && sym_name != nullptr)
4954 outs() << sym_name;
4955 else
4956 outs() << format("0x%" PRIx64"l" "x", n_value);
4957 if (c.instanceMethods != 0)
4958 outs() << " + " << format("0x%" PRIx64"l" "x", c.instanceMethods);
4959 } else
4960 outs() << format("0x%" PRIx64"l" "x", c.instanceMethods);
4961 outs() << "\n";
4962 if (c.instanceMethods + n_value != 0)
4963 print_method_list64_t(c.instanceMethods + n_value, info, "");
4964
4965 outs() << " classMethods ";
4966 sym_name = get_symbol_64(offset + offsetof(struct category64_t, classMethods)__builtin_offsetof(struct category64_t, classMethods),
4967 S, info, n_value, c.classMethods);
4968 if (n_value != 0) {
4969 if (info->verbose && sym_name != nullptr)
4970 outs() << sym_name;
4971 else
4972 outs() << format("0x%" PRIx64"l" "x", n_value);
4973 if (c.classMethods != 0)
4974 outs() << " + " << format("0x%" PRIx64"l" "x", c.classMethods);
4975 } else
4976 outs() << format("0x%" PRIx64"l" "x", c.classMethods);
4977 outs() << "\n";
4978 if (c.classMethods + n_value != 0)
4979 print_method_list64_t(c.classMethods + n_value, info, "");
4980
4981 outs() << " protocols ";
4982 sym_name = get_symbol_64(offset + offsetof(struct category64_t, protocols)__builtin_offsetof(struct category64_t, protocols), S,
4983 info, n_value, c.protocols);
4984 if (n_value != 0) {
4985 if (info->verbose && sym_name != nullptr)
4986 outs() << sym_name;
4987 else
4988 outs() << format("0x%" PRIx64"l" "x", n_value);
4989 if (c.protocols != 0)
4990 outs() << " + " << format("0x%" PRIx64"l" "x", c.protocols);
4991 } else
4992 outs() << format("0x%" PRIx64"l" "x", c.protocols);
4993 outs() << "\n";
4994 if (c.protocols + n_value != 0)
4995 print_protocol_list64_t(c.protocols + n_value, info);
4996
4997 outs() << "instanceProperties ";
4998 sym_name =
4999 get_symbol_64(offset + offsetof(struct category64_t, instanceProperties)__builtin_offsetof(struct category64_t, instanceProperties),
5000 S, info, n_value, c.instanceProperties);
5001 if (n_value != 0) {
5002 if (info->verbose && sym_name != nullptr)
5003 outs() << sym_name;
5004 else
5005 outs() << format("0x%" PRIx64"l" "x", n_value);
5006 if (c.instanceProperties != 0)
5007 outs() << " + " << format("0x%" PRIx64"l" "x", c.instanceProperties);
5008 } else
5009 outs() << format("0x%" PRIx64"l" "x", c.instanceProperties);
5010 outs() << "\n";
5011 if (c.instanceProperties + n_value != 0)
5012 print_objc_property_list64(c.instanceProperties + n_value, info);
5013}
5014
5015static void print_category32_t(uint32_t p, struct DisassembleInfo *info) {
5016 struct category32_t c;
5017 const char *r;
5018 uint32_t offset, left;
5019 SectionRef S, xS;
5020 const char *name;
5021
5022 r = get_pointer_32(p, offset, left, S, info);
5023 if (r == nullptr)
5024 return;
5025 memset(&c, '\0', sizeof(struct category32_t));
5026 if (left < sizeof(struct category32_t)) {
5027 memcpy(&c, r, left);
5028 outs() << " (category_t entends past the end of the section)\n";
5029 } else
5030 memcpy(&c, r, sizeof(struct category32_t));
5031 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5032 swapStruct(c);
5033
5034 outs() << " name " << format("0x%" PRIx32"x", c.name);
5035 name = get_symbol_32(offset + offsetof(struct category32_t, name)__builtin_offsetof(struct category32_t, name), S, info,
5036 c.name);
5037 if (name)
5038 outs() << " " << name;
5039 outs() << "\n";
5040
5041 outs() << " cls " << format("0x%" PRIx32"x", c.cls) << "\n";
5042 if (c.cls != 0)
5043 print_class32_t(c.cls, info);
5044 outs() << " instanceMethods " << format("0x%" PRIx32"x", c.instanceMethods)
5045 << "\n";
5046 if (c.instanceMethods != 0)
5047 print_method_list32_t(c.instanceMethods, info, "");
5048 outs() << " classMethods " << format("0x%" PRIx32"x", c.classMethods)
5049 << "\n";
5050 if (c.classMethods != 0)
5051 print_method_list32_t(c.classMethods, info, "");
5052 outs() << " protocols " << format("0x%" PRIx32"x", c.protocols) << "\n";
5053 if (c.protocols != 0)
5054 print_protocol_list32_t(c.protocols, info);
5055 outs() << "instanceProperties " << format("0x%" PRIx32"x", c.instanceProperties)
5056 << "\n";
5057 if (c.instanceProperties != 0)
5058 print_objc_property_list32(c.instanceProperties, info);
5059}
5060
5061static void print_message_refs64(SectionRef S, struct DisassembleInfo *info) {
5062 uint32_t i, left, offset, xoffset;
5063 uint64_t p, n_value;
5064 struct message_ref64 mr;
5065 const char *name, *sym_name;
5066 const char *r;
5067 SectionRef xS;
5068
5069 if (S == SectionRef())
5070 return;
5071
5072 StringRef SectName;
5073 S.getName(SectName);
5074 DataRefImpl Ref = S.getRawDataRefImpl();
5075 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5076 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5077 offset = 0;
5078 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5079 p = S.getAddress() + i;
5080 r = get_pointer_64(p, offset, left, S, info);
5081 if (r == nullptr)
5082 return;
5083 memset(&mr, '\0', sizeof(struct message_ref64));
5084 if (left < sizeof(struct message_ref64)) {
5085 memcpy(&mr, r, left);
5086 outs() << " (message_ref entends past the end of the section)\n";
5087 } else
5088 memcpy(&mr, r, sizeof(struct message_ref64));
5089 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5090 swapStruct(mr);
5091
5092 outs() << " imp ";
5093 name = get_symbol_64(offset + offsetof(struct message_ref64, imp)__builtin_offsetof(struct message_ref64, imp), S, info,
5094 n_value, mr.imp);
5095 if (n_value != 0) {
5096 outs() << format("0x%" PRIx64"l" "x", n_value) << " ";
5097 if (mr.imp != 0)
5098 outs() << "+ " << format("0x%" PRIx64"l" "x", mr.imp) << " ";
5099 } else
5100 outs() << format("0x%" PRIx64"l" "x", mr.imp) << " ";
5101 if (name != nullptr)
5102 outs() << " " << name;
5103 outs() << "\n";
5104
5105 outs() << " sel ";
5106 sym_name = get_symbol_64(offset + offsetof(struct message_ref64, sel)__builtin_offsetof(struct message_ref64, sel), S,
5107 info, n_value, mr.sel);
5108 if (n_value != 0) {
5109 if (info->verbose && sym_name != nullptr)
5110 outs() << sym_name;
5111 else
5112 outs() << format("0x%" PRIx64"l" "x", n_value);
5113 if (mr.sel != 0)
5114 outs() << " + " << format("0x%" PRIx64"l" "x", mr.sel);
5115 } else
5116 outs() << format("0x%" PRIx64"l" "x", mr.sel);
5117 name = get_pointer_64(mr.sel + n_value, xoffset, left, xS, info);
5118 if (name != nullptr)
5119 outs() << format(" %.*s", left, name);
5120 outs() << "\n";
5121
5122 offset += sizeof(struct message_ref64);
5123 }
5124}
5125
5126static void print_message_refs32(SectionRef S, struct DisassembleInfo *info) {
5127 uint32_t i, left, offset, xoffset, p;
5128 struct message_ref32 mr;
5129 const char *name, *r;
5130 SectionRef xS;
5131
5132 if (S == SectionRef())
5133 return;
5134
5135 StringRef SectName;
5136 S.getName(SectName);
5137 DataRefImpl Ref = S.getRawDataRefImpl();
5138 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5139 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5140 offset = 0;
5141 for (i = 0; i < S.getSize(); i += sizeof(struct message_ref64)) {
5142 p = S.getAddress() + i;
5143 r = get_pointer_32(p, offset, left, S, info);
5144 if (r == nullptr)
5145 return;
5146 memset(&mr, '\0', sizeof(struct message_ref32));
5147 if (left < sizeof(struct message_ref32)) {
5148 memcpy(&mr, r, left);
5149 outs() << " (message_ref entends past the end of the section)\n";
5150 } else
5151 memcpy(&mr, r, sizeof(struct message_ref32));
5152 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5153 swapStruct(mr);
5154
5155 outs() << " imp " << format("0x%" PRIx32"x", mr.imp);
5156 name = get_symbol_32(offset + offsetof(struct message_ref32, imp)__builtin_offsetof(struct message_ref32, imp), S, info,
5157 mr.imp);
5158 if (name != nullptr)
5159 outs() << " " << name;
5160 outs() << "\n";
5161
5162 outs() << " sel " << format("0x%" PRIx32"x", mr.sel);
5163 name = get_pointer_32(mr.sel, xoffset, left, xS, info);
5164 if (name != nullptr)
5165 outs() << " " << name;
5166 outs() << "\n";
5167
5168 offset += sizeof(struct message_ref32);
5169 }
5170}
5171
5172static void print_image_info64(SectionRef S, struct DisassembleInfo *info) {
5173 uint32_t left, offset, swift_version;
5174 uint64_t p;
5175 struct objc_image_info64 o;
5176 const char *r;
5177
5178 if (S == SectionRef())
5179 return;
5180
5181 StringRef SectName;
5182 S.getName(SectName);
5183 DataRefImpl Ref = S.getRawDataRefImpl();
5184 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5185 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5186 p = S.getAddress();
5187 r = get_pointer_64(p, offset, left, S, info);
5188 if (r == nullptr)
5189 return;
5190 memset(&o, '\0', sizeof(struct objc_image_info64));
5191 if (left < sizeof(struct objc_image_info64)) {
5192 memcpy(&o, r, left);
5193 outs() << " (objc_image_info entends past the end of the section)\n";
5194 } else
5195 memcpy(&o, r, sizeof(struct objc_image_info64));
5196 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5197 swapStruct(o);
5198 outs() << " version " << o.version << "\n";
5199 outs() << " flags " << format("0x%" PRIx32"x", o.flags);
5200 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT(1 << 0))
5201 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5202 if (o.flags & OBJC_IMAGE_SUPPORTS_GC(1 << 1))
5203 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5204 swift_version = (o.flags >> 8) & 0xff;
5205 if (swift_version != 0) {
5206 if (swift_version == 1)
5207 outs() << " Swift 1.0";
5208 else if (swift_version == 2)
5209 outs() << " Swift 1.1";
5210 else
5211 outs() << " unknown future Swift version (" << swift_version << ")";
5212 }
5213 outs() << "\n";
5214}
5215
5216static void print_image_info32(SectionRef S, struct DisassembleInfo *info) {
5217 uint32_t left, offset, swift_version, p;
5218 struct objc_image_info32 o;
5219 const char *r;
5220
5221 if (S == SectionRef())
5222 return;
5223
5224 StringRef SectName;
5225 S.getName(SectName);
5226 DataRefImpl Ref = S.getRawDataRefImpl();
5227 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5228 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5229 p = S.getAddress();
5230 r = get_pointer_32(p, offset, left, S, info);
5231 if (r == nullptr)
5232 return;
5233 memset(&o, '\0', sizeof(struct objc_image_info32));
5234 if (left < sizeof(struct objc_image_info32)) {
5235 memcpy(&o, r, left);
5236 outs() << " (objc_image_info entends past the end of the section)\n";
5237 } else
5238 memcpy(&o, r, sizeof(struct objc_image_info32));
5239 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5240 swapStruct(o);
5241 outs() << " version " << o.version << "\n";
5242 outs() << " flags " << format("0x%" PRIx32"x", o.flags);
5243 if (o.flags & OBJC_IMAGE_IS_REPLACEMENT(1 << 0))
5244 outs() << " OBJC_IMAGE_IS_REPLACEMENT";
5245 if (o.flags & OBJC_IMAGE_SUPPORTS_GC(1 << 1))
5246 outs() << " OBJC_IMAGE_SUPPORTS_GC";
5247 swift_version = (o.flags >> 8) & 0xff;
5248 if (swift_version != 0) {
5249 if (swift_version == 1)
5250 outs() << " Swift 1.0";
5251 else if (swift_version == 2)
5252 outs() << " Swift 1.1";
5253 else
5254 outs() << " unknown future Swift version (" << swift_version << ")";
5255 }
5256 outs() << "\n";
5257}
5258
5259static void print_image_info(SectionRef S, struct DisassembleInfo *info) {
5260 uint32_t left, offset, p;
5261 struct imageInfo_t o;
5262 const char *r;
5263
5264 StringRef SectName;
5265 S.getName(SectName);
5266 DataRefImpl Ref = S.getRawDataRefImpl();
5267 StringRef SegName = info->O->getSectionFinalSegmentName(Ref);
5268 outs() << "Contents of (" << SegName << "," << SectName << ") section\n";
5269 p = S.getAddress();
5270 r = get_pointer_32(p, offset, left, S, info);
5271 if (r == nullptr)
5272 return;
5273 memset(&o, '\0', sizeof(struct imageInfo_t));
5274 if (left < sizeof(struct imageInfo_t)) {
5275 memcpy(&o, r, left);
5276 outs() << " (imageInfo entends past the end of the section)\n";
5277 } else
5278 memcpy(&o, r, sizeof(struct imageInfo_t));
5279 if (info->O->isLittleEndian() != sys::IsLittleEndianHost)
5280 swapStruct(o);
5281 outs() << " version " << o.version << "\n";
5282 outs() << " flags " << format("0x%" PRIx32"x", o.flags);
5283 if (o.flags & 0x1)
5284 outs() << " F&C";
5285 if (o.flags & 0x2)
5286 outs() << " GC";
5287 if (o.flags & 0x4)
5288 outs() << " GC-only";
5289 else
5290 outs() << " RR";
5291 outs() << "\n";
5292}
5293
5294static void printObjc2_64bit_MetaData(MachOObjectFile *O, bool verbose) {
5295 SymbolAddressMap AddrMap;
5296 if (verbose)
5297 CreateSymbolAddressMap(O, &AddrMap);
5298
5299 std::vector<SectionRef> Sections;
5300 for (const SectionRef &Section : O->sections()) {
5301 StringRef SectName;
5302 Section.getName(SectName);
5303 Sections.push_back(Section);
5304 }
5305
5306 struct DisassembleInfo info;
5307 // Set up the block of info used by the Symbolizer call backs.
5308 info.verbose = verbose;
5309 info.O = O;
5310 info.AddrMap = &AddrMap;
5311 info.Sections = &Sections;
5312 info.class_name = nullptr;
5313 info.selector_name = nullptr;
5314 info.method = nullptr;
5315 info.demangled_name = nullptr;
5316 info.bindtable = nullptr;
5317 info.adrp_addr = 0;
5318 info.adrp_inst = 0;
5319
5320 info.depth = 0;
5321 SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5322 if (CL == SectionRef())
5323 CL = get_section(O, "__DATA", "__objc_classlist");
5324 info.S = CL;
5325 walk_pointer_list_64("class", CL, O, &info, print_class64_t);
5326
5327 SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5328 if (CR == SectionRef())
5329 CR = get_section(O, "__DATA", "__objc_classrefs");
5330 info.S = CR;
5331 walk_pointer_list_64("class refs", CR, O, &info, nullptr);
5332
5333 SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5334 if (SR == SectionRef())
5335 SR = get_section(O, "__DATA", "__objc_superrefs");
5336 info.S = SR;
5337 walk_pointer_list_64("super refs", SR, O, &info, nullptr);
5338
5339 SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5340 if (CA == SectionRef())
5341 CA = get_section(O, "__DATA", "__objc_catlist");
5342 info.S = CA;
5343 walk_pointer_list_64("category", CA, O, &info, print_category64_t);
5344
5345 SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5346 if (PL == SectionRef())
5347 PL = get_section(O, "__DATA", "__objc_protolist");
5348 info.S = PL;
5349 walk_pointer_list_64("protocol", PL, O, &info, nullptr);
5350
5351 SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5352 if (MR == SectionRef())
5353 MR = get_section(O, "__DATA", "__objc_msgrefs");
5354 info.S = MR;
5355 print_message_refs64(MR, &info);
5356
5357 SectionRef II = get_section(O, "__OBJC2", "__image_info");
5358 if (II == SectionRef())
5359 II = get_section(O, "__DATA", "__objc_imageinfo");
5360 info.S = II;
5361 print_image_info64(II, &info);
5362
5363 if (info.bindtable != nullptr)
5364 delete info.bindtable;
5365}
5366
5367static void printObjc2_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5368 SymbolAddressMap AddrMap;
5369 if (verbose)
5370 CreateSymbolAddressMap(O, &AddrMap);
5371
5372 std::vector<SectionRef> Sections;
5373 for (const SectionRef &Section : O->sections()) {
5374 StringRef SectName;
5375 Section.getName(SectName);
5376 Sections.push_back(Section);
5377 }
5378
5379 struct DisassembleInfo info;
5380 // Set up the block of info used by the Symbolizer call backs.
5381 info.verbose = verbose;
5382 info.O = O;
5383 info.AddrMap = &AddrMap;
5384 info.Sections = &Sections;
5385 info.class_name = nullptr;
5386 info.selector_name = nullptr;
5387 info.method = nullptr;
5388 info.demangled_name = nullptr;
5389 info.bindtable = nullptr;
5390 info.adrp_addr = 0;
5391 info.adrp_inst = 0;
5392
5393 const SectionRef CL = get_section(O, "__OBJC2", "__class_list");
5394 if (CL != SectionRef()) {
5395 info.S = CL;
5396 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5397 } else {
5398 const SectionRef CL = get_section(O, "__DATA", "__objc_classlist");
5399 info.S = CL;
5400 walk_pointer_list_32("class", CL, O, &info, print_class32_t);
5401 }
5402
5403 const SectionRef CR = get_section(O, "__OBJC2", "__class_refs");
5404 if (CR != SectionRef()) {
5405 info.S = CR;
5406 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5407 } else {
5408 const SectionRef CR = get_section(O, "__DATA", "__objc_classrefs");
5409 info.S = CR;
5410 walk_pointer_list_32("class refs", CR, O, &info, nullptr);
5411 }
5412
5413 const SectionRef SR = get_section(O, "__OBJC2", "__super_refs");
5414 if (SR != SectionRef()) {
5415 info.S = SR;
5416 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5417 } else {
5418 const SectionRef SR = get_section(O, "__DATA", "__objc_superrefs");
5419 info.S = SR;
5420 walk_pointer_list_32("super refs", SR, O, &info, nullptr);
5421 }
5422
5423 const SectionRef CA = get_section(O, "__OBJC2", "__category_list");
5424 if (CA != SectionRef()) {
5425 info.S = CA;
5426 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5427 } else {
5428 const SectionRef CA = get_section(O, "__DATA", "__objc_catlist");
5429 info.S = CA;
5430 walk_pointer_list_32("category", CA, O, &info, print_category32_t);
5431 }
5432
5433 const SectionRef PL = get_section(O, "__OBJC2", "__protocol_list");
5434 if (PL != SectionRef()) {
5435 info.S = PL;
5436 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5437 } else {
5438 const SectionRef PL = get_section(O, "__DATA", "__objc_protolist");
5439 info.S = PL;
5440 walk_pointer_list_32("protocol", PL, O, &info, nullptr);
5441 }
5442
5443 const SectionRef MR = get_section(O, "__OBJC2", "__message_refs");
5444 if (MR != SectionRef()) {
5445 info.S = MR;
5446 print_message_refs32(MR, &info);
5447 } else {
5448 const SectionRef MR = get_section(O, "__DATA", "__objc_msgrefs");
5449 info.S = MR;
5450 print_message_refs32(MR, &info);
5451 }
5452
5453 const SectionRef II = get_section(O, "__OBJC2", "__image_info");
5454 if (II != SectionRef()) {
5455 info.S = II;
5456 print_image_info32(II, &info);
5457 } else {
5458 const SectionRef II = get_section(O, "__DATA", "__objc_imageinfo");
5459 info.S = II;
5460 print_image_info32(II, &info);
5461 }
5462}
5463
5464static bool printObjc1_32bit_MetaData(MachOObjectFile *O, bool verbose) {
5465 uint32_t i, j, p, offset, xoffset, left, defs_left, def;
5466 const char *r, *name, *defs;
5467 struct objc_module_t module;
5468 SectionRef S, xS;
5469 struct objc_symtab_t symtab;
5470 struct objc_class_t objc_class;
5471 struct objc_category_t objc_category;
5472
5473 outs() << "Objective-C segment\n";
5474 S = get_section(O, "__OBJC", "__module_info");
5475 if (S == SectionRef())
5476 return false;
5477
5478 SymbolAddressMap AddrMap;
5479 if (verbose)
5480 CreateSymbolAddressMap(O, &AddrMap);
5481
5482 std::vector<SectionRef> Sections;
5483 for (const SectionRef &Section : O->sections()) {
5484 StringRef SectName;
5485 Section.getName(SectName);
5486 Sections.push_back(Section);
5487 }
5488
5489 struct DisassembleInfo info;
5490 // Set up the block of info used by the Symbolizer call backs.
5491 info.verbose = verbose;
5492 info.O = O;
5493 info.AddrMap = &AddrMap;
5494 info.Sections = &Sections;
5495 info.class_name = nullptr;
5496 info.selector_name = nullptr;
5497 info.method = nullptr;
5498 info.demangled_name = nullptr;
5499 info.bindtable = nullptr;
5500 info.adrp_addr = 0;
5501 info.adrp_inst = 0;
5502
5503 for (i = 0; i < S.getSize(); i += sizeof(struct objc_module_t)) {
5504 p = S.getAddress() + i;
5505 r = get_pointer_32(p, offset, left, S, &info, true);
5506 if (r == nullptr)
5507 return true;
5508 memset(&module, '\0', sizeof(struct objc_module_t));
5509 if (left < sizeof(struct objc_module_t)) {
5510 memcpy(&module, r, left);
5511 outs() << " (module extends past end of __module_info section)\n";
5512 } else
5513 memcpy(&module, r, sizeof(struct objc_module_t));
5514 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5515 swapStruct(module);
5516
5517 outs() << "Module " << format("0x%" PRIx32"x", p) << "\n";
5518 outs() << " version " << module.version << "\n";
5519 outs() << " size " << module.size << "\n";
5520 outs() << " name ";
5521 name = get_pointer_32(module.name, xoffset, left, xS, &info, true);
5522 if (name != nullptr)
5523 outs() << format("%.*s", left, name);
5524 else
5525 outs() << format("0x%08" PRIx32"x", module.name)
5526 << "(not in an __OBJC section)";
5527 outs() << "\n";
5528
5529 r = get_pointer_32(module.symtab, xoffset, left, xS, &info, true);
5530 if (module.symtab == 0 || r == nullptr) {
5531 outs() << " symtab " << format("0x%08" PRIx32"x", module.symtab)
5532 << " (not in an __OBJC section)\n";
5533 continue;
5534 }
5535 outs() << " symtab " << format("0x%08" PRIx32"x", module.symtab) << "\n";
5536 memset(&symtab, '\0', sizeof(struct objc_symtab_t));
5537 defs_left = 0;
5538 defs = nullptr;
5539 if (left < sizeof(struct objc_symtab_t)) {
5540 memcpy(&symtab, r, left);
5541 outs() << "\tsymtab extends past end of an __OBJC section)\n";
5542 } else {
5543 memcpy(&symtab, r, sizeof(struct objc_symtab_t));
5544 if (left > sizeof(struct objc_symtab_t)) {
5545 defs_left = left - sizeof(struct objc_symtab_t);
5546 defs = r + sizeof(struct objc_symtab_t);
5547 }
5548 }
5549 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5550 swapStruct(symtab);
5551
5552 outs() << "\tsel_ref_cnt " << symtab.sel_ref_cnt << "\n";
5553 r = get_pointer_32(symtab.refs, xoffset, left, xS, &info, true);
5554 outs() << "\trefs " << format("0x%08" PRIx32"x", symtab.refs);
5555 if (r == nullptr)
5556 outs() << " (not in an __OBJC section)";
5557 outs() << "\n";
5558 outs() << "\tcls_def_cnt " << symtab.cls_def_cnt << "\n";
5559 outs() << "\tcat_def_cnt " << symtab.cat_def_cnt << "\n";
5560 if (symtab.cls_def_cnt > 0)
5561 outs() << "\tClass Definitions\n";
5562 for (j = 0; j < symtab.cls_def_cnt; j++) {
5563 if ((j + 1) * sizeof(uint32_t) > defs_left) {
5564 outs() << "\t(remaining class defs entries entends past the end of the "
5565 << "section)\n";
5566 break;
5567 }
5568 memcpy(&def, defs + j * sizeof(uint32_t), sizeof(uint32_t));
5569 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5570 sys::swapByteOrder(def);
5571
5572 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5573 outs() << "\tdefs[" << j << "] " << format("0x%08" PRIx32"x", def);
5574 if (r != nullptr) {
5575 if (left > sizeof(struct objc_class_t)) {
5576 outs() << "\n";
5577 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5578 } else {
5579 outs() << " (entends past the end of the section)\n";
5580 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5581 memcpy(&objc_class, r, left);
5582 }
5583 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5584 swapStruct(objc_class);
5585 print_objc_class_t(&objc_class, &info);
5586 } else {
5587 outs() << "(not in an __OBJC section)\n";
5588 }
5589
5590 if (CLS_GETINFO(&objc_class, CLS_CLASS)((&objc_class)->info & (0x1))) {
5591 outs() << "\tMeta Class";
5592 r = get_pointer_32(objc_class.isa, xoffset, left, xS, &info, true);
5593 if (r != nullptr) {
5594 if (left > sizeof(struct objc_class_t)) {
5595 outs() << "\n";
5596 memcpy(&objc_class, r, sizeof(struct objc_class_t));
5597 } else {
5598 outs() << " (entends past the end of the section)\n";
5599 memset(&objc_class, '\0', sizeof(struct objc_class_t));
5600 memcpy(&objc_class, r, left);
5601 }
5602 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5603 swapStruct(objc_class);
5604 print_objc_class_t(&objc_class, &info);
5605 } else {
5606 outs() << "(not in an __OBJC section)\n";
5607 }
5608 }
5609 }
5610 if (symtab.cat_def_cnt > 0)
5611 outs() << "\tCategory Definitions\n";
5612 for (j = 0; j < symtab.cat_def_cnt; j++) {
5613 if ((j + symtab.cls_def_cnt + 1) * sizeof(uint32_t) > defs_left) {
5614 outs() << "\t(remaining category defs entries entends past the end of "
5615 << "the section)\n";
5616 break;
5617 }
5618 memcpy(&def, defs + (j + symtab.cls_def_cnt) * sizeof(uint32_t),
5619 sizeof(uint32_t));
5620 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5621 sys::swapByteOrder(def);
5622
5623 r = get_pointer_32(def, xoffset, left, xS, &info, true);
5624 outs() << "\tdefs[" << j + symtab.cls_def_cnt << "] "
5625 << format("0x%08" PRIx32"x", def);
5626 if (r != nullptr) {
5627 if (left > sizeof(struct objc_category_t)) {
5628 outs() << "\n";
5629 memcpy(&objc_category, r, sizeof(struct objc_category_t));
5630 } else {
5631 outs() << " (entends past the end of the section)\n";
5632 memset(&objc_category, '\0', sizeof(struct objc_category_t));
5633 memcpy(&objc_category, r, left);
5634 }
5635 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5636 swapStruct(objc_category);
5637 print_objc_objc_category_t(&objc_category, &info);
5638 } else {
5639 outs() << "(not in an __OBJC section)\n";
5640 }
5641 }
5642 }
5643 const SectionRef II = get_section(O, "__OBJC", "__image_info");
5644 if (II != SectionRef())
5645 print_image_info(II, &info);
5646
5647 return true;
5648}
5649
5650static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
5651 uint32_t size, uint32_t addr) {
5652 SymbolAddressMap AddrMap;
5653 CreateSymbolAddressMap(O, &AddrMap);
5654
5655 std::vector<SectionRef> Sections;
5656 for (const SectionRef &Section : O->sections()) {
5657 StringRef SectName;
5658 Section.getName(SectName);
5659 Sections.push_back(Section);
5660 }
5661
5662 struct DisassembleInfo info;
5663 // Set up the block of info used by the Symbolizer call backs.
5664 info.verbose = true;
5665 info.O = O;
5666 info.AddrMap = &AddrMap;
5667 info.Sections = &Sections;
5668 info.class_name = nullptr;
5669 info.selector_name = nullptr;
5670 info.method = nullptr;
5671 info.demangled_name = nullptr;
5672 info.bindtable = nullptr;
5673 info.adrp_addr = 0;
5674 info.adrp_inst = 0;
5675
5676 const char *p;
5677 struct objc_protocol_t protocol;
5678 uint32_t left, paddr;
5679 for (p = sect; p < sect + size; p += sizeof(struct objc_protocol_t)) {
5680 memset(&protocol, '\0', sizeof(struct objc_protocol_t));
5681 left = size - (p - sect);
5682 if (left < sizeof(struct objc_protocol_t)) {
5683 outs() << "Protocol extends past end of __protocol section\n";
5684 memcpy(&protocol, p, left);
5685 } else
5686 memcpy(&protocol, p, sizeof(struct objc_protocol_t));
5687 if (O->isLittleEndian() != sys::IsLittleEndianHost)
5688 swapStruct(protocol);
5689 paddr = addr + (p - sect);
5690 outs() << "Protocol " << format("0x%" PRIx32"x", paddr);
5691 if (print_protocol(paddr, 0, &info))
5692 outs() << "(not in an __OBJC section)\n";
5693 }
5694}
5695
5696#ifdef HAVE_LIBXAR
5697inline void swapStruct(struct xar_header &xar) {
5698 sys::swapByteOrder(xar.magic);
5699 sys::swapByteOrder(xar.size);
5700 sys::swapByteOrder(xar.version);
5701 sys::swapByteOrder(xar.toc_length_compressed);
5702 sys::swapByteOrder(xar.toc_length_uncompressed);
5703 sys::swapByteOrder(xar.cksum_alg);
5704}
5705
5706static void PrintModeVerbose(uint32_t mode) {
5707 switch(mode & S_IFMT){
5708 case S_IFDIR:
5709 outs() << "d";
5710 break;
5711 case S_IFCHR:
5712 outs() << "c";
5713 break;
5714 case S_IFBLK:
5715 outs() << "b";
5716 break;
5717 case S_IFREG:
5718 outs() << "-";
5719 break;
5720 case S_IFLNK:
5721 outs() << "l";
5722 break;
5723 case S_IFSOCK:
5724 outs() << "s";
5725 break;
5726 default:
5727 outs() << "?";
5728 break;
5729 }
5730
5731 /* owner permissions */
5732 if(mode & S_IREAD)
5733 outs() << "r";
5734 else
5735 outs() << "-";
5736 if(mode & S_IWRITE)
5737 outs() << "w";
5738 else
5739 outs() << "-";
5740 if(mode & S_ISUID)
5741 outs() << "s";
5742 else if(mode & S_IEXEC)
5743 outs() << "x";
5744 else
5745 outs() << "-";
5746
5747 /* group permissions */
5748 if(mode & (S_IREAD >> 3))
5749 outs() << "r";
5750 else
5751 outs() << "-";
5752 if(mode & (S_IWRITE >> 3))
5753 outs() << "w";
5754 else
5755 outs() << "-";
5756 if(mode & S_ISGID)
5757 outs() << "s";
5758 else if(mode & (S_IEXEC >> 3))
5759 outs() << "x";
5760 else
5761 outs() << "-";
5762
5763 /* other permissions */
5764 if(mode & (S_IREAD >> 6))
5765 outs() << "r";
5766 else
5767 outs() << "-";
5768 if(mode & (S_IWRITE >> 6))
5769 outs() << "w";
5770 else
5771 outs() << "-";
5772 if(mode & S_ISVTX)
5773 outs() << "t";
5774 else if(mode & (S_IEXEC >> 6))
5775 outs() << "x";
5776 else
5777 outs() << "-";
5778}
5779
5780static void PrintXarFilesSummary(const char *XarFilename, xar_t xar) {
5781 xar_iter_t xi;
5782 xar_file_t xf;
5783 xar_iter_t xp;
5784 const char *key, *type, *mode, *user, *group, *size, *mtime, *name, *m;
5785 char *endp;
5786 uint32_t mode_value;
5787
5788 xi = xar_iter_new();
5789 if (!xi) {
5790 errs() << "Can't obtain an xar iterator for xar archive "
5791 << XarFilename << "\n";
5792 return;
5793 }
5794
5795 // Go through the xar's files.
5796 for (xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)) {
5797 xp = xar_iter_new();
5798 if(!xp){
5799 errs() << "Can't obtain an xar iterator for xar archive "
5800 << XarFilename << "\n";
5801 return;
5802 }
5803 type = nullptr;
5804 mode = nullptr;
5805 user = nullptr;
5806 group = nullptr;
5807 size = nullptr;
5808 mtime = nullptr;
5809 name = nullptr;
5810 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5811 const char *val = nullptr;
5812 xar_prop_get(xf, key, &val);
5813#if 0 // Useful for debugging.
5814 outs() << "key: " << key << " value: " << val << "\n";
5815#endif
5816 if(strcmp(key, "type") == 0)
5817 type = val;
5818 if(strcmp(key, "mode") == 0)
5819 mode = val;
5820 if(strcmp(key, "user") == 0)
5821 user = val;
5822 if(strcmp(key, "group") == 0)
5823 group = val;
5824 if(strcmp(key, "data/size") == 0)
5825 size = val;
5826 if(strcmp(key, "mtime") == 0)
5827 mtime = val;
5828 if(strcmp(key, "name") == 0)
5829 name = val;
5830 }
5831 if(mode != nullptr){
5832 mode_value = strtoul(mode, &endp, 8);
5833 if(*endp != '\0')
5834 outs() << "(mode: \"" << mode << "\" contains non-octal chars) ";
5835 if(strcmp(type, "file") == 0)
5836 mode_value |= S_IFREG;
5837 PrintModeVerbose(mode_value);
5838 outs() << " ";
5839 }
5840 if(user != nullptr)
5841 outs() << format("%10s/", user);
5842 if(group != nullptr)
5843 outs() << format("%-10s ", group);
5844 if(size != nullptr)
5845 outs() << format("%7s ", size);
5846 if(mtime != nullptr){
5847 for(m = mtime; *m != 'T' && *m != '\0'; m++)
5848 outs() << *m;
5849 if(*m == 'T')
5850 m++;
5851 outs() << " ";
5852 for( ; *m != 'Z' && *m != '\0'; m++)
5853 outs() << *m;
5854 outs() << " ";
5855 }
5856 if(name != nullptr)
5857 outs() << name;
5858 outs() << "\n";
5859 }
5860}
5861
5862static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
5863 uint32_t size, bool verbose,
5864 bool PrintXarHeader, bool PrintXarFileHeaders,
5865 std::string XarMemberName) {
5866 if(size < sizeof(struct xar_header)) {
5867 outs() << "size of (__LLVM,__bundle) section too small (smaller than size "
5868 "of struct xar_header)\n";
5869 return;
5870 }
5871 struct xar_header XarHeader;
5872 memcpy(&XarHeader, sect, sizeof(struct xar_header));
5873 if (sys::IsLittleEndianHost)
5874 swapStruct(XarHeader);
5875 if (PrintXarHeader) {
5876 if (!XarMemberName.empty())
5877 outs() << "In xar member " << XarMemberName << ": ";
5878 else
5879 outs() << "For (__LLVM,__bundle) section: ";
5880 outs() << "xar header\n";
5881 if (XarHeader.magic == XAR_HEADER_MAGIC)
5882 outs() << " magic XAR_HEADER_MAGIC\n";
5883 else
5884 outs() << " magic "
5885 << format_hex(XarHeader.magic, 10, true)
5886 << " (not XAR_HEADER_MAGIC)\n";
5887 outs() << " size " << XarHeader.size << "\n";
5888 outs() << " version " << XarHeader.version << "\n";
5889 outs() << " toc_length_compressed " << XarHeader.toc_length_compressed
5890 << "\n";
5891 outs() << "toc_length_uncompressed " << XarHeader.toc_length_uncompressed
5892 << "\n";
5893 outs() << " cksum_alg ";
5894 switch (XarHeader.cksum_alg) {
5895 case XAR_CKSUM_NONE:
5896 outs() << "XAR_CKSUM_NONE\n";
5897 break;
5898 case XAR_CKSUM_SHA1:
5899 outs() << "XAR_CKSUM_SHA1\n";
5900 break;
5901 case XAR_CKSUM_MD5:
5902 outs() << "XAR_CKSUM_MD5\n";
5903 break;
5904#ifdef XAR_CKSUM_SHA256
5905 case XAR_CKSUM_SHA256:
5906 outs() << "XAR_CKSUM_SHA256\n";
5907 break;
5908#endif
5909#ifdef XAR_CKSUM_SHA512
5910 case XAR_CKSUM_SHA512:
5911 outs() << "XAR_CKSUM_SHA512\n";
5912 break;
5913#endif
5914 default:
5915 outs() << XarHeader.cksum_alg << "\n";
5916 }
5917 }
5918
5919 SmallString<128> XarFilename;
5920 int FD;
5921 std::error_code XarEC =
5922 sys::fs::createTemporaryFile("llvm-objdump", "xar", FD, XarFilename);
5923 if (XarEC) {
5924 errs() << XarEC.message() << "\n";
5925 return;
5926 }
5927 tool_output_file XarFile(XarFilename, FD);
5928 raw_fd_ostream &XarOut = XarFile.os();
5929 StringRef XarContents(sect, size);
5930 XarOut << XarContents;
5931 XarOut.close();
5932 if (XarOut.has_error())
5933 return;
5934
5935 xar_t xar = xar_open(XarFilename.c_str(), READ);
5936 if (!xar) {
5937 errs() << "Can't create temporary xar archive " << XarFilename << "\n";
5938 return;
5939 }
5940
5941 SmallString<128> TocFilename;
5942 std::error_code TocEC =
5943 sys::fs::createTemporaryFile("llvm-objdump", "toc", TocFilename);
5944 if (TocEC) {
5945 errs() << TocEC.message() << "\n";
5946 return;
5947 }
5948 xar_serialize(xar, TocFilename.c_str());
5949
5950 if (PrintXarFileHeaders) {
5951 if (!XarMemberName.empty())
5952 outs() << "In xar member " << XarMemberName << ": ";
5953 else
5954 outs() << "For (__LLVM,__bundle) section: ";
5955 outs() << "xar archive files:\n";
5956 PrintXarFilesSummary(XarFilename.c_str(), xar);
5957 }
5958
5959 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
5960 MemoryBuffer::getFileOrSTDIN(TocFilename.c_str());
5961 if (std::error_code EC = FileOrErr.getError()) {
5962 errs() << EC.message() << "\n";
5963 return;
5964 }
5965 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
5966
5967 if (!XarMemberName.empty())
5968 outs() << "In xar member " << XarMemberName << ": ";
5969 else
5970 outs() << "For (__LLVM,__bundle) section: ";
5971 outs() << "xar table of contents:\n";
5972 outs() << Buffer->getBuffer() << "\n";
5973
5974 // TODO: Go through the xar's files.
5975 xar_iter_t xi = xar_iter_new();
5976 if(!xi){
5977 errs() << "Can't obtain an xar iterator for xar archive "
5978 << XarFilename.c_str() << "\n";
5979 xar_close(xar);
5980 return;
5981 }
5982 for(xar_file_t xf = xar_file_first(xar, xi); xf; xf = xar_file_next(xi)){
5983 const char *key;
5984 xar_iter_t xp;
5985 const char *member_name, *member_type, *member_size_string;
5986 size_t member_size;
5987
5988 xp = xar_iter_new();
5989 if(!xp){
5990 errs() << "Can't obtain an xar iterator for xar archive "
5991 << XarFilename.c_str() << "\n";
5992 xar_close(xar);
5993 return;
5994 }
5995 member_name = NULL__null;
5996 member_type = NULL__null;
5997 member_size_string = NULL__null;
5998 for(key = xar_prop_first(xf, xp); key; key = xar_prop_next(xp)){
5999 const char *val = nullptr;
6000 xar_prop_get(xf, key, &val);
6001#if 0 // Useful for debugging.
6002 outs() << "key: " << key << " value: " << val << "\n";
6003#endif
6004 if(strcmp(key, "name") == 0)
6005 member_name = val;
6006 if(strcmp(key, "type") == 0)
6007 member_type = val;
6008 if(strcmp(key, "data/size") == 0)
6009 member_size_string = val;
6010 }
6011 /*
6012 * If we find a file with a name, date/size and type properties
6013 * and with the type being "file" see if that is a xar file.
6014 */
6015 if (member_name != NULL__null && member_type != NULL__null &&
6016 strcmp(member_type, "file") == 0 &&
6017 member_size_string != NULL__null){
6018 // Extract the file into a buffer.
6019 char *endptr;
6020 member_size = strtoul(member_size_string, &endptr, 10);
6021 if (*endptr == '\0' && member_size != 0) {
6022 char *buffer = (char *) ::operator new (member_size);
6023 if (xar_extract_tobuffersz(xar, xf, &buffer, &member_size) == 0) {
6024#if 0 // Useful for debugging.
6025 outs() << "xar member: " << member_name << " extracted\n";
6026#endif
6027 // Set the XarMemberName we want to see printed in the header.
6028 std::string OldXarMemberName;
6029 // If XarMemberName is already set this is nested. So
6030 // save the old name and create the nested name.
6031 if (!XarMemberName.empty()) {
6032 OldXarMemberName = XarMemberName;
6033 XarMemberName =
6034 (Twine("[") + XarMemberName + "]" + member_name).str();
6035 } else {
6036 OldXarMemberName = "";
6037 XarMemberName = member_name;
6038 }
6039 // See if this is could be a xar file (nested).
6040 if (member_size >= sizeof(struct xar_header)) {
6041#if 0 // Useful for debugging.
6042 outs() << "could be a xar file: " << member_name << "\n";
6043#endif
6044 memcpy((char *)&XarHeader, buffer, sizeof(struct xar_header));
6045 if (sys::IsLittleEndianHost)
6046 swapStruct(XarHeader);
6047 if(XarHeader.magic == XAR_HEADER_MAGIC)
6048 DumpBitcodeSection(O, buffer, member_size, verbose,
6049 PrintXarHeader, PrintXarFileHeaders,
6050 XarMemberName);
6051 }
6052 XarMemberName = OldXarMemberName;
6053 }
6054 delete buffer;
6055 }
6056 }
6057 xar_iter_free(xp);
6058 }
6059 xar_close(xar);
6060}
6061#endif // defined(HAVE_LIBXAR)
6062
6063static void printObjcMetaData(MachOObjectFile *O, bool verbose) {
6064 if (O->is64Bit())
6065 printObjc2_64bit_MetaData(O, verbose);
6066 else {
6067 MachO::mach_header H;
6068 H = O->getHeader();
6069 if (H.cputype == MachO::CPU_TYPE_ARM)
6070 printObjc2_32bit_MetaData(O, verbose);
6071 else {
6072 // This is the 32-bit non-arm cputype case. Which is normally
6073 // the first Objective-C ABI. But it may be the case of a
6074 // binary for the iOS simulator which is the second Objective-C
6075 // ABI. In that case printObjc1_32bit_MetaData() will determine that
6076 // and return false.
6077 if (!printObjc1_32bit_MetaData(O, verbose))
6078 printObjc2_32bit_MetaData(O, verbose);
6079 }
6080 }
6081}
6082
6083// GuessLiteralPointer returns a string which for the item in the Mach-O file
6084// for the address passed in as ReferenceValue for printing as a comment with
6085// the instruction and also returns the corresponding type of that item
6086// indirectly through ReferenceType.
6087//
6088// If ReferenceValue is an address of literal cstring then a pointer to the
6089// cstring is returned and ReferenceType is set to
6090// LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr .
6091//
6092// If ReferenceValue is an address of an Objective-C CFString, Selector ref or
6093// Class ref that name is returned and the ReferenceType is set accordingly.
6094//
6095// Lastly, literals which are Symbol address in a literal pool are looked for
6096// and if found the symbol name is returned and ReferenceType is set to
6097// LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr .
6098//
6099// If there is no item in the Mach-O file for the address passed in as
6100// ReferenceValue nullptr is returned and ReferenceType is unchanged.
6101static const char *GuessLiteralPointer(uint64_t ReferenceValue,
6102 uint64_t ReferencePC,
6103 uint64_t *ReferenceType,
6104 struct DisassembleInfo *info) {
6105 // First see if there is an external relocation entry at the ReferencePC.
6106 if (info->O->getHeader().filetype == MachO::MH_OBJECT) {
6107 uint64_t sect_addr = info->S.getAddress();
6108 uint64_t sect_offset = ReferencePC - sect_addr;
6109 bool reloc_found = false;
6110 DataRefImpl Rel;
6111 MachO::any_relocation_info RE;
6112 bool isExtern = false;
6113 SymbolRef Symbol;
6114 for (const RelocationRef &Reloc : info->S.relocations()) {
6115 uint64_t RelocOffset = Reloc.getOffset();
6116 if (RelocOffset == sect_offset) {
6117 Rel = Reloc.getRawDataRefImpl();
6118 RE = info->O->getRelocation(Rel);
6119 if (info->O->isRelocationScattered(RE))
6120 continue;
6121 isExtern = info->O->getPlainRelocationExternal(RE);
6122 if (isExtern) {
6123 symbol_iterator RelocSym = Reloc.getSymbol();
6124 Symbol = *RelocSym;
6125 }
6126 reloc_found = true;
6127 break;
6128 }
6129 }
6130 // If there is an external relocation entry for a symbol in a section
6131 // then used that symbol's value for the value of the reference.
6132 if (reloc_found && isExtern) {
6133 if (info->O->getAnyRelocationPCRel(RE)) {
6134 unsigned Type = info->O->getAnyRelocationType(RE);
6135 if (Type == MachO::X86_64_RELOC_SIGNED) {
6136 ReferenceValue = Symbol.getValue();
6137 }
6138 }
6139 }
6140 }
6141
6142 // Look for literals such as Objective-C CFStrings refs, Selector refs,
6143 // Message refs and Class refs.
6144 bool classref, selref, msgref, cfstring;
6145 uint64_t pointer_value = GuessPointerPointer(ReferenceValue, info, classref,
6146 selref, msgref, cfstring);
6147 if (classref && pointer_value == 0) {
6148 // Note the ReferenceValue is a pointer into the __objc_classrefs section.
6149 // And the pointer_value in that section is typically zero as it will be
6150 // set by dyld as part of the "bind information".
6151 const char *name = get_dyld_bind_info_symbolname(ReferenceValue, info);
6152 if (name != nullptr) {
6153 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref8;
6154 const char *class_name = strrchr(name, '$');
6155 if (class_name != nullptr && class_name[1] == '_' &&
6156 class_name[2] != '\0') {
6157 info->class_name = class_name + 2;
6158 return name;
6159 }
6160 }
6161 }
6162
6163 if (classref) {
6164 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Class_Ref8;
6165 const char *name =
6166 get_objc2_64bit_class_name(pointer_value, ReferenceValue, info);
6167 if (name != nullptr)
6168 info->class_name = name;
6169 else
6170 name = "bad class ref";
6171 return name;
6172 }
6173
6174 if (cfstring) {
6175 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_CFString_Ref4;
6176 const char *name = get_objc2_64bit_cfstring_name(ReferenceValue, info);
6177 return name;
6178 }
6179
6180 if (selref && pointer_value == 0)
6181 pointer_value = get_objc2_64bit_selref(ReferenceValue, info);
6182
6183 if (pointer_value != 0)
6184 ReferenceValue = pointer_value;
6185
6186 const char *name = GuessCstringPointer(ReferenceValue, info);
6187 if (name) {
6188 if (pointer_value != 0 && selref) {
6189 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Selector_Ref7;
6190 info->selector_name = name;
6191 } else if (pointer_value != 0 && msgref) {
6192 info->class_name = nullptr;
6193 *ReferenceType = LLVMDisassembler_ReferenceType_Out_Objc_Message_Ref6;
6194 info->selector_name = name;
6195 } else
6196 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_CstrAddr3;
6197 return name;
6198 }
6199
6200 // Lastly look for an indirect symbol with this ReferenceValue which is in
6201 // a literal pool. If found return that symbol name.
6202 name = GuessIndirectSymbol(ReferenceValue, info);
6203 if (name) {
6204 *ReferenceType = LLVMDisassembler_ReferenceType_Out_LitPool_SymAddr2;
6205 return name;
6206 }
6207
6208 return nullptr;
6209}
6210
6211// SymbolizerSymbolLookUp is the symbol lookup function passed when creating
6212// the Symbolizer. It looks up the ReferenceValue using the info passed via the
6213// pointer to the struct DisassembleInfo that was passed when MCSymbolizer
6214// is created and returns the symbol name that matches the ReferenceValue or
6215// nullptr if none. The ReferenceType is passed in for the IN type of
6216// reference the instruction is making from the values in defined in the header
6217// "llvm-c/Disassembler.h". On return the ReferenceType can set to a specific
6218// Out type and the ReferenceName will also be set which is added as a comment
6219// to the disassembled instruction.
6220//
6221// If the symbol name is a C++ mangled name then the demangled name is
6222// returned through ReferenceName and ReferenceType is set to
6223// LLVMDisassembler_ReferenceType_DeMangled_Name .
6224//
6225// When this is called to get a symbol name for a branch target then the
6226// ReferenceType will be LLVMDisassembler_ReferenceType_In_Branch and then
6227// SymbolValue will be looked for in the indirect symbol table to determine if
6228// it is an address for a symbol stub. If so then the symbol name for that
6229// stub is returned indirectly through ReferenceName and then ReferenceType is
6230// set to LLVMDisassembler_ReferenceType_Out_SymbolStub.
6231//
6232// When this is called with an value loaded via a PC relative load then
6233// ReferenceType will be LLVMDisassembler_ReferenceType_In_PCrel_Load then the
6234// SymbolValue is checked to be an address of literal pointer, symbol pointer,
6235// or an Objective-C meta data reference. If so the output ReferenceType is
6236// set to correspond to that as well as setting the ReferenceName.
6237static const char *SymbolizerSymbolLookUp(void *DisInfo,
6238 uint64_t ReferenceValue,
6239 uint64_t *ReferenceType,
6240 uint64_t ReferencePC,
6241 const char **ReferenceName) {
6242 struct DisassembleInfo *info = (struct DisassembleInfo *)DisInfo;
6243 // If no verbose symbolic information is wanted then just return nullptr.
6244 if (!info->verbose) {
6245 *ReferenceName = nullptr;
6246 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6247 return nullptr;
6248 }
6249
6250 const char *SymbolName = GuessSymbolName(ReferenceValue, info->AddrMap);
6251
6252 if (*ReferenceType == LLVMDisassembler_ReferenceType_In_Branch1) {
6253 *ReferenceName = GuessIndirectSymbol(ReferenceValue, info);
6254 if (*ReferenceName != nullptr) {
6255 method_reference(info, ReferenceType, ReferenceName);
6256 if (*ReferenceType != LLVMDisassembler_ReferenceType_Out_Objc_Message5)
6257 *ReferenceType = LLVMDisassembler_ReferenceType_Out_SymbolStub1;
6258 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6259 if (info->demangled_name != nullptr)
6260 free(info->demangled_name);
6261 int status;
6262 info->demangled_name =
6263 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
6264 if (info->demangled_name != nullptr) {
6265 *ReferenceName = info->demangled_name;
6266 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name9;
6267 } else
6268 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6269 } else
6270 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6271 } else if (*ReferenceType == LLVMDisassembler_ReferenceType_In_PCrel_Load2) {
6272 *ReferenceName =
6273 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6274 if (*ReferenceName)
6275 method_reference(info, ReferenceType, ReferenceName);
6276 else
6277 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6278 // If this is arm64 and the reference is an adrp instruction save the
6279 // instruction, passed in ReferenceValue and the address of the instruction
6280 // for use later if we see and add immediate instruction.
6281 } else if (info->O->getArch() == Triple::aarch64 &&
6282 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADRP0x100000001) {
6283 info->adrp_inst = ReferenceValue;
6284 info->adrp_addr = ReferencePC;
6285 SymbolName = nullptr;
6286 *ReferenceName = nullptr;
6287 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6288 // If this is arm64 and reference is an add immediate instruction and we
6289 // have
6290 // seen an adrp instruction just before it and the adrp's Xd register
6291 // matches
6292 // this add's Xn register reconstruct the value being referenced and look to
6293 // see if it is a literal pointer. Note the add immediate instruction is
6294 // passed in ReferenceValue.
6295 } else if (info->O->getArch() == Triple::aarch64 &&
6296 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADDXri0x100000002 &&
6297 ReferencePC - 4 == info->adrp_addr &&
6298 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6299 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6300 uint32_t addxri_inst;
6301 uint64_t adrp_imm, addxri_imm;
6302
6303 adrp_imm =
6304 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6305 if (info->adrp_inst & 0x0200000)
6306 adrp_imm |= 0xfffffffffc000000LL;
6307
6308 addxri_inst = ReferenceValue;
6309 addxri_imm = (addxri_inst >> 10) & 0xfff;
6310 if (((addxri_inst >> 22) & 0x3) == 1)
6311 addxri_imm <<= 12;
6312
6313 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6314 (adrp_imm << 12) + addxri_imm;
6315
6316 *ReferenceName =
6317 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6318 if (*ReferenceName == nullptr)
6319 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6320 // If this is arm64 and the reference is a load register instruction and we
6321 // have seen an adrp instruction just before it and the adrp's Xd register
6322 // matches this add's Xn register reconstruct the value being referenced and
6323 // look to see if it is a literal pointer. Note the load register
6324 // instruction is passed in ReferenceValue.
6325 } else if (info->O->getArch() == Triple::aarch64 &&
6326 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXui0x100000003 &&
6327 ReferencePC - 4 == info->adrp_addr &&
6328 (info->adrp_inst & 0x9f000000) == 0x90000000 &&
6329 (info->adrp_inst & 0x1f) == ((ReferenceValue >> 5) & 0x1f)) {
6330 uint32_t ldrxui_inst;
6331 uint64_t adrp_imm, ldrxui_imm;
6332
6333 adrp_imm =
6334 ((info->adrp_inst & 0x00ffffe0) >> 3) | ((info->adrp_inst >> 29) & 0x3);
6335 if (info->adrp_inst & 0x0200000)
6336 adrp_imm |= 0xfffffffffc000000LL;
6337
6338 ldrxui_inst = ReferenceValue;
6339 ldrxui_imm = (ldrxui_inst >> 10) & 0xfff;
6340
6341 ReferenceValue = (info->adrp_addr & 0xfffffffffffff000LL) +
6342 (adrp_imm << 12) + (ldrxui_imm << 3);
6343
6344 *ReferenceName =
6345 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6346 if (*ReferenceName == nullptr)
6347 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6348 }
6349 // If this arm64 and is an load register (PC-relative) instruction the
6350 // ReferenceValue is the PC plus the immediate value.
6351 else if (info->O->getArch() == Triple::aarch64 &&
6352 (*ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_LDRXl0x100000004 ||
6353 *ReferenceType == LLVMDisassembler_ReferenceType_In_ARM64_ADR0x100000005)) {
6354 *ReferenceName =
6355 GuessLiteralPointer(ReferenceValue, ReferencePC, ReferenceType, info);
6356 if (*ReferenceName == nullptr)
6357 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6358 } else if (SymbolName != nullptr && strncmp(SymbolName, "__Z", 3) == 0) {
6359 if (info->demangled_name != nullptr)
6360 free(info->demangled_name);
6361 int status;
6362 info->demangled_name =
6363 itaniumDemangle(SymbolName + 1, nullptr, nullptr, &status);
6364 if (info->demangled_name != nullptr) {
6365 *ReferenceName = info->demangled_name;
6366 *ReferenceType = LLVMDisassembler_ReferenceType_DeMangled_Name9;
6367 }
6368 }
6369 else {
6370 *ReferenceName = nullptr;
6371 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None0;
6372 }
6373
6374 return SymbolName;
6375}
6376
6377/// \brief Emits the comments that are stored in the CommentStream.
6378/// Each comment in the CommentStream must end with a newline.
6379static void emitComments(raw_svector_ostream &CommentStream,
6380 SmallString<128> &CommentsToEmit,
6381 formatted_raw_ostream &FormattedOS,
6382 const MCAsmInfo &MAI) {
6383 // Flush the stream before taking its content.
6384 StringRef Comments = CommentsToEmit.str();
6385 // Get the default information for printing a comment.
6386 StringRef CommentBegin = MAI.getCommentString();
6387 unsigned CommentColumn = MAI.getCommentColumn();
6388 bool IsFirst = true;
6389 while (!Comments.empty()) {
6390 if (!IsFirst)
6391 FormattedOS << '\n';
6392 // Emit a line of comments.
6393 FormattedOS.PadToColumn(CommentColumn);
6394 size_t Position = Comments.find('\n');
6395 FormattedOS << CommentBegin << ' ' << Comments.substr(0, Position);
6396 // Move after the newline character.
6397 Comments = Comments.substr(Position + 1);
6398 IsFirst = false;
6399 }
6400 FormattedOS.flush();
6401
6402 // Tell the comment stream that the vector changed underneath it.
6403 CommentsToEmit.clear();
6404}
6405
6406static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
6407 StringRef DisSegName, StringRef DisSectName) {
6408 const char *McpuDefault = nullptr;
6409 const Target *ThumbTarget = nullptr;
6410 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
6411 if (!TheTarget) {
6412 // GetTarget prints out stuff.
6413 return;
6414 }
6415 if (MCPU.empty() && McpuDefault)
6416 MCPU = McpuDefault;
6417
6418 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
6419 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
6420 if (ThumbTarget)
6421 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
6422
6423 // Package up features to be passed to target/subtarget
6424 std::string FeaturesStr;
6425 if (MAttrs.size()) {
6426 SubtargetFeatures Features;
6427 for (unsigned i = 0; i != MAttrs.size(); ++i)
6428 Features.AddFeature(MAttrs[i]);
6429 FeaturesStr = Features.getString();
6430 }
6431
6432 // Set up disassembler.
6433 std::unique_ptr<const MCRegisterInfo> MRI(
6434 TheTarget->createMCRegInfo(TripleName));
6435 std::unique_ptr<const MCAsmInfo> AsmInfo(
6436 TheTarget->createMCAsmInfo(*MRI, TripleName));
6437 std::unique_ptr<const MCSubtargetInfo> STI(
6438 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
6439 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
6440 std::unique_ptr<MCDisassembler> DisAsm(
6441 TheTarget->createMCDisassembler(*STI, Ctx));
6442 std::unique_ptr<MCSymbolizer> Symbolizer;
6443 struct DisassembleInfo SymbolizerInfo;
6444 std::unique_ptr<MCRelocationInfo> RelInfo(
6445 TheTarget->createMCRelocationInfo(TripleName, Ctx));
6446 if (RelInfo) {
6447 Symbolizer.reset(TheTarget->createMCSymbolizer(
6448 TripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6449 &SymbolizerInfo, &Ctx, std::move(RelInfo)));
6450 DisAsm->setSymbolizer(std::move(Symbolizer));
6451 }
6452 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
6453 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
6454 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI));
6455 // Set the display preference for hex vs. decimal immediates.
6456 IP->setPrintImmHex(PrintImmHex);
6457 // Comment stream and backing vector.
6458 SmallString<128> CommentsToEmit;
6459 raw_svector_ostream CommentStream(CommentsToEmit);
6460 // FIXME: Setting the CommentStream in the InstPrinter is problematic in that
6461 // if it is done then arm64 comments for string literals don't get printed
6462 // and some constant get printed instead and not setting it causes intel
6463 // (32-bit and 64-bit) comments printed with different spacing before the
6464 // comment causing different diffs with the 'C' disassembler library API.
6465 // IP->setCommentStream(CommentStream);
6466
6467 if (!AsmInfo || !STI || !DisAsm || !IP) {
6468 errs() << "error: couldn't initialize disassembler for target "
6469 << TripleName << '\n';
6470 return;
6471 }
6472
6473 // Set up separate thumb disassembler if needed.
6474 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
6475 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
6476 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
6477 std::unique_ptr<MCDisassembler> ThumbDisAsm;
6478 std::unique_ptr<MCInstPrinter> ThumbIP;
6479 std::unique_ptr<MCContext> ThumbCtx;
6480 std::unique_ptr<MCSymbolizer> ThumbSymbolizer;
6481 struct DisassembleInfo ThumbSymbolizerInfo;
6482 std::unique_ptr<MCRelocationInfo> ThumbRelInfo;
6483 if (ThumbTarget) {
6484 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
6485 ThumbAsmInfo.reset(
6486 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
6487 ThumbSTI.reset(
6488 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
6489 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
6490 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
6491 MCContext *PtrThumbCtx = ThumbCtx.get();
6492 ThumbRelInfo.reset(
6493 ThumbTarget->createMCRelocationInfo(ThumbTripleName, *PtrThumbCtx));
6494 if (ThumbRelInfo) {
6495 ThumbSymbolizer.reset(ThumbTarget->createMCSymbolizer(
6496 ThumbTripleName, SymbolizerGetOpInfo, SymbolizerSymbolLookUp,
6497 &ThumbSymbolizerInfo, PtrThumbCtx, std::move(ThumbRelInfo)));
6498 ThumbDisAsm->setSymbolizer(std::move(ThumbSymbolizer));
6499 }
6500 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
6501 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
6502 Triple(ThumbTripleName), ThumbAsmPrinterVariant, *ThumbAsmInfo,
6503 *ThumbInstrInfo, *ThumbMRI));
6504 // Set the display preference for hex vs. decimal immediates.
6505 ThumbIP->setPrintImmHex(PrintImmHex);
6506 }
6507
6508 if (ThumbTarget && (!ThumbAsmInfo || !ThumbSTI || !ThumbDisAsm || !ThumbIP)) {
6509 errs() << "error: couldn't initialize disassembler for target "
6510 << ThumbTripleName << '\n';
6511 return;
6512 }
6513
6514 MachO::mach_header Header = MachOOF->getHeader();
6515
6516 // FIXME: Using the -cfg command line option, this code used to be able to
6517 // annotate relocations with the referenced symbol's name, and if this was
6518 // inside a __[cf]string section, the data it points to. This is now replaced
6519 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
6520 std::vector<SectionRef> Sections;
6521 std::vector<SymbolRef> Symbols;
6522 SmallVector<uint64_t, 8> FoundFns;
6523 uint64_t BaseSegmentAddress;
6524
6525 getSectionsAndSymbols(MachOOF, Sections, Symbols, FoundFns,
6526 BaseSegmentAddress);
6527
6528 // Sort the symbols by address, just in case they didn't come in that way.
6529 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
6530
6531 // Build a data in code table that is sorted on by the address of each entry.
6532 uint64_t BaseAddress = 0;
6533 if (Header.filetype == MachO::MH_OBJECT)
6534 BaseAddress = Sections[0].getAddress();
6535 else
6536 BaseAddress = BaseSegmentAddress;
6537 DiceTable Dices;
6538 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
6539 DI != DE; ++DI) {
6540 uint32_t Offset;
6541 DI->getOffset(Offset);
6542 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
6543 }
6544 array_pod_sort(Dices.begin(), Dices.end());
6545
6546#ifndef NDEBUG
6547 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
6548#else
6549 raw_ostream &DebugOut = nulls();
6550#endif
6551
6552 std::unique_ptr<DIContext> diContext;
6553 ObjectFile *DbgObj = MachOOF;
6554 // Try to find debug info and set up the DIContext for it.
6555 if (UseDbg) {
6556 // A separate DSym file path was specified, parse it as a macho file,
6557 // get the sections and supply it to the section name parsing machinery.
6558 if (!DSYMFile.empty()) {
6559 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
6560 MemoryBuffer::getFileOrSTDIN(DSYMFile);
6561 if (std::error_code EC = BufOrErr.getError()) {
6562 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
6563 return;
6564 }
6565 DbgObj =
6566 ObjectFile::createMachOObjectFile(BufOrErr.get()->getMemBufferRef())
6567 .get()
6568 .release();
6569 }
6570
6571 // Setup the DIContext
6572 diContext.reset(new DWARFContextInMemory(*DbgObj));
6573 }
6574
6575 if (FilterSections.size() == 0)
6576 outs() << "(" << DisSegName << "," << DisSectName << ") section\n";
6577
6578 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
6579 StringRef SectName;
6580 if (Sections[SectIdx].getName(SectName) || SectName != DisSectName)
6581 continue;
6582
6583 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
6584
6585 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
6586 if (SegmentName != DisSegName)
6587 continue;
6588
6589 StringRef BytesStr;
6590 Sections[SectIdx].getContents(BytesStr);
6591 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
6592 BytesStr.size());
6593 uint64_t SectAddress = Sections[SectIdx].getAddress();
6594
6595 bool symbolTableWorked = false;
6596
6597 // Create a map of symbol addresses to symbol names for use by
6598 // the SymbolizerSymbolLookUp() routine.
6599 SymbolAddressMap AddrMap;
6600 bool DisSymNameFound = false;
6601 for (const SymbolRef &Symbol : MachOOF->symbols()) {
6602 Expected<SymbolRef::Type> STOrErr = Symbol.getType();
6603 if (!STOrErr) {
6604 std::string Buf;
6605 raw_string_ostream OS(Buf);
6606 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6607 OS.flush();
6608 report_fatal_error(Buf);
6609 }
6610 SymbolRef::Type ST = *STOrErr;
6611 if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
6612 ST == SymbolRef::ST_Other) {
6613 uint64_t Address = Symbol.getValue();
6614 Expected<StringRef> SymNameOrErr = Symbol.getName();
6615 if (!SymNameOrErr) {
6616 std::string Buf;
6617 raw_string_ostream OS(Buf);
6618 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6619 OS.flush();
6620 report_fatal_error(Buf);
6621 }
6622 StringRef SymName = *SymNameOrErr;
6623 AddrMap[Address] = SymName;
6624 if (!DisSymName.empty() && DisSymName == SymName)
6625 DisSymNameFound = true;
6626 }
6627 }
6628 if (!DisSymName.empty() && !DisSymNameFound) {
6629 outs() << "Can't find -dis-symname: " << DisSymName << "\n";
6630 return;
6631 }
6632 // Set up the block of info used by the Symbolizer call backs.
6633 SymbolizerInfo.verbose = !NoSymbolicOperands;
6634 SymbolizerInfo.O = MachOOF;
6635 SymbolizerInfo.S = Sections[SectIdx];
6636 SymbolizerInfo.AddrMap = &AddrMap;
6637 SymbolizerInfo.Sections = &Sections;
6638 SymbolizerInfo.class_name = nullptr;
6639 SymbolizerInfo.selector_name = nullptr;
6640 SymbolizerInfo.method = nullptr;
6641 SymbolizerInfo.demangled_name = nullptr;
6642 SymbolizerInfo.bindtable = nullptr;
6643 SymbolizerInfo.adrp_addr = 0;
6644 SymbolizerInfo.adrp_inst = 0;
6645 // Same for the ThumbSymbolizer
6646 ThumbSymbolizerInfo.verbose = !NoSymbolicOperands;
6647 ThumbSymbolizerInfo.O = MachOOF;
6648 ThumbSymbolizerInfo.S = Sections[SectIdx];
6649 ThumbSymbolizerInfo.AddrMap = &AddrMap;
6650 ThumbSymbolizerInfo.Sections = &Sections;
6651 ThumbSymbolizerInfo.class_name = nullptr;
6652 ThumbSymbolizerInfo.selector_name = nullptr;
6653 ThumbSymbolizerInfo.method = nullptr;
6654 ThumbSymbolizerInfo.demangled_name = nullptr;
6655 ThumbSymbolizerInfo.bindtable = nullptr;
6656 ThumbSymbolizerInfo.adrp_addr = 0;
6657 ThumbSymbolizerInfo.adrp_inst = 0;
6658
6659 unsigned int Arch = MachOOF->getArch();
6660
6661 // Skip all symbols if this is a stubs file.
6662 if (Bytes.size() == 0)
6663 return;
6664
6665 // Disassemble symbol by symbol.
6666 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
6667 Expected<StringRef> SymNameOrErr = Symbols[SymIdx].getName();
6668 if (!SymNameOrErr) {
6669 std::string Buf;
6670 raw_string_ostream OS(Buf);
6671 logAllUnhandledErrors(SymNameOrErr.takeError(), OS, "");
6672 OS.flush();
6673 report_fatal_error(Buf);
6674 }
6675 StringRef SymName = *SymNameOrErr;
6676
6677 Expected<SymbolRef::Type> STOrErr = Symbols[SymIdx].getType();
6678 if (!STOrErr) {
6679 std::string Buf;
6680 raw_string_ostream OS(Buf);
6681 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6682 OS.flush();
6683 report_fatal_error(Buf);
6684 }
6685 SymbolRef::Type ST = *STOrErr;
6686 if (ST != SymbolRef::ST_Function && ST != SymbolRef::ST_Data)
6687 continue;
6688
6689 // Make sure the symbol is defined in this section.
6690 bool containsSym = Sections[SectIdx].containsSymbol(Symbols[SymIdx]);
6691 if (!containsSym) {
6692 if (!DisSymName.empty() && DisSymName == SymName) {
6693 outs() << "-dis-symname: " << DisSymName << " not in the section\n";
6694 return;
6695 }
6696 continue;
6697 }
6698 // The __mh_execute_header is special and we need to deal with that fact
6699 // this symbol is before the start of the (__TEXT,__text) section and at the
6700 // address of the start of the __TEXT segment. This is because this symbol
6701 // is an N_SECT symbol in the (__TEXT,__text) but its address is before the
6702 // start of the section in a standard MH_EXECUTE filetype.
6703 if (!DisSymName.empty() && DisSymName == "__mh_execute_header") {
6704 outs() << "-dis-symname: __mh_execute_header not in any section\n";
6705 return;
6706 }
6707 // When this code is trying to disassemble a symbol at a time and in the
6708 // case there is only the __mh_execute_header symbol left as in a stripped
6709 // executable, we need to deal with this by ignoring this symbol so the
6710 // whole section is disassembled and this symbol is then not displayed.
6711 if (SymName == "__mh_execute_header" || SymName == "__mh_dylib_header" ||
6712 SymName == "__mh_bundle_header" || SymName == "__mh_object_header" ||
6713 SymName == "__mh_preload_header" || SymName == "__mh_dylinker_header")
6714 continue;
6715
6716 // If we are only disassembling one symbol see if this is that symbol.
6717 if (!DisSymName.empty() && DisSymName != SymName)
6718 continue;
6719
6720 // Start at the address of the symbol relative to the section's address.
6721 uint64_t SectSize = Sections[SectIdx].getSize();
6722 uint64_t Start = Symbols[SymIdx].getValue();
6723 uint64_t SectionAddress = Sections[SectIdx].getAddress();
6724 Start -= SectionAddress;
6725
6726 if (Start > SectSize) {
6727 outs() << "section data ends, " << SymName
6728 << " lies outside valid range\n";
6729 return;
6730 }
6731
6732 // Stop disassembling either at the beginning of the next symbol or at
6733 // the end of the section.
6734 bool containsNextSym = false;
6735 uint64_t NextSym = 0;
6736 uint64_t NextSymIdx = SymIdx + 1;
6737 while (Symbols.size() > NextSymIdx) {
6738 Expected<SymbolRef::Type> STOrErr = Symbols[NextSymIdx].getType();
6739 if (!STOrErr) {
6740 std::string Buf;
6741 raw_string_ostream OS(Buf);
6742 logAllUnhandledErrors(STOrErr.takeError(), OS, "");
6743 OS.flush();
6744 report_fatal_error(Buf);
6745 }
6746 SymbolRef::Type NextSymType = *STOrErr;
6747 if (NextSymType == SymbolRef::ST_Function) {
6748 containsNextSym =
6749 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx]);
6750 NextSym = Symbols[NextSymIdx].getValue();
6751 NextSym -= SectionAddress;
6752 break;
6753 }
6754 ++NextSymIdx;
6755 }
6756
6757 uint64_t End = containsNextSym ? std::min(NextSym, SectSize) : SectSize;
6758 uint64_t Size;
6759
6760 symbolTableWorked = true;
6761
6762 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
6763 bool IsThumb = MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb;
6764
6765 // We only need the dedicated Thumb target if there's a real choice
6766 // (i.e. we're not targeting M-class) and the function is Thumb.
6767 bool UseThumbTarget = IsThumb && ThumbTarget;
6768
6769 outs() << SymName << ":\n";
6770 DILineInfo lastLine;
6771 for (uint64_t Index = Start; Index < End; Index += Size) {
6772 MCInst Inst;
6773
6774 uint64_t PC = SectAddress + Index;
6775 if (!NoLeadingAddr) {
6776 if (FullLeadingAddr) {
6777 if (MachOOF->is64Bit())
6778 outs() << format("%016" PRIx64"l" "x", PC);
6779 else
6780 outs() << format("%08" PRIx64"l" "x", PC);
6781 } else {
6782 outs() << format("%8" PRIx64"l" "x" ":", PC);
6783 }
6784 }
6785 if (!NoShowRawInsn || Arch == Triple::arm)
6786 outs() << "\t";
6787
6788 // Check the data in code table here to see if this is data not an
6789 // instruction to be disassembled.
6790 DiceTable Dice;
6791 Dice.push_back(std::make_pair(PC, DiceRef()));
6792 dice_table_iterator DTI =
6793 std::search(Dices.begin(), Dices.end(), Dice.begin(), Dice.end(),
6794 compareDiceTableEntries);
6795 if (DTI != Dices.end()) {
6796 uint16_t Length;
6797 DTI->second.getLength(Length);
6798 uint16_t Kind;
6799 DTI->second.getKind(Kind);
6800 Size = DumpDataInCode(Bytes.data() + Index, Length, Kind);
6801 if ((Kind == MachO::DICE_KIND_JUMP_TABLE8) &&
6802 (PC == (DTI->first + Length - 1)) && (Length & 1))
6803 Size++;
6804 continue;
6805 }
6806
6807 SmallVector<char, 64> AnnotationsBytes;
6808 raw_svector_ostream Annotations(AnnotationsBytes);
6809
6810 bool gotInst;
6811 if (UseThumbTarget)
6812 gotInst = ThumbDisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
6813 PC, DebugOut, Annotations);
6814 else
6815 gotInst = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), PC,
6816 DebugOut, Annotations);
6817 if (gotInst) {
6818 if (!NoShowRawInsn || Arch == Triple::arm) {
6819 dumpBytes(makeArrayRef(Bytes.data() + Index, Size), outs());
6820 }
6821 formatted_raw_ostream FormattedOS(outs());
6822 StringRef AnnotationsStr = Annotations.str();
6823 if (UseThumbTarget)
6824 ThumbIP->printInst(&Inst, FormattedOS, AnnotationsStr, *ThumbSTI);
6825 else
6826 IP->printInst(&Inst, FormattedOS, AnnotationsStr, *STI);
6827 emitComments(CommentStream, CommentsToEmit, FormattedOS, *AsmInfo);
6828
6829 // Print debug info.
6830 if (diContext) {
6831 DILineInfo dli = diContext->getLineInfoForAddress(PC);
6832 // Print valid line info if it changed.
6833 if (dli != lastLine && dli.Line != 0)
6834 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
6835 << dli.Column;
6836 lastLine = dli;
6837 }
6838 outs() << "\n";
6839 } else {
6840 unsigned int Arch = MachOOF->getArch();
6841 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6842 outs() << format("\t.byte 0x%02x #bad opcode\n",
6843 *(Bytes.data() + Index) & 0xff);
6844 Size = 1; // skip exactly one illegible byte and move on.
6845 } else if (Arch == Triple::aarch64 ||
6846 (Arch == Triple::arm && !IsThumb)) {
6847 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6848 (*(Bytes.data() + Index + 1) & 0xff) << 8 |
6849 (*(Bytes.data() + Index + 2) & 0xff) << 16 |
6850 (*(Bytes.data() + Index + 3) & 0xff) << 24;
6851 outs() << format("\t.long\t0x%08x\n", opcode);
6852 Size = 4;
6853 } else if (Arch == Triple::arm) {
6854 assert(IsThumb && "ARM mode should have been dealt with above")((IsThumb && "ARM mode should have been dealt with above"
) ? static_cast<void> (0) : __assert_fail ("IsThumb && \"ARM mode should have been dealt with above\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 6854, __PRETTY_FUNCTION__))
;
6855 uint32_t opcode = (*(Bytes.data() + Index) & 0xff) |
6856 (*(Bytes.data() + Index + 1) & 0xff) << 8;
6857 outs() << format("\t.short\t0x%04x\n", opcode);
6858 Size = 2;
6859 } else{
6860 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6861 if (Size == 0)
6862 Size = 1; // skip illegible bytes
6863 }
6864 }
6865 }
6866 }
6867 if (!symbolTableWorked) {
6868 // Reading the symbol table didn't work, disassemble the whole section.
6869 uint64_t SectAddress = Sections[SectIdx].getAddress();
6870 uint64_t SectSize = Sections[SectIdx].getSize();
6871 uint64_t InstSize;
6872 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
6873 MCInst Inst;
6874
6875 uint64_t PC = SectAddress + Index;
6876 if (DisAsm->getInstruction(Inst, InstSize, Bytes.slice(Index), PC,
6877 DebugOut, nulls())) {
6878 if (!NoLeadingAddr) {
6879 if (FullLeadingAddr) {
6880 if (MachOOF->is64Bit())
6881 outs() << format("%016" PRIx64"l" "x", PC);
6882 else
6883 outs() << format("%08" PRIx64"l" "x", PC);
6884 } else {
6885 outs() << format("%8" PRIx64"l" "x" ":", PC);
6886 }
6887 }
6888 if (!NoShowRawInsn || Arch == Triple::arm) {
6889 outs() << "\t";
6890 dumpBytes(makeArrayRef(Bytes.data() + Index, InstSize), outs());
6891 }
6892 IP->printInst(&Inst, outs(), "", *STI);
6893 outs() << "\n";
6894 } else {
6895 unsigned int Arch = MachOOF->getArch();
6896 if (Arch == Triple::x86_64 || Arch == Triple::x86) {
6897 outs() << format("\t.byte 0x%02x #bad opcode\n",
6898 *(Bytes.data() + Index) & 0xff);
6899 InstSize = 1; // skip exactly one illegible byte and move on.
6900 } else {
6901 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
6902 if (InstSize == 0)
6903 InstSize = 1; // skip illegible bytes
6904 }
6905 }
6906 }
6907 }
6908 // The TripleName's need to be reset if we are called again for a different
6909 // archtecture.
6910 TripleName = "";
6911 ThumbTripleName = "";
6912
6913 if (SymbolizerInfo.method != nullptr)
6914 free(SymbolizerInfo.method);
6915 if (SymbolizerInfo.demangled_name != nullptr)
6916 free(SymbolizerInfo.demangled_name);
6917 if (SymbolizerInfo.bindtable != nullptr)
6918 delete SymbolizerInfo.bindtable;
6919 if (ThumbSymbolizerInfo.method != nullptr)
6920 free(ThumbSymbolizerInfo.method);
6921 if (ThumbSymbolizerInfo.demangled_name != nullptr)
6922 free(ThumbSymbolizerInfo.demangled_name);
6923 if (ThumbSymbolizerInfo.bindtable != nullptr)
6924 delete ThumbSymbolizerInfo.bindtable;
6925 }
6926}
6927
6928//===----------------------------------------------------------------------===//
6929// __compact_unwind section dumping
6930//===----------------------------------------------------------------------===//
6931
6932namespace {
6933
6934template <typename T> static uint64_t readNext(const char *&Buf) {
6935 using llvm::support::little;
6936 using llvm::support::unaligned;
6937
6938 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
6939 Buf += sizeof(T);
6940 return Val;
6941}
6942
6943struct CompactUnwindEntry {
6944 uint32_t OffsetInSection;
6945
6946 uint64_t FunctionAddr;
6947 uint32_t Length;
6948 uint32_t CompactEncoding;
6949 uint64_t PersonalityAddr;
6950 uint64_t LSDAAddr;
6951
6952 RelocationRef FunctionReloc;
6953 RelocationRef PersonalityReloc;
6954 RelocationRef LSDAReloc;
6955
6956 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
6957 : OffsetInSection(Offset) {
6958 if (Is64)
6959 read<uint64_t>(Contents.data() + Offset);
6960 else
6961 read<uint32_t>(Contents.data() + Offset);
6962 }
6963
6964private:
6965 template <typename UIntPtr> void read(const char *Buf) {
6966 FunctionAddr = readNext<UIntPtr>(Buf);
6967 Length = readNext<uint32_t>(Buf);
6968 CompactEncoding = readNext<uint32_t>(Buf);
6969 PersonalityAddr = readNext<UIntPtr>(Buf);
6970 LSDAAddr = readNext<UIntPtr>(Buf);
6971 }
6972};
6973}
6974
6975/// Given a relocation from __compact_unwind, consisting of the RelocationRef
6976/// and data being relocated, determine the best base Name and Addend to use for
6977/// display purposes.
6978///
6979/// 1. An Extern relocation will directly reference a symbol (and the data is
6980/// then already an addend), so use that.
6981/// 2. Otherwise the data is an offset in the object file's layout; try to find
6982// a symbol before it in the same section, and use the offset from there.
6983/// 3. Finally, if all that fails, fall back to an offset from the start of the
6984/// referenced section.
6985static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
6986 std::map<uint64_t, SymbolRef> &Symbols,
6987 const RelocationRef &Reloc, uint64_t Addr,
6988 StringRef &Name, uint64_t &Addend) {
6989 if (Reloc.getSymbol() != Obj->symbol_end()) {
6990 Expected<StringRef> NameOrErr = Reloc.getSymbol()->getName();
6991 if (!NameOrErr) {
6992 std::string Buf;
6993 raw_string_ostream OS(Buf);
6994 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
6995 OS.flush();
6996 report_fatal_error(Buf);
6997 }
6998 Name = *NameOrErr;
6999 Addend = Addr;
7000 return;
7001 }
7002
7003 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
7004 SectionRef RelocSection = Obj->getAnyRelocationSection(RE);
7005
7006 uint64_t SectionAddr = RelocSection.getAddress();
7007
7008 auto Sym = Symbols.upper_bound(Addr);
7009 if (Sym == Symbols.begin()) {
7010 // The first symbol in the object is after this reference, the best we can
7011 // do is section-relative notation.
7012 RelocSection.getName(Name);
7013 Addend = Addr - SectionAddr;
7014 return;
7015 }
7016
7017 // Go back one so that SymbolAddress <= Addr.
7018 --Sym;
7019
7020 auto SectOrErr = Sym->second.getSection();
7021 if (!SectOrErr) {
7022 std::string Buf;
7023 raw_string_ostream OS(Buf);
7024 logAllUnhandledErrors(SectOrErr.takeError(), OS, "");
7025 OS.flush();
7026 report_fatal_error(Buf);
7027 }
7028 section_iterator SymSection = *SectOrErr;
7029 if (RelocSection == *SymSection) {
7030 // There's a valid symbol in the same section before this reference.
7031 Expected<StringRef> NameOrErr = Sym->second.getName();
7032 if (!NameOrErr) {
7033 std::string Buf;
7034 raw_string_ostream OS(Buf);
7035 logAllUnhandledErrors(NameOrErr.takeError(), OS, "");
7036 OS.flush();
7037 report_fatal_error(Buf);
7038 }
7039 Name = *NameOrErr;
7040 Addend = Addr - Sym->first;
7041 return;
7042 }
7043
7044 // There is a symbol before this reference, but it's in a different
7045 // section. Probably not helpful to mention it, so use the section name.
7046 RelocSection.getName(Name);
7047 Addend = Addr - SectionAddr;
7048}
7049
7050static void printUnwindRelocDest(const MachOObjectFile *Obj,
7051 std::map<uint64_t, SymbolRef> &Symbols,
7052 const RelocationRef &Reloc, uint64_t Addr) {
7053 StringRef Name;
7054 uint64_t Addend;
7055
7056 if (!Reloc.getObject())
7057 return;
7058
7059 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
7060
7061 outs() << Name;
7062 if (Addend)
7063 outs() << " + " << format("0x%" PRIx64"l" "x", Addend);
7064}
7065
7066static void
7067printMachOCompactUnwindSection(const MachOObjectFile *Obj,
7068 std::map<uint64_t, SymbolRef> &Symbols,
7069 const SectionRef &CompactUnwind) {
7070
7071 assert(Obj->isLittleEndian() &&((Obj->isLittleEndian() && "There should not be a big-endian .o with __compact_unwind"
) ? static_cast<void> (0) : __assert_fail ("Obj->isLittleEndian() && \"There should not be a big-endian .o with __compact_unwind\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7072, __PRETTY_FUNCTION__))
7072 "There should not be a big-endian .o with __compact_unwind")((Obj->isLittleEndian() && "There should not be a big-endian .o with __compact_unwind"
) ? static_cast<void> (0) : __assert_fail ("Obj->isLittleEndian() && \"There should not be a big-endian .o with __compact_unwind\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7072, __PRETTY_FUNCTION__))
;
7073
7074 bool Is64 = Obj->is64Bit();
7075 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
7076 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
7077
7078 StringRef Contents;
7079 CompactUnwind.getContents(Contents);
7080
7081 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
7082
7083 // First populate the initial raw offsets, encodings and so on from the entry.
7084 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
7085 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
7086 CompactUnwinds.push_back(Entry);
7087 }
7088
7089 // Next we need to look at the relocations to find out what objects are
7090 // actually being referred to.
7091 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
7092 uint64_t RelocAddress = Reloc.getOffset();
7093
7094 uint32_t EntryIdx = RelocAddress / EntrySize;
7095 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
7096 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
7097
7098 if (OffsetInEntry == 0)
7099 Entry.FunctionReloc = Reloc;
7100 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
7101 Entry.PersonalityReloc = Reloc;
7102 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
7103 Entry.LSDAReloc = Reloc;
7104 else
7105 llvm_unreachable("Unexpected relocation in __compact_unwind section")::llvm::llvm_unreachable_internal("Unexpected relocation in __compact_unwind section"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7105)
;
7106 }
7107
7108 // Finally, we're ready to print the data we've gathered.
7109 outs() << "Contents of __compact_unwind section:\n";
7110 for (auto &Entry : CompactUnwinds) {
7111 outs() << " Entry at offset "
7112 << format("0x%" PRIx32"x", Entry.OffsetInSection) << ":\n";
7113
7114 // 1. Start of the region this entry applies to.
7115 outs() << " start: " << format("0x%" PRIx64"l" "x",
7116 Entry.FunctionAddr) << ' ';
7117 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc, Entry.FunctionAddr);
7118 outs() << '\n';
7119
7120 // 2. Length of the region this entry applies to.
7121 outs() << " length: " << format("0x%" PRIx32"x", Entry.Length)
7122 << '\n';
7123 // 3. The 32-bit compact encoding.
7124 outs() << " compact encoding: "
7125 << format("0x%08" PRIx32"x", Entry.CompactEncoding) << '\n';
7126
7127 // 4. The personality function, if present.
7128 if (Entry.PersonalityReloc.getObject()) {
7129 outs() << " personality function: "
7130 << format("0x%" PRIx64"l" "x", Entry.PersonalityAddr) << ' ';
7131 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
7132 Entry.PersonalityAddr);
7133 outs() << '\n';
7134 }
7135
7136 // 5. This entry's language-specific data area.
7137 if (Entry.LSDAReloc.getObject()) {
7138 outs() << " LSDA: " << format("0x%" PRIx64"l" "x",
7139 Entry.LSDAAddr) << ' ';
7140 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
7141 outs() << '\n';
7142 }
7143 }
7144}
7145
7146//===----------------------------------------------------------------------===//
7147// __unwind_info section dumping
7148//===----------------------------------------------------------------------===//
7149
7150static void printRegularSecondLevelUnwindPage(const char *PageStart) {
7151 const char *Pos = PageStart;
7152 uint32_t Kind = readNext<uint32_t>(Pos);
7153 (void)Kind;
7154 assert(Kind == 2 && "kind for a regular 2nd level index should be 2")((Kind == 2 && "kind for a regular 2nd level index should be 2"
) ? static_cast<void> (0) : __assert_fail ("Kind == 2 && \"kind for a regular 2nd level index should be 2\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7154, __PRETTY_FUNCTION__))
;
7155
7156 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7157 uint16_t NumEntries = readNext<uint16_t>(Pos);
7158
7159 Pos = PageStart + EntriesStart;
7160 for (unsigned i = 0; i < NumEntries; ++i) {
7161 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7162 uint32_t Encoding = readNext<uint32_t>(Pos);
7163
7164 outs() << " [" << i << "]: "
7165 << "function offset=" << format("0x%08" PRIx32"x", FunctionOffset)
7166 << ", "
7167 << "encoding=" << format("0x%08" PRIx32"x", Encoding) << '\n';
7168 }
7169}
7170
7171static void printCompressedSecondLevelUnwindPage(
7172 const char *PageStart, uint32_t FunctionBase,
7173 const SmallVectorImpl<uint32_t> &CommonEncodings) {
7174 const char *Pos = PageStart;
7175 uint32_t Kind = readNext<uint32_t>(Pos);
7176 (void)Kind;
7177 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3")((Kind == 3 && "kind for a compressed 2nd level index should be 3"
) ? static_cast<void> (0) : __assert_fail ("Kind == 3 && \"kind for a compressed 2nd level index should be 3\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7177, __PRETTY_FUNCTION__))
;
7178
7179 uint16_t EntriesStart = readNext<uint16_t>(Pos);
7180 uint16_t NumEntries = readNext<uint16_t>(Pos);
7181
7182 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
7183 readNext<uint16_t>(Pos);
7184 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
7185 PageStart + EncodingsStart);
7186
7187 Pos = PageStart + EntriesStart;
7188 for (unsigned i = 0; i < NumEntries; ++i) {
7189 uint32_t Entry = readNext<uint32_t>(Pos);
7190 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
7191 uint32_t EncodingIdx = Entry >> 24;
7192
7193 uint32_t Encoding;
7194 if (EncodingIdx < CommonEncodings.size())
7195 Encoding = CommonEncodings[EncodingIdx];
7196 else
7197 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
7198
7199 outs() << " [" << i << "]: "
7200 << "function offset=" << format("0x%08" PRIx32"x", FunctionOffset)
7201 << ", "
7202 << "encoding[" << EncodingIdx
7203 << "]=" << format("0x%08" PRIx32"x", Encoding) << '\n';
7204 }
7205}
7206
7207static void printMachOUnwindInfoSection(const MachOObjectFile *Obj,
7208 std::map<uint64_t, SymbolRef> &Symbols,
7209 const SectionRef &UnwindInfo) {
7210
7211 assert(Obj->isLittleEndian() &&((Obj->isLittleEndian() && "There should not be a big-endian .o with __unwind_info"
) ? static_cast<void> (0) : __assert_fail ("Obj->isLittleEndian() && \"There should not be a big-endian .o with __unwind_info\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7212, __PRETTY_FUNCTION__))
7212 "There should not be a big-endian .o with __unwind_info")((Obj->isLittleEndian() && "There should not be a big-endian .o with __unwind_info"
) ? static_cast<void> (0) : __assert_fail ("Obj->isLittleEndian() && \"There should not be a big-endian .o with __unwind_info\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7212, __PRETTY_FUNCTION__))
;
7213
7214 outs() << "Contents of __unwind_info section:\n";
7215
7216 StringRef Contents;
7217 UnwindInfo.getContents(Contents);
7218 const char *Pos = Contents.data();
7219
7220 //===----------------------------------
7221 // Section header
7222 //===----------------------------------
7223
7224 uint32_t Version = readNext<uint32_t>(Pos);
7225 outs() << " Version: "
7226 << format("0x%" PRIx32"x", Version) << '\n';
7227 assert(Version == 1 && "only understand version 1")((Version == 1 && "only understand version 1") ? static_cast
<void> (0) : __assert_fail ("Version == 1 && \"only understand version 1\""
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7227, __PRETTY_FUNCTION__))
;
7228
7229 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
7230 outs() << " Common encodings array section offset: "
7231 << format("0x%" PRIx32"x", CommonEncodingsStart) << '\n';
7232 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
7233 outs() << " Number of common encodings in array: "
7234 << format("0x%" PRIx32"x", NumCommonEncodings) << '\n';
7235
7236 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
7237 outs() << " Personality function array section offset: "
7238 << format("0x%" PRIx32"x", PersonalitiesStart) << '\n';
7239 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
7240 outs() << " Number of personality functions in array: "
7241 << format("0x%" PRIx32"x", NumPersonalities) << '\n';
7242
7243 uint32_t IndicesStart = readNext<uint32_t>(Pos);
7244 outs() << " Index array section offset: "
7245 << format("0x%" PRIx32"x", IndicesStart) << '\n';
7246 uint32_t NumIndices = readNext<uint32_t>(Pos);
7247 outs() << " Number of indices in array: "
7248 << format("0x%" PRIx32"x", NumIndices) << '\n';
7249
7250 //===----------------------------------
7251 // A shared list of common encodings
7252 //===----------------------------------
7253
7254 // These occupy indices in the range [0, N] whenever an encoding is referenced
7255 // from a compressed 2nd level index table. In practice the linker only
7256 // creates ~128 of these, so that indices are available to embed encodings in
7257 // the 2nd level index.
7258
7259 SmallVector<uint32_t, 64> CommonEncodings;
7260 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
7261 Pos = Contents.data() + CommonEncodingsStart;
7262 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
7263 uint32_t Encoding = readNext<uint32_t>(Pos);
7264 CommonEncodings.push_back(Encoding);
7265
7266 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32"x", Encoding)
7267 << '\n';
7268 }
7269
7270 //===----------------------------------
7271 // Personality functions used in this executable
7272 //===----------------------------------
7273
7274 // There should be only a handful of these (one per source language,
7275 // roughly). Particularly since they only get 2 bits in the compact encoding.
7276
7277 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
7278 Pos = Contents.data() + PersonalitiesStart;
7279 for (unsigned i = 0; i < NumPersonalities; ++i) {
7280 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
7281 outs() << " personality[" << i + 1
7282 << "]: " << format("0x%08" PRIx32"x", PersonalityFn) << '\n';
7283 }
7284
7285 //===----------------------------------
7286 // The level 1 index entries
7287 //===----------------------------------
7288
7289 // These specify an approximate place to start searching for the more detailed
7290 // information, sorted by PC.
7291
7292 struct IndexEntry {
7293 uint32_t FunctionOffset;
7294 uint32_t SecondLevelPageStart;
7295 uint32_t LSDAStart;
7296 };
7297
7298 SmallVector<IndexEntry, 4> IndexEntries;
7299
7300 outs() << " Top level indices: (count = " << NumIndices << ")\n";
7301 Pos = Contents.data() + IndicesStart;
7302 for (unsigned i = 0; i < NumIndices; ++i) {
7303 IndexEntry Entry;
7304
7305 Entry.FunctionOffset = readNext<uint32_t>(Pos);
7306 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
7307 Entry.LSDAStart = readNext<uint32_t>(Pos);
7308 IndexEntries.push_back(Entry);
7309
7310 outs() << " [" << i << "]: "
7311 << "function offset=" << format("0x%08" PRIx32"x", Entry.FunctionOffset)
7312 << ", "
7313 << "2nd level page offset="
7314 << format("0x%08" PRIx32"x", Entry.SecondLevelPageStart) << ", "
7315 << "LSDA offset=" << format("0x%08" PRIx32"x", Entry.LSDAStart) << '\n';
7316 }
7317
7318 //===----------------------------------
7319 // Next come the LSDA tables
7320 //===----------------------------------
7321
7322 // The LSDA layout is rather implicit: it's a contiguous array of entries from
7323 // the first top-level index's LSDAOffset to the last (sentinel).
7324
7325 outs() << " LSDA descriptors:\n";
7326 Pos = Contents.data() + IndexEntries[0].LSDAStart;
7327 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
7328 (2 * sizeof(uint32_t));
7329 for (int i = 0; i < NumLSDAs; ++i) {
7330 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
7331 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
7332 outs() << " [" << i << "]: "
7333 << "function offset=" << format("0x%08" PRIx32"x", FunctionOffset)
7334 << ", "
7335 << "LSDA offset=" << format("0x%08" PRIx32"x", LSDAOffset) << '\n';
7336 }
7337
7338 //===----------------------------------
7339 // Finally, the 2nd level indices
7340 //===----------------------------------
7341
7342 // Generally these are 4K in size, and have 2 possible forms:
7343 // + Regular stores up to 511 entries with disparate encodings
7344 // + Compressed stores up to 1021 entries if few enough compact encoding
7345 // values are used.
7346 outs() << " Second level indices:\n";
7347 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
7348 // The final sentinel top-level index has no associated 2nd level page
7349 if (IndexEntries[i].SecondLevelPageStart == 0)
7350 break;
7351
7352 outs() << " Second level index[" << i << "]: "
7353 << "offset in section="
7354 << format("0x%08" PRIx32"x", IndexEntries[i].SecondLevelPageStart)
7355 << ", "
7356 << "base function offset="
7357 << format("0x%08" PRIx32"x", IndexEntries[i].FunctionOffset) << '\n';
7358
7359 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
7360 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
7361 if (Kind == 2)
7362 printRegularSecondLevelUnwindPage(Pos);
7363 else if (Kind == 3)
7364 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
7365 CommonEncodings);
7366 else
7367 llvm_unreachable("Do not know how to print this kind of 2nd level page")::llvm::llvm_unreachable_internal("Do not know how to print this kind of 2nd level page"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 7367)
;
7368 }
7369}
7370
7371void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
7372 std::map<uint64_t, SymbolRef> Symbols;
7373 for (const SymbolRef &SymRef : Obj->symbols()) {
7374 // Discard any undefined or absolute symbols. They're not going to take part
7375 // in the convenience lookup for unwind info and just take up resources.
7376 auto SectOrErr = SymRef.getSection();
7377 if (!SectOrErr) {
7378 // TODO: Actually report errors helpfully.
7379 consumeError(SectOrErr.takeError());
7380 continue;
7381 }
7382 section_iterator Section = *SectOrErr;
7383 if (Section == Obj->section_end())
7384 continue;
7385
7386 uint64_t Addr = SymRef.getValue();
7387 Symbols.insert(std::make_pair(Addr, SymRef));
7388 }
7389
7390 for (const SectionRef &Section : Obj->sections()) {
7391 StringRef SectName;
7392 Section.getName(SectName);
7393 if (SectName == "__compact_unwind")
7394 printMachOCompactUnwindSection(Obj, Symbols, Section);
7395 else if (SectName == "__unwind_info")
7396 printMachOUnwindInfoSection(Obj, Symbols, Section);
7397 }
7398}
7399
7400static void PrintMachHeader(uint32_t magic, uint32_t cputype,
7401 uint32_t cpusubtype, uint32_t filetype,
7402 uint32_t ncmds, uint32_t sizeofcmds, uint32_t flags,
7403 bool verbose) {
7404 outs() << "Mach header\n";
7405 outs() << " magic cputype cpusubtype caps filetype ncmds "
7406 "sizeofcmds flags\n";
7407 if (verbose) {
7408 if (magic == MachO::MH_MAGIC)
7409 outs() << " MH_MAGIC";
7410 else if (magic == MachO::MH_MAGIC_64)
7411 outs() << "MH_MAGIC_64";
7412 else
7413 outs() << format(" 0x%08" PRIx32"x", magic);
7414 switch (cputype) {
7415 case MachO::CPU_TYPE_I386:
7416 outs() << " I386";
7417 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7418 case MachO::CPU_SUBTYPE_I386_ALL:
7419 outs() << " ALL";
7420 break;
7421 default:
7422 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7423 break;
7424 }
7425 break;
7426 case MachO::CPU_TYPE_X86_64:
7427 outs() << " X86_64";
7428 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7429 case MachO::CPU_SUBTYPE_X86_64_ALL:
7430 outs() << " ALL";
7431 break;
7432 case MachO::CPU_SUBTYPE_X86_64_H:
7433 outs() << " Haswell";
7434 break;
7435 default:
7436 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7437 break;
7438 }
7439 break;
7440 case MachO::CPU_TYPE_ARM:
7441 outs() << " ARM";
7442 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7443 case MachO::CPU_SUBTYPE_ARM_ALL:
7444 outs() << " ALL";
7445 break;
7446 case MachO::CPU_SUBTYPE_ARM_V4T:
7447 outs() << " V4T";
7448 break;
7449 case MachO::CPU_SUBTYPE_ARM_V5TEJ:
7450 outs() << " V5TEJ";
7451 break;
7452 case MachO::CPU_SUBTYPE_ARM_XSCALE:
7453 outs() << " XSCALE";
7454 break;
7455 case MachO::CPU_SUBTYPE_ARM_V6:
7456 outs() << " V6";
7457 break;
7458 case MachO::CPU_SUBTYPE_ARM_V6M:
7459 outs() << " V6M";
7460 break;
7461 case MachO::CPU_SUBTYPE_ARM_V7:
7462 outs() << " V7";
7463 break;
7464 case MachO::CPU_SUBTYPE_ARM_V7EM:
7465 outs() << " V7EM";
7466 break;
7467 case MachO::CPU_SUBTYPE_ARM_V7K:
7468 outs() << " V7K";
7469 break;
7470 case MachO::CPU_SUBTYPE_ARM_V7M:
7471 outs() << " V7M";
7472 break;
7473 case MachO::CPU_SUBTYPE_ARM_V7S:
7474 outs() << " V7S";
7475 break;
7476 default:
7477 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7478 break;
7479 }
7480 break;
7481 case MachO::CPU_TYPE_ARM64:
7482 outs() << " ARM64";
7483 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7484 case MachO::CPU_SUBTYPE_ARM64_ALL:
7485 outs() << " ALL";
7486 break;
7487 default:
7488 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7489 break;
7490 }
7491 break;
7492 case MachO::CPU_TYPE_POWERPC:
7493 outs() << " PPC";
7494 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7495 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7496 outs() << " ALL";
7497 break;
7498 default:
7499 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7500 break;
7501 }
7502 break;
7503 case MachO::CPU_TYPE_POWERPC64:
7504 outs() << " PPC64";
7505 switch (cpusubtype & ~MachO::CPU_SUBTYPE_MASK) {
7506 case MachO::CPU_SUBTYPE_POWERPC_ALL:
7507 outs() << " ALL";
7508 break;
7509 default:
7510 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7511 break;
7512 }
7513 break;
7514 default:
7515 outs() << format(" %7d", cputype);
7516 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7517 break;
7518 }
7519 if ((cpusubtype & MachO::CPU_SUBTYPE_MASK) == MachO::CPU_SUBTYPE_LIB64) {
7520 outs() << " LIB64";
7521 } else {
7522 outs() << format(" 0x%02" PRIx32"x",
7523 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7524 }
7525 switch (filetype) {
7526 case MachO::MH_OBJECT:
7527 outs() << " OBJECT";
7528 break;
7529 case MachO::MH_EXECUTE:
7530 outs() << " EXECUTE";
7531 break;
7532 case MachO::MH_FVMLIB:
7533 outs() << " FVMLIB";
7534 break;
7535 case MachO::MH_CORE:
7536 outs() << " CORE";
7537 break;
7538 case MachO::MH_PRELOAD:
7539 outs() << " PRELOAD";
7540 break;
7541 case MachO::MH_DYLIB:
7542 outs() << " DYLIB";
7543 break;
7544 case MachO::MH_DYLIB_STUB:
7545 outs() << " DYLIB_STUB";
7546 break;
7547 case MachO::MH_DYLINKER:
7548 outs() << " DYLINKER";
7549 break;
7550 case MachO::MH_BUNDLE:
7551 outs() << " BUNDLE";
7552 break;
7553 case MachO::MH_DSYM:
7554 outs() << " DSYM";
7555 break;
7556 case MachO::MH_KEXT_BUNDLE:
7557 outs() << " KEXTBUNDLE";
7558 break;
7559 default:
7560 outs() << format(" %10u", filetype);
7561 break;
7562 }
7563 outs() << format(" %5u", ncmds);
7564 outs() << format(" %10u", sizeofcmds);
7565 uint32_t f = flags;
7566 if (f & MachO::MH_NOUNDEFS) {
7567 outs() << " NOUNDEFS";
7568 f &= ~MachO::MH_NOUNDEFS;
7569 }
7570 if (f & MachO::MH_INCRLINK) {
7571 outs() << " INCRLINK";
7572 f &= ~MachO::MH_INCRLINK;
7573 }
7574 if (f & MachO::MH_DYLDLINK) {
7575 outs() << " DYLDLINK";
7576 f &= ~MachO::MH_DYLDLINK;
7577 }
7578 if (f & MachO::MH_BINDATLOAD) {
7579 outs() << " BINDATLOAD";
7580 f &= ~MachO::MH_BINDATLOAD;
7581 }
7582 if (f & MachO::MH_PREBOUND) {
7583 outs() << " PREBOUND";
7584 f &= ~MachO::MH_PREBOUND;
7585 }
7586 if (f & MachO::MH_SPLIT_SEGS) {
7587 outs() << " SPLIT_SEGS";
7588 f &= ~MachO::MH_SPLIT_SEGS;
7589 }
7590 if (f & MachO::MH_LAZY_INIT) {
7591 outs() << " LAZY_INIT";
7592 f &= ~MachO::MH_LAZY_INIT;
7593 }
7594 if (f & MachO::MH_TWOLEVEL) {
7595 outs() << " TWOLEVEL";
7596 f &= ~MachO::MH_TWOLEVEL;
7597 }
7598 if (f & MachO::MH_FORCE_FLAT) {
7599 outs() << " FORCE_FLAT";
7600 f &= ~MachO::MH_FORCE_FLAT;
7601 }
7602 if (f & MachO::MH_NOMULTIDEFS) {
7603 outs() << " NOMULTIDEFS";
7604 f &= ~MachO::MH_NOMULTIDEFS;
7605 }
7606 if (f & MachO::MH_NOFIXPREBINDING) {
7607 outs() << " NOFIXPREBINDING";
7608 f &= ~MachO::MH_NOFIXPREBINDING;
7609 }
7610 if (f & MachO::MH_PREBINDABLE) {
7611 outs() << " PREBINDABLE";
7612 f &= ~MachO::MH_PREBINDABLE;
7613 }
7614 if (f & MachO::MH_ALLMODSBOUND) {
7615 outs() << " ALLMODSBOUND";
7616 f &= ~MachO::MH_ALLMODSBOUND;
7617 }
7618 if (f & MachO::MH_SUBSECTIONS_VIA_SYMBOLS) {
7619 outs() << " SUBSECTIONS_VIA_SYMBOLS";
7620 f &= ~MachO::MH_SUBSECTIONS_VIA_SYMBOLS;
7621 }
7622 if (f & MachO::MH_CANONICAL) {
7623 outs() << " CANONICAL";
7624 f &= ~MachO::MH_CANONICAL;
7625 }
7626 if (f & MachO::MH_WEAK_DEFINES) {
7627 outs() << " WEAK_DEFINES";
7628 f &= ~MachO::MH_WEAK_DEFINES;
7629 }
7630 if (f & MachO::MH_BINDS_TO_WEAK) {
7631 outs() << " BINDS_TO_WEAK";
7632 f &= ~MachO::MH_BINDS_TO_WEAK;
7633 }
7634 if (f & MachO::MH_ALLOW_STACK_EXECUTION) {
7635 outs() << " ALLOW_STACK_EXECUTION";
7636 f &= ~MachO::MH_ALLOW_STACK_EXECUTION;
7637 }
7638 if (f & MachO::MH_DEAD_STRIPPABLE_DYLIB) {
7639 outs() << " DEAD_STRIPPABLE_DYLIB";
7640 f &= ~MachO::MH_DEAD_STRIPPABLE_DYLIB;
7641 }
7642 if (f & MachO::MH_PIE) {
7643 outs() << " PIE";
7644 f &= ~MachO::MH_PIE;
7645 }
7646 if (f & MachO::MH_NO_REEXPORTED_DYLIBS) {
7647 outs() << " NO_REEXPORTED_DYLIBS";
7648 f &= ~MachO::MH_NO_REEXPORTED_DYLIBS;
7649 }
7650 if (f & MachO::MH_HAS_TLV_DESCRIPTORS) {
7651 outs() << " MH_HAS_TLV_DESCRIPTORS";
7652 f &= ~MachO::MH_HAS_TLV_DESCRIPTORS;
7653 }
7654 if (f & MachO::MH_NO_HEAP_EXECUTION) {
7655 outs() << " MH_NO_HEAP_EXECUTION";
7656 f &= ~MachO::MH_NO_HEAP_EXECUTION;
7657 }
7658 if (f & MachO::MH_APP_EXTENSION_SAFE) {
7659 outs() << " APP_EXTENSION_SAFE";
7660 f &= ~MachO::MH_APP_EXTENSION_SAFE;
7661 }
7662 if (f != 0 || flags == 0)
7663 outs() << format(" 0x%08" PRIx32"x", f);
7664 } else {
7665 outs() << format(" 0x%08" PRIx32"x", magic);
7666 outs() << format(" %7d", cputype);
7667 outs() << format(" %10d", cpusubtype & ~MachO::CPU_SUBTYPE_MASK);
7668 outs() << format(" 0x%02" PRIx32"x",
7669 (cpusubtype & MachO::CPU_SUBTYPE_MASK) >> 24);
7670 outs() << format(" %10u", filetype);
7671 outs() << format(" %5u", ncmds);
7672 outs() << format(" %10u", sizeofcmds);
7673 outs() << format(" 0x%08" PRIx32"x", flags);
7674 }
7675 outs() << "\n";
7676}
7677
7678static void PrintSegmentCommand(uint32_t cmd, uint32_t cmdsize,
7679 StringRef SegName, uint64_t vmaddr,
7680 uint64_t vmsize, uint64_t fileoff,
7681 uint64_t filesize, uint32_t maxprot,
7682 uint32_t initprot, uint32_t nsects,
7683 uint32_t flags, uint32_t object_size,
7684 bool verbose) {
7685 uint64_t expected_cmdsize;
7686 if (cmd == MachO::LC_SEGMENT) {
7687 outs() << " cmd LC_SEGMENT\n";
7688 expected_cmdsize = nsects;
7689 expected_cmdsize *= sizeof(struct MachO::section);
7690 expected_cmdsize += sizeof(struct MachO::segment_command);
7691 } else {
7692 outs() << " cmd LC_SEGMENT_64\n";
7693 expected_cmdsize = nsects;
7694 expected_cmdsize *= sizeof(struct MachO::section_64);
7695 expected_cmdsize += sizeof(struct MachO::segment_command_64);
7696 }
7697 outs() << " cmdsize " << cmdsize;
7698 if (cmdsize != expected_cmdsize)
7699 outs() << " Inconsistent size\n";
7700 else
7701 outs() << "\n";
7702 outs() << " segname " << SegName << "\n";
7703 if (cmd == MachO::LC_SEGMENT_64) {
7704 outs() << " vmaddr " << format("0x%016" PRIx64"l" "x", vmaddr) << "\n";
7705 outs() << " vmsize " << format("0x%016" PRIx64"l" "x", vmsize) << "\n";
7706 } else {
7707 outs() << " vmaddr " << format("0x%08" PRIx64"l" "x", vmaddr) << "\n";
7708 outs() << " vmsize " << format("0x%08" PRIx64"l" "x", vmsize) << "\n";
7709 }
7710 outs() << " fileoff " << fileoff;
7711 if (fileoff > object_size)
7712 outs() << " (past end of file)\n";
7713 else
7714 outs() << "\n";
7715 outs() << " filesize " << filesize;
7716 if (fileoff + filesize > object_size)
7717 outs() << " (past end of file)\n";
7718 else
7719 outs() << "\n";
7720 if (verbose) {
7721 if ((maxprot &
7722 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7723 MachO::VM_PROT_EXECUTE)) != 0)
7724 outs() << " maxprot ?" << format("0x%08" PRIx32"x", maxprot) << "\n";
7725 else {
7726 outs() << " maxprot ";
7727 outs() << ((maxprot & MachO::VM_PROT_READ) ? "r" : "-");
7728 outs() << ((maxprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7729 outs() << ((maxprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7730 }
7731 if ((initprot &
7732 ~(MachO::VM_PROT_READ | MachO::VM_PROT_WRITE |
7733 MachO::VM_PROT_EXECUTE)) != 0)
7734 outs() << " initprot ?" << format("0x%08" PRIx32"x", initprot) << "\n";
7735 else {
7736 outs() << " initprot ";
7737 outs() << ((initprot & MachO::VM_PROT_READ) ? "r" : "-");
7738 outs() << ((initprot & MachO::VM_PROT_WRITE) ? "w" : "-");
7739 outs() << ((initprot & MachO::VM_PROT_EXECUTE) ? "x\n" : "-\n");
7740 }
7741 } else {
7742 outs() << " maxprot " << format("0x%08" PRIx32"x", maxprot) << "\n";
7743 outs() << " initprot " << format("0x%08" PRIx32"x", initprot) << "\n";
7744 }
7745 outs() << " nsects " << nsects << "\n";
7746 if (verbose) {
7747 outs() << " flags";
7748 if (flags == 0)
7749 outs() << " (none)\n";
7750 else {
7751 if (flags & MachO::SG_HIGHVM) {
7752 outs() << " HIGHVM";
7753 flags &= ~MachO::SG_HIGHVM;
7754 }
7755 if (flags & MachO::SG_FVMLIB) {
7756 outs() << " FVMLIB";
7757 flags &= ~MachO::SG_FVMLIB;
7758 }
7759 if (flags & MachO::SG_NORELOC) {
7760 outs() << " NORELOC";
7761 flags &= ~MachO::SG_NORELOC;
7762 }
7763 if (flags & MachO::SG_PROTECTED_VERSION_1) {
7764 outs() << " PROTECTED_VERSION_1";
7765 flags &= ~MachO::SG_PROTECTED_VERSION_1;
7766 }
7767 if (flags)
7768 outs() << format(" 0x%08" PRIx32"x", flags) << " (unknown flags)\n";
7769 else
7770 outs() << "\n";
7771 }
7772 } else {
7773 outs() << " flags " << format("0x%" PRIx32"x", flags) << "\n";
7774 }
7775}
7776
7777static void PrintSection(const char *sectname, const char *segname,
7778 uint64_t addr, uint64_t size, uint32_t offset,
7779 uint32_t align, uint32_t reloff, uint32_t nreloc,
7780 uint32_t flags, uint32_t reserved1, uint32_t reserved2,
7781 uint32_t cmd, const char *sg_segname,
7782 uint32_t filetype, uint32_t object_size,
7783 bool verbose) {
7784 outs() << "Section\n";
7785 outs() << " sectname " << format("%.16s\n", sectname);
7786 outs() << " segname " << format("%.16s", segname);
7787 if (filetype != MachO::MH_OBJECT && strncmp(sg_segname, segname, 16) != 0)
7788 outs() << " (does not match segment)\n";
7789 else
7790 outs() << "\n";
7791 if (cmd == MachO::LC_SEGMENT_64) {
7792 outs() << " addr " << format("0x%016" PRIx64"l" "x", addr) << "\n";
7793 outs() << " size " << format("0x%016" PRIx64"l" "x", size);
7794 } else {
7795 outs() << " addr " << format("0x%08" PRIx64"l" "x", addr) << "\n";
7796 outs() << " size " << format("0x%08" PRIx64"l" "x", size);
7797 }
7798 if ((flags & MachO::S_ZEROFILL) != 0 && offset + size > object_size)
7799 outs() << " (past end of file)\n";
7800 else
7801 outs() << "\n";
7802 outs() << " offset " << offset;
7803 if (offset > object_size)
7804 outs() << " (past end of file)\n";
7805 else
7806 outs() << "\n";
7807 uint32_t align_shifted = 1 << align;
7808 outs() << " align 2^" << align << " (" << align_shifted << ")\n";
7809 outs() << " reloff " << reloff;
7810 if (reloff > object_size)
7811 outs() << " (past end of file)\n";
7812 else
7813 outs() << "\n";
7814 outs() << " nreloc " << nreloc;
7815 if (reloff + nreloc * sizeof(struct MachO::relocation_info) > object_size)
7816 outs() << " (past end of file)\n";
7817 else
7818 outs() << "\n";
7819 uint32_t section_type = flags & MachO::SECTION_TYPE;
7820 if (verbose) {
7821 outs() << " type";
7822 if (section_type == MachO::S_REGULAR)
7823 outs() << " S_REGULAR\n";
7824 else if (section_type == MachO::S_ZEROFILL)
7825 outs() << " S_ZEROFILL\n";
7826 else if (section_type == MachO::S_CSTRING_LITERALS)
7827 outs() << " S_CSTRING_LITERALS\n";
7828 else if (section_type == MachO::S_4BYTE_LITERALS)
7829 outs() << " S_4BYTE_LITERALS\n";
7830 else if (section_type == MachO::S_8BYTE_LITERALS)
7831 outs() << " S_8BYTE_LITERALS\n";
7832 else if (section_type == MachO::S_16BYTE_LITERALS)
7833 outs() << " S_16BYTE_LITERALS\n";
7834 else if (section_type == MachO::S_LITERAL_POINTERS)
7835 outs() << " S_LITERAL_POINTERS\n";
7836 else if (section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS)
7837 outs() << " S_NON_LAZY_SYMBOL_POINTERS\n";
7838 else if (section_type == MachO::S_LAZY_SYMBOL_POINTERS)
7839 outs() << " S_LAZY_SYMBOL_POINTERS\n";
7840 else if (section_type == MachO::S_SYMBOL_STUBS)
7841 outs() << " S_SYMBOL_STUBS\n";
7842 else if (section_type == MachO::S_MOD_INIT_FUNC_POINTERS)
7843 outs() << " S_MOD_INIT_FUNC_POINTERS\n";
7844 else if (section_type == MachO::S_MOD_TERM_FUNC_POINTERS)
7845 outs() << " S_MOD_TERM_FUNC_POINTERS\n";
7846 else if (section_type == MachO::S_COALESCED)
7847 outs() << " S_COALESCED\n";
7848 else if (section_type == MachO::S_INTERPOSING)
7849 outs() << " S_INTERPOSING\n";
7850 else if (section_type == MachO::S_DTRACE_DOF)
7851 outs() << " S_DTRACE_DOF\n";
7852 else if (section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS)
7853 outs() << " S_LAZY_DYLIB_SYMBOL_POINTERS\n";
7854 else if (section_type == MachO::S_THREAD_LOCAL_REGULAR)
7855 outs() << " S_THREAD_LOCAL_REGULAR\n";
7856 else if (section_type == MachO::S_THREAD_LOCAL_ZEROFILL)
7857 outs() << " S_THREAD_LOCAL_ZEROFILL\n";
7858 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLES)
7859 outs() << " S_THREAD_LOCAL_VARIABLES\n";
7860 else if (section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7861 outs() << " S_THREAD_LOCAL_VARIABLE_POINTERS\n";
7862 else if (section_type == MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS)
7863 outs() << " S_THREAD_LOCAL_INIT_FUNCTION_POINTERS\n";
7864 else
7865 outs() << format("0x%08" PRIx32"x", section_type) << "\n";
7866 outs() << "attributes";
7867 uint32_t section_attributes = flags & MachO::SECTION_ATTRIBUTES;
7868 if (section_attributes & MachO::S_ATTR_PURE_INSTRUCTIONS)
7869 outs() << " PURE_INSTRUCTIONS";
7870 if (section_attributes & MachO::S_ATTR_NO_TOC)
7871 outs() << " NO_TOC";
7872 if (section_attributes & MachO::S_ATTR_STRIP_STATIC_SYMS)
7873 outs() << " STRIP_STATIC_SYMS";
7874 if (section_attributes & MachO::S_ATTR_NO_DEAD_STRIP)
7875 outs() << " NO_DEAD_STRIP";
7876 if (section_attributes & MachO::S_ATTR_LIVE_SUPPORT)
7877 outs() << " LIVE_SUPPORT";
7878 if (section_attributes & MachO::S_ATTR_SELF_MODIFYING_CODE)
7879 outs() << " SELF_MODIFYING_CODE";
7880 if (section_attributes & MachO::S_ATTR_DEBUG)
7881 outs() << " DEBUG";
7882 if (section_attributes & MachO::S_ATTR_SOME_INSTRUCTIONS)
7883 outs() << " SOME_INSTRUCTIONS";
7884 if (section_attributes & MachO::S_ATTR_EXT_RELOC)
7885 outs() << " EXT_RELOC";
7886 if (section_attributes & MachO::S_ATTR_LOC_RELOC)
7887 outs() << " LOC_RELOC";
7888 if (section_attributes == 0)
7889 outs() << " (none)";
7890 outs() << "\n";
7891 } else
7892 outs() << " flags " << format("0x%08" PRIx32"x", flags) << "\n";
7893 outs() << " reserved1 " << reserved1;
7894 if (section_type == MachO::S_SYMBOL_STUBS ||
7895 section_type == MachO::S_LAZY_SYMBOL_POINTERS ||
7896 section_type == MachO::S_LAZY_DYLIB_SYMBOL_POINTERS ||
7897 section_type == MachO::S_NON_LAZY_SYMBOL_POINTERS ||
7898 section_type == MachO::S_THREAD_LOCAL_VARIABLE_POINTERS)
7899 outs() << " (index into indirect symbol table)\n";
7900 else
7901 outs() << "\n";
7902 outs() << " reserved2 " << reserved2;
7903 if (section_type == MachO::S_SYMBOL_STUBS)
7904 outs() << " (size of stubs)\n";
7905 else
7906 outs() << "\n";
7907}
7908
7909static void PrintSymtabLoadCommand(MachO::symtab_command st, bool Is64Bit,
7910 uint32_t object_size) {
7911 outs() << " cmd LC_SYMTAB\n";
7912 outs() << " cmdsize " << st.cmdsize;
7913 if (st.cmdsize != sizeof(struct MachO::symtab_command))
7914 outs() << " Incorrect size\n";
7915 else
7916 outs() << "\n";
7917 outs() << " symoff " << st.symoff;
7918 if (st.symoff > object_size)
7919 outs() << " (past end of file)\n";
7920 else
7921 outs() << "\n";
7922 outs() << " nsyms " << st.nsyms;
7923 uint64_t big_size;
7924 if (Is64Bit) {
7925 big_size = st.nsyms;
7926 big_size *= sizeof(struct MachO::nlist_64);
7927 big_size += st.symoff;
7928 if (big_size > object_size)
7929 outs() << " (past end of file)\n";
7930 else
7931 outs() << "\n";
7932 } else {
7933 big_size = st.nsyms;
7934 big_size *= sizeof(struct MachO::nlist);
7935 big_size += st.symoff;
7936 if (big_size > object_size)
7937 outs() << " (past end of file)\n";
7938 else
7939 outs() << "\n";
7940 }
7941 outs() << " stroff " << st.stroff;
7942 if (st.stroff > object_size)
7943 outs() << " (past end of file)\n";
7944 else
7945 outs() << "\n";
7946 outs() << " strsize " << st.strsize;
7947 big_size = st.stroff;
7948 big_size += st.strsize;
7949 if (big_size > object_size)
7950 outs() << " (past end of file)\n";
7951 else
7952 outs() << "\n";
7953}
7954
7955static void PrintDysymtabLoadCommand(MachO::dysymtab_command dyst,
7956 uint32_t nsyms, uint32_t object_size,
7957 bool Is64Bit) {
7958 outs() << " cmd LC_DYSYMTAB\n";
7959 outs() << " cmdsize " << dyst.cmdsize;
7960 if (dyst.cmdsize != sizeof(struct MachO::dysymtab_command))
7961 outs() << " Incorrect size\n";
7962 else
7963 outs() << "\n";
7964 outs() << " ilocalsym " << dyst.ilocalsym;
7965 if (dyst.ilocalsym > nsyms)
7966 outs() << " (greater than the number of symbols)\n";
7967 else
7968 outs() << "\n";
7969 outs() << " nlocalsym " << dyst.nlocalsym;
7970 uint64_t big_size;
7971 big_size = dyst.ilocalsym;
7972 big_size += dyst.nlocalsym;
7973 if (big_size > nsyms)
7974 outs() << " (past the end of the symbol table)\n";
7975 else
7976 outs() << "\n";
7977 outs() << " iextdefsym " << dyst.iextdefsym;
7978 if (dyst.iextdefsym > nsyms)
7979 outs() << " (greater than the number of symbols)\n";
7980 else
7981 outs() << "\n";
7982 outs() << " nextdefsym " << dyst.nextdefsym;
7983 big_size = dyst.iextdefsym;
7984 big_size += dyst.nextdefsym;
7985 if (big_size > nsyms)
7986 outs() << " (past the end of the symbol table)\n";
7987 else
7988 outs() << "\n";
7989 outs() << " iundefsym " << dyst.iundefsym;
7990 if (dyst.iundefsym > nsyms)
7991 outs() << " (greater than the number of symbols)\n";
7992 else
7993 outs() << "\n";
7994 outs() << " nundefsym " << dyst.nundefsym;
7995 big_size = dyst.iundefsym;
7996 big_size += dyst.nundefsym;
7997 if (big_size > nsyms)
7998 outs() << " (past the end of the symbol table)\n";
7999 else
8000 outs() << "\n";
8001 outs() << " tocoff " << dyst.tocoff;
8002 if (dyst.tocoff > object_size)
8003 outs() << " (past end of file)\n";
8004 else
8005 outs() << "\n";
8006 outs() << " ntoc " << dyst.ntoc;
8007 big_size = dyst.ntoc;
8008 big_size *= sizeof(struct MachO::dylib_table_of_contents);
8009 big_size += dyst.tocoff;
8010 if (big_size > object_size)
8011 outs() << " (past end of file)\n";
8012 else
8013 outs() << "\n";
8014 outs() << " modtaboff " << dyst.modtaboff;
8015 if (dyst.modtaboff > object_size)
8016 outs() << " (past end of file)\n";
8017 else
8018 outs() << "\n";
8019 outs() << " nmodtab " << dyst.nmodtab;
8020 uint64_t modtabend;
8021 if (Is64Bit) {
8022 modtabend = dyst.nmodtab;
8023 modtabend *= sizeof(struct MachO::dylib_module_64);
8024 modtabend += dyst.modtaboff;
8025 } else {
8026 modtabend = dyst.nmodtab;
8027 modtabend *= sizeof(struct MachO::dylib_module);
8028 modtabend += dyst.modtaboff;
8029 }
8030 if (modtabend > object_size)
8031 outs() << " (past end of file)\n";
8032 else
8033 outs() << "\n";
8034 outs() << " extrefsymoff " << dyst.extrefsymoff;
8035 if (dyst.extrefsymoff > object_size)
8036 outs() << " (past end of file)\n";
8037 else
8038 outs() << "\n";
8039 outs() << " nextrefsyms " << dyst.nextrefsyms;
8040 big_size = dyst.nextrefsyms;
8041 big_size *= sizeof(struct MachO::dylib_reference);
8042 big_size += dyst.extrefsymoff;
8043 if (big_size > object_size)
8044 outs() << " (past end of file)\n";
8045 else
8046 outs() << "\n";
8047 outs() << " indirectsymoff " << dyst.indirectsymoff;
8048 if (dyst.indirectsymoff > object_size)
8049 outs() << " (past end of file)\n";
8050 else
8051 outs() << "\n";
8052 outs() << " nindirectsyms " << dyst.nindirectsyms;
8053 big_size = dyst.nindirectsyms;
8054 big_size *= sizeof(uint32_t);
8055 big_size += dyst.indirectsymoff;
8056 if (big_size > object_size)
8057 outs() << " (past end of file)\n";
8058 else
8059 outs() << "\n";
8060 outs() << " extreloff " << dyst.extreloff;
8061 if (dyst.extreloff > object_size)
8062 outs() << " (past end of file)\n";
8063 else
8064 outs() << "\n";
8065 outs() << " nextrel " << dyst.nextrel;
8066 big_size = dyst.nextrel;
8067 big_size *= sizeof(struct MachO::relocation_info);
8068 big_size += dyst.extreloff;
8069 if (big_size > object_size)
8070 outs() << " (past end of file)\n";
8071 else
8072 outs() << "\n";
8073 outs() << " locreloff " << dyst.locreloff;
8074 if (dyst.locreloff > object_size)
8075 outs() << " (past end of file)\n";
8076 else
8077 outs() << "\n";
8078 outs() << " nlocrel " << dyst.nlocrel;
8079 big_size = dyst.nlocrel;
8080 big_size *= sizeof(struct MachO::relocation_info);
8081 big_size += dyst.locreloff;
8082 if (big_size > object_size)
8083 outs() << " (past end of file)\n";
8084 else
8085 outs() << "\n";
8086}
8087
8088static void PrintDyldInfoLoadCommand(MachO::dyld_info_command dc,
8089 uint32_t object_size) {
8090 if (dc.cmd == MachO::LC_DYLD_INFO)
8091 outs() << " cmd LC_DYLD_INFO\n";
8092 else
8093 outs() << " cmd LC_DYLD_INFO_ONLY\n";
8094 outs() << " cmdsize " << dc.cmdsize;
8095 if (dc.cmdsize != sizeof(struct MachO::dyld_info_command))
8096 outs() << " Incorrect size\n";
8097 else
8098 outs() << "\n";
8099 outs() << " rebase_off " << dc.rebase_off;
8100 if (dc.rebase_off > object_size)
8101 outs() << " (past end of file)\n";
8102 else
8103 outs() << "\n";
8104 outs() << " rebase_size " << dc.rebase_size;
8105 uint64_t big_size;
8106 big_size = dc.rebase_off;
8107 big_size += dc.rebase_size;
8108 if (big_size > object_size)
8109 outs() << " (past end of file)\n";
8110 else
8111 outs() << "\n";
8112 outs() << " bind_off " << dc.bind_off;
8113 if (dc.bind_off > object_size)
8114 outs() << " (past end of file)\n";
8115 else
8116 outs() << "\n";
8117 outs() << " bind_size " << dc.bind_size;
8118 big_size = dc.bind_off;
8119 big_size += dc.bind_size;
8120 if (big_size > object_size)
8121 outs() << " (past end of file)\n";
8122 else
8123 outs() << "\n";
8124 outs() << " weak_bind_off " << dc.weak_bind_off;
8125 if (dc.weak_bind_off > object_size)
8126 outs() << " (past end of file)\n";
8127 else
8128 outs() << "\n";
8129 outs() << " weak_bind_size " << dc.weak_bind_size;
8130 big_size = dc.weak_bind_off;
8131 big_size += dc.weak_bind_size;
8132 if (big_size > object_size)
8133 outs() << " (past end of file)\n";
8134 else
8135 outs() << "\n";
8136 outs() << " lazy_bind_off " << dc.lazy_bind_off;
8137 if (dc.lazy_bind_off > object_size)
8138 outs() << " (past end of file)\n";
8139 else
8140 outs() << "\n";
8141 outs() << " lazy_bind_size " << dc.lazy_bind_size;
8142 big_size = dc.lazy_bind_off;
8143 big_size += dc.lazy_bind_size;
8144 if (big_size > object_size)
8145 outs() << " (past end of file)\n";
8146 else
8147 outs() << "\n";
8148 outs() << " export_off " << dc.export_off;
8149 if (dc.export_off > object_size)
8150 outs() << " (past end of file)\n";
8151 else
8152 outs() << "\n";
8153 outs() << " export_size " << dc.export_size;
8154 big_size = dc.export_off;
8155 big_size += dc.export_size;
8156 if (big_size > object_size)
8157 outs() << " (past end of file)\n";
8158 else
8159 outs() << "\n";
8160}
8161
8162static void PrintDyldLoadCommand(MachO::dylinker_command dyld,
8163 const char *Ptr) {
8164 if (dyld.cmd == MachO::LC_ID_DYLINKER)
8165 outs() << " cmd LC_ID_DYLINKER\n";
8166 else if (dyld.cmd == MachO::LC_LOAD_DYLINKER)
8167 outs() << " cmd LC_LOAD_DYLINKER\n";
8168 else if (dyld.cmd == MachO::LC_DYLD_ENVIRONMENT)
8169 outs() << " cmd LC_DYLD_ENVIRONMENT\n";
8170 else
8171 outs() << " cmd ?(" << dyld.cmd << ")\n";
8172 outs() << " cmdsize " << dyld.cmdsize;
8173 if (dyld.cmdsize < sizeof(struct MachO::dylinker_command))
8174 outs() << " Incorrect size\n";
8175 else
8176 outs() << "\n";
8177 if (dyld.name >= dyld.cmdsize)
8178 outs() << " name ?(bad offset " << dyld.name << ")\n";
8179 else {
8180 const char *P = (const char *)(Ptr) + dyld.name;
8181 outs() << " name " << P << " (offset " << dyld.name << ")\n";
8182 }
8183}
8184
8185static void PrintUuidLoadCommand(MachO::uuid_command uuid) {
8186 outs() << " cmd LC_UUID\n";
8187 outs() << " cmdsize " << uuid.cmdsize;
8188 if (uuid.cmdsize != sizeof(struct MachO::uuid_command))
8189 outs() << " Incorrect size\n";
8190 else
8191 outs() << "\n";
8192 outs() << " uuid ";
8193 for (int i = 0; i < 16; ++i) {
8194 outs() << format("%02" PRIX32"X", uuid.uuid[i]);
8195 if (i == 3 || i == 5 || i == 7 || i == 9)
8196 outs() << "-";
8197 }
8198 outs() << "\n";
8199}
8200
8201static void PrintRpathLoadCommand(MachO::rpath_command rpath, const char *Ptr) {
8202 outs() << " cmd LC_RPATH\n";
8203 outs() << " cmdsize " << rpath.cmdsize;
8204 if (rpath.cmdsize < sizeof(struct MachO::rpath_command))
8205 outs() << " Incorrect size\n";
8206 else
8207 outs() << "\n";
8208 if (rpath.path >= rpath.cmdsize)
8209 outs() << " path ?(bad offset " << rpath.path << ")\n";
8210 else {
8211 const char *P = (const char *)(Ptr) + rpath.path;
8212 outs() << " path " << P << " (offset " << rpath.path << ")\n";
8213 }
8214}
8215
8216static void PrintVersionMinLoadCommand(MachO::version_min_command vd) {
8217 StringRef LoadCmdName;
8218 switch (vd.cmd) {
8219 case MachO::LC_VERSION_MIN_MACOSX:
8220 LoadCmdName = "LC_VERSION_MIN_MACOSX";
8221 break;
8222 case MachO::LC_VERSION_MIN_IPHONEOS:
8223 LoadCmdName = "LC_VERSION_MIN_IPHONEOS";
8224 break;
8225 case MachO::LC_VERSION_MIN_TVOS:
8226 LoadCmdName = "LC_VERSION_MIN_TVOS";
8227 break;
8228 case MachO::LC_VERSION_MIN_WATCHOS:
8229 LoadCmdName = "LC_VERSION_MIN_WATCHOS";
8230 break;
8231 default:
8232 llvm_unreachable("Unknown version min load command")::llvm::llvm_unreachable_internal("Unknown version min load command"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 8232)
;
8233 }
8234
8235 outs() << " cmd " << LoadCmdName << '\n';
8236 outs() << " cmdsize " << vd.cmdsize;
8237 if (vd.cmdsize != sizeof(struct MachO::version_min_command))
8238 outs() << " Incorrect size\n";
8239 else
8240 outs() << "\n";
8241 outs() << " version "
8242 << MachOObjectFile::getVersionMinMajor(vd, false) << "."
8243 << MachOObjectFile::getVersionMinMinor(vd, false);
8244 uint32_t Update = MachOObjectFile::getVersionMinUpdate(vd, false);
8245 if (Update != 0)
8246 outs() << "." << Update;
8247 outs() << "\n";
8248 if (vd.sdk == 0)
8249 outs() << " sdk n/a";
8250 else {
8251 outs() << " sdk "
8252 << MachOObjectFile::getVersionMinMajor(vd, true) << "."
8253 << MachOObjectFile::getVersionMinMinor(vd, true);
8254 }
8255 Update = MachOObjectFile::getVersionMinUpdate(vd, true);
8256 if (Update != 0)
8257 outs() << "." << Update;
8258 outs() << "\n";
8259}
8260
8261static void PrintSourceVersionCommand(MachO::source_version_command sd) {
8262 outs() << " cmd LC_SOURCE_VERSION\n";
8263 outs() << " cmdsize " << sd.cmdsize;
8264 if (sd.cmdsize != sizeof(struct MachO::source_version_command))
8265 outs() << " Incorrect size\n";
8266 else
8267 outs() << "\n";
8268 uint64_t a = (sd.version >> 40) & 0xffffff;
8269 uint64_t b = (sd.version >> 30) & 0x3ff;
8270 uint64_t c = (sd.version >> 20) & 0x3ff;
8271 uint64_t d = (sd.version >> 10) & 0x3ff;
8272 uint64_t e = sd.version & 0x3ff;
8273 outs() << " version " << a << "." << b;
8274 if (e != 0)
8275 outs() << "." << c << "." << d << "." << e;
8276 else if (d != 0)
8277 outs() << "." << c << "." << d;
8278 else if (c != 0)
8279 outs() << "." << c;
8280 outs() << "\n";
8281}
8282
8283static void PrintEntryPointCommand(MachO::entry_point_command ep) {
8284 outs() << " cmd LC_MAIN\n";
8285 outs() << " cmdsize " << ep.cmdsize;
8286 if (ep.cmdsize != sizeof(struct MachO::entry_point_command))
8287 outs() << " Incorrect size\n";
8288 else
8289 outs() << "\n";
8290 outs() << " entryoff " << ep.entryoff << "\n";
8291 outs() << " stacksize " << ep.stacksize << "\n";
8292}
8293
8294static void PrintEncryptionInfoCommand(MachO::encryption_info_command ec,
8295 uint32_t object_size) {
8296 outs() << " cmd LC_ENCRYPTION_INFO\n";
8297 outs() << " cmdsize " << ec.cmdsize;
8298 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command))
8299 outs() << " Incorrect size\n";
8300 else
8301 outs() << "\n";
8302 outs() << " cryptoff " << ec.cryptoff;
8303 if (ec.cryptoff > object_size)
8304 outs() << " (past end of file)\n";
8305 else
8306 outs() << "\n";
8307 outs() << " cryptsize " << ec.cryptsize;
8308 if (ec.cryptsize > object_size)
8309 outs() << " (past end of file)\n";
8310 else
8311 outs() << "\n";
8312 outs() << " cryptid " << ec.cryptid << "\n";
8313}
8314
8315static void PrintEncryptionInfoCommand64(MachO::encryption_info_command_64 ec,
8316 uint32_t object_size) {
8317 outs() << " cmd LC_ENCRYPTION_INFO_64\n";
8318 outs() << " cmdsize " << ec.cmdsize;
8319 if (ec.cmdsize != sizeof(struct MachO::encryption_info_command_64))
8320 outs() << " Incorrect size\n";
8321 else
8322 outs() << "\n";
8323 outs() << " cryptoff " << ec.cryptoff;
8324 if (ec.cryptoff > object_size)
8325 outs() << " (past end of file)\n";
8326 else
8327 outs() << "\n";
8328 outs() << " cryptsize " << ec.cryptsize;
8329 if (ec.cryptsize > object_size)
8330 outs() << " (past end of file)\n";
8331 else
8332 outs() << "\n";
8333 outs() << " cryptid " << ec.cryptid << "\n";
8334 outs() << " pad " << ec.pad << "\n";
8335}
8336
8337static void PrintLinkerOptionCommand(MachO::linker_option_command lo,
8338 const char *Ptr) {
8339 outs() << " cmd LC_LINKER_OPTION\n";
8340 outs() << " cmdsize " << lo.cmdsize;
8341 if (lo.cmdsize < sizeof(struct MachO::linker_option_command))
8342 outs() << " Incorrect size\n";
8343 else
8344 outs() << "\n";
8345 outs() << " count " << lo.count << "\n";
8346 const char *string = Ptr + sizeof(struct MachO::linker_option_command);
8347 uint32_t left = lo.cmdsize - sizeof(struct MachO::linker_option_command);
8348 uint32_t i = 0;
8349 while (left > 0) {
8350 while (*string == '\0' && left > 0) {
8351 string++;
8352 left--;
8353 }
8354 if (left > 0) {
8355 i++;
8356 outs() << " string #" << i << " " << format("%.*s\n", left, string);
8357 uint32_t NullPos = StringRef(string, left).find('\0');
8358 uint32_t len = std::min(NullPos, left) + 1;
8359 string += len;
8360 left -= len;
8361 }
8362 }
8363 if (lo.count != i)
8364 outs() << " count " << lo.count << " does not match number of strings "
8365 << i << "\n";
8366}
8367
8368static void PrintSubFrameworkCommand(MachO::sub_framework_command sub,
8369 const char *Ptr) {
8370 outs() << " cmd LC_SUB_FRAMEWORK\n";
8371 outs() << " cmdsize " << sub.cmdsize;
8372 if (sub.cmdsize < sizeof(struct MachO::sub_framework_command))
8373 outs() << " Incorrect size\n";
8374 else
8375 outs() << "\n";
8376 if (sub.umbrella < sub.cmdsize) {
8377 const char *P = Ptr + sub.umbrella;
8378 outs() << " umbrella " << P << " (offset " << sub.umbrella << ")\n";
8379 } else {
8380 outs() << " umbrella ?(bad offset " << sub.umbrella << ")\n";
8381 }
8382}
8383
8384static void PrintSubUmbrellaCommand(MachO::sub_umbrella_command sub,
8385 const char *Ptr) {
8386 outs() << " cmd LC_SUB_UMBRELLA\n";
8387 outs() << " cmdsize " << sub.cmdsize;
8388 if (sub.cmdsize < sizeof(struct MachO::sub_umbrella_command))
8389 outs() << " Incorrect size\n";
8390 else
8391 outs() << "\n";
8392 if (sub.sub_umbrella < sub.cmdsize) {
8393 const char *P = Ptr + sub.sub_umbrella;
8394 outs() << " sub_umbrella " << P << " (offset " << sub.sub_umbrella << ")\n";
8395 } else {
8396 outs() << " sub_umbrella ?(bad offset " << sub.sub_umbrella << ")\n";
8397 }
8398}
8399
8400static void PrintSubLibraryCommand(MachO::sub_library_command sub,
8401 const char *Ptr) {
8402 outs() << " cmd LC_SUB_LIBRARY\n";
8403 outs() << " cmdsize " << sub.cmdsize;
8404 if (sub.cmdsize < sizeof(struct MachO::sub_library_command))
8405 outs() << " Incorrect size\n";
8406 else
8407 outs() << "\n";
8408 if (sub.sub_library < sub.cmdsize) {
8409 const char *P = Ptr + sub.sub_library;
8410 outs() << " sub_library " << P << " (offset " << sub.sub_library << ")\n";
8411 } else {
8412 outs() << " sub_library ?(bad offset " << sub.sub_library << ")\n";
8413 }
8414}
8415
8416static void PrintSubClientCommand(MachO::sub_client_command sub,
8417 const char *Ptr) {
8418 outs() << " cmd LC_SUB_CLIENT\n";
8419 outs() << " cmdsize " << sub.cmdsize;
8420 if (sub.cmdsize < sizeof(struct MachO::sub_client_command))
8421 outs() << " Incorrect size\n";
8422 else
8423 outs() << "\n";
8424 if (sub.client < sub.cmdsize) {
8425 const char *P = Ptr + sub.client;
8426 outs() << " client " << P << " (offset " << sub.client << ")\n";
8427 } else {
8428 outs() << " client ?(bad offset " << sub.client << ")\n";
8429 }
8430}
8431
8432static void PrintRoutinesCommand(MachO::routines_command r) {
8433 outs() << " cmd LC_ROUTINES\n";
8434 outs() << " cmdsize " << r.cmdsize;
8435 if (r.cmdsize != sizeof(struct MachO::routines_command))
8436 outs() << " Incorrect size\n";
8437 else
8438 outs() << "\n";
8439 outs() << " init_address " << format("0x%08" PRIx32"x", r.init_address) << "\n";
8440 outs() << " init_module " << r.init_module << "\n";
8441 outs() << " reserved1 " << r.reserved1 << "\n";
8442 outs() << " reserved2 " << r.reserved2 << "\n";
8443 outs() << " reserved3 " << r.reserved3 << "\n";
8444 outs() << " reserved4 " << r.reserved4 << "\n";
8445 outs() << " reserved5 " << r.reserved5 << "\n";
8446 outs() << " reserved6 " << r.reserved6 << "\n";
8447}
8448
8449static void PrintRoutinesCommand64(MachO::routines_command_64 r) {
8450 outs() << " cmd LC_ROUTINES_64\n";
8451 outs() << " cmdsize " << r.cmdsize;
8452 if (r.cmdsize != sizeof(struct MachO::routines_command_64))
8453 outs() << " Incorrect size\n";
8454 else
8455 outs() << "\n";
8456 outs() << " init_address " << format("0x%016" PRIx64"l" "x", r.init_address) << "\n";
8457 outs() << " init_module " << r.init_module << "\n";
8458 outs() << " reserved1 " << r.reserved1 << "\n";
8459 outs() << " reserved2 " << r.reserved2 << "\n";
8460 outs() << " reserved3 " << r.reserved3 << "\n";
8461 outs() << " reserved4 " << r.reserved4 << "\n";
8462 outs() << " reserved5 " << r.reserved5 << "\n";
8463 outs() << " reserved6 " << r.reserved6 << "\n";
8464}
8465
8466static void Print_x86_thread_state64_t(MachO::x86_thread_state64_t &cpu64) {
8467 outs() << " rax " << format("0x%016" PRIx64"l" "x", cpu64.rax);
8468 outs() << " rbx " << format("0x%016" PRIx64"l" "x", cpu64.rbx);
8469 outs() << " rcx " << format("0x%016" PRIx64"l" "x", cpu64.rcx) << "\n";
8470 outs() << " rdx " << format("0x%016" PRIx64"l" "x", cpu64.rdx);
8471 outs() << " rdi " << format("0x%016" PRIx64"l" "x", cpu64.rdi);
8472 outs() << " rsi " << format("0x%016" PRIx64"l" "x", cpu64.rsi) << "\n";
8473 outs() << " rbp " << format("0x%016" PRIx64"l" "x", cpu64.rbp);
8474 outs() << " rsp " << format("0x%016" PRIx64"l" "x", cpu64.rsp);
8475 outs() << " r8 " << format("0x%016" PRIx64"l" "x", cpu64.r8) << "\n";
8476 outs() << " r9 " << format("0x%016" PRIx64"l" "x", cpu64.r9);
8477 outs() << " r10 " << format("0x%016" PRIx64"l" "x", cpu64.r10);
8478 outs() << " r11 " << format("0x%016" PRIx64"l" "x", cpu64.r11) << "\n";
8479 outs() << " r12 " << format("0x%016" PRIx64"l" "x", cpu64.r12);
8480 outs() << " r13 " << format("0x%016" PRIx64"l" "x", cpu64.r13);
8481 outs() << " r14 " << format("0x%016" PRIx64"l" "x", cpu64.r14) << "\n";
8482 outs() << " r15 " << format("0x%016" PRIx64"l" "x", cpu64.r15);
8483 outs() << " rip " << format("0x%016" PRIx64"l" "x", cpu64.rip) << "\n";
8484 outs() << "rflags " << format("0x%016" PRIx64"l" "x", cpu64.rflags);
8485 outs() << " cs " << format("0x%016" PRIx64"l" "x", cpu64.cs);
8486 outs() << " fs " << format("0x%016" PRIx64"l" "x", cpu64.fs) << "\n";
8487 outs() << " gs " << format("0x%016" PRIx64"l" "x", cpu64.gs) << "\n";
8488}
8489
8490static void Print_mmst_reg(MachO::mmst_reg_t &r) {
8491 uint32_t f;
8492 outs() << "\t mmst_reg ";
8493 for (f = 0; f < 10; f++)
8494 outs() << format("%02" PRIx32"x", (r.mmst_reg[f] & 0xff)) << " ";
8495 outs() << "\n";
8496 outs() << "\t mmst_rsrv ";
8497 for (f = 0; f < 6; f++)
8498 outs() << format("%02" PRIx32"x", (r.mmst_rsrv[f] & 0xff)) << " ";
8499 outs() << "\n";
8500}
8501
8502static void Print_xmm_reg(MachO::xmm_reg_t &r) {
8503 uint32_t f;
8504 outs() << "\t xmm_reg ";
8505 for (f = 0; f < 16; f++)
8506 outs() << format("%02" PRIx32"x", (r.xmm_reg[f] & 0xff)) << " ";
8507 outs() << "\n";
8508}
8509
8510static void Print_x86_float_state_t(MachO::x86_float_state64_t &fpu) {
8511 outs() << "\t fpu_reserved[0] " << fpu.fpu_reserved[0];
8512 outs() << " fpu_reserved[1] " << fpu.fpu_reserved[1] << "\n";
8513 outs() << "\t control: invalid " << fpu.fpu_fcw.invalid;
8514 outs() << " denorm " << fpu.fpu_fcw.denorm;
8515 outs() << " zdiv " << fpu.fpu_fcw.zdiv;
8516 outs() << " ovrfl " << fpu.fpu_fcw.ovrfl;
8517 outs() << " undfl " << fpu.fpu_fcw.undfl;
8518 outs() << " precis " << fpu.fpu_fcw.precis << "\n";
8519 outs() << "\t\t pc ";
8520 if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_24B)
8521 outs() << "FP_PREC_24B ";
8522 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_53B)
8523 outs() << "FP_PREC_53B ";
8524 else if (fpu.fpu_fcw.pc == MachO::x86_FP_PREC_64B)
8525 outs() << "FP_PREC_64B ";
8526 else
8527 outs() << fpu.fpu_fcw.pc << " ";
8528 outs() << "rc ";
8529 if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_NEAR)
8530 outs() << "FP_RND_NEAR ";
8531 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_DOWN)
8532 outs() << "FP_RND_DOWN ";
8533 else if (fpu.fpu_fcw.rc == MachO::x86_FP_RND_UP)
8534 outs() << "FP_RND_UP ";
8535 else if (fpu.fpu_fcw.rc == MachO::x86_FP_CHOP)
8536 outs() << "FP_CHOP ";
8537 outs() << "\n";
8538 outs() << "\t status: invalid " << fpu.fpu_fsw.invalid;
8539 outs() << " denorm " << fpu.fpu_fsw.denorm;
8540 outs() << " zdiv " << fpu.fpu_fsw.zdiv;
8541 outs() << " ovrfl " << fpu.fpu_fsw.ovrfl;
8542 outs() << " undfl " << fpu.fpu_fsw.undfl;
8543 outs() << " precis " << fpu.fpu_fsw.precis;
8544 outs() << " stkflt " << fpu.fpu_fsw.stkflt << "\n";
8545 outs() << "\t errsumm " << fpu.fpu_fsw.errsumm;
8546 outs() << " c0 " << fpu.fpu_fsw.c0;
8547 outs() << " c1 " << fpu.fpu_fsw.c1;
8548 outs() << " c2 " << fpu.fpu_fsw.c2;
8549 outs() << " tos " << fpu.fpu_fsw.tos;
8550 outs() << " c3 " << fpu.fpu_fsw.c3;
8551 outs() << " busy " << fpu.fpu_fsw.busy << "\n";
8552 outs() << "\t fpu_ftw " << format("0x%02" PRIx32"x", fpu.fpu_ftw);
8553 outs() << " fpu_rsrv1 " << format("0x%02" PRIx32"x", fpu.fpu_rsrv1);
8554 outs() << " fpu_fop " << format("0x%04" PRIx32"x", fpu.fpu_fop);
8555 outs() << " fpu_ip " << format("0x%08" PRIx32"x", fpu.fpu_ip) << "\n";
8556 outs() << "\t fpu_cs " << format("0x%04" PRIx32"x", fpu.fpu_cs);
8557 outs() << " fpu_rsrv2 " << format("0x%04" PRIx32"x", fpu.fpu_rsrv2);
8558 outs() << " fpu_dp " << format("0x%08" PRIx32"x", fpu.fpu_dp);
8559 outs() << " fpu_ds " << format("0x%04" PRIx32"x", fpu.fpu_ds) << "\n";
8560 outs() << "\t fpu_rsrv3 " << format("0x%04" PRIx32"x", fpu.fpu_rsrv3);
8561 outs() << " fpu_mxcsr " << format("0x%08" PRIx32"x", fpu.fpu_mxcsr);
8562 outs() << " fpu_mxcsrmask " << format("0x%08" PRIx32"x", fpu.fpu_mxcsrmask);
8563 outs() << "\n";
8564 outs() << "\t fpu_stmm0:\n";
8565 Print_mmst_reg(fpu.fpu_stmm0);
8566 outs() << "\t fpu_stmm1:\n";
8567 Print_mmst_reg(fpu.fpu_stmm1);
8568 outs() << "\t fpu_stmm2:\n";
8569 Print_mmst_reg(fpu.fpu_stmm2);
8570 outs() << "\t fpu_stmm3:\n";
8571 Print_mmst_reg(fpu.fpu_stmm3);
8572 outs() << "\t fpu_stmm4:\n";
8573 Print_mmst_reg(fpu.fpu_stmm4);
8574 outs() << "\t fpu_stmm5:\n";
8575 Print_mmst_reg(fpu.fpu_stmm5);
8576 outs() << "\t fpu_stmm6:\n";
8577 Print_mmst_reg(fpu.fpu_stmm6);
8578 outs() << "\t fpu_stmm7:\n";
8579 Print_mmst_reg(fpu.fpu_stmm7);
8580 outs() << "\t fpu_xmm0:\n";
8581 Print_xmm_reg(fpu.fpu_xmm0);
8582 outs() << "\t fpu_xmm1:\n";
8583 Print_xmm_reg(fpu.fpu_xmm1);
8584 outs() << "\t fpu_xmm2:\n";
8585 Print_xmm_reg(fpu.fpu_xmm2);
8586 outs() << "\t fpu_xmm3:\n";
8587 Print_xmm_reg(fpu.fpu_xmm3);
8588 outs() << "\t fpu_xmm4:\n";
8589 Print_xmm_reg(fpu.fpu_xmm4);
8590 outs() << "\t fpu_xmm5:\n";
8591 Print_xmm_reg(fpu.fpu_xmm5);
8592 outs() << "\t fpu_xmm6:\n";
8593 Print_xmm_reg(fpu.fpu_xmm6);
8594 outs() << "\t fpu_xmm7:\n";
8595 Print_xmm_reg(fpu.fpu_xmm7);
8596 outs() << "\t fpu_xmm8:\n";
8597 Print_xmm_reg(fpu.fpu_xmm8);
8598 outs() << "\t fpu_xmm9:\n";
8599 Print_xmm_reg(fpu.fpu_xmm9);
8600 outs() << "\t fpu_xmm10:\n";
8601 Print_xmm_reg(fpu.fpu_xmm10);
8602 outs() << "\t fpu_xmm11:\n";
8603 Print_xmm_reg(fpu.fpu_xmm11);
8604 outs() << "\t fpu_xmm12:\n";
8605 Print_xmm_reg(fpu.fpu_xmm12);
8606 outs() << "\t fpu_xmm13:\n";
8607 Print_xmm_reg(fpu.fpu_xmm13);
8608 outs() << "\t fpu_xmm14:\n";
8609 Print_xmm_reg(fpu.fpu_xmm14);
8610 outs() << "\t fpu_xmm15:\n";
8611 Print_xmm_reg(fpu.fpu_xmm15);
8612 outs() << "\t fpu_rsrv4:\n";
8613 for (uint32_t f = 0; f < 6; f++) {
8614 outs() << "\t ";
8615 for (uint32_t g = 0; g < 16; g++)
8616 outs() << format("%02" PRIx32"x", fpu.fpu_rsrv4[f * g]) << " ";
8617 outs() << "\n";
8618 }
8619 outs() << "\t fpu_reserved1 " << format("0x%08" PRIx32"x", fpu.fpu_reserved1);
8620 outs() << "\n";
8621}
8622
8623static void Print_x86_exception_state_t(MachO::x86_exception_state64_t &exc64) {
8624 outs() << "\t trapno " << format("0x%08" PRIx32"x", exc64.trapno);
8625 outs() << " err " << format("0x%08" PRIx32"x", exc64.err);
8626 outs() << " faultvaddr " << format("0x%016" PRIx64"l" "x", exc64.faultvaddr) << "\n";
8627}
8628
8629static void Print_arm_thread_state32_t(MachO::arm_thread_state32_t &cpu32) {
8630 outs() << "\t r0 " << format("0x%08" PRIx32"x", cpu32.r[0]);
8631 outs() << " r1 " << format("0x%08" PRIx32"x", cpu32.r[1]);
8632 outs() << " r2 " << format("0x%08" PRIx32"x", cpu32.r[2]);
8633 outs() << " r3 " << format("0x%08" PRIx32"x", cpu32.r[3]) << "\n";
8634 outs() << "\t r4 " << format("0x%08" PRIx32"x", cpu32.r[4]);
8635 outs() << " r5 " << format("0x%08" PRIx32"x", cpu32.r[5]);
8636 outs() << " r6 " << format("0x%08" PRIx32"x", cpu32.r[6]);
8637 outs() << " r7 " << format("0x%08" PRIx32"x", cpu32.r[7]) << "\n";
8638 outs() << "\t r8 " << format("0x%08" PRIx32"x", cpu32.r[8]);
8639 outs() << " r9 " << format("0x%08" PRIx32"x", cpu32.r[9]);
8640 outs() << " r10 " << format("0x%08" PRIx32"x", cpu32.r[10]);
8641 outs() << " r11 " << format("0x%08" PRIx32"x", cpu32.r[11]) << "\n";
8642 outs() << "\t r12 " << format("0x%08" PRIx32"x", cpu32.r[12]);
8643 outs() << " sp " << format("0x%08" PRIx32"x", cpu32.sp);
8644 outs() << " lr " << format("0x%08" PRIx32"x", cpu32.lr);
8645 outs() << " pc " << format("0x%08" PRIx32"x", cpu32.pc) << "\n";
8646 outs() << "\t cpsr " << format("0x%08" PRIx32"x", cpu32.cpsr) << "\n";
8647}
8648
8649static void Print_arm_thread_state64_t(MachO::arm_thread_state64_t &cpu64) {
8650 outs() << "\t x0 " << format("0x%016" PRIx64"l" "x", cpu64.x[0]);
8651 outs() << " x1 " << format("0x%016" PRIx64"l" "x", cpu64.x[1]);
8652 outs() << " x2 " << format("0x%016" PRIx64"l" "x", cpu64.x[2]) << "\n";
8653 outs() << "\t x3 " << format("0x%016" PRIx64"l" "x", cpu64.x[3]);
8654 outs() << " x4 " << format("0x%016" PRIx64"l" "x", cpu64.x[4]);
8655 outs() << " x5 " << format("0x%016" PRIx64"l" "x", cpu64.x[5]) << "\n";
8656 outs() << "\t x6 " << format("0x%016" PRIx64"l" "x", cpu64.x[6]);
8657 outs() << " x7 " << format("0x%016" PRIx64"l" "x", cpu64.x[7]);
8658 outs() << " x8 " << format("0x%016" PRIx64"l" "x", cpu64.x[8]) << "\n";
8659 outs() << "\t x9 " << format("0x%016" PRIx64"l" "x", cpu64.x[9]);
8660 outs() << " x10 " << format("0x%016" PRIx64"l" "x", cpu64.x[10]);
8661 outs() << " x11 " << format("0x%016" PRIx64"l" "x", cpu64.x[11]) << "\n";
8662 outs() << "\t x12 " << format("0x%016" PRIx64"l" "x", cpu64.x[12]);
8663 outs() << " x13 " << format("0x%016" PRIx64"l" "x", cpu64.x[13]);
8664 outs() << " x14 " << format("0x%016" PRIx64"l" "x", cpu64.x[14]) << "\n";
8665 outs() << "\t x15 " << format("0x%016" PRIx64"l" "x", cpu64.x[15]);
8666 outs() << " x16 " << format("0x%016" PRIx64"l" "x", cpu64.x[16]);
8667 outs() << " x17 " << format("0x%016" PRIx64"l" "x", cpu64.x[17]) << "\n";
8668 outs() << "\t x18 " << format("0x%016" PRIx64"l" "x", cpu64.x[18]);
8669 outs() << " x19 " << format("0x%016" PRIx64"l" "x", cpu64.x[19]);
8670 outs() << " x20 " << format("0x%016" PRIx64"l" "x", cpu64.x[20]) << "\n";
8671 outs() << "\t x21 " << format("0x%016" PRIx64"l" "x", cpu64.x[21]);
8672 outs() << " x22 " << format("0x%016" PRIx64"l" "x", cpu64.x[22]);
8673 outs() << " x23 " << format("0x%016" PRIx64"l" "x", cpu64.x[23]) << "\n";
8674 outs() << "\t x24 " << format("0x%016" PRIx64"l" "x", cpu64.x[24]);
8675 outs() << " x25 " << format("0x%016" PRIx64"l" "x", cpu64.x[25]);
8676 outs() << " x26 " << format("0x%016" PRIx64"l" "x", cpu64.x[26]) << "\n";
8677 outs() << "\t x27 " << format("0x%016" PRIx64"l" "x", cpu64.x[27]);
8678 outs() << " x28 " << format("0x%016" PRIx64"l" "x", cpu64.x[28]);
8679 outs() << " fp " << format("0x%016" PRIx64"l" "x", cpu64.fp) << "\n";
8680 outs() << "\t lr " << format("0x%016" PRIx64"l" "x", cpu64.lr);
8681 outs() << " sp " << format("0x%016" PRIx64"l" "x", cpu64.sp);
8682 outs() << " pc " << format("0x%016" PRIx64"l" "x", cpu64.pc) << "\n";
8683 outs() << "\t cpsr " << format("0x%08" PRIx32"x", cpu64.cpsr) << "\n";
8684}
8685
8686static void PrintThreadCommand(MachO::thread_command t, const char *Ptr,
8687 bool isLittleEndian, uint32_t cputype) {
8688 if (t.cmd == MachO::LC_THREAD)
8689 outs() << " cmd LC_THREAD\n";
8690 else if (t.cmd == MachO::LC_UNIXTHREAD)
8691 outs() << " cmd LC_UNIXTHREAD\n";
8692 else
8693 outs() << " cmd " << t.cmd << " (unknown)\n";
8694 outs() << " cmdsize " << t.cmdsize;
8695 if (t.cmdsize < sizeof(struct MachO::thread_command) + 2 * sizeof(uint32_t))
8696 outs() << " Incorrect size\n";
8697 else
8698 outs() << "\n";
8699
8700 const char *begin = Ptr + sizeof(struct MachO::thread_command);
8701 const char *end = Ptr + t.cmdsize;
8702 uint32_t flavor, count, left;
8703 if (cputype == MachO::CPU_TYPE_X86_64) {
8704 while (begin < end) {
8705 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8706 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8707 begin += sizeof(uint32_t);
8708 } else {
8709 flavor = 0;
8710 begin = end;
8711 }
8712 if (isLittleEndian != sys::IsLittleEndianHost)
8713 sys::swapByteOrder(flavor);
8714 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8715 memcpy((char *)&count, begin, sizeof(uint32_t));
8716 begin += sizeof(uint32_t);
8717 } else {
8718 count = 0;
8719 begin = end;
8720 }
8721 if (isLittleEndian != sys::IsLittleEndianHost)
8722 sys::swapByteOrder(count);
8723 if (flavor == MachO::x86_THREAD_STATE64) {
8724 outs() << " flavor x86_THREAD_STATE64\n";
8725 if (count == MachO::x86_THREAD_STATE64_COUNT)
8726 outs() << " count x86_THREAD_STATE64_COUNT\n";
8727 else
8728 outs() << " count " << count
8729 << " (not x86_THREAD_STATE64_COUNT)\n";
8730 MachO::x86_thread_state64_t cpu64;
8731 left = end - begin;
8732 if (left >= sizeof(MachO::x86_thread_state64_t)) {
8733 memcpy(&cpu64, begin, sizeof(MachO::x86_thread_state64_t));
8734 begin += sizeof(MachO::x86_thread_state64_t);
8735 } else {
8736 memset(&cpu64, '\0', sizeof(MachO::x86_thread_state64_t));
8737 memcpy(&cpu64, begin, left);
8738 begin += left;
8739 }
8740 if (isLittleEndian != sys::IsLittleEndianHost)
8741 swapStruct(cpu64);
8742 Print_x86_thread_state64_t(cpu64);
8743 } else if (flavor == MachO::x86_THREAD_STATE) {
8744 outs() << " flavor x86_THREAD_STATE\n";
8745 if (count == MachO::x86_THREAD_STATE_COUNT)
8746 outs() << " count x86_THREAD_STATE_COUNT\n";
8747 else
8748 outs() << " count " << count
8749 << " (not x86_THREAD_STATE_COUNT)\n";
8750 struct MachO::x86_thread_state_t ts;
8751 left = end - begin;
8752 if (left >= sizeof(MachO::x86_thread_state_t)) {
8753 memcpy(&ts, begin, sizeof(MachO::x86_thread_state_t));
8754 begin += sizeof(MachO::x86_thread_state_t);
8755 } else {
8756 memset(&ts, '\0', sizeof(MachO::x86_thread_state_t));
8757 memcpy(&ts, begin, left);
8758 begin += left;
8759 }
8760 if (isLittleEndian != sys::IsLittleEndianHost)
8761 swapStruct(ts);
8762 if (ts.tsh.flavor == MachO::x86_THREAD_STATE64) {
8763 outs() << "\t tsh.flavor x86_THREAD_STATE64 ";
8764 if (ts.tsh.count == MachO::x86_THREAD_STATE64_COUNT)
8765 outs() << "tsh.count x86_THREAD_STATE64_COUNT\n";
8766 else
8767 outs() << "tsh.count " << ts.tsh.count
8768 << " (not x86_THREAD_STATE64_COUNT\n";
8769 Print_x86_thread_state64_t(ts.uts.ts64);
8770 } else {
8771 outs() << "\t tsh.flavor " << ts.tsh.flavor << " tsh.count "
8772 << ts.tsh.count << "\n";
8773 }
8774 } else if (flavor == MachO::x86_FLOAT_STATE) {
8775 outs() << " flavor x86_FLOAT_STATE\n";
8776 if (count == MachO::x86_FLOAT_STATE_COUNT)
8777 outs() << " count x86_FLOAT_STATE_COUNT\n";
8778 else
8779 outs() << " count " << count << " (not x86_FLOAT_STATE_COUNT)\n";
8780 struct MachO::x86_float_state_t fs;
8781 left = end - begin;
8782 if (left >= sizeof(MachO::x86_float_state_t)) {
8783 memcpy(&fs, begin, sizeof(MachO::x86_float_state_t));
8784 begin += sizeof(MachO::x86_float_state_t);
8785 } else {
8786 memset(&fs, '\0', sizeof(MachO::x86_float_state_t));
8787 memcpy(&fs, begin, left);
8788 begin += left;
8789 }
8790 if (isLittleEndian != sys::IsLittleEndianHost)
8791 swapStruct(fs);
8792 if (fs.fsh.flavor == MachO::x86_FLOAT_STATE64) {
8793 outs() << "\t fsh.flavor x86_FLOAT_STATE64 ";
8794 if (fs.fsh.count == MachO::x86_FLOAT_STATE64_COUNT)
8795 outs() << "fsh.count x86_FLOAT_STATE64_COUNT\n";
8796 else
8797 outs() << "fsh.count " << fs.fsh.count
8798 << " (not x86_FLOAT_STATE64_COUNT\n";
8799 Print_x86_float_state_t(fs.ufs.fs64);
8800 } else {
8801 outs() << "\t fsh.flavor " << fs.fsh.flavor << " fsh.count "
8802 << fs.fsh.count << "\n";
8803 }
8804 } else if (flavor == MachO::x86_EXCEPTION_STATE) {
8805 outs() << " flavor x86_EXCEPTION_STATE\n";
8806 if (count == MachO::x86_EXCEPTION_STATE_COUNT)
8807 outs() << " count x86_EXCEPTION_STATE_COUNT\n";
8808 else
8809 outs() << " count " << count
8810 << " (not x86_EXCEPTION_STATE_COUNT)\n";
8811 struct MachO::x86_exception_state_t es;
8812 left = end - begin;
8813 if (left >= sizeof(MachO::x86_exception_state_t)) {
8814 memcpy(&es, begin, sizeof(MachO::x86_exception_state_t));
8815 begin += sizeof(MachO::x86_exception_state_t);
8816 } else {
8817 memset(&es, '\0', sizeof(MachO::x86_exception_state_t));
8818 memcpy(&es, begin, left);
8819 begin += left;
8820 }
8821 if (isLittleEndian != sys::IsLittleEndianHost)
8822 swapStruct(es);
8823 if (es.esh.flavor == MachO::x86_EXCEPTION_STATE64) {
8824 outs() << "\t esh.flavor x86_EXCEPTION_STATE64\n";
8825 if (es.esh.count == MachO::x86_EXCEPTION_STATE64_COUNT)
8826 outs() << "\t esh.count x86_EXCEPTION_STATE64_COUNT\n";
8827 else
8828 outs() << "\t esh.count " << es.esh.count
8829 << " (not x86_EXCEPTION_STATE64_COUNT\n";
8830 Print_x86_exception_state_t(es.ues.es64);
8831 } else {
8832 outs() << "\t esh.flavor " << es.esh.flavor << " esh.count "
8833 << es.esh.count << "\n";
8834 }
8835 } else {
8836 outs() << " flavor " << flavor << " (unknown)\n";
8837 outs() << " count " << count << "\n";
8838 outs() << " state (unknown)\n";
8839 begin += count * sizeof(uint32_t);
8840 }
8841 }
8842 } else if (cputype == MachO::CPU_TYPE_ARM) {
8843 while (begin < end) {
8844 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8845 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8846 begin += sizeof(uint32_t);
8847 } else {
8848 flavor = 0;
8849 begin = end;
8850 }
8851 if (isLittleEndian != sys::IsLittleEndianHost)
8852 sys::swapByteOrder(flavor);
8853 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8854 memcpy((char *)&count, begin, sizeof(uint32_t));
8855 begin += sizeof(uint32_t);
8856 } else {
8857 count = 0;
8858 begin = end;
8859 }
8860 if (isLittleEndian != sys::IsLittleEndianHost)
8861 sys::swapByteOrder(count);
8862 if (flavor == MachO::ARM_THREAD_STATE) {
8863 outs() << " flavor ARM_THREAD_STATE\n";
8864 if (count == MachO::ARM_THREAD_STATE_COUNT)
8865 outs() << " count ARM_THREAD_STATE_COUNT\n";
8866 else
8867 outs() << " count " << count
8868 << " (not ARM_THREAD_STATE_COUNT)\n";
8869 MachO::arm_thread_state32_t cpu32;
8870 left = end - begin;
8871 if (left >= sizeof(MachO::arm_thread_state32_t)) {
8872 memcpy(&cpu32, begin, sizeof(MachO::arm_thread_state32_t));
8873 begin += sizeof(MachO::arm_thread_state32_t);
8874 } else {
8875 memset(&cpu32, '\0', sizeof(MachO::arm_thread_state32_t));
8876 memcpy(&cpu32, begin, left);
8877 begin += left;
8878 }
8879 if (isLittleEndian != sys::IsLittleEndianHost)
8880 swapStruct(cpu32);
8881 Print_arm_thread_state32_t(cpu32);
8882 } else {
8883 outs() << " flavor " << flavor << " (unknown)\n";
8884 outs() << " count " << count << "\n";
8885 outs() << " state (unknown)\n";
8886 begin += count * sizeof(uint32_t);
8887 }
8888 }
8889 } else if (cputype == MachO::CPU_TYPE_ARM64) {
8890 while (begin < end) {
8891 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8892 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8893 begin += sizeof(uint32_t);
8894 } else {
8895 flavor = 0;
8896 begin = end;
8897 }
8898 if (isLittleEndian != sys::IsLittleEndianHost)
8899 sys::swapByteOrder(flavor);
8900 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8901 memcpy((char *)&count, begin, sizeof(uint32_t));
8902 begin += sizeof(uint32_t);
8903 } else {
8904 count = 0;
8905 begin = end;
8906 }
8907 if (isLittleEndian != sys::IsLittleEndianHost)
8908 sys::swapByteOrder(count);
8909 if (flavor == MachO::ARM_THREAD_STATE64) {
8910 outs() << " flavor ARM_THREAD_STATE64\n";
8911 if (count == MachO::ARM_THREAD_STATE64_COUNT)
8912 outs() << " count ARM_THREAD_STATE64_COUNT\n";
8913 else
8914 outs() << " count " << count
8915 << " (not ARM_THREAD_STATE64_COUNT)\n";
8916 MachO::arm_thread_state64_t cpu64;
8917 left = end - begin;
8918 if (left >= sizeof(MachO::arm_thread_state64_t)) {
8919 memcpy(&cpu64, begin, sizeof(MachO::arm_thread_state64_t));
8920 begin += sizeof(MachO::arm_thread_state64_t);
8921 } else {
8922 memset(&cpu64, '\0', sizeof(MachO::arm_thread_state64_t));
8923 memcpy(&cpu64, begin, left);
8924 begin += left;
8925 }
8926 if (isLittleEndian != sys::IsLittleEndianHost)
8927 swapStruct(cpu64);
8928 Print_arm_thread_state64_t(cpu64);
8929 } else {
8930 outs() << " flavor " << flavor << " (unknown)\n";
8931 outs() << " count " << count << "\n";
8932 outs() << " state (unknown)\n";
8933 begin += count * sizeof(uint32_t);
8934 }
8935 }
8936 } else {
8937 while (begin < end) {
8938 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8939 memcpy((char *)&flavor, begin, sizeof(uint32_t));
8940 begin += sizeof(uint32_t);
8941 } else {
8942 flavor = 0;
8943 begin = end;
8944 }
8945 if (isLittleEndian != sys::IsLittleEndianHost)
8946 sys::swapByteOrder(flavor);
8947 if (end - begin > (ptrdiff_t)sizeof(uint32_t)) {
8948 memcpy((char *)&count, begin, sizeof(uint32_t));
8949 begin += sizeof(uint32_t);
8950 } else {
8951 count = 0;
8952 begin = end;
8953 }
8954 if (isLittleEndian != sys::IsLittleEndianHost)
8955 sys::swapByteOrder(count);
8956 outs() << " flavor " << flavor << "\n";
8957 outs() << " count " << count << "\n";
8958 outs() << " state (Unknown cputype/cpusubtype)\n";
8959 begin += count * sizeof(uint32_t);
8960 }
8961 }
8962}
8963
8964static void PrintDylibCommand(MachO::dylib_command dl, const char *Ptr) {
8965 if (dl.cmd == MachO::LC_ID_DYLIB)
8966 outs() << " cmd LC_ID_DYLIB\n";
8967 else if (dl.cmd == MachO::LC_LOAD_DYLIB)
8968 outs() << " cmd LC_LOAD_DYLIB\n";
8969 else if (dl.cmd == MachO::LC_LOAD_WEAK_DYLIB)
8970 outs() << " cmd LC_LOAD_WEAK_DYLIB\n";
8971 else if (dl.cmd == MachO::LC_REEXPORT_DYLIB)
8972 outs() << " cmd LC_REEXPORT_DYLIB\n";
8973 else if (dl.cmd == MachO::LC_LAZY_LOAD_DYLIB)
8974 outs() << " cmd LC_LAZY_LOAD_DYLIB\n";
8975 else if (dl.cmd == MachO::LC_LOAD_UPWARD_DYLIB)
8976 outs() << " cmd LC_LOAD_UPWARD_DYLIB\n";
8977 else
8978 outs() << " cmd " << dl.cmd << " (unknown)\n";
8979 outs() << " cmdsize " << dl.cmdsize;
8980 if (dl.cmdsize < sizeof(struct MachO::dylib_command))
8981 outs() << " Incorrect size\n";
8982 else
8983 outs() << "\n";
8984 if (dl.dylib.name < dl.cmdsize) {
8985 const char *P = (const char *)(Ptr) + dl.dylib.name;
8986 outs() << " name " << P << " (offset " << dl.dylib.name << ")\n";
8987 } else {
8988 outs() << " name ?(bad offset " << dl.dylib.name << ")\n";
8989 }
8990 outs() << " time stamp " << dl.dylib.timestamp << " ";
8991 time_t t = dl.dylib.timestamp;
8992 outs() << ctime(&t);
8993 outs() << " current version ";
8994 if (dl.dylib.current_version == 0xffffffff)
8995 outs() << "n/a\n";
8996 else
8997 outs() << ((dl.dylib.current_version >> 16) & 0xffff) << "."
8998 << ((dl.dylib.current_version >> 8) & 0xff) << "."
8999 << (dl.dylib.current_version & 0xff) << "\n";
9000 outs() << "compatibility version ";
9001 if (dl.dylib.compatibility_version == 0xffffffff)
9002 outs() << "n/a\n";
9003 else
9004 outs() << ((dl.dylib.compatibility_version >> 16) & 0xffff) << "."
9005 << ((dl.dylib.compatibility_version >> 8) & 0xff) << "."
9006 << (dl.dylib.compatibility_version & 0xff) << "\n";
9007}
9008
9009static void PrintLinkEditDataCommand(MachO::linkedit_data_command ld,
9010 uint32_t object_size) {
9011 if (ld.cmd == MachO::LC_CODE_SIGNATURE)
9012 outs() << " cmd LC_CODE_SIGNATURE\n";
9013 else if (ld.cmd == MachO::LC_SEGMENT_SPLIT_INFO)
9014 outs() << " cmd LC_SEGMENT_SPLIT_INFO\n";
9015 else if (ld.cmd == MachO::LC_FUNCTION_STARTS)
9016 outs() << " cmd LC_FUNCTION_STARTS\n";
9017 else if (ld.cmd == MachO::LC_DATA_IN_CODE)
9018 outs() << " cmd LC_DATA_IN_CODE\n";
9019 else if (ld.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS)
9020 outs() << " cmd LC_DYLIB_CODE_SIGN_DRS\n";
9021 else if (ld.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT)
9022 outs() << " cmd LC_LINKER_OPTIMIZATION_HINT\n";
9023 else
9024 outs() << " cmd " << ld.cmd << " (?)\n";
9025 outs() << " cmdsize " << ld.cmdsize;
9026 if (ld.cmdsize != sizeof(struct MachO::linkedit_data_command))
9027 outs() << " Incorrect size\n";
9028 else
9029 outs() << "\n";
9030 outs() << " dataoff " << ld.dataoff;
9031 if (ld.dataoff > object_size)
9032 outs() << " (past end of file)\n";
9033 else
9034 outs() << "\n";
9035 outs() << " datasize " << ld.datasize;
9036 uint64_t big_size = ld.dataoff;
9037 big_size += ld.datasize;
9038 if (big_size > object_size)
9039 outs() << " (past end of file)\n";
9040 else
9041 outs() << "\n";
9042}
9043
9044static void PrintLoadCommands(const MachOObjectFile *Obj, uint32_t filetype,
9045 uint32_t cputype, bool verbose) {
9046 StringRef Buf = Obj->getData();
9047 unsigned Index = 0;
9048 for (const auto &Command : Obj->load_commands()) {
9049 outs() << "Load command " << Index++ << "\n";
9050 if (Command.C.cmd == MachO::LC_SEGMENT) {
9051 MachO::segment_command SLC = Obj->getSegmentLoadCommand(Command);
9052 const char *sg_segname = SLC.segname;
9053 PrintSegmentCommand(SLC.cmd, SLC.cmdsize, SLC.segname, SLC.vmaddr,
9054 SLC.vmsize, SLC.fileoff, SLC.filesize, SLC.maxprot,
9055 SLC.initprot, SLC.nsects, SLC.flags, Buf.size(),
9056 verbose);
9057 for (unsigned j = 0; j < SLC.nsects; j++) {
9058 MachO::section S = Obj->getSection(Command, j);
9059 PrintSection(S.sectname, S.segname, S.addr, S.size, S.offset, S.align,
9060 S.reloff, S.nreloc, S.flags, S.reserved1, S.reserved2,
9061 SLC.cmd, sg_segname, filetype, Buf.size(), verbose);
9062 }
9063 } else if (Command.C.cmd == MachO::LC_SEGMENT_64) {
9064 MachO::segment_command_64 SLC_64 = Obj->getSegment64LoadCommand(Command);
9065 const char *sg_segname = SLC_64.segname;
9066 PrintSegmentCommand(SLC_64.cmd, SLC_64.cmdsize, SLC_64.segname,
9067 SLC_64.vmaddr, SLC_64.vmsize, SLC_64.fileoff,
9068 SLC_64.filesize, SLC_64.maxprot, SLC_64.initprot,
9069 SLC_64.nsects, SLC_64.flags, Buf.size(), verbose);
9070 for (unsigned j = 0; j < SLC_64.nsects; j++) {
9071 MachO::section_64 S_64 = Obj->getSection64(Command, j);
9072 PrintSection(S_64.sectname, S_64.segname, S_64.addr, S_64.size,
9073 S_64.offset, S_64.align, S_64.reloff, S_64.nreloc,
9074 S_64.flags, S_64.reserved1, S_64.reserved2, SLC_64.cmd,
9075 sg_segname, filetype, Buf.size(), verbose);
9076 }
9077 } else if (Command.C.cmd == MachO::LC_SYMTAB) {
9078 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9079 PrintSymtabLoadCommand(Symtab, Obj->is64Bit(), Buf.size());
9080 } else if (Command.C.cmd == MachO::LC_DYSYMTAB) {
9081 MachO::dysymtab_command Dysymtab = Obj->getDysymtabLoadCommand();
9082 MachO::symtab_command Symtab = Obj->getSymtabLoadCommand();
9083 PrintDysymtabLoadCommand(Dysymtab, Symtab.nsyms, Buf.size(),
9084 Obj->is64Bit());
9085 } else if (Command.C.cmd == MachO::LC_DYLD_INFO ||
9086 Command.C.cmd == MachO::LC_DYLD_INFO_ONLY) {
9087 MachO::dyld_info_command DyldInfo = Obj->getDyldInfoLoadCommand(Command);
9088 PrintDyldInfoLoadCommand(DyldInfo, Buf.size());
9089 } else if (Command.C.cmd == MachO::LC_LOAD_DYLINKER ||
9090 Command.C.cmd == MachO::LC_ID_DYLINKER ||
9091 Command.C.cmd == MachO::LC_DYLD_ENVIRONMENT) {
9092 MachO::dylinker_command Dyld = Obj->getDylinkerCommand(Command);
9093 PrintDyldLoadCommand(Dyld, Command.Ptr);
9094 } else if (Command.C.cmd == MachO::LC_UUID) {
9095 MachO::uuid_command Uuid = Obj->getUuidCommand(Command);
9096 PrintUuidLoadCommand(Uuid);
9097 } else if (Command.C.cmd == MachO::LC_RPATH) {
9098 MachO::rpath_command Rpath = Obj->getRpathCommand(Command);
9099 PrintRpathLoadCommand(Rpath, Command.Ptr);
9100 } else if (Command.C.cmd == MachO::LC_VERSION_MIN_MACOSX ||
9101 Command.C.cmd == MachO::LC_VERSION_MIN_IPHONEOS ||
9102 Command.C.cmd == MachO::LC_VERSION_MIN_TVOS ||
9103 Command.C.cmd == MachO::LC_VERSION_MIN_WATCHOS) {
9104 MachO::version_min_command Vd = Obj->getVersionMinLoadCommand(Command);
9105 PrintVersionMinLoadCommand(Vd);
9106 } else if (Command.C.cmd == MachO::LC_SOURCE_VERSION) {
9107 MachO::source_version_command Sd = Obj->getSourceVersionCommand(Command);
9108 PrintSourceVersionCommand(Sd);
9109 } else if (Command.C.cmd == MachO::LC_MAIN) {
9110 MachO::entry_point_command Ep = Obj->getEntryPointCommand(Command);
9111 PrintEntryPointCommand(Ep);
9112 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO) {
9113 MachO::encryption_info_command Ei =
9114 Obj->getEncryptionInfoCommand(Command);
9115 PrintEncryptionInfoCommand(Ei, Buf.size());
9116 } else if (Command.C.cmd == MachO::LC_ENCRYPTION_INFO_64) {
9117 MachO::encryption_info_command_64 Ei =
9118 Obj->getEncryptionInfoCommand64(Command);
9119 PrintEncryptionInfoCommand64(Ei, Buf.size());
9120 } else if (Command.C.cmd == MachO::LC_LINKER_OPTION) {
9121 MachO::linker_option_command Lo =
9122 Obj->getLinkerOptionLoadCommand(Command);
9123 PrintLinkerOptionCommand(Lo, Command.Ptr);
9124 } else if (Command.C.cmd == MachO::LC_SUB_FRAMEWORK) {
9125 MachO::sub_framework_command Sf = Obj->getSubFrameworkCommand(Command);
9126 PrintSubFrameworkCommand(Sf, Command.Ptr);
9127 } else if (Command.C.cmd == MachO::LC_SUB_UMBRELLA) {
9128 MachO::sub_umbrella_command Sf = Obj->getSubUmbrellaCommand(Command);
9129 PrintSubUmbrellaCommand(Sf, Command.Ptr);
9130 } else if (Command.C.cmd == MachO::LC_SUB_LIBRARY) {
9131 MachO::sub_library_command Sl = Obj->getSubLibraryCommand(Command);
9132 PrintSubLibraryCommand(Sl, Command.Ptr);
9133 } else if (Command.C.cmd == MachO::LC_SUB_CLIENT) {
9134 MachO::sub_client_command Sc = Obj->getSubClientCommand(Command);
9135 PrintSubClientCommand(Sc, Command.Ptr);
9136 } else if (Command.C.cmd == MachO::LC_ROUTINES) {
9137 MachO::routines_command Rc = Obj->getRoutinesCommand(Command);
9138 PrintRoutinesCommand(Rc);
9139 } else if (Command.C.cmd == MachO::LC_ROUTINES_64) {
9140 MachO::routines_command_64 Rc = Obj->getRoutinesCommand64(Command);
9141 PrintRoutinesCommand64(Rc);
9142 } else if (Command.C.cmd == MachO::LC_THREAD ||
9143 Command.C.cmd == MachO::LC_UNIXTHREAD) {
9144 MachO::thread_command Tc = Obj->getThreadCommand(Command);
9145 PrintThreadCommand(Tc, Command.Ptr, Obj->isLittleEndian(), cputype);
9146 } else if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
9147 Command.C.cmd == MachO::LC_ID_DYLIB ||
9148 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
9149 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
9150 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
9151 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
9152 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
9153 PrintDylibCommand(Dl, Command.Ptr);
9154 } else if (Command.C.cmd == MachO::LC_CODE_SIGNATURE ||
9155 Command.C.cmd == MachO::LC_SEGMENT_SPLIT_INFO ||
9156 Command.C.cmd == MachO::LC_FUNCTION_STARTS ||
9157 Command.C.cmd == MachO::LC_DATA_IN_CODE ||
9158 Command.C.cmd == MachO::LC_DYLIB_CODE_SIGN_DRS ||
9159 Command.C.cmd == MachO::LC_LINKER_OPTIMIZATION_HINT) {
9160 MachO::linkedit_data_command Ld =
9161 Obj->getLinkeditDataLoadCommand(Command);
9162 PrintLinkEditDataCommand(Ld, Buf.size());
9163 } else {
9164 outs() << " cmd ?(" << format("0x%08" PRIx32"x", Command.C.cmd)
9165 << ")\n";
9166 outs() << " cmdsize " << Command.C.cmdsize << "\n";
9167 // TODO: get and print the raw bytes of the load command.
9168 }
9169 // TODO: print all the other kinds of load commands.
9170 }
9171}
9172
9173static void PrintMachHeader(const MachOObjectFile *Obj, bool verbose) {
9174 if (Obj->is64Bit()) {
9175 MachO::mach_header_64 H_64;
9176 H_64 = Obj->getHeader64();
9177 PrintMachHeader(H_64.magic, H_64.cputype, H_64.cpusubtype, H_64.filetype,
9178 H_64.ncmds, H_64.sizeofcmds, H_64.flags, verbose);
9179 } else {
9180 MachO::mach_header H;
9181 H = Obj->getHeader();
9182 PrintMachHeader(H.magic, H.cputype, H.cpusubtype, H.filetype, H.ncmds,
9183 H.sizeofcmds, H.flags, verbose);
9184 }
9185}
9186
9187void llvm::printMachOFileHeader(const object::ObjectFile *Obj) {
9188 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
9189 PrintMachHeader(file, !NonVerbose);
9190}
9191
9192void llvm::printMachOLoadCommands(const object::ObjectFile *Obj) {
9193 const MachOObjectFile *file = dyn_cast<const MachOObjectFile>(Obj);
9194 uint32_t filetype = 0;
9195 uint32_t cputype = 0;
9196 if (file->is64Bit()) {
9197 MachO::mach_header_64 H_64;
9198 H_64 = file->getHeader64();
9199 filetype = H_64.filetype;
9200 cputype = H_64.cputype;
9201 } else {
9202 MachO::mach_header H;
9203 H = file->getHeader();
9204 filetype = H.filetype;
9205 cputype = H.cputype;
9206 }
9207 PrintLoadCommands(file, filetype, cputype, !NonVerbose);
9208}
9209
9210//===----------------------------------------------------------------------===//
9211// export trie dumping
9212//===----------------------------------------------------------------------===//
9213
9214void llvm::printMachOExportsTrie(const object::MachOObjectFile *Obj) {
9215 for (const llvm::object::ExportEntry &Entry : Obj->exports()) {
9216 uint64_t Flags = Entry.flags();
9217 bool ReExport = (Flags & MachO::EXPORT_SYMBOL_FLAGS_REEXPORT);
9218 bool WeakDef = (Flags & MachO::EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION);
9219 bool ThreadLocal = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9220 MachO::EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL);
9221 bool Abs = ((Flags & MachO::EXPORT_SYMBOL_FLAGS_KIND_MASK) ==
9222 MachO::EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE);
9223 bool Resolver = (Flags & MachO::EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER);
9224 if (ReExport)
9225 outs() << "[re-export] ";
9226 else
9227 outs() << format("0x%08llX ",
9228 Entry.address()); // FIXME:add in base address
9229 outs() << Entry.name();
9230 if (WeakDef || ThreadLocal || Resolver || Abs) {
9231 bool NeedsComma = false;
9232 outs() << " [";
9233 if (WeakDef) {
9234 outs() << "weak_def";
9235 NeedsComma = true;
9236 }
9237 if (ThreadLocal) {
9238 if (NeedsComma)
9239 outs() << ", ";
9240 outs() << "per-thread";
9241 NeedsComma = true;
9242 }
9243 if (Abs) {
9244 if (NeedsComma)
9245 outs() << ", ";
9246 outs() << "absolute";
9247 NeedsComma = true;
9248 }
9249 if (Resolver) {
9250 if (NeedsComma)
9251 outs() << ", ";
9252 outs() << format("resolver=0x%08llX", Entry.other());
9253 NeedsComma = true;
9254 }
9255 outs() << "]";
9256 }
9257 if (ReExport) {
9258 StringRef DylibName = "unknown";
9259 int Ordinal = Entry.other() - 1;
9260 Obj->getLibraryShortNameByIndex(Ordinal, DylibName);
9261 if (Entry.otherName().empty())
9262 outs() << " (from " << DylibName << ")";
9263 else
9264 outs() << " (" << Entry.otherName() << " from " << DylibName << ")";
9265 }
9266 outs() << "\n";
9267 }
9268}
9269
9270//===----------------------------------------------------------------------===//
9271// rebase table dumping
9272//===----------------------------------------------------------------------===//
9273
9274namespace {
9275class SegInfo {
9276public:
9277 SegInfo(const object::MachOObjectFile *Obj);
9278
9279 StringRef segmentName(uint32_t SegIndex);
9280 StringRef sectionName(uint32_t SegIndex, uint64_t SegOffset);
9281 uint64_t address(uint32_t SegIndex, uint64_t SegOffset);
9282 bool isValidSegIndexAndOffset(uint32_t SegIndex, uint64_t SegOffset);
9283
9284private:
9285 struct SectionInfo {
9286 uint64_t Address;
9287 uint64_t Size;
9288 StringRef SectionName;
9289 StringRef SegmentName;
9290 uint64_t OffsetInSegment;
9291 uint64_t SegmentStartAddress;
9292 uint32_t SegmentIndex;
9293 };
9294 const SectionInfo &findSection(uint32_t SegIndex, uint64_t SegOffset);
9295 SmallVector<SectionInfo, 32> Sections;
9296};
9297}
9298
9299SegInfo::SegInfo(const object::MachOObjectFile *Obj) {
9300 // Build table of sections so segIndex/offset pairs can be translated.
9301 uint32_t CurSegIndex = Obj->hasPageZeroSegment() ? 1 : 0;
9302 StringRef CurSegName;
9303 uint64_t CurSegAddress;
9304 for (const SectionRef &Section : Obj->sections()) {
9305 SectionInfo Info;
9306 error(Section.getName(Info.SectionName));
9307 Info.Address = Section.getAddress();
9308 Info.Size = Section.getSize();
9309 Info.SegmentName =
9310 Obj->getSectionFinalSegmentName(Section.getRawDataRefImpl());
9311 if (!Info.SegmentName.equals(CurSegName)) {
9312 ++CurSegIndex;
9313 CurSegName = Info.SegmentName;
9314 CurSegAddress = Info.Address;
9315 }
9316 Info.SegmentIndex = CurSegIndex - 1;
9317 Info.OffsetInSegment = Info.Address - CurSegAddress;
9318 Info.SegmentStartAddress = CurSegAddress;
9319 Sections.push_back(Info);
9320 }
9321}
9322
9323StringRef SegInfo::segmentName(uint32_t SegIndex) {
9324 for (const SectionInfo &SI : Sections) {
9325 if (SI.SegmentIndex == SegIndex)
9326 return SI.SegmentName;
9327 }
9328 llvm_unreachable("invalid segIndex")::llvm::llvm_unreachable_internal("invalid segIndex", "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 9328)
;
9329}
9330
9331bool SegInfo::isValidSegIndexAndOffset(uint32_t SegIndex,
9332 uint64_t OffsetInSeg) {
9333 for (const SectionInfo &SI : Sections) {
9334 if (SI.SegmentIndex != SegIndex)
9335 continue;
9336 if (SI.OffsetInSegment > OffsetInSeg)
9337 continue;
9338 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9339 continue;
9340 return true;
9341 }
9342 return false;
9343}
9344
9345const SegInfo::SectionInfo &SegInfo::findSection(uint32_t SegIndex,
9346 uint64_t OffsetInSeg) {
9347 for (const SectionInfo &SI : Sections) {
9348 if (SI.SegmentIndex != SegIndex)
9349 continue;
9350 if (SI.OffsetInSegment > OffsetInSeg)
9351 continue;
9352 if (OffsetInSeg >= (SI.OffsetInSegment + SI.Size))
9353 continue;
9354 return SI;
9355 }
9356 llvm_unreachable("segIndex and offset not in any section")::llvm::llvm_unreachable_internal("segIndex and offset not in any section"
, "/tmp/buildd/llvm-toolchain-snapshot-4.0~svn285991/tools/llvm-objdump/MachODump.cpp"
, 9356)
;
9357}
9358
9359StringRef SegInfo::sectionName(uint32_t SegIndex, uint64_t OffsetInSeg) {
9360 return findSection(SegIndex, OffsetInSeg).SectionName;
9361}
9362
9363uint64_t SegInfo::address(uint32_t SegIndex, uint64_t OffsetInSeg) {
9364 const SectionInfo &SI = findSection(SegIndex, OffsetInSeg);
9365 return SI.SegmentStartAddress + OffsetInSeg;
9366}
9367
9368void llvm::printMachORebaseTable(const object::MachOObjectFile *Obj) {
9369 // Build table of sections so names can used in final output.
9370 SegInfo sectionTable(Obj);
9371
9372 outs() << "segment section address type\n";
9373 for (const llvm::object::MachORebaseEntry &Entry : Obj->rebaseTable()) {
9374 uint32_t SegIndex = Entry.segmentIndex();
9375 uint64_t OffsetInSeg = Entry.segmentOffset();
9376 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9377 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9378 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9379
9380 // Table lines look like: __DATA __nl_symbol_ptr 0x0000F00C pointer
9381 outs() << format("%-8s %-18s 0x%08" PRIX64"l" "X" " %s\n",
9382 SegmentName.str().c_str(), SectionName.str().c_str(),
9383 Address, Entry.typeName().str().c_str());
9384 }
9385}
9386
9387static StringRef ordinalName(const object::MachOObjectFile *Obj, int Ordinal) {
9388 StringRef DylibName;
9389 switch (Ordinal) {
9390 case MachO::BIND_SPECIAL_DYLIB_SELF:
9391 return "this-image";
9392 case MachO::BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE:
9393 return "main-executable";
9394 case MachO::BIND_SPECIAL_DYLIB_FLAT_LOOKUP:
9395 return "flat-namespace";
9396 default:
9397 if (Ordinal > 0) {
9398 std::error_code EC =
9399 Obj->getLibraryShortNameByIndex(Ordinal - 1, DylibName);
9400 if (EC)
9401 return "<<bad library ordinal>>";
9402 return DylibName;
9403 }
9404 }
9405 return "<<unknown special ordinal>>";
9406}
9407
9408//===----------------------------------------------------------------------===//
9409// bind table dumping
9410//===----------------------------------------------------------------------===//
9411
9412void llvm::printMachOBindTable(const object::MachOObjectFile *Obj) {
9413 // Build table of sections so names can used in final output.
9414 SegInfo sectionTable(Obj);
9415
9416 outs() << "segment section address type "
9417 "addend dylib symbol\n";
9418 for (const llvm::object::MachOBindEntry &Entry : Obj->bindTable()) {
9419 uint32_t SegIndex = Entry.segmentIndex();
9420 uint64_t OffsetInSeg = Entry.segmentOffset();
9421 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9422 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9423 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9424
9425 // Table lines look like:
9426 // __DATA __got 0x00012010 pointer 0 libSystem ___stack_chk_guard
9427 StringRef Attr;
9428 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_WEAK_IMPORT)
9429 Attr = " (weak_import)";
9430 outs() << left_justify(SegmentName, 8) << " "
9431 << left_justify(SectionName, 18) << " "
9432 << format_hex(Address, 10, true) << " "
9433 << left_justify(Entry.typeName(), 8) << " "
9434 << format_decimal(Entry.addend(), 8) << " "
9435 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
9436 << Entry.symbolName() << Attr << "\n";
9437 }
9438}
9439
9440//===----------------------------------------------------------------------===//
9441// lazy bind table dumping
9442//===----------------------------------------------------------------------===//
9443
9444void llvm::printMachOLazyBindTable(const object::MachOObjectFile *Obj) {
9445 // Build table of sections so names can used in final output.
9446 SegInfo sectionTable(Obj);
9447
9448 outs() << "segment section address "
9449 "dylib symbol\n";
9450 for (const llvm::object::MachOBindEntry &Entry : Obj->lazyBindTable()) {
9451 uint32_t SegIndex = Entry.segmentIndex();
9452 uint64_t OffsetInSeg = Entry.segmentOffset();
9453 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9454 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9455 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9456
9457 // Table lines look like:
9458 // __DATA __got 0x00012010 libSystem ___stack_chk_guard
9459 outs() << left_justify(SegmentName, 8) << " "
9460 << left_justify(SectionName, 18) << " "
9461 << format_hex(Address, 10, true) << " "
9462 << left_justify(ordinalName(Obj, Entry.ordinal()), 16) << " "
9463 << Entry.symbolName() << "\n";
9464 }
9465}
9466
9467//===----------------------------------------------------------------------===//
9468// weak bind table dumping
9469//===----------------------------------------------------------------------===//
9470
9471void llvm::printMachOWeakBindTable(const object::MachOObjectFile *Obj) {
9472 // Build table of sections so names can used in final output.
9473 SegInfo sectionTable(Obj);
9474
9475 outs() << "segment section address "
9476 "type addend symbol\n";
9477 for (const llvm::object::MachOBindEntry &Entry : Obj->weakBindTable()) {
9478 // Strong symbols don't have a location to update.
9479 if (Entry.flags() & MachO::BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION) {
9480 outs() << " strong "
9481 << Entry.symbolName() << "\n";
9482 continue;
9483 }
9484 uint32_t SegIndex = Entry.segmentIndex();
9485 uint64_t OffsetInSeg = Entry.segmentOffset();
9486 StringRef SegmentName = sectionTable.segmentName(SegIndex);
9487 StringRef SectionName = sectionTable.sectionName(SegIndex, OffsetInSeg);
9488 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9489
9490 // Table lines look like:
9491 // __DATA __data 0x00001000 pointer 0 _foo
9492 outs() << left_justify(SegmentName, 8) << " "
9493 << left_justify(SectionName, 18) << " "
9494 << format_hex(Address, 10, true) << " "
9495 << left_justify(Entry.typeName(), 8) << " "
9496 << format_decimal(Entry.addend(), 8) << " " << Entry.symbolName()
9497 << "\n";
9498 }
9499}
9500
9501// get_dyld_bind_info_symbolname() is used for disassembly and passed an
9502// address, ReferenceValue, in the Mach-O file and looks in the dyld bind
9503// information for that address. If the address is found its binding symbol
9504// name is returned. If not nullptr is returned.
9505static const char *get_dyld_bind_info_symbolname(uint64_t ReferenceValue,
9506 struct DisassembleInfo *info) {
9507 if (info->bindtable == nullptr) {
9508 info->bindtable = new (BindTable);
9509 SegInfo sectionTable(info->O);
9510 for (const llvm::object::MachOBindEntry &Entry : info->O->bindTable()) {
9511 uint32_t SegIndex = Entry.segmentIndex();
9512 uint64_t OffsetInSeg = Entry.segmentOffset();
9513 if (!sectionTable.isValidSegIndexAndOffset(SegIndex, OffsetInSeg))
9514 continue;
9515 uint64_t Address = sectionTable.address(SegIndex, OffsetInSeg);
9516 const char *SymbolName = nullptr;
9517 StringRef name = Entry.symbolName();
9518 if (!name.empty())
9519 SymbolName = name.data();
9520 info->bindtable->push_back(std::make_pair(Address, SymbolName));
9521 }
9522 }
9523 for (bind_table_iterator BI = info->bindtable->begin(),
9524 BE = info->bindtable->end();
9525 BI != BE; ++BI) {
9526 uint64_t Address = BI->first;
9527 if (ReferenceValue == Address) {
9528 const char *SymbolName = BI->second;
9529 return SymbolName;
9530 }
9531 }
9532 return nullptr;
9533}