bd9bd61e9ede99b674e7cf42a081b3831ad555ba
[oota-llvm.git] / lib / CodeGen / MachO.h
1 //=== MachO.h - Mach-O structures and constants -----------------*- C++ -*-===//
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 defines MachO .
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef MACHO_H
15 #define MACHO_H
16
17 #include "llvm/Constants.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/CodeGen/MachineRelocation.h"
20 #include "llvm/Target/TargetAsmInfo.h"
21 #include <string>
22 #include <vector>
23
24 namespace llvm {
25
26 typedef std::vector<unsigned char> DataBuffer;
27   
28 /// MachOSym - This struct contains information about each symbol that is
29 /// added to logical symbol table for the module.  This is eventually
30 /// turned into a real symbol table in the file.
31 struct MachOSym {
32   const GlobalValue *GV;    // The global value this corresponds to.
33   std::string GVName;       // The mangled name of the global value.
34   uint32_t    n_strx;       // index into the string table
35   uint8_t     n_type;       // type flag
36   uint8_t     n_sect;       // section number or NO_SECT
37   int16_t     n_desc;       // see <mach-o/stab.h>
38   uint64_t    n_value;      // value for this symbol (or stab offset)
39   
40   // Constants for the n_sect field
41   // see <mach-o/nlist.h>
42   enum { NO_SECT = 0 };   // symbol is not in any section
43
44   // Constants for the n_type field
45   // see <mach-o/nlist.h>
46   enum { N_UNDF  = 0x0,  // undefined, n_sect == NO_SECT
47          N_ABS   = 0x2,  // absolute, n_sect == NO_SECT
48          N_SECT  = 0xe,  // defined in section number n_sect
49          N_PBUD  = 0xc,  // prebound undefined (defined in a dylib)
50          N_INDR  = 0xa   // indirect
51   };
52   // The following bits are OR'd into the types above. For example, a type
53   // of 0x0f would be an external N_SECT symbol (0x0e | 0x01).
54   enum { N_EXT  = 0x01,   // external symbol bit
55          N_PEXT = 0x10    // private external symbol bit
56   };
57   
58   // Constants for the n_desc field
59   // see <mach-o/loader.h>
60   enum { REFERENCE_FLAG_UNDEFINED_NON_LAZY          = 0,
61          REFERENCE_FLAG_UNDEFINED_LAZY              = 1,
62          REFERENCE_FLAG_DEFINED                     = 2,
63          REFERENCE_FLAG_PRIVATE_DEFINED             = 3,
64          REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY  = 4,
65          REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY      = 5
66   };
67   enum { N_NO_DEAD_STRIP = 0x0020, // symbol is not to be dead stripped
68          N_WEAK_REF      = 0x0040, // symbol is weak referenced
69          N_WEAK_DEF      = 0x0080  // coalesced symbol is a weak definition
70   };
71   
72   MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
73            const TargetAsmInfo *TAI);
74
75   struct SymCmp {
76     // FIXME: this does not appear to be sorting 'f' after 'F'
77     bool operator()(const MachOSym &LHS, const MachOSym &RHS) {
78       return LHS.GVName < RHS.GVName;
79     }
80   };
81
82
83   /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
84   /// a local symbol rather than an external symbol.
85   
86   static inline bool PartitionByLocal(const MachOSym &Sym) {
87     return (Sym.n_type & (MachOSym::N_EXT | MachOSym::N_PEXT)) == 0;
88   }
89   
90   /// PartitionByDefined - Simple boolean predicate that returns true if Sym is
91   /// defined in this module.
92   
93   static inline bool PartitionByDefined(const MachOSym &Sym) {
94     // FIXME: Do N_ABS or N_INDR count as defined?
95     return (Sym.n_type & MachOSym::N_SECT) == MachOSym::N_SECT;
96   }
97
98 }; // end struct MachOSym
99
100 /// MachOHeader - This struct contains the header information about a
101 /// specific architecture type/subtype pair that is emitted to the file.
102
103 struct MachOHeader {
104   uint32_t  magic;      // mach magic number identifier
105   uint32_t  filetype;   // type of file
106   uint32_t  ncmds;      // number of load commands
107   uint32_t  sizeofcmds; // the size of all the load commands
108   uint32_t  flags;      // flags
109   uint32_t  reserved;   // 64-bit only
110   
111   /// HeaderData - The actual data for the header which we are building
112   /// up for emission to the file.
113   DataBuffer HeaderData;
114
115   // Constants for the filetype field
116   // see <mach-o/loader.h> for additional info on the various types
117   enum { MH_OBJECT     = 1, // relocatable object file
118          MH_EXECUTE    = 2, // demand paged executable file
119          MH_FVMLIB     = 3, // fixed VM shared library file
120          MH_CORE       = 4, // core file
121          MH_PRELOAD    = 5, // preloaded executable file
122          MH_DYLIB      = 6, // dynamically bound shared library
123          MH_DYLINKER   = 7, // dynamic link editor
124          MH_BUNDLE     = 8, // dynamically bound bundle file
125          MH_DYLIB_STUB = 9, // shared library stub for static linking only
126          MH_DSYM       = 10 // companion file wiht only debug sections
127   };
128   
129   // Constants for the flags field
130   enum { MH_NOUNDEFS                = 1 << 0,
131             // the object file has no undefined references
132          MH_INCRLINK                = 1 << 1,
133             // the object file is the output of an incremental link against
134             // a base file and cannot be link edited again
135          MH_DYLDLINK                = 1 << 2,
136             // the object file is input for the dynamic linker and cannot be
137             // statically link edited again.
138          MH_BINDATLOAD              = 1 << 3,
139             // the object file's undefined references are bound by the
140             // dynamic linker when loaded.
141          MH_PREBOUND                = 1 << 4,
142             // the file has its dynamic undefined references prebound
143          MH_SPLIT_SEGS              = 1 << 5,
144             // the file has its read-only and read-write segments split
145             // see <mach/shared_memory_server.h>
146          MH_LAZY_INIT               = 1 << 6,
147             // the shared library init routine is to be run lazily via
148             // catching memory faults to its writable segments (obsolete)
149          MH_TWOLEVEL                = 1 << 7,
150             // the image is using two-level namespace bindings
151          MH_FORCE_FLAT              = 1 << 8,
152             // the executable is forcing all images to use flat namespace
153             // bindings.
154          MH_NOMULTIDEFS             = 1 << 8,
155             // this umbrella guarantees no multiple definitions of symbols
156             // in its sub-images so the two-level namespace hints can
157             // always be used.
158          MH_NOFIXPREBINDING         = 1 << 10,
159             // do not have dyld notify the prebidning agent about this
160             // executable.
161          MH_PREBINDABLE             = 1 << 11,
162             // the binary is not prebound but can have its prebinding
163             // redone.  only used when MH_PREBOUND is not set.
164          MH_ALLMODSBOUND            = 1 << 12,
165             // indicates that this binary binds to all two-level namespace
166             // modules of its dependent libraries.  Only used when
167             // MH_PREBINDABLE and MH_TWOLEVEL are both set.
168          MH_SUBSECTIONS_VIA_SYMBOLS = 1 << 13,
169             // safe to divide up the sections into sub-sections via symbols
170             // for dead code stripping.
171          MH_CANONICAL               = 1 << 14,
172             // the binary has been canonicalized via the unprebind operation
173          MH_WEAK_DEFINES            = 1 << 15,
174             // the final linked image contains external weak symbols
175          MH_BINDS_TO_WEAK           = 1 << 16,
176             // the final linked image uses weak symbols
177          MH_ALLOW_STACK_EXECUTION   = 1 << 17
178             // When this bit is set, all stacks in the task will be given
179             // stack execution privilege.  Only used in MH_EXECUTE filetype
180   };
181
182   MachOHeader() : magic(0), filetype(0), ncmds(0), sizeofcmds(0), flags(0),
183                   reserved(0) { }
184   
185   /// cmdSize - This routine returns the size of the MachOSection as written
186   /// to disk, depending on whether the destination is a 64 bit Mach-O file.
187   unsigned cmdSize(bool is64Bit) const {
188     if (is64Bit)
189       return 8 * sizeof(uint32_t);
190     else
191       return 7 * sizeof(uint32_t);
192   }
193
194   /// setMagic - This routine sets the appropriate value for the 'magic'
195   /// field based on pointer size and endianness.
196   void setMagic(bool isLittleEndian, bool is64Bit) {
197     if (isLittleEndian)
198       if (is64Bit) magic = 0xcffaedfe;
199       else         magic = 0xcefaedfe;
200     else
201       if (is64Bit) magic = 0xfeedfacf;
202       else         magic = 0xfeedface;
203   }
204
205 }; // end struct MachOHeader
206     
207 /// MachOSegment - This struct contains the necessary information to
208 /// emit the load commands for each section in the file.
209 struct MachOSegment {
210   uint32_t    cmd;      // LC_SEGMENT or LC_SEGMENT_64
211   uint32_t    cmdsize;  // Total size of this struct and section commands
212   std::string segname;  // segment name
213   uint64_t    vmaddr;   // address of this segment
214   uint64_t    vmsize;   // size of this segment, may be larger than filesize
215   uint64_t    fileoff;  // offset in file
216   uint64_t    filesize; // amount to read from file
217   uint32_t    maxprot;  // maximum VM protection
218   uint32_t    initprot; // initial VM protection
219   uint32_t    nsects;   // number of sections in this segment
220   uint32_t    flags;    // flags
221   
222   // The following constants are getting pulled in by one of the
223   // system headers, which creates a neat clash with the enum.
224 #if !defined(VM_PROT_NONE)
225 #define VM_PROT_NONE    0x00
226 #endif
227 #if !defined(VM_PROT_READ)
228 #define VM_PROT_READ    0x01
229 #endif
230 #if !defined(VM_PROT_WRITE)
231 #define VM_PROT_WRITE   0x02
232 #endif
233 #if !defined(VM_PROT_EXECUTE)
234 #define VM_PROT_EXECUTE 0x04
235 #endif
236 #if !defined(VM_PROT_ALL)
237 #define VM_PROT_ALL     0x07
238 #endif
239
240   // Constants for the vm protection fields
241   // see <mach-o/vm_prot.h>
242   enum { SEG_VM_PROT_NONE     = VM_PROT_NONE, 
243          SEG_VM_PROT_READ     = VM_PROT_READ, // read permission
244          SEG_VM_PROT_WRITE    = VM_PROT_WRITE, // write permission
245          SEG_VM_PROT_EXECUTE  = VM_PROT_EXECUTE,
246          SEG_VM_PROT_ALL      = VM_PROT_ALL
247   };
248   
249   // Constants for the cmd field
250   // see <mach-o/loader.h>
251   enum { LC_SEGMENT    = 0x01,  // segment of this file to be mapped
252          LC_SEGMENT_64 = 0x19   // 64-bit segment of this file to be mapped
253   };
254   
255   /// cmdSize - This routine returns the size of the MachOSection as written
256   /// to disk, depending on whether the destination is a 64 bit Mach-O file.
257   unsigned cmdSize(bool is64Bit) const {
258     if (is64Bit)
259       return 6 * sizeof(uint32_t) + 4 * sizeof(uint64_t) + 16;
260     else
261       return 10 * sizeof(uint32_t) + 16;  // addresses only 32 bits
262   }
263
264   MachOSegment(const std::string &seg, bool is64Bit)
265     : cmd(is64Bit ? LC_SEGMENT_64 : LC_SEGMENT), cmdsize(0), segname(seg),
266       vmaddr(0), vmsize(0), fileoff(0), filesize(0), maxprot(VM_PROT_ALL),
267       initprot(VM_PROT_ALL), nsects(0), flags(0) { }
268 };
269
270 /// MachOSection - This struct contains information about each section in a 
271 /// particular segment that is emitted to the file.  This is eventually
272 /// turned into the SectionCommand in the load command for a particlar
273 /// segment.
274
275 struct MachOSection { 
276   std::string  sectname; // name of this section, 
277   std::string  segname;  // segment this section goes in
278   uint64_t  addr;        // memory address of this section
279   uint64_t  size;        // size in bytes of this section
280   uint32_t  offset;      // file offset of this section
281   uint32_t  align;       // section alignment (power of 2)
282   uint32_t  reloff;      // file offset of relocation entries
283   uint32_t  nreloc;      // number of relocation entries
284   uint32_t  flags;       // flags (section type and attributes)
285   uint32_t  reserved1;   // reserved (for offset or index)
286   uint32_t  reserved2;   // reserved (for count or sizeof)
287   uint32_t  reserved3;   // reserved (64 bit only)
288   
289   /// A unique number for this section, which will be used to match symbols
290   /// to the correct section.
291   uint32_t Index;
292   
293   /// SectionData - The actual data for this section which we are building
294   /// up for emission to the file.
295   DataBuffer SectionData;
296
297   /// RelocBuffer - A buffer to hold the mach-o relocations before we write
298   /// them out at the appropriate location in the file.
299   DataBuffer RelocBuffer;
300   
301   /// Relocations - The relocations that we have encountered so far in this 
302   /// section that we will need to convert to MachORelocation entries when
303   /// the file is written.
304   std::vector<MachineRelocation> Relocations;
305   
306   // Constants for the section types (low 8 bits of flags field)
307   // see <mach-o/loader.h>
308   enum { S_REGULAR = 0,
309             // regular section
310          S_ZEROFILL = 1,
311             // zero fill on demand section
312          S_CSTRING_LITERALS = 2,
313             // section with only literal C strings
314          S_4BYTE_LITERALS = 3,
315             // section with only 4 byte literals
316          S_8BYTE_LITERALS = 4,
317             // section with only 8 byte literals
318          S_LITERAL_POINTERS = 5, 
319             // section with only pointers to literals
320          S_NON_LAZY_SYMBOL_POINTERS = 6,
321             // section with only non-lazy symbol pointers
322          S_LAZY_SYMBOL_POINTERS = 7,
323             // section with only lazy symbol pointers
324          S_SYMBOL_STUBS = 8,
325             // section with only symbol stubs
326             // byte size of stub in the reserved2 field
327          S_MOD_INIT_FUNC_POINTERS = 9,
328             // section with only function pointers for initialization
329          S_MOD_TERM_FUNC_POINTERS = 10,
330             // section with only function pointers for termination
331          S_COALESCED = 11,
332             // section contains symbols that are coalesced
333          S_GB_ZEROFILL = 12,
334             // zero fill on demand section (that can be larger than 4GB)
335          S_INTERPOSING = 13,
336             // section with only pairs of function pointers for interposing
337          S_16BYTE_LITERALS = 14
338             // section with only 16 byte literals
339   };
340   
341   // Constants for the section flags (high 24 bits of flags field)
342   // see <mach-o/loader.h>
343   enum { S_ATTR_PURE_INSTRUCTIONS   = 1 << 31,
344             // section contains only true machine instructions
345          S_ATTR_NO_TOC              = 1 << 30,
346             // section contains coalesced symbols that are not to be in a 
347             // ranlib table of contents
348          S_ATTR_STRIP_STATIC_SYMS   = 1 << 29,
349             // ok to strip static symbols in this section in files with the
350             // MY_DYLDLINK flag
351          S_ATTR_NO_DEAD_STRIP       = 1 << 28,
352             // no dead stripping
353          S_ATTR_LIVE_SUPPORT        = 1 << 27,
354             // blocks are live if they reference live blocks
355          S_ATTR_SELF_MODIFYING_CODE = 1 << 26,
356             // used with i386 code stubs written on by dyld
357          S_ATTR_DEBUG               = 1 << 25,
358             // a debug section
359          S_ATTR_SOME_INSTRUCTIONS   = 1 << 10,
360             // section contains some machine instructions
361          S_ATTR_EXT_RELOC           = 1 << 9,
362             // section has external relocation entries
363          S_ATTR_LOC_RELOC           = 1 << 8
364             // section has local relocation entries
365   };
366
367   /// cmdSize - This routine returns the size of the MachOSection as written
368   /// to disk, depending on whether the destination is a 64 bit Mach-O file.
369   unsigned cmdSize(bool is64Bit) const {
370     if (is64Bit)
371       return 7 * sizeof(uint32_t) + 2 * sizeof(uint64_t) + 32;
372     else
373       return 9 * sizeof(uint32_t) + 32;  // addresses only 32 bits
374   }
375
376   MachOSection(const std::string &seg, const std::string &sect)
377     : sectname(sect), segname(seg), addr(0), size(0), offset(0), align(2),
378       reloff(0), nreloc(0), flags(0), reserved1(0), reserved2(0),
379       reserved3(0) { }
380
381 }; // end struct MachOSection
382
383     /// MachOSymTab - This struct contains information about the offsets and 
384     /// size of symbol table information.
385     /// segment.
386     struct MachODySymTab {
387       uint32_t cmd;             // LC_DYSYMTAB
388       uint32_t cmdsize;         // sizeof( MachODySymTab )
389       uint32_t ilocalsym;       // index to local symbols
390       uint32_t nlocalsym;       // number of local symbols
391       uint32_t iextdefsym;      // index to externally defined symbols
392       uint32_t nextdefsym;      // number of externally defined symbols
393       uint32_t iundefsym;       // index to undefined symbols
394       uint32_t nundefsym;       // number of undefined symbols
395       uint32_t tocoff;          // file offset to table of contents
396       uint32_t ntoc;            // number of entries in table of contents
397       uint32_t modtaboff;       // file offset to module table
398       uint32_t nmodtab;         // number of module table entries
399       uint32_t extrefsymoff;    // offset to referenced symbol table
400       uint32_t nextrefsyms;     // number of referenced symbol table entries
401       uint32_t indirectsymoff;  // file offset to the indirect symbol table
402       uint32_t nindirectsyms;   // number of indirect symbol table entries
403       uint32_t extreloff;       // offset to external relocation entries
404       uint32_t nextrel;         // number of external relocation entries
405       uint32_t locreloff;       // offset to local relocation entries
406       uint32_t nlocrel;         // number of local relocation entries
407
408       // Constants for the cmd field
409       // see <mach-o/loader.h>
410       enum { LC_DYSYMTAB = 0x0B  // dynamic link-edit symbol table info
411       };
412       
413       MachODySymTab() : cmd(LC_DYSYMTAB), cmdsize(20 * sizeof(uint32_t)),
414         ilocalsym(0), nlocalsym(0), iextdefsym(0), nextdefsym(0),
415         iundefsym(0), nundefsym(0), tocoff(0), ntoc(0), modtaboff(0),
416         nmodtab(0), extrefsymoff(0), nextrefsyms(0), indirectsymoff(0),
417         nindirectsyms(0), extreloff(0), nextrel(0), locreloff(0), nlocrel(0) { }
418     };
419
420 } // end namespace llvm
421
422 #endif
423