[sanitizer] Improve FreeBSD ASLR detection
[llvm-project.git] / llvm / tools / llvm-readobj / MachODumper.cpp
blob599b0355917e98db2204c7cb839aadb80c8162fb
1 //===- MachODumper.cpp - Object file dumping utility for llvm -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the MachO-specific dumper for llvm-readobj.
11 //===----------------------------------------------------------------------===//
13 #include "ObjDumper.h"
14 #include "StackMapPrinter.h"
15 #include "llvm-readobj.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Object/MachO.h"
19 #include "llvm/Support/BinaryStreamReader.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/ScopedPrinter.h"
23 using namespace llvm;
24 using namespace object;
26 namespace {
28 class MachODumper : public ObjDumper {
29 public:
30 MachODumper(const MachOObjectFile *Obj, ScopedPrinter &Writer)
31 : ObjDumper(Writer, Obj->getFileName()), Obj(Obj) {}
33 void printFileHeaders() override;
34 void printSectionHeaders() override;
35 void printRelocations() override;
36 void printUnwindInfo() override;
37 void printStackMap() const override;
38 void printCGProfile() override;
40 void printNeededLibraries() override;
42 // MachO-specific.
43 void printMachODataInCode() override;
44 void printMachOVersionMin() override;
45 void printMachODysymtab() override;
46 void printMachOSegment() override;
47 void printMachOIndirectSymbols() override;
48 void printMachOLinkerOptions () override;
50 private:
51 template<class MachHeader>
52 void printFileHeaders(const MachHeader &Header);
54 StringRef getSymbolName(const SymbolRef &Symbol);
56 void printSymbols() override;
57 void printDynamicSymbols() override;
58 void printSymbol(const SymbolRef &Symbol);
60 void printRelocation(const RelocationRef &Reloc);
62 void printRelocation(const MachOObjectFile *Obj, const RelocationRef &Reloc);
64 void printSectionHeaders(const MachOObjectFile *Obj);
66 const MachOObjectFile *Obj;
69 } // namespace
72 namespace llvm {
74 std::unique_ptr<ObjDumper> createMachODumper(const object::MachOObjectFile &Obj,
75 ScopedPrinter &Writer) {
76 return std::make_unique<MachODumper>(&Obj, Writer);
79 } // namespace llvm
81 const EnumEntry<uint32_t> MachOMagics[] = {
82 { "Magic", MachO::MH_MAGIC },
83 { "Cigam", MachO::MH_CIGAM },
84 { "Magic64", MachO::MH_MAGIC_64 },
85 { "Cigam64", MachO::MH_CIGAM_64 },
86 { "FatMagic", MachO::FAT_MAGIC },
87 { "FatCigam", MachO::FAT_CIGAM },
90 const EnumEntry<uint32_t> MachOHeaderFileTypes[] = {
91 { "Relocatable", MachO::MH_OBJECT },
92 { "Executable", MachO::MH_EXECUTE },
93 { "FixedVMLibrary", MachO::MH_FVMLIB },
94 { "Core", MachO::MH_CORE },
95 { "PreloadedExecutable", MachO::MH_PRELOAD },
96 { "DynamicLibrary", MachO::MH_DYLIB },
97 { "DynamicLinker", MachO::MH_DYLINKER },
98 { "Bundle", MachO::MH_BUNDLE },
99 { "DynamicLibraryStub", MachO::MH_DYLIB_STUB },
100 { "DWARFSymbol", MachO::MH_DSYM },
101 { "KextBundle", MachO::MH_KEXT_BUNDLE },
104 const EnumEntry<uint32_t> MachOHeaderCpuTypes[] = {
105 { "Any" , static_cast<uint32_t>(MachO::CPU_TYPE_ANY) },
106 { "X86" , MachO::CPU_TYPE_X86 },
107 { "X86-64" , MachO::CPU_TYPE_X86_64 },
108 { "Mc98000" , MachO::CPU_TYPE_MC98000 },
109 { "Arm" , MachO::CPU_TYPE_ARM },
110 { "Arm64" , MachO::CPU_TYPE_ARM64 },
111 { "Sparc" , MachO::CPU_TYPE_SPARC },
112 { "PowerPC" , MachO::CPU_TYPE_POWERPC },
113 { "PowerPC64" , MachO::CPU_TYPE_POWERPC64 },
116 const EnumEntry<uint32_t> MachOHeaderCpuSubtypesX86[] = {
117 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_I386_ALL),
118 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_386),
119 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_486),
120 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_486SX),
121 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_586),
122 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTPRO),
123 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTII_M3),
124 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTII_M5),
125 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_CELERON),
126 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_CELERON_MOBILE),
127 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_3),
128 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_3_M),
129 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_3_XEON),
130 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_M),
131 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_4),
132 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_PENTIUM_4_M),
133 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ITANIUM),
134 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ITANIUM_2),
135 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_XEON),
136 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_XEON_MP),
139 const EnumEntry<uint32_t> MachOHeaderCpuSubtypesX64[] = {
140 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_X86_64_ALL),
141 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_X86_ARCH1),
142 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_X86_64_H),
145 const EnumEntry<uint32_t> MachOHeaderCpuSubtypesARM[] = {
146 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_ALL),
147 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V4T),
148 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V6),
149 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V5),
150 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V5TEJ),
151 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_XSCALE),
152 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7),
153 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7S),
154 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7K),
155 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V6M),
156 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7M),
157 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM_V7EM),
160 const EnumEntry<uint32_t> MachOHeaderCpuSubtypesARM64[] = {
161 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM64_ALL),
162 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM64_V8),
163 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_ARM64E),
166 const EnumEntry<uint32_t> MachOHeaderCpuSubtypesSPARC[] = {
167 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_SPARC_ALL),
170 const EnumEntry<uint32_t> MachOHeaderCpuSubtypesPPC[] = {
171 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_ALL),
172 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_601),
173 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_602),
174 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_603),
175 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_603e),
176 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_603ev),
177 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_604),
178 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_604e),
179 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_620),
180 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_750),
181 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_7400),
182 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_7450),
183 LLVM_READOBJ_ENUM_ENT(MachO, CPU_SUBTYPE_POWERPC_970),
186 const EnumEntry<uint32_t> MachOHeaderFlags[] = {
187 LLVM_READOBJ_ENUM_ENT(MachO, MH_NOUNDEFS),
188 LLVM_READOBJ_ENUM_ENT(MachO, MH_INCRLINK),
189 LLVM_READOBJ_ENUM_ENT(MachO, MH_DYLDLINK),
190 LLVM_READOBJ_ENUM_ENT(MachO, MH_BINDATLOAD),
191 LLVM_READOBJ_ENUM_ENT(MachO, MH_PREBOUND),
192 LLVM_READOBJ_ENUM_ENT(MachO, MH_SPLIT_SEGS),
193 LLVM_READOBJ_ENUM_ENT(MachO, MH_LAZY_INIT),
194 LLVM_READOBJ_ENUM_ENT(MachO, MH_TWOLEVEL),
195 LLVM_READOBJ_ENUM_ENT(MachO, MH_FORCE_FLAT),
196 LLVM_READOBJ_ENUM_ENT(MachO, MH_NOMULTIDEFS),
197 LLVM_READOBJ_ENUM_ENT(MachO, MH_NOFIXPREBINDING),
198 LLVM_READOBJ_ENUM_ENT(MachO, MH_PREBINDABLE),
199 LLVM_READOBJ_ENUM_ENT(MachO, MH_ALLMODSBOUND),
200 LLVM_READOBJ_ENUM_ENT(MachO, MH_SUBSECTIONS_VIA_SYMBOLS),
201 LLVM_READOBJ_ENUM_ENT(MachO, MH_CANONICAL),
202 LLVM_READOBJ_ENUM_ENT(MachO, MH_WEAK_DEFINES),
203 LLVM_READOBJ_ENUM_ENT(MachO, MH_BINDS_TO_WEAK),
204 LLVM_READOBJ_ENUM_ENT(MachO, MH_ALLOW_STACK_EXECUTION),
205 LLVM_READOBJ_ENUM_ENT(MachO, MH_ROOT_SAFE),
206 LLVM_READOBJ_ENUM_ENT(MachO, MH_SETUID_SAFE),
207 LLVM_READOBJ_ENUM_ENT(MachO, MH_NO_REEXPORTED_DYLIBS),
208 LLVM_READOBJ_ENUM_ENT(MachO, MH_PIE),
209 LLVM_READOBJ_ENUM_ENT(MachO, MH_DEAD_STRIPPABLE_DYLIB),
210 LLVM_READOBJ_ENUM_ENT(MachO, MH_HAS_TLV_DESCRIPTORS),
211 LLVM_READOBJ_ENUM_ENT(MachO, MH_NO_HEAP_EXECUTION),
212 LLVM_READOBJ_ENUM_ENT(MachO, MH_APP_EXTENSION_SAFE),
215 const EnumEntry<unsigned> MachOSectionTypes[] = {
216 { "Regular" , MachO::S_REGULAR },
217 { "ZeroFill" , MachO::S_ZEROFILL },
218 { "CStringLiterals" , MachO::S_CSTRING_LITERALS },
219 { "4ByteLiterals" , MachO::S_4BYTE_LITERALS },
220 { "8ByteLiterals" , MachO::S_8BYTE_LITERALS },
221 { "LiteralPointers" , MachO::S_LITERAL_POINTERS },
222 { "NonLazySymbolPointers" , MachO::S_NON_LAZY_SYMBOL_POINTERS },
223 { "LazySymbolPointers" , MachO::S_LAZY_SYMBOL_POINTERS },
224 { "SymbolStubs" , MachO::S_SYMBOL_STUBS },
225 { "ModInitFuncPointers" , MachO::S_MOD_INIT_FUNC_POINTERS },
226 { "ModTermFuncPointers" , MachO::S_MOD_TERM_FUNC_POINTERS },
227 { "Coalesced" , MachO::S_COALESCED },
228 { "GBZeroFill" , MachO::S_GB_ZEROFILL },
229 { "Interposing" , MachO::S_INTERPOSING },
230 { "16ByteLiterals" , MachO::S_16BYTE_LITERALS },
231 { "DTraceDOF" , MachO::S_DTRACE_DOF },
232 { "LazyDylibSymbolPointers" , MachO::S_LAZY_DYLIB_SYMBOL_POINTERS },
233 { "ThreadLocalRegular" , MachO::S_THREAD_LOCAL_REGULAR },
234 { "ThreadLocalZerofill" , MachO::S_THREAD_LOCAL_ZEROFILL },
235 { "ThreadLocalVariables" , MachO::S_THREAD_LOCAL_VARIABLES },
236 { "ThreadLocalVariablePointers" , MachO::S_THREAD_LOCAL_VARIABLE_POINTERS },
237 { "ThreadLocalInitFunctionPointers", MachO::S_THREAD_LOCAL_INIT_FUNCTION_POINTERS }
240 const EnumEntry<unsigned> MachOSectionAttributes[] = {
241 { "LocReloc" , 1 << 0 /*S_ATTR_LOC_RELOC */ },
242 { "ExtReloc" , 1 << 1 /*S_ATTR_EXT_RELOC */ },
243 { "SomeInstructions" , 1 << 2 /*S_ATTR_SOME_INSTRUCTIONS */ },
244 { "Debug" , 1 << 17 /*S_ATTR_DEBUG */ },
245 { "SelfModifyingCode", 1 << 18 /*S_ATTR_SELF_MODIFYING_CODE*/ },
246 { "LiveSupport" , 1 << 19 /*S_ATTR_LIVE_SUPPORT */ },
247 { "NoDeadStrip" , 1 << 20 /*S_ATTR_NO_DEAD_STRIP */ },
248 { "StripStaticSyms" , 1 << 21 /*S_ATTR_STRIP_STATIC_SYMS */ },
249 { "NoTOC" , 1 << 22 /*S_ATTR_NO_TOC */ },
250 { "PureInstructions" , 1 << 23 /*S_ATTR_PURE_INSTRUCTIONS */ },
253 const EnumEntry<unsigned> MachOSymbolRefTypes[] = {
254 { "UndefinedNonLazy", 0 },
255 { "ReferenceFlagUndefinedLazy", 1 },
256 { "ReferenceFlagDefined", 2 },
257 { "ReferenceFlagPrivateDefined", 3 },
258 { "ReferenceFlagPrivateUndefinedNonLazy", 4 },
259 { "ReferenceFlagPrivateUndefinedLazy", 5 }
262 const EnumEntry<unsigned> MachOSymbolFlags[] = {
263 { "ThumbDef", 0x8 },
264 { "ReferencedDynamically", 0x10 },
265 { "NoDeadStrip", 0x20 },
266 { "WeakRef", 0x40 },
267 { "WeakDef", 0x80 },
268 { "SymbolResolver", 0x100 },
269 { "AltEntry", 0x200 },
270 { "ColdFunc", 0x400 },
273 const EnumEntry<unsigned> MachOSymbolTypes[] = {
274 { "Undef", 0x0 },
275 { "Abs", 0x2 },
276 { "Indirect", 0xA },
277 { "PreboundUndef", 0xC },
278 { "Section", 0xE }
281 namespace {
282 struct MachOSection {
283 ArrayRef<char> Name;
284 ArrayRef<char> SegmentName;
285 uint64_t Address;
286 uint64_t Size;
287 uint32_t Offset;
288 uint32_t Alignment;
289 uint32_t RelocationTableOffset;
290 uint32_t NumRelocationTableEntries;
291 uint32_t Flags;
292 uint32_t Reserved1;
293 uint32_t Reserved2;
294 uint32_t Reserved3;
297 struct MachOSegment {
298 std::string CmdName;
299 std::string SegName;
300 uint64_t cmdsize;
301 uint64_t vmaddr;
302 uint64_t vmsize;
303 uint64_t fileoff;
304 uint64_t filesize;
305 uint32_t maxprot;
306 uint32_t initprot;
307 uint32_t nsects;
308 uint32_t flags;
311 struct MachOSymbol {
312 uint32_t StringIndex;
313 uint8_t Type;
314 uint8_t SectionIndex;
315 uint16_t Flags;
316 uint64_t Value;
320 static std::string getMask(uint32_t prot)
322 // TODO (davide): This always assumes prot is valid.
323 // Catch mistakes and report if needed.
324 std::string Prot;
325 Prot = "";
326 Prot += (prot & MachO::VM_PROT_READ) ? "r" : "-";
327 Prot += (prot & MachO::VM_PROT_WRITE) ? "w" : "-";
328 Prot += (prot & MachO::VM_PROT_EXECUTE) ? "x" : "-";
329 return Prot;
332 static void getSection(const MachOObjectFile *Obj,
333 DataRefImpl Sec,
334 MachOSection &Section) {
335 if (!Obj->is64Bit()) {
336 MachO::section Sect = Obj->getSection(Sec);
337 Section.Address = Sect.addr;
338 Section.Size = Sect.size;
339 Section.Offset = Sect.offset;
340 Section.Alignment = Sect.align;
341 Section.RelocationTableOffset = Sect.reloff;
342 Section.NumRelocationTableEntries = Sect.nreloc;
343 Section.Flags = Sect.flags;
344 Section.Reserved1 = Sect.reserved1;
345 Section.Reserved2 = Sect.reserved2;
346 return;
348 MachO::section_64 Sect = Obj->getSection64(Sec);
349 Section.Address = Sect.addr;
350 Section.Size = Sect.size;
351 Section.Offset = Sect.offset;
352 Section.Alignment = Sect.align;
353 Section.RelocationTableOffset = Sect.reloff;
354 Section.NumRelocationTableEntries = Sect.nreloc;
355 Section.Flags = Sect.flags;
356 Section.Reserved1 = Sect.reserved1;
357 Section.Reserved2 = Sect.reserved2;
358 Section.Reserved3 = Sect.reserved3;
361 static void getSegment(const MachOObjectFile *Obj,
362 const MachOObjectFile::LoadCommandInfo &L,
363 MachOSegment &Segment) {
364 if (!Obj->is64Bit()) {
365 MachO::segment_command SC = Obj->getSegmentLoadCommand(L);
366 Segment.CmdName = "LC_SEGMENT";
367 Segment.SegName = SC.segname;
368 Segment.cmdsize = SC.cmdsize;
369 Segment.vmaddr = SC.vmaddr;
370 Segment.vmsize = SC.vmsize;
371 Segment.fileoff = SC.fileoff;
372 Segment.filesize = SC.filesize;
373 Segment.maxprot = SC.maxprot;
374 Segment.initprot = SC.initprot;
375 Segment.nsects = SC.nsects;
376 Segment.flags = SC.flags;
377 return;
379 MachO::segment_command_64 SC = Obj->getSegment64LoadCommand(L);
380 Segment.CmdName = "LC_SEGMENT_64";
381 Segment.SegName = SC.segname;
382 Segment.cmdsize = SC.cmdsize;
383 Segment.vmaddr = SC.vmaddr;
384 Segment.vmsize = SC.vmsize;
385 Segment.fileoff = SC.fileoff;
386 Segment.filesize = SC.filesize;
387 Segment.maxprot = SC.maxprot;
388 Segment.initprot = SC.initprot;
389 Segment.nsects = SC.nsects;
390 Segment.flags = SC.flags;
393 static void getSymbol(const MachOObjectFile *Obj,
394 DataRefImpl DRI,
395 MachOSymbol &Symbol) {
396 if (!Obj->is64Bit()) {
397 MachO::nlist Entry = Obj->getSymbolTableEntry(DRI);
398 Symbol.StringIndex = Entry.n_strx;
399 Symbol.Type = Entry.n_type;
400 Symbol.SectionIndex = Entry.n_sect;
401 Symbol.Flags = Entry.n_desc;
402 Symbol.Value = Entry.n_value;
403 return;
405 MachO::nlist_64 Entry = Obj->getSymbol64TableEntry(DRI);
406 Symbol.StringIndex = Entry.n_strx;
407 Symbol.Type = Entry.n_type;
408 Symbol.SectionIndex = Entry.n_sect;
409 Symbol.Flags = Entry.n_desc;
410 Symbol.Value = Entry.n_value;
413 void MachODumper::printFileHeaders() {
414 DictScope H(W, "MachHeader");
415 if (!Obj->is64Bit()) {
416 printFileHeaders(Obj->getHeader());
417 } else {
418 printFileHeaders(Obj->getHeader64());
419 W.printHex("Reserved", Obj->getHeader64().reserved);
423 template<class MachHeader>
424 void MachODumper::printFileHeaders(const MachHeader &Header) {
425 W.printEnum("Magic", Header.magic, makeArrayRef(MachOMagics));
426 W.printEnum("CpuType", Header.cputype, makeArrayRef(MachOHeaderCpuTypes));
427 uint32_t subtype = Header.cpusubtype & ~MachO::CPU_SUBTYPE_MASK;
428 switch (Header.cputype) {
429 case MachO::CPU_TYPE_X86:
430 W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesX86));
431 break;
432 case MachO::CPU_TYPE_X86_64:
433 W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesX64));
434 break;
435 case MachO::CPU_TYPE_ARM:
436 W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesARM));
437 break;
438 case MachO::CPU_TYPE_POWERPC:
439 W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesPPC));
440 break;
441 case MachO::CPU_TYPE_SPARC:
442 W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesSPARC));
443 break;
444 case MachO::CPU_TYPE_ARM64:
445 W.printEnum("CpuSubType", subtype, makeArrayRef(MachOHeaderCpuSubtypesARM64));
446 break;
447 case MachO::CPU_TYPE_POWERPC64:
448 default:
449 W.printHex("CpuSubtype", subtype);
451 W.printEnum("FileType", Header.filetype, makeArrayRef(MachOHeaderFileTypes));
452 W.printNumber("NumOfLoadCommands", Header.ncmds);
453 W.printNumber("SizeOfLoadCommands", Header.sizeofcmds);
454 W.printFlags("Flags", Header.flags, makeArrayRef(MachOHeaderFlags));
457 void MachODumper::printSectionHeaders() { return printSectionHeaders(Obj); }
459 void MachODumper::printSectionHeaders(const MachOObjectFile *Obj) {
460 ListScope Group(W, "Sections");
462 int SectionIndex = -1;
463 for (const SectionRef &Section : Obj->sections()) {
464 ++SectionIndex;
466 MachOSection MOSection;
467 getSection(Obj, Section.getRawDataRefImpl(), MOSection);
468 DataRefImpl DR = Section.getRawDataRefImpl();
469 StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
470 ArrayRef<char> RawName = Obj->getSectionRawName(DR);
471 StringRef SegmentName = Obj->getSectionFinalSegmentName(DR);
472 ArrayRef<char> RawSegmentName = Obj->getSectionRawFinalSegmentName(DR);
474 DictScope SectionD(W, "Section");
475 W.printNumber("Index", SectionIndex);
476 W.printBinary("Name", Name, RawName);
477 W.printBinary("Segment", SegmentName, RawSegmentName);
478 W.printHex("Address", MOSection.Address);
479 W.printHex("Size", MOSection.Size);
480 W.printNumber("Offset", MOSection.Offset);
481 W.printNumber("Alignment", MOSection.Alignment);
482 W.printHex("RelocationOffset", MOSection.RelocationTableOffset);
483 W.printNumber("RelocationCount", MOSection.NumRelocationTableEntries);
484 W.printEnum("Type", MOSection.Flags & 0xFF,
485 makeArrayRef(MachOSectionTypes));
486 W.printFlags("Attributes", MOSection.Flags >> 8,
487 makeArrayRef(MachOSectionAttributes));
488 W.printHex("Reserved1", MOSection.Reserved1);
489 W.printHex("Reserved2", MOSection.Reserved2);
490 if (Obj->is64Bit())
491 W.printHex("Reserved3", MOSection.Reserved3);
493 if (opts::SectionRelocations) {
494 ListScope D(W, "Relocations");
495 for (const RelocationRef &Reloc : Section.relocations())
496 printRelocation(Reloc);
499 if (opts::SectionSymbols) {
500 ListScope D(W, "Symbols");
501 for (const SymbolRef &Symbol : Obj->symbols()) {
502 if (!Section.containsSymbol(Symbol))
503 continue;
505 printSymbol(Symbol);
509 if (opts::SectionData && !Section.isBSS())
510 W.printBinaryBlock("SectionData", unwrapOrError(Obj->getFileName(),
511 Section.getContents()));
515 void MachODumper::printRelocations() {
516 ListScope D(W, "Relocations");
518 std::error_code EC;
519 for (const SectionRef &Section : Obj->sections()) {
520 StringRef Name = unwrapOrError(Obj->getFileName(), Section.getName());
521 bool PrintedGroup = false;
522 for (const RelocationRef &Reloc : Section.relocations()) {
523 if (!PrintedGroup) {
524 W.startLine() << "Section " << Name << " {\n";
525 W.indent();
526 PrintedGroup = true;
529 printRelocation(Reloc);
532 if (PrintedGroup) {
533 W.unindent();
534 W.startLine() << "}\n";
539 void MachODumper::printRelocation(const RelocationRef &Reloc) {
540 return printRelocation(Obj, Reloc);
543 void MachODumper::printRelocation(const MachOObjectFile *Obj,
544 const RelocationRef &Reloc) {
545 uint64_t Offset = Reloc.getOffset();
546 SmallString<32> RelocName;
547 Reloc.getTypeName(RelocName);
549 DataRefImpl DR = Reloc.getRawDataRefImpl();
550 MachO::any_relocation_info RE = Obj->getRelocation(DR);
551 bool IsScattered = Obj->isRelocationScattered(RE);
552 bool IsExtern = !IsScattered && Obj->getPlainRelocationExternal(RE);
554 StringRef TargetName;
555 if (IsExtern) {
556 symbol_iterator Symbol = Reloc.getSymbol();
557 if (Symbol != Obj->symbol_end()) {
558 TargetName = getSymbolName(*Symbol);
560 } else if (!IsScattered) {
561 section_iterator SecI = Obj->getRelocationSection(DR);
562 if (SecI != Obj->section_end())
563 TargetName = unwrapOrError(Obj->getFileName(), SecI->getName());
565 if (TargetName.empty())
566 TargetName = "-";
568 if (opts::ExpandRelocs) {
569 DictScope Group(W, "Relocation");
570 W.printHex("Offset", Offset);
571 W.printNumber("PCRel", Obj->getAnyRelocationPCRel(RE));
572 W.printNumber("Length", Obj->getAnyRelocationLength(RE));
573 W.printNumber("Type", RelocName, Obj->getAnyRelocationType(RE));
574 if (IsScattered) {
575 W.printHex("Value", Obj->getScatteredRelocationValue(RE));
576 } else {
577 const char *Kind = IsExtern ? "Symbol" : "Section";
578 W.printNumber(Kind, TargetName, Obj->getPlainRelocationSymbolNum(RE));
580 } else {
581 SmallString<32> SymbolNameOrOffset("0x");
582 if (IsScattered) {
583 // Scattered relocations don't really have an associated symbol for some
584 // reason, even if one exists in the symtab at the correct address.
585 SymbolNameOrOffset += utohexstr(Obj->getScatteredRelocationValue(RE));
586 } else {
587 SymbolNameOrOffset = TargetName;
590 raw_ostream& OS = W.startLine();
591 OS << W.hex(Offset)
592 << " " << Obj->getAnyRelocationPCRel(RE)
593 << " " << Obj->getAnyRelocationLength(RE);
594 if (IsScattered)
595 OS << " n/a";
596 else
597 OS << " " << Obj->getPlainRelocationExternal(RE);
598 OS << " " << RelocName
599 << " " << IsScattered
600 << " " << SymbolNameOrOffset
601 << "\n";
605 StringRef MachODumper::getSymbolName(const SymbolRef &Symbol) {
606 Expected<StringRef> SymbolNameOrErr = Symbol.getName();
607 if (!SymbolNameOrErr) {
608 reportError(SymbolNameOrErr.takeError(), Obj->getFileName());
610 return *SymbolNameOrErr;
613 void MachODumper::printSymbols() {
614 ListScope Group(W, "Symbols");
616 for (const SymbolRef &Symbol : Obj->symbols()) {
617 printSymbol(Symbol);
621 void MachODumper::printDynamicSymbols() {
622 ListScope Group(W, "DynamicSymbols");
625 void MachODumper::printSymbol(const SymbolRef &Symbol) {
626 StringRef SymbolName = getSymbolName(Symbol);
628 MachOSymbol MOSymbol;
629 getSymbol(Obj, Symbol.getRawDataRefImpl(), MOSymbol);
631 StringRef SectionName = "";
632 // Don't ask a Mach-O STABS symbol for its section unless we know that
633 // STAB symbol's section field refers to a valid section index. Otherwise
634 // the symbol may error trying to load a section that does not exist.
635 // TODO: Add a whitelist of STABS symbol types that contain valid section
636 // indices.
637 if (!(MOSymbol.Type & MachO::N_STAB)) {
638 Expected<section_iterator> SecIOrErr = Symbol.getSection();
639 if (!SecIOrErr)
640 reportError(SecIOrErr.takeError(), Obj->getFileName());
642 section_iterator SecI = *SecIOrErr;
643 if (SecI != Obj->section_end())
644 SectionName = unwrapOrError(Obj->getFileName(), SecI->getName());
647 DictScope D(W, "Symbol");
648 W.printNumber("Name", SymbolName, MOSymbol.StringIndex);
649 if (MOSymbol.Type & MachO::N_STAB) {
650 W.printHex("Type", "SymDebugTable", MOSymbol.Type);
651 } else {
652 if (MOSymbol.Type & MachO::N_PEXT)
653 W.startLine() << "PrivateExtern\n";
654 if (MOSymbol.Type & MachO::N_EXT)
655 W.startLine() << "Extern\n";
656 W.printEnum("Type", uint8_t(MOSymbol.Type & MachO::N_TYPE),
657 makeArrayRef(MachOSymbolTypes));
659 W.printHex("Section", SectionName, MOSymbol.SectionIndex);
660 W.printEnum("RefType", static_cast<uint16_t>(MOSymbol.Flags & 0x7),
661 makeArrayRef(MachOSymbolRefTypes));
662 W.printFlags("Flags", static_cast<uint16_t>(MOSymbol.Flags & ~0x7),
663 makeArrayRef(MachOSymbolFlags));
664 W.printHex("Value", MOSymbol.Value);
667 void MachODumper::printUnwindInfo() {
668 W.startLine() << "UnwindInfo not implemented.\n";
671 void MachODumper::printStackMap() const {
672 object::SectionRef StackMapSection;
673 for (auto Sec : Obj->sections()) {
674 StringRef Name;
675 if (Expected<StringRef> NameOrErr = Sec.getName())
676 Name = *NameOrErr;
677 else
678 consumeError(NameOrErr.takeError());
680 if (Name == "__llvm_stackmaps") {
681 StackMapSection = Sec;
682 break;
686 if (StackMapSection == object::SectionRef())
687 return;
689 StringRef StackMapContents =
690 unwrapOrError(Obj->getFileName(), StackMapSection.getContents());
691 ArrayRef<uint8_t> StackMapContentsArray =
692 arrayRefFromStringRef(StackMapContents);
694 if (Obj->isLittleEndian())
695 prettyPrintStackMap(
696 W, StackMapParser<support::little>(StackMapContentsArray));
697 else
698 prettyPrintStackMap(
699 W, StackMapParser<support::big>(StackMapContentsArray));
702 void MachODumper::printCGProfile() {
703 object::SectionRef CGProfileSection;
704 for (auto Sec : Obj->sections()) {
705 StringRef Name;
706 if (Expected<StringRef> NameOrErr = Sec.getName())
707 Name = *NameOrErr;
708 else
709 consumeError(NameOrErr.takeError());
711 if (Name == "__cg_profile") {
712 CGProfileSection = Sec;
713 break;
716 if (CGProfileSection == object::SectionRef())
717 return;
719 StringRef CGProfileContents =
720 unwrapOrError(Obj->getFileName(), CGProfileSection.getContents());
721 BinaryStreamReader Reader(CGProfileContents, Obj->isLittleEndian()
722 ? llvm::support::little
723 : llvm::support::big);
725 ListScope L(W, "CGProfile");
726 while (!Reader.empty()) {
727 uint32_t FromIndex, ToIndex;
728 uint64_t Count;
729 if (Error Err = Reader.readInteger(FromIndex))
730 reportError(std::move(Err), Obj->getFileName());
731 if (Error Err = Reader.readInteger(ToIndex))
732 reportError(std::move(Err), Obj->getFileName());
733 if (Error Err = Reader.readInteger(Count))
734 reportError(std::move(Err), Obj->getFileName());
735 DictScope D(W, "CGProfileEntry");
736 W.printNumber("From", getSymbolName(*Obj->getSymbolByIndex(FromIndex)),
737 FromIndex);
738 W.printNumber("To", getSymbolName(*Obj->getSymbolByIndex(ToIndex)),
739 ToIndex);
740 W.printNumber("Weight", Count);
744 void MachODumper::printNeededLibraries() {
745 ListScope D(W, "NeededLibraries");
747 using LibsTy = std::vector<StringRef>;
748 LibsTy Libs;
750 for (const auto &Command : Obj->load_commands()) {
751 if (Command.C.cmd == MachO::LC_LOAD_DYLIB ||
752 Command.C.cmd == MachO::LC_ID_DYLIB ||
753 Command.C.cmd == MachO::LC_LOAD_WEAK_DYLIB ||
754 Command.C.cmd == MachO::LC_REEXPORT_DYLIB ||
755 Command.C.cmd == MachO::LC_LAZY_LOAD_DYLIB ||
756 Command.C.cmd == MachO::LC_LOAD_UPWARD_DYLIB) {
757 MachO::dylib_command Dl = Obj->getDylibIDLoadCommand(Command);
758 if (Dl.dylib.name < Dl.cmdsize) {
759 auto *P = static_cast<const char*>(Command.Ptr) + Dl.dylib.name;
760 Libs.push_back(P);
765 llvm::stable_sort(Libs);
767 for (const auto &L : Libs) {
768 W.startLine() << L << "\n";
772 void MachODumper::printMachODataInCode() {
773 for (const auto &Load : Obj->load_commands()) {
774 if (Load.C.cmd == MachO::LC_DATA_IN_CODE) {
775 MachO::linkedit_data_command LLC = Obj->getLinkeditDataLoadCommand(Load);
776 DictScope Group(W, "DataInCode");
777 W.printNumber("Data offset", LLC.dataoff);
778 W.printNumber("Data size", LLC.datasize);
779 ListScope D(W, "Data entries");
780 unsigned NumRegions = LLC.datasize / sizeof(MachO::data_in_code_entry);
781 for (unsigned i = 0; i < NumRegions; ++i) {
782 MachO::data_in_code_entry DICE = Obj->getDataInCodeTableEntry(
783 LLC.dataoff, i);
784 DictScope Group(W, "Entry");
785 W.printNumber("Index", i);
786 W.printNumber("Offset", DICE.offset);
787 W.printNumber("Length", DICE.length);
788 W.printNumber("Kind", DICE.kind);
794 void MachODumper::printMachOVersionMin() {
795 for (const auto &Load : Obj->load_commands()) {
796 StringRef Cmd;
797 switch (Load.C.cmd) {
798 case MachO::LC_VERSION_MIN_MACOSX:
799 Cmd = "LC_VERSION_MIN_MACOSX";
800 break;
801 case MachO::LC_VERSION_MIN_IPHONEOS:
802 Cmd = "LC_VERSION_MIN_IPHONEOS";
803 break;
804 case MachO::LC_VERSION_MIN_TVOS:
805 Cmd = "LC_VERSION_MIN_TVOS";
806 break;
807 case MachO::LC_VERSION_MIN_WATCHOS:
808 Cmd = "LC_VERSION_MIN_WATCHOS";
809 break;
810 case MachO::LC_BUILD_VERSION:
811 Cmd = "LC_BUILD_VERSION";
812 break;
813 default:
814 continue;
817 DictScope Group(W, "MinVersion");
818 // Handle LC_BUILD_VERSION.
819 if (Load.C.cmd == MachO::LC_BUILD_VERSION) {
820 MachO::build_version_command BVC = Obj->getBuildVersionLoadCommand(Load);
821 W.printString("Cmd", Cmd);
822 W.printNumber("Size", BVC.cmdsize);
823 W.printString("Platform",
824 MachOObjectFile::getBuildPlatform(BVC.platform));
825 W.printString("Version", MachOObjectFile::getVersionString(BVC.minos));
826 if (BVC.sdk)
827 W.printString("SDK", MachOObjectFile::getVersionString(BVC.sdk));
828 else
829 W.printString("SDK", StringRef("n/a"));
830 continue;
833 MachO::version_min_command VMC = Obj->getVersionMinLoadCommand(Load);
834 W.printString("Cmd", Cmd);
835 W.printNumber("Size", VMC.cmdsize);
836 SmallString<32> Version;
837 Version = utostr(MachOObjectFile::getVersionMinMajor(VMC, false)) + "." +
838 utostr(MachOObjectFile::getVersionMinMinor(VMC, false));
839 uint32_t Update = MachOObjectFile::getVersionMinUpdate(VMC, false);
840 if (Update != 0)
841 Version += "." + utostr(MachOObjectFile::getVersionMinUpdate(VMC, false));
842 W.printString("Version", Version);
843 SmallString<32> SDK;
844 if (VMC.sdk == 0)
845 SDK = "n/a";
846 else {
847 SDK = utostr(MachOObjectFile::getVersionMinMajor(VMC, true)) + "." +
848 utostr(MachOObjectFile::getVersionMinMinor(VMC, true));
849 uint32_t Update = MachOObjectFile::getVersionMinUpdate(VMC, true);
850 if (Update != 0)
851 SDK += "." + utostr(MachOObjectFile::getVersionMinUpdate(VMC, true));
853 W.printString("SDK", SDK);
857 void MachODumper::printMachODysymtab() {
858 for (const auto &Load : Obj->load_commands()) {
859 if (Load.C.cmd == MachO::LC_DYSYMTAB) {
860 MachO::dysymtab_command DLC = Obj->getDysymtabLoadCommand();
861 DictScope Group(W, "Dysymtab");
862 W.printNumber("ilocalsym", DLC.ilocalsym);
863 W.printNumber("nlocalsym", DLC.nlocalsym);
864 W.printNumber("iextdefsym", DLC.iextdefsym);
865 W.printNumber("nextdefsym", DLC.nextdefsym);
866 W.printNumber("iundefsym", DLC.iundefsym);
867 W.printNumber("nundefsym", DLC.nundefsym);
868 W.printNumber("tocoff", DLC.tocoff);
869 W.printNumber("ntoc", DLC.ntoc);
870 W.printNumber("modtaboff", DLC.modtaboff);
871 W.printNumber("nmodtab", DLC.nmodtab);
872 W.printNumber("extrefsymoff", DLC.extrefsymoff);
873 W.printNumber("nextrefsyms", DLC.nextrefsyms);
874 W.printNumber("indirectsymoff", DLC.indirectsymoff);
875 W.printNumber("nindirectsyms", DLC.nindirectsyms);
876 W.printNumber("extreloff", DLC.extreloff);
877 W.printNumber("nextrel", DLC.nextrel);
878 W.printNumber("locreloff", DLC.locreloff);
879 W.printNumber("nlocrel", DLC.nlocrel);
884 void MachODumper::printMachOSegment() {
885 for (const auto &Load : Obj->load_commands()) {
886 if (Load.C.cmd == MachO::LC_SEGMENT || Load.C.cmd == MachO::LC_SEGMENT_64) {
887 MachOSegment MOSegment;
888 getSegment(Obj, Load, MOSegment);
889 DictScope Group(W, "Segment");
890 W.printString("Cmd", MOSegment.CmdName);
891 W.printString("Name", MOSegment.SegName);
892 W.printNumber("Size", MOSegment.cmdsize);
893 W.printHex("vmaddr", MOSegment.vmaddr);
894 W.printHex("vmsize", MOSegment.vmsize);
895 W.printNumber("fileoff", MOSegment.fileoff);
896 W.printNumber("filesize", MOSegment.filesize);
897 W.printString("maxprot", getMask(MOSegment.maxprot));
898 W.printString("initprot", getMask(MOSegment.initprot));
899 W.printNumber("nsects", MOSegment.nsects);
900 W.printHex("flags", MOSegment.flags);
905 void MachODumper::printMachOIndirectSymbols() {
906 for (const auto &Load : Obj->load_commands()) {
907 if (Load.C.cmd == MachO::LC_DYSYMTAB) {
908 MachO::dysymtab_command DLC = Obj->getDysymtabLoadCommand();
909 DictScope Group(W, "Indirect Symbols");
910 W.printNumber("Number", DLC.nindirectsyms);
911 ListScope D(W, "Symbols");
912 for (unsigned i = 0; i < DLC.nindirectsyms; ++i) {
913 DictScope Group(W, "Entry");
914 W.printNumber("Entry Index", i);
915 W.printHex("Symbol Index", Obj->getIndirectSymbolTableEntry(DLC, i));
921 void MachODumper::printMachOLinkerOptions() {
922 for (const auto &Load : Obj->load_commands()) {
923 if (Load.C.cmd == MachO::LC_LINKER_OPTION) {
924 MachO::linker_option_command LOLC = Obj->getLinkerOptionLoadCommand(Load);
925 DictScope Group(W, "Linker Options");
926 W.printNumber("Size", LOLC.cmdsize);
927 ListScope D(W, "Strings");
928 uint64_t DataSize = LOLC.cmdsize - sizeof(MachO::linker_option_command);
929 const char *P = Load.Ptr + sizeof(MachO::linker_option_command);
930 StringRef Data(P, DataSize);
931 for (unsigned i = 0; i < LOLC.count; ++i) {
932 std::pair<StringRef,StringRef> Split = Data.split('\0');
933 W.printString("Value", Split.first);
934 Data = Split.second;