LLVM API Documentation

MachOWriter.h

Go to the documentation of this file.
00001 //=== MachOWriter.h - Target-independent Mach-O writer support --*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the MachOWriter class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef MACHOWRITER_H
00015 #define MACHOWRITER_H
00016 
00017 #include "llvm/Constants.h"
00018 #include "llvm/DerivedTypes.h"
00019 #include "llvm/CodeGen/MachineFunctionPass.h"
00020 #include "llvm/CodeGen/MachineRelocation.h"
00021 #include "llvm/Target/TargetData.h"
00022 #include "llvm/Target/TargetMachine.h"
00023 #include "llvm/Target/TargetMachOWriterInfo.h"
00024 #include <map>
00025 
00026 namespace llvm {
00027   class GlobalVariable;
00028   class Mangler;
00029   class MachineCodeEmitter;
00030   class MachOCodeEmitter;
00031   class OutputBuffer;
00032   class raw_ostream;
00033 
00034   /// MachOSym - This struct contains information about each symbol that is
00035   /// added to logical symbol table for the module.  This is eventually
00036   /// turned into a real symbol table in the file.
00037   struct MachOSym {
00038     const GlobalValue *GV;    // The global value this corresponds to.
00039     std::string GVName;       // The mangled name of the global value.
00040     uint32_t    n_strx;       // index into the string table
00041     uint8_t     n_type;       // type flag
00042     uint8_t     n_sect;       // section number or NO_SECT
00043     int16_t     n_desc;       // see <mach-o/stab.h>
00044     uint64_t    n_value;      // value for this symbol (or stab offset)
00045     
00046     // Constants for the n_sect field
00047     // see <mach-o/nlist.h>
00048     enum { NO_SECT = 0 };   // symbol is not in any section
00049 
00050     // Constants for the n_type field
00051     // see <mach-o/nlist.h>
00052     enum { N_UNDF  = 0x0,  // undefined, n_sect == NO_SECT
00053            N_ABS   = 0x2,  // absolute, n_sect == NO_SECT
00054            N_SECT  = 0xe,  // defined in section number n_sect
00055            N_PBUD  = 0xc,  // prebound undefined (defined in a dylib)
00056            N_INDR  = 0xa   // indirect
00057     };
00058     // The following bits are OR'd into the types above. For example, a type
00059     // of 0x0f would be an external N_SECT symbol (0x0e | 0x01).
00060     enum { N_EXT  = 0x01,   // external symbol bit
00061            N_PEXT = 0x10    // private external symbol bit
00062     };
00063     
00064     // Constants for the n_desc field
00065     // see <mach-o/loader.h>
00066     enum { REFERENCE_FLAG_UNDEFINED_NON_LAZY          = 0,
00067            REFERENCE_FLAG_UNDEFINED_LAZY              = 1,
00068            REFERENCE_FLAG_DEFINED                     = 2,
00069            REFERENCE_FLAG_PRIVATE_DEFINED             = 3,
00070            REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY  = 4,
00071            REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY      = 5
00072     };
00073     enum { N_NO_DEAD_STRIP = 0x0020, // symbol is not to be dead stripped
00074            N_WEAK_REF      = 0x0040, // symbol is weak referenced
00075            N_WEAK_DEF      = 0x0080  // coalesced symbol is a weak definition
00076     };
00077     
00078     MachOSym(const GlobalValue *gv, std::string name, uint8_t sect,
00079              TargetMachine &TM);
00080   };
00081       
00082   /// MachOWriter - This class implements the common target-independent code for
00083   /// writing Mach-O files.  Targets should derive a class from this to
00084   /// parameterize the output format.
00085   ///
00086   class MachOWriter : public MachineFunctionPass {
00087     friend class MachOCodeEmitter;
00088   public:
00089     static char ID;
00090     MachineCodeEmitter &getMachineCodeEmitter() const {
00091       return *(MachineCodeEmitter*)MCE;
00092     }
00093 
00094     MachOWriter(raw_ostream &O, TargetMachine &TM);
00095     virtual ~MachOWriter();
00096 
00097     virtual const char *getPassName() const {
00098       return "Mach-O Writer";
00099     }
00100 
00101     typedef std::vector<unsigned char> DataBuffer;
00102   protected:
00103     /// Output stream to send the resultant object file to.
00104     ///
00105     raw_ostream &O;
00106 
00107     /// Target machine description.
00108     ///
00109     TargetMachine &TM;
00110 
00111     /// Mang - The object used to perform name mangling for this module.
00112     ///
00113     Mangler *Mang;
00114     
00115     /// MCE - The MachineCodeEmitter object that we are exposing to emit machine
00116     /// code for functions to the .o file.
00117     MachOCodeEmitter *MCE;
00118 
00119     /// is64Bit/isLittleEndian - This information is inferred from the target
00120     /// machine directly, indicating what header values and flags to set.
00121     bool is64Bit, isLittleEndian;
00122 
00123     /// doInitialization - Emit the file header and all of the global variables
00124     /// for the module to the Mach-O file.
00125     bool doInitialization(Module &M);
00126 
00127     bool runOnMachineFunction(MachineFunction &MF);
00128 
00129     /// doFinalization - Now that the module has been completely processed, emit
00130     /// the Mach-O file to 'O'.
00131     bool doFinalization(Module &M);
00132 
00133     /// MachOHeader - This struct contains the header information about a
00134     /// specific architecture type/subtype pair that is emitted to the file.
00135     struct MachOHeader {
00136       uint32_t  magic;      // mach magic number identifier
00137       uint32_t  filetype;   // type of file
00138       uint32_t  ncmds;      // number of load commands
00139       uint32_t  sizeofcmds; // the size of all the load commands
00140       uint32_t  flags;      // flags
00141       uint32_t  reserved;   // 64-bit only
00142       
00143       /// HeaderData - The actual data for the header which we are building
00144       /// up for emission to the file.
00145       DataBuffer HeaderData;
00146 
00147       // Constants for the filetype field
00148       // see <mach-o/loader.h> for additional info on the various types
00149       enum { MH_OBJECT     = 1, // relocatable object file
00150              MH_EXECUTE    = 2, // demand paged executable file
00151              MH_FVMLIB     = 3, // fixed VM shared library file
00152              MH_CORE       = 4, // core file
00153              MH_PRELOAD    = 5, // preloaded executable file
00154              MH_DYLIB      = 6, // dynamically bound shared library
00155              MH_DYLINKER   = 7, // dynamic link editor
00156              MH_BUNDLE     = 8, // dynamically bound bundle file
00157              MH_DYLIB_STUB = 9, // shared library stub for static linking only
00158              MH_DSYM       = 10 // companion file wiht only debug sections
00159       };
00160       
00161       // Constants for the flags field
00162       enum { MH_NOUNDEFS                = 1 << 0,
00163                 // the object file has no undefined references
00164              MH_INCRLINK                = 1 << 1,
00165                 // the object file is the output of an incremental link against
00166                 // a base file and cannot be link edited again
00167              MH_DYLDLINK                = 1 << 2,
00168                 // the object file is input for the dynamic linker and cannot be
00169                 // statically link edited again.
00170              MH_BINDATLOAD              = 1 << 3,
00171                 // the object file's undefined references are bound by the
00172                 // dynamic linker when loaded.
00173              MH_PREBOUND                = 1 << 4,
00174                 // the file has its dynamic undefined references prebound
00175              MH_SPLIT_SEGS              = 1 << 5,
00176                 // the file has its read-only and read-write segments split
00177                 // see <mach/shared_memory_server.h>
00178              MH_LAZY_INIT               = 1 << 6,
00179                 // the shared library init routine is to be run lazily via
00180                 // catching memory faults to its writable segments (obsolete)
00181              MH_TWOLEVEL                = 1 << 7,
00182                 // the image is using two-level namespace bindings
00183              MH_FORCE_FLAT              = 1 << 8,
00184                 // the executable is forcing all images to use flat namespace
00185                 // bindings.
00186              MH_NOMULTIDEFS             = 1 << 8,
00187                 // this umbrella guarantees no multiple definitions of symbols
00188                 // in its sub-images so the two-level namespace hints can
00189                 // always be used.
00190              MH_NOFIXPREBINDING         = 1 << 10,
00191                 // do not have dyld notify the prebidning agent about this
00192                 // executable.
00193              MH_PREBINDABLE             = 1 << 11,
00194                 // the binary is not prebound but can have its prebinding
00195                 // redone.  only used when MH_PREBOUND is not set.
00196              MH_ALLMODSBOUND            = 1 << 12,
00197                 // indicates that this binary binds to all two-level namespace
00198                 // modules of its dependent libraries.  Only used when
00199                 // MH_PREBINDABLE and MH_TWOLEVEL are both set.
00200              MH_SUBSECTIONS_VIA_SYMBOLS = 1 << 13,
00201                 // safe to divide up the sections into sub-sections via symbols
00202                 // for dead code stripping.
00203              MH_CANONICAL               = 1 << 14,
00204                 // the binary has been canonicalized via the unprebind operation
00205              MH_WEAK_DEFINES            = 1 << 15,
00206                 // the final linked image contains external weak symbols
00207              MH_BINDS_TO_WEAK           = 1 << 16,
00208                 // the final linked image uses weak symbols
00209              MH_ALLOW_STACK_EXECUTION   = 1 << 17
00210                 // When this bit is set, all stacks in the task will be given
00211                 // stack execution privilege.  Only used in MH_EXECUTE filetype
00212       };
00213 
00214       MachOHeader() : magic(0), filetype(0), ncmds(0), sizeofcmds(0), flags(0),
00215                       reserved(0) { }
00216       
00217       /// cmdSize - This routine returns the size of the MachOSection as written
00218       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
00219       unsigned cmdSize(bool is64Bit) const {
00220         if (is64Bit)
00221           return 8 * sizeof(uint32_t);
00222         else
00223           return 7 * sizeof(uint32_t);
00224       }
00225 
00226       /// setMagic - This routine sets the appropriate value for the 'magic'
00227       /// field based on pointer size and endianness.
00228       void setMagic(bool isLittleEndian, bool is64Bit) {
00229         if (isLittleEndian)
00230           if (is64Bit) magic = 0xcffaedfe;
00231           else         magic = 0xcefaedfe;
00232         else
00233           if (is64Bit) magic = 0xfeedfacf;
00234           else         magic = 0xfeedface;
00235       }
00236     };
00237     
00238     /// Header - An instance of MachOHeader that we will update while we build
00239     /// the file, and then emit during finalization.
00240     MachOHeader Header;
00241     
00242     /// MachOSegment - This struct contains the necessary information to
00243     /// emit the load commands for each section in the file.
00244     struct MachOSegment {
00245       uint32_t    cmd;      // LC_SEGMENT or LC_SEGMENT_64
00246       uint32_t    cmdsize;  // Total size of this struct and section commands
00247       std::string segname;  // segment name
00248       uint64_t    vmaddr;   // address of this segment
00249       uint64_t    vmsize;   // size of this segment, may be larger than filesize
00250       uint64_t    fileoff;  // offset in file
00251       uint64_t    filesize; // amount to read from file
00252       uint32_t    maxprot;  // maximum VM protection
00253       uint32_t    initprot; // initial VM protection
00254       uint32_t    nsects;   // number of sections in this segment
00255       uint32_t    flags;    // flags
00256       
00257       // The following constants are getting pulled in by one of the
00258       // system headers, which creates a neat clash with the enum.
00259 #if !defined(VM_PROT_NONE)
00260 #define VM_PROT_NONE    0x00
00261 #endif
00262 #if !defined(VM_PROT_READ)
00263 #define VM_PROT_READ    0x01
00264 #endif
00265 #if !defined(VM_PROT_WRITE)
00266 #define VM_PROT_WRITE   0x02
00267 #endif
00268 #if !defined(VM_PROT_EXECUTE)
00269 #define VM_PROT_EXECUTE 0x04
00270 #endif
00271 #if !defined(VM_PROT_ALL)
00272 #define VM_PROT_ALL     0x07
00273 #endif
00274 
00275       // Constants for the vm protection fields
00276       // see <mach-o/vm_prot.h>
00277       enum { SEG_VM_PROT_NONE     = VM_PROT_NONE, 
00278              SEG_VM_PROT_READ     = VM_PROT_READ, // read permission
00279              SEG_VM_PROT_WRITE    = VM_PROT_WRITE, // write permission
00280              SEG_VM_PROT_EXECUTE  = VM_PROT_EXECUTE,
00281              SEG_VM_PROT_ALL      = VM_PROT_ALL
00282       };
00283       
00284       // Constants for the cmd field
00285       // see <mach-o/loader.h>
00286       enum { LC_SEGMENT    = 0x01,  // segment of this file to be mapped
00287              LC_SEGMENT_64 = 0x19   // 64-bit segment of this file to be mapped
00288       };
00289       
00290       /// cmdSize - This routine returns the size of the MachOSection as written
00291       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
00292       unsigned cmdSize(bool is64Bit) const {
00293         if (is64Bit)
00294           return 6 * sizeof(uint32_t) + 4 * sizeof(uint64_t) + 16;
00295         else
00296           return 10 * sizeof(uint32_t) + 16;  // addresses only 32 bits
00297       }
00298 
00299       MachOSegment(const std::string &seg, bool is64Bit)
00300         : cmd(is64Bit ? LC_SEGMENT_64 : LC_SEGMENT), cmdsize(0), segname(seg),
00301           vmaddr(0), vmsize(0), fileoff(0), filesize(0), maxprot(VM_PROT_ALL),
00302           initprot(VM_PROT_ALL), nsects(0), flags(0) { }
00303     };
00304 
00305     /// MachOSection - This struct contains information about each section in a 
00306     /// particular segment that is emitted to the file.  This is eventually
00307     /// turned into the SectionCommand in the load command for a particlar
00308     /// segment.
00309     struct MachOSection { 
00310       std::string  sectname; // name of this section, 
00311       std::string  segname;  // segment this section goes in
00312       uint64_t  addr;        // memory address of this section
00313       uint64_t  size;        // size in bytes of this section
00314       uint32_t  offset;      // file offset of this section
00315       uint32_t  align;       // section alignment (power of 2)
00316       uint32_t  reloff;      // file offset of relocation entries
00317       uint32_t  nreloc;      // number of relocation entries
00318       uint32_t  flags;       // flags (section type and attributes)
00319       uint32_t  reserved1;   // reserved (for offset or index)
00320       uint32_t  reserved2;   // reserved (for count or sizeof)
00321       uint32_t  reserved3;   // reserved (64 bit only)
00322       
00323       /// A unique number for this section, which will be used to match symbols
00324       /// to the correct section.
00325       uint32_t Index;
00326       
00327       /// SectionData - The actual data for this section which we are building
00328       /// up for emission to the file.
00329       DataBuffer SectionData;
00330 
00331       /// RelocBuffer - A buffer to hold the mach-o relocations before we write
00332       /// them out at the appropriate location in the file.
00333       DataBuffer RelocBuffer;
00334       
00335       /// Relocations - The relocations that we have encountered so far in this 
00336       /// section that we will need to convert to MachORelocation entries when
00337       /// the file is written.
00338       std::vector<MachineRelocation> Relocations;
00339       
00340       // Constants for the section types (low 8 bits of flags field)
00341       // see <mach-o/loader.h>
00342       enum { S_REGULAR = 0,
00343                 // regular section
00344              S_ZEROFILL = 1,
00345                 // zero fill on demand section
00346              S_CSTRING_LITERALS = 2,
00347                 // section with only literal C strings
00348              S_4BYTE_LITERALS = 3,
00349                 // section with only 4 byte literals
00350              S_8BYTE_LITERALS = 4,
00351                 // section with only 8 byte literals
00352              S_LITERAL_POINTERS = 5, 
00353                 // section with only pointers to literals
00354              S_NON_LAZY_SYMBOL_POINTERS = 6,
00355                 // section with only non-lazy symbol pointers
00356              S_LAZY_SYMBOL_POINTERS = 7,
00357                 // section with only lazy symbol pointers
00358              S_SYMBOL_STUBS = 8,
00359                 // section with only symbol stubs
00360                 // byte size of stub in the reserved2 field
00361              S_MOD_INIT_FUNC_POINTERS = 9,
00362                 // section with only function pointers for initialization
00363              S_MOD_TERM_FUNC_POINTERS = 10,
00364                 // section with only function pointers for termination
00365              S_COALESCED = 11,
00366                 // section contains symbols that are coalesced
00367              S_GB_ZEROFILL = 12,
00368                 // zero fill on demand section (that can be larger than 4GB)
00369              S_INTERPOSING = 13,
00370                 // section with only pairs of function pointers for interposing
00371              S_16BYTE_LITERALS = 14
00372                 // section with only 16 byte literals
00373       };
00374       
00375       // Constants for the section flags (high 24 bits of flags field)
00376       // see <mach-o/loader.h>
00377       enum { S_ATTR_PURE_INSTRUCTIONS   = 1 << 31,
00378                 // section contains only true machine instructions
00379              S_ATTR_NO_TOC              = 1 << 30,
00380                 // section contains coalesced symbols that are not to be in a 
00381                 // ranlib table of contents
00382              S_ATTR_STRIP_STATIC_SYMS   = 1 << 29,
00383                 // ok to strip static symbols in this section in files with the
00384                 // MY_DYLDLINK flag
00385              S_ATTR_NO_DEAD_STRIP       = 1 << 28,
00386                 // no dead stripping
00387              S_ATTR_LIVE_SUPPORT        = 1 << 27,
00388                 // blocks are live if they reference live blocks
00389              S_ATTR_SELF_MODIFYING_CODE = 1 << 26,
00390                 // used with i386 code stubs written on by dyld
00391              S_ATTR_DEBUG               = 1 << 25,
00392                 // a debug section
00393              S_ATTR_SOME_INSTRUCTIONS   = 1 << 10,
00394                 // section contains some machine instructions
00395              S_ATTR_EXT_RELOC           = 1 << 9,
00396                 // section has external relocation entries
00397              S_ATTR_LOC_RELOC           = 1 << 8
00398                 // section has local relocation entries
00399       };
00400 
00401       /// cmdSize - This routine returns the size of the MachOSection as written
00402       /// to disk, depending on whether the destination is a 64 bit Mach-O file.
00403       unsigned cmdSize(bool is64Bit) const {
00404         if (is64Bit)
00405           return 7 * sizeof(uint32_t) + 2 * sizeof(uint64_t) + 32;
00406         else
00407           return 9 * sizeof(uint32_t) + 32;  // addresses only 32 bits
00408       }
00409 
00410       MachOSection(const std::string &seg, const std::string &sect)
00411         : sectname(sect), segname(seg), addr(0), size(0), offset(0), align(2),
00412           reloff(0), nreloc(0), flags(0), reserved1(0), reserved2(0),
00413           reserved3(0) { }
00414     };
00415 
00416   private:
00417 
00418     /// SectionList - This is the list of sections that we have emitted to the
00419     /// file.  Once the file has been completely built, the segment load command
00420     /// SectionCommands are constructed from this info.
00421     std::vector<MachOSection*> SectionList;
00422 
00423     /// SectionLookup - This is a mapping from section name to SectionList entry
00424     std::map<std::string, MachOSection*> SectionLookup;
00425     
00426     /// GVSection - This is a mapping from a GlobalValue to a MachOSection,
00427     /// to aid in emitting relocations.
00428     std::map<GlobalValue*, MachOSection*> GVSection;
00429 
00430     /// GVOffset - This is a mapping from a GlobalValue to an offset from the 
00431     /// start of the section in which the GV resides, to aid in emitting
00432     /// relocations.
00433     std::map<GlobalValue*, intptr_t> GVOffset;
00434 
00435     /// getSection - Return the section with the specified name, creating a new
00436     /// section if one does not already exist.
00437     MachOSection *getSection(const std::string &seg, const std::string &sect,
00438                              unsigned Flags = 0) {
00439       MachOSection *MOS = SectionLookup[seg+sect];
00440       if (MOS) return MOS;
00441 
00442       MOS = new MachOSection(seg, sect);
00443       SectionList.push_back(MOS);
00444       MOS->Index = SectionList.size();
00445       MOS->flags = MachOSection::S_REGULAR | Flags;
00446       SectionLookup[seg+sect] = MOS;
00447       return MOS;
00448     }
00449     MachOSection *getTextSection(bool isCode = true) {
00450       if (isCode)
00451         return getSection("__TEXT", "__text", 
00452                           MachOSection::S_ATTR_PURE_INSTRUCTIONS |
00453                           MachOSection::S_ATTR_SOME_INSTRUCTIONS);
00454       else
00455         return getSection("__TEXT", "__text");
00456     }
00457     MachOSection *getBSSSection() {
00458       return getSection("__DATA", "__bss", MachOSection::S_ZEROFILL);
00459     }
00460     MachOSection *getDataSection() {
00461       return getSection("__DATA", "__data");
00462     }
00463     MachOSection *getConstSection(Constant *C) {
00464       const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
00465       if (CVA && CVA->isCString())
00466         return getSection("__TEXT", "__cstring", 
00467                           MachOSection::S_CSTRING_LITERALS);
00468       
00469       const Type *Ty = C->getType();
00470       if (Ty->isPrimitiveType() || Ty->isInteger()) {
00471         unsigned Size = TM.getTargetData()->getTypePaddedSize(Ty);
00472         switch(Size) {
00473         default: break; // Fall through to __TEXT,__const
00474         case 4:
00475           return getSection("__TEXT", "__literal4",
00476                             MachOSection::S_4BYTE_LITERALS);
00477         case 8:
00478           return getSection("__TEXT", "__literal8",
00479                             MachOSection::S_8BYTE_LITERALS);
00480         case 16:
00481           return getSection("__TEXT", "__literal16",
00482                             MachOSection::S_16BYTE_LITERALS);
00483         }
00484       }
00485       return getSection("__TEXT", "__const");
00486     }
00487     MachOSection *getJumpTableSection() {
00488       if (TM.getRelocationModel() == Reloc::PIC_)
00489         return getTextSection(false);
00490       else
00491         return getSection("__TEXT", "__const");
00492     }
00493     
00494     /// MachOSymTab - This struct contains information about the offsets and 
00495     /// size of symbol table information.
00496     /// segment.
00497     struct MachOSymTab {
00498       uint32_t cmd;     // LC_SYMTAB
00499       uint32_t cmdsize; // sizeof( MachOSymTab )
00500       uint32_t symoff;  // symbol table offset
00501       uint32_t nsyms;   // number of symbol table entries
00502       uint32_t stroff;  // string table offset
00503       uint32_t strsize; // string table size in bytes
00504 
00505       // Constants for the cmd field
00506       // see <mach-o/loader.h>
00507       enum { LC_SYMTAB = 0x02  // link-edit stab symbol table info
00508       };
00509       
00510       MachOSymTab() : cmd(LC_SYMTAB), cmdsize(6 * sizeof(uint32_t)), symoff(0),
00511         nsyms(0), stroff(0), strsize(0) { }
00512     };
00513     
00514     /// MachOSymTab - This struct contains information about the offsets and 
00515     /// size of symbol table information.
00516     /// segment.
00517     struct MachODySymTab {
00518       uint32_t cmd;             // LC_DYSYMTAB
00519       uint32_t cmdsize;         // sizeof( MachODySymTab )
00520       uint32_t ilocalsym;       // index to local symbols
00521       uint32_t nlocalsym;       // number of local symbols
00522       uint32_t iextdefsym;      // index to externally defined symbols
00523       uint32_t nextdefsym;      // number of externally defined symbols
00524       uint32_t iundefsym;       // index to undefined symbols
00525       uint32_t nundefsym;       // number of undefined symbols
00526       uint32_t tocoff;          // file offset to table of contents
00527       uint32_t ntoc;            // number of entries in table of contents
00528       uint32_t modtaboff;       // file offset to module table
00529       uint32_t nmodtab;         // number of module table entries
00530       uint32_t extrefsymoff;    // offset to referenced symbol table
00531       uint32_t nextrefsyms;     // number of referenced symbol table entries
00532       uint32_t indirectsymoff;  // file offset to the indirect symbol table
00533       uint32_t nindirectsyms;   // number of indirect symbol table entries
00534       uint32_t extreloff;       // offset to external relocation entries
00535       uint32_t nextrel;         // number of external relocation entries
00536       uint32_t locreloff;       // offset to local relocation entries
00537       uint32_t nlocrel;         // number of local relocation entries
00538 
00539       // Constants for the cmd field
00540       // see <mach-o/loader.h>
00541       enum { LC_DYSYMTAB = 0x0B  // dynamic link-edit symbol table info
00542       };
00543       
00544       MachODySymTab() : cmd(LC_DYSYMTAB), cmdsize(20 * sizeof(uint32_t)),
00545         ilocalsym(0), nlocalsym(0), iextdefsym(0), nextdefsym(0),
00546         iundefsym(0), nundefsym(0), tocoff(0), ntoc(0), modtaboff(0),
00547         nmodtab(0), extrefsymoff(0), nextrefsyms(0), indirectsymoff(0),
00548         nindirectsyms(0), extreloff(0), nextrel(0), locreloff(0), nlocrel(0) { }
00549     };
00550     
00551     /// SymTab - The "stab" style symbol table information
00552     MachOSymTab   SymTab;     
00553     /// DySymTab - symbol table info for the dynamic link editor
00554     MachODySymTab DySymTab;
00555 
00556     struct MachOSymCmp {
00557       // FIXME: this does not appear to be sorting 'f' after 'F'
00558       bool operator()(const MachOSym &LHS, const MachOSym &RHS) {
00559         return LHS.GVName < RHS.GVName;
00560       }
00561     };
00562 
00563     /// PartitionByLocal - Simple boolean predicate that returns true if Sym is
00564     /// a local symbol rather than an external symbol.
00565     static bool PartitionByLocal(const MachOSym &Sym);
00566 
00567     /// PartitionByDefined - Simple boolean predicate that returns true if Sym 
00568     /// is defined in this module.
00569     static bool PartitionByDefined(const MachOSym &Sym);
00570 
00571   protected:
00572   
00573     /// SymbolTable - This is the list of symbols we have emitted to the file.
00574     /// This actually gets rearranged before emission to the file (to put the
00575     /// local symbols first in the list).
00576     std::vector<MachOSym> SymbolTable;
00577     
00578     /// SymT - A buffer to hold the symbol table before we write it out at the
00579     /// appropriate location in the file.
00580     DataBuffer SymT;
00581     
00582     /// StrT - A buffer to hold the string table before we write it out at the
00583     /// appropriate location in the file.
00584     DataBuffer StrT;
00585     
00586     /// PendingSyms - This is a list of externally defined symbols that we have
00587     /// been asked to emit, but have not seen a reference to.  When a reference
00588     /// is seen, the symbol will move from this list to the SymbolTable.
00589     std::vector<GlobalValue*> PendingGlobals;
00590     
00591     /// DynamicSymbolTable - This is just a vector of indices into
00592     /// SymbolTable to aid in emitting the DYSYMTAB load command.
00593     std::vector<unsigned> DynamicSymbolTable;
00594     
00595     static void InitMem(const Constant *C, void *Addr, intptr_t Offset,
00596                         const TargetData *TD, 
00597                         std::vector<MachineRelocation> &MRs);
00598 
00599   private:
00600     void AddSymbolToSection(MachOSection *MOS, GlobalVariable *GV);
00601     void EmitGlobal(GlobalVariable *GV);
00602     void EmitHeaderAndLoadCommands();
00603     void EmitSections();
00604     void BufferSymbolAndStringTable();
00605     void CalculateRelocations(MachOSection &MOS);
00606 
00607     MachineRelocation GetJTRelocation(unsigned Offset,
00608                                       MachineBasicBlock *MBB) const {
00609       return TM.getMachOWriterInfo()->GetJTRelocation(Offset, MBB);
00610     }
00611 
00612     /// GetTargetRelocation - Returns the number of relocations.
00613     unsigned GetTargetRelocation(MachineRelocation &MR,
00614                                  unsigned FromIdx,
00615                                  unsigned ToAddr,
00616                                  unsigned ToIndex,
00617                                  OutputBuffer &RelocOut,
00618                                  OutputBuffer &SecOut,
00619                                  bool Scattered,
00620                                  bool Extern) {
00621       return TM.getMachOWriterInfo()->GetTargetRelocation(MR, FromIdx, ToAddr,
00622                                                           ToIndex, RelocOut,
00623                                                           SecOut, Scattered,
00624                                                           Extern);
00625     }
00626   };
00627 }
00628 
00629 #endif