1 //=== MachOWriter.h - Target-independent Mach-O writer support --*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Nate Begeman and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the MachOWriter class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CODEGEN_MACHOWRITER_H
15 #define LLVM_CODEGEN_MACHOWRITER_H
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/MachineRelocation.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetMachine.h"
22 #include "llvm/Target/TargetMachOWriterInfo.h"
27 class MachineCodeEmitter;
28 class MachOCodeEmitter;
30 /// MachOSym - This struct contains information about each symbol that is
31 /// added to logical symbol table for the module. This is eventually
32 /// turned into a real symbol table in the file.
34 const GlobalValue *GV; // The global value this corresponds to.
35 std::string GVName; // The mangled name of the global value.
36 uint32_t n_strx; // index into the string table
37 uint8_t n_type; // type flag
38 uint8_t n_sect; // section number or NO_SECT
39 int16_t n_desc; // see <mach-o/stab.h>
40 uint64_t n_value; // value for this symbol (or stab offset)
42 // Constants for the n_sect field
43 // see <mach-o/nlist.h>
44 enum { NO_SECT = 0 }; // symbol is not in any section
46 // Constants for the n_type field
47 // see <mach-o/nlist.h>
48 enum { N_UNDF = 0x0, // undefined, n_sect == NO_SECT
49 N_ABS = 0x2, // absolute, n_sect == NO_SECT
50 N_SECT = 0xe, // defined in section number n_sect
51 N_PBUD = 0xc, // prebound undefined (defined in a dylib)
52 N_INDR = 0xa // indirect
54 // The following bits are OR'd into the types above. For example, a type
55 // of 0x0f would be an external N_SECT symbol (0x0e | 0x01).
56 enum { N_EXT = 0x01, // external symbol bit
57 N_PEXT = 0x10 // private external symbol bit
60 // Constants for the n_desc field
61 // see <mach-o/loader.h>
62 enum { REFERENCE_FLAG_UNDEFINED_NON_LAZY = 0,
63 REFERENCE_FLAG_UNDEFINED_LAZY = 1,
64 REFERENCE_FLAG_DEFINED = 2,
65 REFERENCE_FLAG_PRIVATE_DEFINED = 3,
66 REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY = 4,
67 REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY = 5
69 enum { N_NO_DEAD_STRIP = 0x0020, // symbol is not to be dead stripped
70 N_WEAK_REF = 0x0040, // symbol is weak referenced
71 N_WEAK_DEF = 0x0080 // coalesced symbol is a weak definition
74 MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
78 /// MachOWriter - This class implements the common target-independent code for
79 /// writing Mach-O files. Targets should derive a class from this to
80 /// parameterize the output format.
82 class MachOWriter : public MachineFunctionPass {
83 friend class MachOCodeEmitter;
85 MachineCodeEmitter &getMachineCodeEmitter() const {
86 return *(MachineCodeEmitter*)MCE;
88 virtual ~MachOWriter();
90 virtual const char *getPassName() const {
91 return "Mach-O Writer";
94 typedef std::vector<unsigned char> DataBuffer;
96 MachOWriter(std::ostream &O, TargetMachine &TM);
98 /// Output stream to send the resultant object file to.
102 /// Target machine description.
106 /// Mang - The object used to perform name mangling for this module.
110 /// MCE - The MachineCodeEmitter object that we are exposing to emit machine
111 /// code for functions to the .o file.
112 MachOCodeEmitter *MCE;
114 /// is64Bit/isLittleEndian - This information is inferred from the target
115 /// machine directly, indicating what header values and flags to set.
116 bool is64Bit, isLittleEndian;
118 /// doInitialization - Emit the file header and all of the global variables
119 /// for the module to the Mach-O file.
120 bool doInitialization(Module &M);
122 bool runOnMachineFunction(MachineFunction &MF);
124 /// doFinalization - Now that the module has been completely processed, emit
125 /// the Mach-O file to 'O'.
126 bool doFinalization(Module &M);
128 /// MachOHeader - This struct contains the header information about a
129 /// specific architecture type/subtype pair that is emitted to the file.
131 uint32_t magic; // mach magic number identifier
132 uint32_t filetype; // type of file
133 uint32_t ncmds; // number of load commands
134 uint32_t sizeofcmds; // the size of all the load commands
135 uint32_t flags; // flags
136 uint32_t reserved; // 64-bit only
138 /// HeaderData - The actual data for the header which we are building
139 /// up for emission to the file.
140 DataBuffer HeaderData;
142 // Constants for the filetype field
143 // see <mach-o/loader.h> for additional info on the various types
144 enum { MH_OBJECT = 1, // relocatable object file
145 MH_EXECUTE = 2, // demand paged executable file
146 MH_FVMLIB = 3, // fixed VM shared library file
147 MH_CORE = 4, // core file
148 MH_PRELOAD = 5, // preloaded executable file
149 MH_DYLIB = 6, // dynamically bound shared library
150 MH_DYLINKER = 7, // dynamic link editor
151 MH_BUNDLE = 8, // dynamically bound bundle file
152 MH_DYLIB_STUB = 9, // shared library stub for static linking only
153 MH_DSYM = 10 // companion file wiht only debug sections
156 // Constants for the flags field
157 enum { MH_NOUNDEFS = 1 << 0,
158 // the object file has no undefined references
159 MH_INCRLINK = 1 << 1,
160 // the object file is the output of an incremental link against
161 // a base file and cannot be link edited again
162 MH_DYLDLINK = 1 << 2,
163 // the object file is input for the dynamic linker and cannot be
164 // statically link edited again.
165 MH_BINDATLOAD = 1 << 3,
166 // the object file's undefined references are bound by the
167 // dynamic linker when loaded.
168 MH_PREBOUND = 1 << 4,
169 // the file has its dynamic undefined references prebound
170 MH_SPLIT_SEGS = 1 << 5,
171 // the file has its read-only and read-write segments split
172 // see <mach/shared_memory_server.h>
173 MH_LAZY_INIT = 1 << 6,
174 // the shared library init routine is to be run lazily via
175 // catching memory faults to its writable segments (obsolete)
176 MH_TWOLEVEL = 1 << 7,
177 // the image is using two-level namespace bindings
178 MH_FORCE_FLAT = 1 << 8,
179 // the executable is forcing all images to use flat namespace
181 MH_NOMULTIDEFS = 1 << 8,
182 // this umbrella guarantees no multiple definitions of symbols
183 // in its sub-images so the two-level namespace hints can
185 MH_NOFIXPREBINDING = 1 << 10,
186 // do not have dyld notify the prebidning agent about this
188 MH_PREBINDABLE = 1 << 11,
189 // the binary is not prebound but can have its prebinding
190 // redone. only used when MH_PREBOUND is not set.
191 MH_ALLMODSBOUND = 1 << 12,
192 // indicates that this binary binds to all two-level namespace
193 // modules of its dependent libraries. Only used when
194 // MH_PREBINDABLE and MH_TWOLEVEL are both set.
195 MH_SUBSECTIONS_VIA_SYMBOLS = 1 << 13,
196 // safe to divide up the sections into sub-sections via symbols
197 // for dead code stripping.
198 MH_CANONICAL = 1 << 14,
199 // the binary has been canonicalized via the unprebind operation
200 MH_WEAK_DEFINES = 1 << 15,
201 // the final linked image contains external weak symbols
202 MH_BINDS_TO_WEAK = 1 << 16,
203 // the final linked image uses weak symbols
204 MH_ALLOW_STACK_EXECUTION = 1 << 17
205 // When this bit is set, all stacks in the task will be given
206 // stack execution privilege. Only used in MH_EXECUTE filetype
209 MachOHeader() : magic(0), filetype(0), ncmds(0), sizeofcmds(0), flags(0),
212 /// cmdSize - This routine returns the size of the MachOSection as written
213 /// to disk, depending on whether the destination is a 64 bit Mach-O file.
214 unsigned cmdSize(bool is64Bit) const {
216 return 8 * sizeof(uint32_t);
218 return 7 * sizeof(uint32_t);
221 /// setMagic - This routine sets the appropriate value for the 'magic'
222 /// field based on pointer size and endianness.
223 void setMagic(bool isLittleEndian, bool is64Bit) {
225 if (is64Bit) magic = 0xcffaedfe;
226 else magic = 0xcefaedfe;
228 if (is64Bit) magic = 0xfeedfacf;
229 else magic = 0xfeedface;
233 /// Header - An instance of MachOHeader that we will update while we build
234 /// the file, and then emit during finalization.
237 /// MachOSegment - This struct contains the necessary information to
238 /// emit the load commands for each section in the file.
239 struct MachOSegment {
240 uint32_t cmd; // LC_SEGMENT or LC_SEGMENT_64
241 uint32_t cmdsize; // Total size of this struct and section commands
242 std::string segname; // segment name
243 uint64_t vmaddr; // address of this segment
244 uint64_t vmsize; // size of this segment, may be larger than filesize
245 uint64_t fileoff; // offset in file
246 uint64_t filesize; // amount to read from file
247 uint32_t maxprot; // maximum VM protection
248 uint32_t initprot; // initial VM protection
249 uint32_t nsects; // number of sections in this segment
250 uint32_t flags; // flags
252 // The following constants are getting pulled in by one of the
253 // system headers, which creates a neat clash with the enum.
254 #if !defined(VM_PROT_NONE)
255 #define VM_PROT_NONE 0x00
257 #if !defined(VM_PROT_READ)
258 #define VM_PROT_READ 0x01
260 #if !defined(VM_PROT_WRITE)
261 #define VM_PROT_WRITE 0x02
263 #if !defined(VM_PROT_EXECUTE)
264 #define VM_PROT_EXECUTE 0x04
266 #if !defined(VM_PROT_ALL)
267 #define VM_PROT_ALL 0x07
270 // Constants for the vm protection fields
271 // see <mach-o/vm_prot.h>
272 enum { SEG_VM_PROT_NONE = VM_PROT_NONE,
273 SEG_VM_PROT_READ = VM_PROT_READ, // read permission
274 SEG_VM_PROT_WRITE = VM_PROT_WRITE, // write permission
275 SEG_VM_PROT_EXECUTE = VM_PROT_EXECUTE,
276 SEG_VM_PROT_ALL = VM_PROT_ALL
279 // Constants for the cmd field
280 // see <mach-o/loader.h>
281 enum { LC_SEGMENT = 0x01, // segment of this file to be mapped
282 LC_SEGMENT_64 = 0x19 // 64-bit segment of this file to be mapped
285 /// cmdSize - This routine returns the size of the MachOSection as written
286 /// to disk, depending on whether the destination is a 64 bit Mach-O file.
287 unsigned cmdSize(bool is64Bit) const {
289 return 6 * sizeof(uint32_t) + 4 * sizeof(uint64_t) + 16;
291 return 10 * sizeof(uint32_t) + 16; // addresses only 32 bits
294 MachOSegment(const std::string &seg, bool is64Bit)
295 : cmd(is64Bit ? LC_SEGMENT_64 : LC_SEGMENT), cmdsize(0), segname(seg),
296 vmaddr(0), vmsize(0), fileoff(0), filesize(0), maxprot(VM_PROT_ALL),
297 initprot(VM_PROT_ALL), nsects(0), flags(0) { }
300 /// MachORelocation - This struct contains information about each relocation
301 /// that needs to be emitted to the file.
302 /// see <mach-o/reloc.h>
303 struct MachORelocation {
304 uint32_t r_address; // offset in the section to what is being relocated
305 uint32_t r_symbolnum; // symbol index if r_extern == 1 else section index
306 bool r_pcrel; // was relocated pc-relative already
307 uint8_t r_length; // length = 2 ^ r_length
309 uint8_t r_type; // if not 0, machine-specific relocation type.
311 uint32_t getPackedFields() {
312 return (r_symbolnum << 8) | (r_pcrel << 7) | ((r_length & 3) << 5) |
313 (r_extern << 4) | (r_type & 15);
316 MachORelocation(uint32_t addr, uint32_t index, bool pcrel, uint8_t len,
317 bool ext, uint8_t type) : r_address(addr),
318 r_symbolnum(index), r_pcrel(pcrel), r_length(len), r_extern(ext),
322 /// MachOSection - This struct contains information about each section in a
323 /// particular segment that is emitted to the file. This is eventually
324 /// turned into the SectionCommand in the load command for a particlar
326 struct MachOSection {
327 std::string sectname; // name of this section,
328 std::string segname; // segment this section goes in
329 uint64_t addr; // memory address of this section
330 uint64_t size; // size in bytes of this section
331 uint32_t offset; // file offset of this section
332 uint32_t align; // section alignment (power of 2)
333 uint32_t reloff; // file offset of relocation entries
334 uint32_t nreloc; // number of relocation entries
335 uint32_t flags; // flags (section type and attributes)
336 uint32_t reserved1; // reserved (for offset or index)
337 uint32_t reserved2; // reserved (for count or sizeof)
338 uint32_t reserved3; // reserved (64 bit only)
340 /// A unique number for this section, which will be used to match symbols
341 /// to the correct section.
344 /// SectionData - The actual data for this section which we are building
345 /// up for emission to the file.
346 DataBuffer SectionData;
348 /// RelocBuffer - A buffer to hold the mach-o relocations before we write
349 /// them out at the appropriate location in the file.
350 DataBuffer RelocBuffer;
352 /// Relocations - The relocations that we have encountered so far in this
353 /// section that we will need to convert to MachORelocation entries when
354 /// the file is written.
355 std::vector<MachineRelocation> Relocations;
357 // Constants for the section types (low 8 bits of flags field)
358 // see <mach-o/loader.h>
359 enum { S_REGULAR = 0,
362 // zero fill on demand section
363 S_CSTRING_LITERALS = 2,
364 // section with only literal C strings
365 S_4BYTE_LITERALS = 3,
366 // section with only 4 byte literals
367 S_8BYTE_LITERALS = 4,
368 // section with only 8 byte literals
369 S_LITERAL_POINTERS = 5,
370 // section with only pointers to literals
371 S_NON_LAZY_SYMBOL_POINTERS = 6,
372 // section with only non-lazy symbol pointers
373 S_LAZY_SYMBOL_POINTERS = 7,
374 // section with only lazy symbol pointers
376 // section with only symbol stubs
377 // byte size of stub in the reserved2 field
378 S_MOD_INIT_FUNC_POINTERS = 9,
379 // section with only function pointers for initialization
380 S_MOD_TERM_FUNC_POINTERS = 10,
381 // section with only function pointers for termination
383 // section contains symbols that are coalesced
385 // zero fill on demand section (that can be larger than 4GB)
387 // section with only pairs of function pointers for interposing
388 S_16BYTE_LITERALS = 14
389 // section with only 16 byte literals
392 // Constants for the section flags (high 24 bits of flags field)
393 // see <mach-o/loader.h>
394 enum { S_ATTR_PURE_INSTRUCTIONS = 1 << 31,
395 // section contains only true machine instructions
396 S_ATTR_NO_TOC = 1 << 30,
397 // section contains coalesced symbols that are not to be in a
398 // ranlib table of contents
399 S_ATTR_STRIP_STATIC_SYMS = 1 << 29,
400 // ok to strip static symbols in this section in files with the
402 S_ATTR_NO_DEAD_STRIP = 1 << 28,
404 S_ATTR_LIVE_SUPPORT = 1 << 27,
405 // blocks are live if they reference live blocks
406 S_ATTR_SELF_MODIFYING_CODE = 1 << 26,
407 // used with i386 code stubs written on by dyld
408 S_ATTR_DEBUG = 1 << 25,
410 S_ATTR_SOME_INSTRUCTIONS = 1 << 10,
411 // section contains some machine instructions
412 S_ATTR_EXT_RELOC = 1 << 9,
413 // section has external relocation entries
414 S_ATTR_LOC_RELOC = 1 << 8
415 // section has local relocation entries
418 /// cmdSize - This routine returns the size of the MachOSection as written
419 /// to disk, depending on whether the destination is a 64 bit Mach-O file.
420 unsigned cmdSize(bool is64Bit) const {
422 return 7 * sizeof(uint32_t) + 2 * sizeof(uint64_t) + 32;
424 return 9 * sizeof(uint32_t) + 32; // addresses only 32 bits
427 MachOSection(const std::string &seg, const std::string §)
428 : sectname(sect), segname(seg), addr(0), size(0), offset(0), align(2),
429 reloff(0), nreloc(0), flags(0), reserved1(0), reserved2(0),
435 /// SectionList - This is the list of sections that we have emitted to the
436 /// file. Once the file has been completely built, the segment load command
437 /// SectionCommands are constructed from this info.
438 std::vector<MachOSection*> SectionList;
440 /// SectionLookup - This is a mapping from section name to SectionList entry
441 std::map<std::string, MachOSection*> SectionLookup;
443 /// GVSection - This is a mapping from a GlobalValue to a MachOSection,
444 /// to aid in emitting relocations.
445 std::map<GlobalValue*, MachOSection*> GVSection;
447 /// GVOffset - This is a mapping from a GlobalValue to an offset from the
448 /// start of the section in which the GV resides, to aid in emitting
450 std::map<GlobalValue*, intptr_t> GVOffset;
452 /// getSection - Return the section with the specified name, creating a new
453 /// section if one does not already exist.
454 MachOSection *getSection(const std::string &seg, const std::string §,
455 unsigned Flags = 0) {
456 MachOSection *MOS = SectionLookup[seg+sect];
459 MOS = new MachOSection(seg, sect);
460 SectionList.push_back(MOS);
461 MOS->Index = SectionList.size();
462 MOS->flags = MachOSection::S_REGULAR | Flags;
463 SectionLookup[seg+sect] = MOS;
466 MachOSection *getTextSection(bool isCode = true) {
468 return getSection("__TEXT", "__text",
469 MachOSection::S_ATTR_PURE_INSTRUCTIONS |
470 MachOSection::S_ATTR_SOME_INSTRUCTIONS);
472 return getSection("__TEXT", "__text");
474 MachOSection *getBSSSection() {
475 return getSection("__DATA", "__bss", MachOSection::S_ZEROFILL);
477 MachOSection *getDataSection() {
478 return getSection("__DATA", "__data");
480 MachOSection *getConstSection(const Type *Ty) {
481 // FIXME: support cstring literals and pointer literal
482 if (Ty->isPrimitiveType() || Ty->isInteger()) {
483 unsigned Size = TM.getTargetData()->getTypeSize(Ty);
485 default: break; // Fall through to __TEXT,__const
487 return getSection("__TEXT", "__literal4",
488 MachOSection::S_4BYTE_LITERALS);
490 return getSection("__TEXT", "__literal8",
491 MachOSection::S_8BYTE_LITERALS);
493 return getSection("__TEXT", "__literal16",
494 MachOSection::S_16BYTE_LITERALS);
497 return getSection("__TEXT", "__const");
499 MachOSection *getJumpTableSection() {
500 if (TM.getRelocationModel() == Reloc::PIC_)
501 return getTextSection(false);
503 return getSection("__TEXT", "__const");
506 /// MachOSymTab - This struct contains information about the offsets and
507 /// size of symbol table information.
510 uint32_t cmd; // LC_SYMTAB
511 uint32_t cmdsize; // sizeof( MachOSymTab )
512 uint32_t symoff; // symbol table offset
513 uint32_t nsyms; // number of symbol table entries
514 uint32_t stroff; // string table offset
515 uint32_t strsize; // string table size in bytes
517 // Constants for the cmd field
518 // see <mach-o/loader.h>
519 enum { LC_SYMTAB = 0x02 // link-edit stab symbol table info
522 MachOSymTab() : cmd(LC_SYMTAB), cmdsize(6 * sizeof(uint32_t)), symoff(0),
523 nsyms(0), stroff(0), strsize(0) { }
526 /// MachOSymTab - This struct contains information about the offsets and
527 /// size of symbol table information.
529 struct MachODySymTab {
530 uint32_t cmd; // LC_DYSYMTAB
531 uint32_t cmdsize; // sizeof( MachODySymTab )
532 uint32_t ilocalsym; // index to local symbols
533 uint32_t nlocalsym; // number of local symbols
534 uint32_t iextdefsym; // index to externally defined symbols
535 uint32_t nextdefsym; // number of externally defined symbols
536 uint32_t iundefsym; // index to undefined symbols
537 uint32_t nundefsym; // number of undefined symbols
538 uint32_t tocoff; // file offset to table of contents
539 uint32_t ntoc; // number of entries in table of contents
540 uint32_t modtaboff; // file offset to module table
541 uint32_t nmodtab; // number of module table entries
542 uint32_t extrefsymoff; // offset to referenced symbol table
543 uint32_t nextrefsyms; // number of referenced symbol table entries
544 uint32_t indirectsymoff; // file offset to the indirect symbol table
545 uint32_t nindirectsyms; // number of indirect symbol table entries
546 uint32_t extreloff; // offset to external relocation entries
547 uint32_t nextrel; // number of external relocation entries
548 uint32_t locreloff; // offset to local relocation entries
549 uint32_t nlocrel; // number of local relocation entries
551 // Constants for the cmd field
552 // see <mach-o/loader.h>
553 enum { LC_DYSYMTAB = 0x0B // dynamic link-edit symbol table info
556 MachODySymTab() : cmd(LC_DYSYMTAB), cmdsize(20 * sizeof(uint32_t)),
557 ilocalsym(0), nlocalsym(0), iextdefsym(0), nextdefsym(0),
558 iundefsym(0), nundefsym(0), tocoff(0), ntoc(0), modtaboff(0),
559 nmodtab(0), extrefsymoff(0), nextrefsyms(0), indirectsymoff(0),
560 nindirectsyms(0), extreloff(0), nextrel(0), locreloff(0), nlocrel(0) { }
563 /// SymTab - The "stab" style symbol table information
565 /// DySymTab - symbol table info for the dynamic link editor
566 MachODySymTab DySymTab;
569 // FIXME: this does not appear to be sorting 'f' after 'F'
570 bool operator()(const MachOSym &LHS, const MachOSym &RHS) {
571 return LHS.GVName < RHS.GVName;
575 /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
576 /// a local symbol rather than an external symbol.
577 static bool PartitionByLocal(const MachOSym &Sym);
579 /// PartitionByDefined - Simple boolean predicate that returns true if Sym
580 /// is defined in this module.
581 static bool PartitionByDefined(const MachOSym &Sym);
585 /// SymbolTable - This is the list of symbols we have emitted to the file.
586 /// This actually gets rearranged before emission to the file (to put the
587 /// local symbols first in the list).
588 std::vector<MachOSym> SymbolTable;
590 /// SymT - A buffer to hold the symbol table before we write it out at the
591 /// appropriate location in the file.
594 /// StrT - A buffer to hold the string table before we write it out at the
595 /// appropriate location in the file.
598 /// PendingSyms - This is a list of externally defined symbols that we have
599 /// been asked to emit, but have not seen a reference to. When a reference
600 /// is seen, the symbol will move from this list to the SymbolTable.
601 std::vector<MachOSym> PendingSyms;
603 /// DynamicSymbolTable - This is just a vector of indices into
604 /// SymbolTable to aid in emitting the DYSYMTAB load command.
605 std::vector<unsigned> DynamicSymbolTable;
607 static void InitMem(const Constant *C, void *Addr, intptr_t Offset,
608 const TargetData *TD,
609 std::vector<MachineRelocation> &MRs);
612 void AddSymbolToSection(MachOSection *MOS, GlobalVariable *GV);
613 void EmitGlobal(GlobalVariable *GV);
614 void EmitHeaderAndLoadCommands();
616 void BufferSymbolAndStringTable();
617 void CalculateRelocations(MachOSection &MOS);
619 MachineRelocation GetJTRelocation(unsigned Offset,
620 MachineBasicBlock *MBB) const {
621 return TM.getMachOWriterInfo()->GetJTRelocation(Offset, MBB);
623 virtual void GetTargetRelocation(MachineRelocation &MR, MachOSection &From,
624 MachOSection &To) = 0;