Properly size the string table, and emit symbol table and string table
[oota-llvm.git] / include / llvm / CodeGen / MachOWriter.h
1 //=== MachOWriter.h - Target-independent Mach-O writer support --*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MachOWriter class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #ifndef LLVM_CODEGEN_MACHOWRITER_H
15 #define LLVM_CODEGEN_MACHOWRITER_H
16
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/Target/TargetData.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include <list>
22
23 namespace llvm {
24   class GlobalVariable;
25   class Mangler;
26   class MachineCodeEmitter;
27   class MachOCodeEmitter;
28
29   /// MachOWriter - This class implements the common target-independent code for
30   /// writing Mach-O files.  Targets should derive a class from this to
31   /// parameterize the output format.
32   ///
33   class MachOWriter : public MachineFunctionPass {
34     friend class MachOCodeEmitter;
35   public:
36     MachineCodeEmitter &getMachineCodeEmitter() const {
37       return *(MachineCodeEmitter*)MCE;
38     }
39
40     ~MachOWriter();
41
42     typedef std::vector<unsigned char> DataBuffer;
43
44   protected:
45     MachOWriter(std::ostream &O, TargetMachine &TM);
46
47     /// Output stream to send the resultant object file to.
48     ///
49     std::ostream &O;
50
51     /// Target machine description.
52     ///
53     TargetMachine &TM;
54
55     /// Mang - The object used to perform name mangling for this module.
56     ///
57     Mangler *Mang;
58
59     /// MCE - The MachineCodeEmitter object that we are exposing to emit machine
60     /// code for functions to the .o file.
61     MachOCodeEmitter *MCE;
62
63     /// is64Bit/isLittleEndian - This information is inferred from the target
64     /// machine directly, indicating what header values and flags to set.
65     bool is64Bit, isLittleEndian;
66
67     /// doInitialization - Emit the file header and all of the global variables
68     /// for the module to the Mach-O file.
69     bool doInitialization(Module &M);
70
71     bool runOnMachineFunction(MachineFunction &MF);
72
73     /// doFinalization - Now that the module has been completely processed, emit
74     /// the Mach-O file to 'O'.
75     bool doFinalization(Module &M);
76
77     /// MachOHeader - This struct contains the header information about a
78     /// specific architecture type/subtype pair that is emitted to the file.
79     struct MachOHeader {
80       uint32_t  magic;      // mach magic number identifier
81       uint32_t  cputype;    // cpu specifier
82       uint32_t  cpusubtype; // machine specifier
83       uint32_t  filetype;   // type of file
84       uint32_t  ncmds;      // number of load commands
85       uint32_t  sizeofcmds; // the size of all the load commands
86       uint32_t  flags;      // flags
87       uint32_t  reserved;   // 64-bit only
88       
89       /// HeaderData - The actual data for the header which we are building
90       /// up for emission to the file.
91       DataBuffer HeaderData;
92
93       // Constants for the cputype field
94       // see <mach/machine.h>
95       enum { CPU_TYPE_I386      = 7,
96              CPU_TYPE_X86_64    = 7 | 0x1000000,
97              CPU_TYPE_ARM       = 12,
98              CPU_TYPE_SPARC     = 14,
99              CPU_TYPE_POWERPC   = 18,
100              CPU_TYPE_POWERPC64 = 18 | 0x1000000
101       };
102       
103       // Constants for the cpusubtype field
104       // see <mach/machine.h>
105       enum { CPU_SUBTYPE_I386_ALL    = 3,
106              CPU_SUBTYPE_X86_64_ALL  = 3,
107              CPU_SUBTYPE_ARM_ALL     = 0,
108              CPU_SUBTYPE_SPARC_ALL   = 0,
109              CPU_SUBTYPE_POWERPC_ALL = 0
110       };
111              
112       // Constants for the filetype field
113       // see <mach-o/loader.h> for additional info on the various types
114       enum { MH_OBJECT     = 1, // relocatable object file
115              MH_EXECUTE    = 2, // demand paged executable file
116              MH_FVMLIB     = 3, // fixed VM shared library file
117              MH_CORE       = 4, // core file
118              MH_PRELOAD    = 5, // preloaded executable file
119              MH_DYLIB      = 6, // dynamically bound shared library
120              MH_DYLINKER   = 7, // dynamic link editor
121              MH_BUNDLE     = 8, // dynamically bound bundle file
122              MH_DYLIB_STUB = 9, // shared library stub for static linking only
123              MH_DSYM       = 10 // companion file wiht only debug sections
124       };
125       
126       // Constants for the flags field
127       enum { MH_NOUNDEFS                = 1 << 0,
128                 // the object file has no undefined references
129              MH_INCRLINK                = 1 << 1,
130                 // the object file is the output of an incremental link against
131                 // a base file and cannot be link edited again
132              MH_DYLDLINK                = 1 << 2,
133                 // the object file is input for the dynamic linker and cannot be
134                 // statically link edited again.
135              MH_BINDATLOAD              = 1 << 3,
136                 // the object file's undefined references are bound by the
137                 // dynamic linker when loaded.
138              MH_PREBOUND                = 1 << 4,
139                 // the file has its dynamic undefined references prebound
140              MH_SPLIT_SEGS              = 1 << 5,
141                 // the file has its read-only and read-write segments split
142                 // see <mach/shared_memory_server.h>
143              MH_LAZY_INIT               = 1 << 6,
144                 // the shared library init routine is to be run lazily via
145                 // catching memory faults to its writable segments (obsolete)
146              MH_TWOLEVEL                = 1 << 7,
147                 // the image is using two-level namespace bindings
148              MH_FORCE_FLAT              = 1 << 8,
149                 // the executable is forcing all images to use flat namespace
150                 // bindings.
151              MH_NOMULTIDEFS             = 1 << 8,
152                 // this umbrella guarantees no multiple definitions of symbols
153                 // in its sub-images so the two-level namespace hints can
154                 // always be used.
155              MH_NOFIXPREBINDING         = 1 << 10,
156                 // do not have dyld notify the prebidning agent about this
157                 // executable.
158              MH_PREBINDABLE             = 1 << 11,
159                 // the binary is not prebound but can have its prebinding
160                 // redone.  only used when MH_PREBOUND is not set.
161              MH_ALLMODSBOUND            = 1 << 12,
162                 // indicates that this binary binds to all two-level namespace
163                 // modules of its dependent libraries.  Only used when
164                 // MH_PREBINDABLE and MH_TWOLEVEL are both set.
165              MH_SUBSECTIONS_VIA_SYMBOLS = 1 << 13,
166                 // safe to divide up the sections into sub-sections via symbols
167                 // for dead code stripping.
168              MH_CANONICAL               = 1 << 14,
169                 // the binary has been canonicalized via the unprebind operation
170              MH_WEAK_DEFINES            = 1 << 15,
171                 // the final linked image contains external weak symbols
172              MH_BINDS_TO_WEAK           = 1 << 16,
173                 // the final linked image uses weak symbols
174              MH_ALLOW_STACK_EXECUTION   = 1 << 17
175                 // When this bit is set, all stacks in the task will be given
176                 // stack execution privilege.  Only used in MH_EXECUTE filetype
177       };
178
179       MachOHeader() : magic(0), cputype(0), cpusubtype(0), filetype(0),
180                       ncmds(0), sizeofcmds(0), flags(0), reserved(0) { }
181       
182       /// cmdSize - This routine returns the size of the MachOSection as written
183       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
184       unsigned cmdSize(bool is64Bit) const {
185         if (is64Bit)
186           return 8 * sizeof(uint32_t);
187         else
188           return 7 * sizeof(uint32_t);
189       }
190
191       /// setMagic - This routine sets the appropriate value for the 'magic'
192       /// field based on pointer size and endianness.
193       void setMagic(bool isLittleEndian, bool is64Bit) {
194         if (isLittleEndian)
195           if (is64Bit) magic = 0xcffaedfe;
196           else         magic = 0xcefaedfe;
197         else
198           if (is64Bit) magic = 0xfeedfacf;
199           else         magic = 0xfeedface;
200       }
201     };
202     
203     /// Header - An instance of MachOHeader that we will update while we build
204     /// the file, and then emit during finalization.
205     MachOHeader Header;
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       // Constants for the vm protection fields
223       // see <mach-o/vm_prot.h>
224       enum { VM_PROT_NONE    = 0x00, 
225              VM_PROT_READ    = 0x01, // read permission
226              VM_PROT_WRITE   = 0x02, // write permission
227              VM_PROT_EXECUTE = 0x04, // execute permission,
228              VM_PROT_ALL     = 0x07
229       };
230       
231       // Constants for the cmd field
232       // see <mach-o/loader.h>
233       enum { LC_SEGMENT    = 0x01,  // segment of this file to be mapped
234              LC_SEGMENT_64 = 0x19   // 64-bit segment of this file to be mapped
235       };
236       
237       /// cmdSize - This routine returns the size of the MachOSection as written
238       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
239       unsigned cmdSize(bool is64Bit) const {
240         if (is64Bit)
241           return 6 * sizeof(uint32_t) + 4 * sizeof(uint64_t) + 16;
242         else
243           return 10 * sizeof(uint32_t) + 16;  // addresses only 32 bits
244       }
245
246       MachOSegment(const std::string &seg, bool is64Bit)
247         : cmd(is64Bit ? LC_SEGMENT_64 : LC_SEGMENT), cmdsize(0), segname(seg),
248           vmaddr(0), vmsize(0), fileoff(0), filesize(0), maxprot(VM_PROT_ALL),
249           initprot(VM_PROT_ALL), nsects(0), flags(0) { }
250     };
251
252     /// MachOSection - This struct contains information about each section in a 
253     /// particular segment that is emitted to the file.  This is eventually
254     /// turned into the SectionCommand in the load command for a particlar
255     /// segment.
256     struct MachOSection { 
257       std::string  sectname; // name of this section, 
258       std::string  segname;  // segment this section goes in
259       uint64_t  addr;        // memory address of this section
260       uint64_t  size;        // size in bytes of this section
261       uint32_t  offset;      // file offset of this section
262       uint32_t  align;       // section alignment (power of 2)
263       uint32_t  reloff;      // file offset of relocation entries
264       uint32_t  nreloc;      // number of relocation entries
265       uint32_t  flags;       // flags (section type and attributes)
266       uint32_t  reserved1;   // reserved (for offset or index)
267       uint32_t  reserved2;   // reserved (for count or sizeof)
268       uint32_t  reserved3;   // reserved (64 bit only)
269       
270       /// A unique number for this section, which will be used to match symbols
271       /// to the correct section.
272       uint32_t Index;
273       
274       /// SectionData - The actual data for this section which we are building
275       /// up for emission to the file.
276       DataBuffer SectionData;
277       
278       // Constants for the section types (low 8 bits of flags field)
279       // see <mach-o/loader.h>
280       enum { S_REGULAR = 0,
281                 // regular section
282              S_ZEROFILL = 1,
283                 // zero fill on demand section
284              S_CSTRING_LITERALS = 2,
285                 // section with only literal C strings
286              S_4BYTE_LITERALS = 3,
287                 // section with only 4 byte literals
288              S_8BYTE_LITERALS = 4,
289                 // section with only 8 byte literals
290              S_LITERAL_POINTERS = 5, 
291                 // section with only pointers to literals
292              S_NON_LAZY_SYMBOL_POINTERS = 6,
293                 // section with only non-lazy symbol pointers
294              S_LAZY_SYMBOL_POINTERS = 7,
295                 // section with only lazy symbol pointers
296              S_SYMBOL_STUBS = 8,
297                 // section with only symbol stubs
298                 // byte size of stub in the reserved2 field
299              S_MOD_INIT_FUNC_POINTERS = 9,
300                 // section with only function pointers for initialization
301              S_MOD_TERM_FUNC_POINTERS = 10,
302                 // section with only function pointers for termination
303              S_COALESCED = 11,
304                 // section contains symbols that are coalesced
305              S_GB_ZEROFILL = 12,
306                 // zero fill on demand section (that can be larger than 4GB)
307              S_INTERPOSING = 13,
308                 // section with only pairs of function pointers for interposing
309              S_16BYTE_LITERALS = 14
310                 // section with only 16 byte literals
311       };
312       
313       // Constants for the section flags (high 24 bits of flags field)
314       // see <mach-o/loader.h>
315       enum { S_ATTR_PURE_INSTRUCTIONS   = 1 << 31,
316                 // section contains only true machine instructions
317              S_ATTR_NO_TOC              = 1 << 30,
318                 // section contains coalesced symbols that are not to be in a 
319                 // ranlib table of contents
320              S_ATTR_STRIP_STATIC_SYMS   = 1 << 29,
321                 // ok to strip static symbols in this section in files with the
322                 // MY_DYLDLINK flag
323              S_ATTR_NO_DEAD_STRIP       = 1 << 28,
324                 // no dead stripping
325              S_ATTR_LIVE_SUPPORT        = 1 << 27,
326                 // blocks are live if they reference live blocks
327              S_ATTR_SELF_MODIFYING_CODE = 1 << 26,
328                 // used with i386 code stubs written on by dyld
329              S_ATTR_DEBUG               = 1 << 25,
330                 // a debug section
331              S_ATTR_SOME_INSTRUCTIONS   = 1 << 10,
332                 // section contains some machine instructions
333              S_ATTR_EXT_RELOC           = 1 << 9,
334                 // section has external relocation entries
335              S_ATTR_LOC_RELOC           = 1 << 8
336                 // section has local relocation entries
337       };
338
339       /// cmdSize - This routine returns the size of the MachOSection as written
340       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
341       unsigned cmdSize(bool is64Bit) const {
342         if (is64Bit)
343           return 7 * sizeof(uint32_t) + 2 * sizeof(uint64_t) + 32;
344         else
345           return 9 * sizeof(uint32_t) + 32;  // addresses only 32 bits
346       }
347
348       MachOSection(const std::string &seg, const std::string &sect)
349         : sectname(sect), segname(seg), addr(0), size(0), offset(0), align(0),
350           reloff(0), nreloc(0), flags(0), reserved1(0), reserved2(0),
351           reserved3(0) { }
352     };
353
354   private:
355
356     /// SectionList - This is the list of sections that we have emitted to the
357     /// file.  Once the file has been completely built, the segment load command
358     /// SectionCommands are constructed from this info.
359     std::list<MachOSection> SectionList;
360
361     /// SectionLookup - This is a mapping from section name to SectionList entry
362     std::map<std::string, MachOSection*> SectionLookup;
363
364     /// getSection - Return the section with the specified name, creating a new
365     /// section if one does not already exist.
366     MachOSection &getSection(const std::string &seg, const std::string &sect,
367                              unsigned Flags = 0) {
368       MachOSection *&SN = SectionLookup[seg+sect];
369       if (SN) return *SN;
370
371       SectionList.push_back(MachOSection(seg, sect));
372       SN = &SectionList.back();
373       SN->Index = SectionList.size();
374       SN->flags = MachOSection::S_REGULAR | Flags;
375       return *SN;
376     }
377     MachOSection &getTextSection() {
378       return getSection("__TEXT", "__text", 
379                         MachOSection::S_ATTR_PURE_INSTRUCTIONS |
380                         MachOSection::S_ATTR_SOME_INSTRUCTIONS);
381     }
382     MachOSection &getBSSSection() {
383       return getSection("__DATA", "__bss", MachOSection::S_ZEROFILL);
384     }
385     MachOSection &getDataSection() {
386       return getSection("__DATA", "__data");
387     }
388     MachOSection &getConstSection(const Type *Ty) {
389       // FIXME: support cstring literals and pointer literal
390       if (Ty->isPrimitiveType()) {
391         unsigned Size = TM.getTargetData()->getTypeSize(Ty);
392         switch(Size) {
393         default: break; // Fall through to __TEXT,__const
394         case 4:
395           return getSection("__TEXT", "__literal4",
396                             MachOSection::S_4BYTE_LITERALS);
397         case 8:
398           return getSection("__TEXT", "__literal8",
399                             MachOSection::S_8BYTE_LITERALS);
400         case 16:
401           return getSection("__TEXT", "__literal16",
402                             MachOSection::S_16BYTE_LITERALS);
403         }
404       }
405       return getSection("__TEXT", "__const");
406     }
407     
408     /// MachOSymTab - This struct contains information about the offsets and 
409     /// size of symbol table information.
410     /// segment.
411     struct MachOSymTab {
412       uint32_t cmd;     // LC_SYMTAB
413       uint32_t cmdsize; // sizeof( MachOSymTab )
414       uint32_t symoff;  // symbol table offset
415       uint32_t nsyms;   // number of symbol table entries
416       uint32_t stroff;  // string table offset
417       uint32_t strsize; // string table size in bytes
418
419       // Constants for the cmd field
420       // see <mach-o/loader.h>
421       enum { LC_SYMTAB = 0x02  // link-edit stab symbol table info
422       };
423       
424       MachOSymTab() : cmd(LC_SYMTAB), cmdsize(6 * sizeof(uint32_t)), symoff(0),
425         nsyms(0), stroff(0), strsize(0) { }
426     };
427     
428     /// MachOSymTab - This struct contains information about the offsets and 
429     /// size of symbol table information.
430     /// segment.
431     struct MachODySymTab {
432       uint32_t cmd;             // LC_DYSYMTAB
433       uint32_t cmdsize;         // sizeof( MachODySymTab )
434       uint32_t ilocalsym;       // index to local symbols
435       uint32_t nlocalsym;       // number of local symbols
436       uint32_t iextdefsym;      // index to externally defined symbols
437       uint32_t nextdefsym;      // number of externally defined symbols
438       uint32_t iundefsym;       // index to undefined symbols
439       uint32_t nundefsym;       // number of undefined symbols
440       uint32_t tocoff;          // file offset to table of contents
441       uint32_t ntoc;            // number of entries in table of contents
442       uint32_t modtaboff;       // file offset to module table
443       uint32_t nmodtab;         // number of module table entries
444       uint32_t extrefsymoff;    // offset to referenced symbol table
445       uint32_t nextrefsyms;     // number of referenced symbol table entries
446       uint32_t indirectsymoff;  // file offset to the indirect symbol table
447       uint32_t nindirectsyms;   // number of indirect symbol table entries
448       uint32_t extreloff;       // offset to external relocation entries
449       uint32_t nextrel;         // number of external relocation entries
450       uint32_t locreloff;       // offset to local relocation entries
451       uint32_t nlocrel;         // number of local relocation entries
452
453       // Constants for the cmd field
454       // see <mach-o/loader.h>
455       enum { LC_DYSYMTAB = 0x0B  // dynamic link-edit symbol table info
456       };
457       
458       MachODySymTab() : cmd(LC_DYSYMTAB), cmdsize(20 * sizeof(uint32_t)),
459         ilocalsym(0), nlocalsym(0), iextdefsym(0), nextdefsym(0),
460         iundefsym(0), nundefsym(0), tocoff(0), ntoc(0), modtaboff(0),
461         nmodtab(0), extrefsymoff(0), nextrefsyms(0), indirectsymoff(0),
462         nindirectsyms(0), extreloff(0), nextrel(0), locreloff(0), nlocrel(0) { }
463     };
464     
465     /// SymTab - The "stab" style symbol table information
466     MachOSymTab   SymTab;     
467     /// DySymTab - symbol table info for the dynamic link editor
468     MachODySymTab DySymTab;
469
470     /// MachOSym - This struct contains information about each symbol that is
471     /// added to logical symbol table for the module.  This is eventually
472     /// turned into a real symbol table in the file.
473     struct MachOSym {
474       const GlobalValue *GV;    // The global value this corresponds to.
475       std::string GVName;       // The mangled name of the global value.
476       uint32_t    n_strx;       // index into the string table
477       uint8_t     n_type;       // type flag
478       uint8_t     n_sect;       // section number or NO_SECT
479       int16_t     n_desc;       // see <mach-o/stab.h>
480       uint64_t    n_value;      // value for this symbol (or stab offset)
481       
482       // Constants for the n_sect field
483       // see <mach-o/nlist.h>
484       enum { NO_SECT = 0 };   // symbol is not in any section
485
486       // Constants for the n_type field
487       // see <mach-o/nlist.h>
488       enum { N_UNDF  = 0x0,  // undefined, n_sect == NO_SECT
489              N_ABS   = 0x2,  // absolute, n_sect == NO_SECT
490              N_SECT  = 0xe,  // defined in section number n_sect
491              N_PBUD  = 0xc,  // prebound undefined (defined in a dylib)
492              N_INDR  = 0xa   // indirect
493       };
494       // The following bits are OR'd into the types above. For example, a type
495       // of 0x0f would be an external N_SECT symbol (0x0e | 0x01).
496       enum { N_EXT  = 0x01,   // external symbol bit
497              N_PEXT = 0x10    // private external symbol bit
498       };
499       
500       // Constants for the n_desc field
501       // see <mach-o/loader.h>
502       enum { REFERENCE_FLAG_UNDEFINED_NON_LAZY          = 0,
503              REFERENCE_FLAG_UNDEFINED_LAZY              = 1,
504              REFERENCE_FLAG_DEFINED                     = 2,
505              REFERENCE_FLAG_PRIVATE_DEFINED             = 3,
506              REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY  = 4,
507              REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY      = 5
508       };
509       enum { N_NO_DEAD_STRIP = 0x0020, // symbol is not to be dead stripped
510              N_WEAK_REF      = 0x0040, // symbol is weak referenced
511              N_WEAK_DEF      = 0x0080  // coalesced symbol is a weak definition
512       };
513       
514       MachOSym(const GlobalValue *gv, std::string name, uint8_t sect) : GV(gv), 
515         GVName(name), n_strx(0), n_type(sect == NO_SECT ? N_UNDF : N_SECT), 
516         n_sect(sect), n_desc(0), n_value(0) {
517         // FIXME: names aren't getting the proper global/local prefix
518       }
519     };
520
521     struct MachOSymCmp {
522       bool operator()(const MachOSym &LHS, const MachOSym &RHS) {
523         return LHS.GVName < RHS.GVName;
524       }
525     };
526
527     /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
528     /// a local symbol rather than an external symbol.
529     static bool PartitionByLocal(const MachOSym &Sym);
530
531     /// PartitionByDefined - Simple boolean predicate that returns true if Sym 
532     /// is defined in this module.
533     static bool PartitionByDefined(const MachOWriter::MachOSym &Sym);
534
535     /// SymbolTable - This is the list of symbols we have emitted to the file.
536     /// This actually gets rearranged before emission to the file (to put the
537     /// local symbols first in the list).
538     std::vector<MachOSym> SymbolTable;
539     
540     /// SymT - A buffer to hold the symbol table before we write it out at the
541     /// appropriate location in the file.
542     DataBuffer SymT;
543     
544     /// StrT - A buffer to hold the string table before we write it out at the
545     /// appropriate location in the file.
546     DataBuffer StrT;
547     
548     /// PendingSyms - This is a list of externally defined symbols that we have
549     /// been asked to emit, but have not seen a reference to.  When a reference
550     /// is seen, the symbol will move from this list to the SymbolTable.
551     std::vector<MachOSym> PendingSyms;
552     
553     /// DynamicSymbolTable - This is just a vector of indices into
554     /// SymbolTable to aid in emitting the DYSYMTAB load command.
555     std::vector<unsigned> DynamicSymbolTable;
556     
557     // align - Emit padding into the file until the current output position is
558     // aligned to the specified power of two boundary.
559     static void align(DataBuffer &Output, unsigned Boundary) {
560       assert(Boundary && (Boundary & (Boundary-1)) == 0 &&
561              "Must align to 2^k boundary");
562       size_t Size = Output.size();
563       if (Size & (Boundary-1)) {
564         // Add padding to get alignment to the correct place.
565         size_t Pad = Boundary-(Size & (Boundary-1));
566         Output.resize(Size+Pad);
567       }
568     }
569
570     void outbyte(DataBuffer &Output, unsigned char X) {
571       Output.push_back(X);
572     }
573     void outhalf(DataBuffer &Output, unsigned short X) {
574       if (isLittleEndian) {
575         Output.push_back(X&255);
576         Output.push_back(X >> 8);
577       } else {
578         Output.push_back(X >> 8);
579         Output.push_back(X&255);
580       }
581     }
582     void outword(DataBuffer &Output, unsigned X) {
583       if (isLittleEndian) {
584         Output.push_back((X >>  0) & 255);
585         Output.push_back((X >>  8) & 255);
586         Output.push_back((X >> 16) & 255);
587         Output.push_back((X >> 24) & 255);
588       } else {
589         Output.push_back((X >> 24) & 255);
590         Output.push_back((X >> 16) & 255);
591         Output.push_back((X >>  8) & 255);
592         Output.push_back((X >>  0) & 255);
593       }
594     }
595     void outxword(DataBuffer &Output, uint64_t X) {
596       if (isLittleEndian) {
597         Output.push_back(unsigned(X >>  0) & 255);
598         Output.push_back(unsigned(X >>  8) & 255);
599         Output.push_back(unsigned(X >> 16) & 255);
600         Output.push_back(unsigned(X >> 24) & 255);
601         Output.push_back(unsigned(X >> 32) & 255);
602         Output.push_back(unsigned(X >> 40) & 255);
603         Output.push_back(unsigned(X >> 48) & 255);
604         Output.push_back(unsigned(X >> 56) & 255);
605       } else {
606         Output.push_back(unsigned(X >> 56) & 255);
607         Output.push_back(unsigned(X >> 48) & 255);
608         Output.push_back(unsigned(X >> 40) & 255);
609         Output.push_back(unsigned(X >> 32) & 255);
610         Output.push_back(unsigned(X >> 24) & 255);
611         Output.push_back(unsigned(X >> 16) & 255);
612         Output.push_back(unsigned(X >>  8) & 255);
613         Output.push_back(unsigned(X >>  0) & 255);
614       }
615     }
616     void outaddr32(DataBuffer &Output, unsigned X) {
617       outword(Output, X);
618     }
619     void outaddr64(DataBuffer &Output, uint64_t X) {
620       outxword(Output, X);
621     }
622     void outaddr(DataBuffer &Output, uint64_t X) {
623       if (!is64Bit)
624         outword(Output, (unsigned)X);
625       else
626         outxword(Output, X);
627     }
628     void outstring(DataBuffer &Output, std::string &S, unsigned Length) {
629       unsigned len_to_copy = S.length() < Length ? S.length() : Length;
630       unsigned len_to_fill = S.length() < Length ? Length-S.length() : 0;
631       
632       for (unsigned i = 0; i < len_to_copy; ++i)
633         outbyte(Output, S[i]);
634
635       for (unsigned i = 0; i < len_to_fill; ++i)
636         outbyte(Output, 0);
637       
638     }
639   private:
640     void AddSymbolToSection(MachOSection &MOS, GlobalVariable *GV);
641     void EmitGlobal(GlobalVariable *GV);
642     void EmitHeaderAndLoadCommands();
643     void EmitSections();
644     void EmitRelocations();
645     void BufferSymbolAndStringTable();
646   };
647 }
648
649 #endif