LLVM API Documentation

ELFWriter.cpp

Go to the documentation of this file.
00001 //===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
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 implements the target-independent ELF writer.  This file writes out
00011 // the ELF file in the following order:
00012 //
00013 //  #1. ELF Header
00014 //  #2. '.text' section
00015 //  #3. '.data' section
00016 //  #4. '.bss' section  (conceptual position in file)
00017 //  ...
00018 //  #X. '.shstrtab' section
00019 //  #Y. Section Table
00020 //
00021 // The entries in the section table are laid out as:
00022 //  #0. Null entry [required]
00023 //  #1. ".text" entry - the program code
00024 //  #2. ".data" entry - global variables with initializers.     [ if needed ]
00025 //  #3. ".bss" entry  - global variables without initializers.  [ if needed ]
00026 //  ...
00027 //  #N. ".shstrtab" entry - String table for the section names.
00028 //
00029 //===----------------------------------------------------------------------===//
00030 
00031 #define DEBUG_TYPE "elfwriter"
00032 #include "ELF.h"
00033 #include "ELFWriter.h"
00034 #include "ELFCodeEmitter.h"
00035 #include "llvm/Constants.h"
00036 #include "llvm/Module.h"
00037 #include "llvm/PassManager.h"
00038 #include "llvm/DerivedTypes.h"
00039 #include "llvm/CodeGen/BinaryObject.h"
00040 #include "llvm/CodeGen/FileWriters.h"
00041 #include "llvm/CodeGen/MachineCodeEmitter.h"
00042 #include "llvm/CodeGen/ObjectCodeEmitter.h"
00043 #include "llvm/CodeGen/MachineCodeEmitter.h"
00044 #include "llvm/CodeGen/MachineConstantPool.h"
00045 #include "llvm/MC/MCContext.h"
00046 #include "llvm/MC/MCSectionELF.h"
00047 #include "llvm/Target/TargetAsmInfo.h"
00048 #include "llvm/Target/TargetData.h"
00049 #include "llvm/Target/TargetELFWriterInfo.h"
00050 #include "llvm/Target/TargetLowering.h"
00051 #include "llvm/Target/TargetLoweringObjectFile.h"
00052 #include "llvm/Target/TargetMachine.h"
00053 #include "llvm/Support/Mangler.h"
00054 #include "llvm/Support/Streams.h"
00055 #include "llvm/Support/raw_ostream.h"
00056 #include "llvm/Support/Debug.h"
00057 #include "llvm/Support/ErrorHandling.h"
00058 
00059 using namespace llvm;
00060 
00061 char ELFWriter::ID = 0;
00062 
00063 /// AddELFWriter - Add the ELF writer to the function pass manager
00064 ObjectCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
00065                                       raw_ostream &O,
00066                                       TargetMachine &TM) {
00067   ELFWriter *EW = new ELFWriter(O, TM);
00068   PM.add(EW);
00069   return EW->getObjectCodeEmitter();
00070 }
00071 
00072 //===----------------------------------------------------------------------===//
00073 //                          ELFWriter Implementation
00074 //===----------------------------------------------------------------------===//
00075 
00076 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
00077   : MachineFunctionPass(&ID), O(o), TM(tm),
00078     OutContext(*new MCContext()),
00079     TLOF(TM.getTargetLowering()->getObjFileLowering()),
00080     is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
00081     isLittleEndian(TM.getTargetData()->isLittleEndian()),
00082     ElfHdr(isLittleEndian, is64Bit) {
00083 
00084   TAI = TM.getTargetAsmInfo();
00085   TEW = TM.getELFWriterInfo();
00086 
00087   // Create the object code emitter object for this target.
00088   ElfCE = new ELFCodeEmitter(*this);
00089 
00090   // Inital number of sections
00091   NumSections = 0;
00092 }
00093 
00094 ELFWriter::~ELFWriter() {
00095   delete ElfCE;
00096   delete &OutContext;
00097 }
00098 
00099 // doInitialization - Emit the file header and all of the global variables for
00100 // the module to the ELF file.
00101 bool ELFWriter::doInitialization(Module &M) {
00102   // Initialize TargetLoweringObjectFile.
00103   const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
00104   
00105   Mang = new Mangler(M);
00106 
00107   // ELF Header
00108   // ----------
00109   // Fields e_shnum e_shstrndx are only known after all section have
00110   // been emitted. They locations in the ouput buffer are recorded so
00111   // to be patched up later.
00112   //
00113   // Note
00114   // ----
00115   // emitWord method behaves differently for ELF32 and ELF64, writing
00116   // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
00117 
00118   ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
00119   ElfHdr.emitByte('E');  // e_ident[EI_MAG1]
00120   ElfHdr.emitByte('L');  // e_ident[EI_MAG2]
00121   ElfHdr.emitByte('F');  // e_ident[EI_MAG3]
00122 
00123   ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
00124   ElfHdr.emitByte(TEW->getEIData());  // e_ident[EI_DATA]
00125   ElfHdr.emitByte(EV_CURRENT);        // e_ident[EI_VERSION]
00126   ElfHdr.emitAlignment(16);           // e_ident[EI_NIDENT-EI_PAD]
00127 
00128   ElfHdr.emitWord16(ET_REL);             // e_type
00129   ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
00130   ElfHdr.emitWord32(EV_CURRENT);         // e_version
00131   ElfHdr.emitWord(0);                    // e_entry, no entry point in .o file
00132   ElfHdr.emitWord(0);                    // e_phoff, no program header for .o
00133   ELFHdr_e_shoff_Offset = ElfHdr.size();
00134   ElfHdr.emitWord(0);                    // e_shoff = sec hdr table off in bytes
00135   ElfHdr.emitWord32(TEW->getEFlags());   // e_flags = whatever the target wants
00136   ElfHdr.emitWord16(TEW->getHdrSize());  // e_ehsize = ELF header size
00137   ElfHdr.emitWord16(0);                  // e_phentsize = prog header entry size
00138   ElfHdr.emitWord16(0);                  // e_phnum = # prog header entries = 0
00139 
00140   // e_shentsize = Section header entry size
00141   ElfHdr.emitWord16(TEW->getSHdrSize());
00142 
00143   // e_shnum     = # of section header ents
00144   ELFHdr_e_shnum_Offset = ElfHdr.size();
00145   ElfHdr.emitWord16(0); // Placeholder
00146 
00147   // e_shstrndx  = Section # of '.shstrtab'
00148   ELFHdr_e_shstrndx_Offset = ElfHdr.size();
00149   ElfHdr.emitWord16(0); // Placeholder
00150 
00151   // Add the null section, which is required to be first in the file.
00152   getNullSection();
00153 
00154   // The first entry in the symtab is the null symbol and the second
00155   // is a local symbol containing the module/file name
00156   SymbolList.push_back(new ELFSym());
00157   SymbolList.push_back(ELFSym::getFileSym());
00158 
00159   return false;
00160 }
00161 
00162 // AddPendingGlobalSymbol - Add a global to be processed and to
00163 // the global symbol lookup, use a zero index because the table
00164 // index will be determined later.
00165 void ELFWriter::AddPendingGlobalSymbol(const GlobalValue *GV, 
00166                                        bool AddToLookup /* = false */) {
00167   PendingGlobals.insert(GV);
00168   if (AddToLookup) 
00169     GblSymLookup[GV] = 0;
00170 }
00171 
00172 // AddPendingExternalSymbol - Add the external to be processed
00173 // and to the external symbol lookup, use a zero index because
00174 // the symbol table index will be determined later.
00175 void ELFWriter::AddPendingExternalSymbol(const char *External) {
00176   PendingExternals.insert(External);
00177   ExtSymLookup[External] = 0;
00178 }
00179 
00180 ELFSection &ELFWriter::getDataSection() {
00181   const MCSectionELF *Data = (const MCSectionELF *)TLOF.getDataSection();
00182   return getSection(Data->getSectionName(), Data->getType(), 
00183                     Data->getFlags(), 4);
00184 }
00185 
00186 ELFSection &ELFWriter::getBSSSection() {
00187   const MCSectionELF *BSS = (const MCSectionELF *)TLOF.getBSSSection();
00188   return getSection(BSS->getSectionName(), BSS->getType(), BSS->getFlags(), 4);
00189 }
00190 
00191 // getCtorSection - Get the static constructor section
00192 ELFSection &ELFWriter::getCtorSection() {
00193   const MCSectionELF *Ctor = (const MCSectionELF *)TLOF.getStaticCtorSection();
00194   return getSection(Ctor->getSectionName(), Ctor->getType(), Ctor->getFlags()); 
00195 }
00196 
00197 // getDtorSection - Get the static destructor section
00198 ELFSection &ELFWriter::getDtorSection() {
00199   const MCSectionELF *Dtor = (const MCSectionELF *)TLOF.getStaticDtorSection();
00200   return getSection(Dtor->getSectionName(), Dtor->getType(), Dtor->getFlags());
00201 }
00202 
00203 // getTextSection - Get the text section for the specified function
00204 ELFSection &ELFWriter::getTextSection(Function *F) {
00205   const MCSectionELF *Text = 
00206     (const MCSectionELF *)TLOF.SectionForGlobal(F, Mang, TM);
00207   return getSection(Text->getSectionName(), Text->getType(), Text->getFlags());
00208 }
00209 
00210 // getJumpTableSection - Get a read only section for constants when 
00211 // emitting jump tables. TODO: add PIC support
00212 ELFSection &ELFWriter::getJumpTableSection() {
00213   const MCSectionELF *JT = 
00214     (const MCSectionELF *)TLOF.getSectionForConstant(SectionKind::getReadOnly());
00215   return getSection(JT->getSectionName(), JT->getType(), JT->getFlags(),
00216                     TM.getTargetData()->getPointerABIAlignment());
00217 }
00218 
00219 // getConstantPoolSection - Get a constant pool section based on the machine 
00220 // constant pool entry type and relocation info.
00221 ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
00222   SectionKind Kind;
00223   switch (CPE.getRelocationInfo()) {
00224   default: llvm_unreachable("Unknown section kind");
00225   case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
00226   case 1:
00227     Kind = SectionKind::getReadOnlyWithRelLocal();
00228     break;
00229   case 0:
00230     switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
00231     case 4:  Kind = SectionKind::getMergeableConst4(); break;
00232     case 8:  Kind = SectionKind::getMergeableConst8(); break;
00233     case 16: Kind = SectionKind::getMergeableConst16(); break;
00234     default: Kind = SectionKind::getMergeableConst(); break;
00235     }
00236   }
00237 
00238   const MCSectionELF *CPSect = 
00239     (const MCSectionELF *)TLOF.getSectionForConstant(Kind);
00240   return getSection(CPSect->getSectionName(), CPSect->getType(), 
00241                     CPSect->getFlags(), CPE.getAlignment());
00242 }
00243 
00244 // getRelocSection - Return the relocation section of section 'S'. 'RelA' 
00245 // is true if the relocation section contains entries with addends.
00246 ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
00247   unsigned SectionType = TEW->hasRelocationAddend() ?
00248                 ELFSection::SHT_RELA : ELFSection::SHT_REL;
00249 
00250   std::string SectionName(".rel");
00251   if (TEW->hasRelocationAddend())
00252     SectionName.append("a");
00253   SectionName.append(S.getName());
00254 
00255   return getSection(SectionName, SectionType, 0, TEW->getPrefELFAlignment());
00256 }
00257 
00258 // getGlobalELFVisibility - Returns the ELF specific visibility type
00259 unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
00260   switch (GV->getVisibility()) {
00261   default:
00262     llvm_unreachable("unknown visibility type");
00263   case GlobalValue::DefaultVisibility:
00264     return ELFSym::STV_DEFAULT;
00265   case GlobalValue::HiddenVisibility:
00266     return ELFSym::STV_HIDDEN;
00267   case GlobalValue::ProtectedVisibility:
00268     return ELFSym::STV_PROTECTED;
00269   }
00270   return 0;
00271 }
00272 
00273 // getGlobalELFBinding - Returns the ELF specific binding type
00274 unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
00275   if (GV->hasInternalLinkage())
00276     return ELFSym::STB_LOCAL;
00277 
00278   if (GV->isWeakForLinker() && !GV->hasCommonLinkage())
00279     return ELFSym::STB_WEAK;
00280 
00281   return ELFSym::STB_GLOBAL;
00282 }
00283 
00284 // getGlobalELFType - Returns the ELF specific type for a global
00285 unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
00286   if (GV->isDeclaration())
00287     return ELFSym::STT_NOTYPE;
00288 
00289   if (isa<Function>(GV))
00290     return ELFSym::STT_FUNC;
00291 
00292   return ELFSym::STT_OBJECT;
00293 }
00294 
00295 // IsELFUndefSym - True if the global value must be marked as a symbol
00296 // which points to a SHN_UNDEF section. This means that the symbol has
00297 // no definition on the module.
00298 static bool IsELFUndefSym(const GlobalValue *GV) {
00299   return GV->isDeclaration() || (isa<Function>(GV));
00300 }
00301 
00302 // AddToSymbolList - Update the symbol lookup and If the symbol is 
00303 // private add it to PrivateSyms list, otherwise to SymbolList. 
00304 void ELFWriter::AddToSymbolList(ELFSym *GblSym) {
00305   assert(GblSym->isGlobalValue() && "Symbol must be a global value");
00306 
00307   const GlobalValue *GV = GblSym->getGlobalValue(); 
00308   if (GV->hasPrivateLinkage()) {
00309     // For a private symbols, keep track of the index inside 
00310     // the private list since it will never go to the symbol 
00311     // table and won't be patched up later.
00312     PrivateSyms.push_back(GblSym);
00313     GblSymLookup[GV] = PrivateSyms.size()-1;
00314   } else {
00315     // Non private symbol are left with zero indices until 
00316     // they are patched up during the symbol table emition 
00317     // (where the indicies are created).
00318     SymbolList.push_back(GblSym);
00319     GblSymLookup[GV] = 0;
00320   }
00321 }
00322 
00323 // EmitGlobal - Choose the right section for global and emit it
00324 void ELFWriter::EmitGlobal(const GlobalValue *GV) {
00325 
00326   // Check if the referenced symbol is already emitted
00327   if (GblSymLookup.find(GV) != GblSymLookup.end())
00328     return;
00329 
00330   // Handle ELF Bind, Visibility and Type for the current symbol
00331   unsigned SymBind = getGlobalELFBinding(GV);
00332   unsigned SymType = getGlobalELFType(GV);
00333   bool IsUndefSym = IsELFUndefSym(GV);
00334 
00335   ELFSym *GblSym = IsUndefSym ? ELFSym::getUndefGV(GV, SymBind)
00336     : ELFSym::getGV(GV, SymBind, SymType, getGlobalELFVisibility(GV));
00337 
00338   if (!IsUndefSym) {
00339     assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
00340     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00341 
00342     // Handle special llvm globals
00343     if (EmitSpecialLLVMGlobal(GVar))
00344       return;
00345 
00346     // Get the ELF section where this global belongs from TLOF
00347     const MCSectionELF *S = 
00348       (const MCSectionELF *)TLOF.SectionForGlobal(GV, Mang, TM);
00349     ELFSection &ES = 
00350       getSection(S->getSectionName(), S->getType(), S->getFlags());
00351     SectionKind Kind = S->getKind();
00352 
00353     // The symbol align should update the section alignment if needed
00354     const TargetData *TD = TM.getTargetData();
00355     unsigned Align = TD->getPreferredAlignment(GVar);
00356     unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
00357     GblSym->Size = Size;
00358 
00359     if (S->HasCommonSymbols()) { // Symbol must go to a common section
00360       GblSym->SectionIdx = ELFSection::SHN_COMMON;
00361 
00362       // A new linkonce section is created for each global in the
00363       // common section, the default alignment is 1 and the symbol
00364       // value contains its alignment.
00365       ES.Align = 1;
00366       GblSym->Value = Align;
00367 
00368     } else if (Kind.isBSS() || Kind.isThreadBSS()) { // Symbol goes to BSS.
00369       GblSym->SectionIdx = ES.SectionIdx;
00370 
00371       // Update the size with alignment and the next object can
00372       // start in the right offset in the section
00373       if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
00374       ES.Align = std::max(ES.Align, Align);
00375 
00376       // GblSym->Value should contain the virtual offset inside the section.
00377       // Virtual because the BSS space is not allocated on ELF objects
00378       GblSym->Value = ES.Size;
00379       ES.Size += Size;
00380 
00381     } else { // The symbol must go to some kind of data section
00382       GblSym->SectionIdx = ES.SectionIdx;
00383 
00384       // GblSym->Value should contain the symbol offset inside the section,
00385       // and all symbols should start on their required alignment boundary
00386       ES.Align = std::max(ES.Align, Align);
00387       ES.emitAlignment(Align);
00388       GblSym->Value = ES.size();
00389 
00390       // Emit the global to the data section 'ES'
00391       EmitGlobalConstant(GVar->getInitializer(), ES);
00392     }
00393   }
00394 
00395   AddToSymbolList(GblSym);
00396 }
00397 
00398 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
00399                                          ELFSection &GblS) {
00400 
00401   // Print the fields in successive locations. Pad to align if needed!
00402   const TargetData *TD = TM.getTargetData();
00403   unsigned Size = TD->getTypeAllocSize(CVS->getType());
00404   const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
00405   uint64_t sizeSoFar = 0;
00406   for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
00407     const Constant* field = CVS->getOperand(i);
00408 
00409     // Check if padding is needed and insert one or more 0s.
00410     uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
00411     uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
00412                         - cvsLayout->getElementOffset(i)) - fieldSize;
00413     sizeSoFar += fieldSize + padSize;
00414 
00415     // Now print the actual field value.
00416     EmitGlobalConstant(field, GblS);
00417 
00418     // Insert padding - this may include padding to increase the size of the
00419     // current field up to the ABI size (if the struct is not packed) as well
00420     // as padding to ensure that the next field starts at the right offset.
00421     GblS.emitZeros(padSize);
00422   }
00423   assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
00424          "Layout of constant struct may be incorrect!");
00425 }
00426 
00427 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
00428   const TargetData *TD = TM.getTargetData();
00429   unsigned Size = TD->getTypeAllocSize(CV->getType());
00430 
00431   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
00432     for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
00433       EmitGlobalConstant(CVA->getOperand(i), GblS);
00434     return;
00435   } else if (isa<ConstantAggregateZero>(CV)) {
00436     GblS.emitZeros(Size);
00437     return;
00438   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
00439     EmitGlobalConstantStruct(CVS, GblS);
00440     return;
00441   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
00442     APInt Val = CFP->getValueAPF().bitcastToAPInt();
00443     if (CFP->getType() == Type::getDoubleTy(CV->getContext()))
00444       GblS.emitWord64(Val.getZExtValue());
00445     else if (CFP->getType() == Type::getFloatTy(CV->getContext()))
00446       GblS.emitWord32(Val.getZExtValue());
00447     else if (CFP->getType() == Type::getX86_FP80Ty(CV->getContext())) {
00448       unsigned PadSize = 
00449              TD->getTypeAllocSize(Type::getX86_FP80Ty(CV->getContext()))-
00450              TD->getTypeStoreSize(Type::getX86_FP80Ty(CV->getContext()));
00451       GblS.emitWordFP80(Val.getRawData(), PadSize);
00452     } else if (CFP->getType() == Type::getPPC_FP128Ty(CV->getContext()))
00453       llvm_unreachable("PPC_FP128Ty global emission not implemented");
00454     return;
00455   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
00456     if (Size == 1)
00457       GblS.emitByte(CI->getZExtValue());
00458     else if (Size == 2) 
00459       GblS.emitWord16(CI->getZExtValue());
00460     else if (Size == 4)
00461       GblS.emitWord32(CI->getZExtValue());
00462     else 
00463       EmitGlobalConstantLargeInt(CI, GblS);
00464     return;
00465   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
00466     const VectorType *PTy = CP->getType();
00467     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
00468       EmitGlobalConstant(CP->getOperand(I), GblS);
00469     return;
00470   } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
00471     // Resolve a constant expression which returns a (Constant, Offset)
00472     // pair. If 'Res.first' is a GlobalValue, emit a relocation with 
00473     // the offset 'Res.second', otherwise emit a global constant like
00474     // it is always done for not contant expression types.
00475     CstExprResTy Res = ResolveConstantExpr(CE);
00476     const Constant *Op = Res.first;
00477 
00478     if (isa<GlobalValue>(Op))
00479       EmitGlobalDataRelocation(cast<const GlobalValue>(Op), 
00480                                TD->getTypeAllocSize(Op->getType()), 
00481                                GblS, Res.second);
00482     else
00483       EmitGlobalConstant(Op, GblS);
00484 
00485     return;
00486   } else if (CV->getType()->getTypeID() == Type::PointerTyID) {
00487     // Fill the data entry with zeros or emit a relocation entry
00488     if (isa<ConstantPointerNull>(CV))
00489       GblS.emitZeros(Size);
00490     else 
00491       EmitGlobalDataRelocation(cast<const GlobalValue>(CV), 
00492                                Size, GblS);
00493     return;
00494   } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
00495     // This is a constant address for a global variable or function and
00496     // therefore must be referenced using a relocation entry.
00497     EmitGlobalDataRelocation(GV, Size, GblS);
00498     return;
00499   }
00500 
00501   std::string msg;
00502   raw_string_ostream ErrorMsg(msg);
00503   ErrorMsg << "Constant unimp for type: " << *CV->getType();
00504   llvm_report_error(ErrorMsg.str());
00505 }
00506 
00507 // ResolveConstantExpr - Resolve the constant expression until it stop
00508 // yielding other constant expressions.
00509 CstExprResTy ELFWriter::ResolveConstantExpr(const Constant *CV) {
00510   const TargetData *TD = TM.getTargetData();
00511   
00512   // There ins't constant expression inside others anymore
00513   if (!isa<ConstantExpr>(CV))
00514     return std::make_pair(CV, 0);
00515 
00516   const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
00517   switch (CE->getOpcode()) {
00518   case Instruction::BitCast:
00519     return ResolveConstantExpr(CE->getOperand(0));
00520   
00521   case Instruction::GetElementPtr: {
00522     const Constant *ptrVal = CE->getOperand(0);
00523     SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
00524     int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
00525                                           idxVec.size());
00526     return std::make_pair(ptrVal, Offset);
00527   }
00528   case Instruction::IntToPtr: {
00529     Constant *Op = CE->getOperand(0);
00530     Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
00531                                       false/*ZExt*/);
00532     return ResolveConstantExpr(Op);
00533   }
00534   case Instruction::PtrToInt: {
00535     Constant *Op = CE->getOperand(0);
00536     const Type *Ty = CE->getType();
00537 
00538     // We can emit the pointer value into this slot if the slot is an
00539     // integer slot greater or equal to the size of the pointer.
00540     if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
00541       return ResolveConstantExpr(Op);
00542 
00543     llvm_unreachable("Integer size less then pointer size");
00544   }
00545   case Instruction::Add:
00546   case Instruction::Sub: {
00547     // Only handle cases where there's a constant expression with GlobalValue
00548     // as first operand and ConstantInt as second, which are the cases we can
00549     // solve direclty using a relocation entry. GlobalValue=Op0, CstInt=Op1
00550     // 1)  Instruction::Add  => (global) + CstInt
00551     // 2)  Instruction::Sub  => (global) + -CstInt
00552     const Constant *Op0 = CE->getOperand(0); 
00553     const Constant *Op1 = CE->getOperand(1); 
00554     assert(isa<ConstantInt>(Op1) && "Op1 must be a ConstantInt");
00555 
00556     CstExprResTy Res = ResolveConstantExpr(Op0);
00557     assert(isa<GlobalValue>(Res.first) && "Op0 must be a GlobalValue");
00558 
00559     const APInt &RHS = cast<ConstantInt>(Op1)->getValue();
00560     switch (CE->getOpcode()) {
00561     case Instruction::Add: 
00562       return std::make_pair(Res.first, RHS.getSExtValue());
00563     case Instruction::Sub:
00564       return std::make_pair(Res.first, (-RHS).getSExtValue());
00565     }
00566   }
00567   }
00568 
00569   std::string msg(CE->getOpcodeName());
00570   raw_string_ostream ErrorMsg(msg);
00571   ErrorMsg << ": Unsupported ConstantExpr type";
00572   llvm_report_error(ErrorMsg.str());
00573 
00574   return std::make_pair(CV, 0); // silence warning
00575 }
00576 
00577 void ELFWriter::EmitGlobalDataRelocation(const GlobalValue *GV, unsigned Size,
00578                                          ELFSection &GblS, int64_t Offset) {
00579   // Create the relocation entry for the global value
00580   MachineRelocation MR =
00581     MachineRelocation::getGV(GblS.getCurrentPCOffset(),
00582                              TEW->getAbsoluteLabelMachineRelTy(),
00583                              const_cast<GlobalValue*>(GV),
00584                              Offset);
00585 
00586   // Fill the data entry with zeros
00587   GblS.emitZeros(Size);
00588 
00589   // Add the relocation entry for the current data section
00590   GblS.addRelocation(MR);
00591 }
00592 
00593 void ELFWriter::EmitGlobalConstantLargeInt(const ConstantInt *CI, 
00594                                            ELFSection &S) {
00595   const TargetData *TD = TM.getTargetData();
00596   unsigned BitWidth = CI->getBitWidth();
00597   assert(isPowerOf2_32(BitWidth) &&
00598          "Non-power-of-2-sized integers not handled!");
00599 
00600   const uint64_t *RawData = CI->getValue().getRawData();
00601   uint64_t Val = 0;
00602   for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
00603     Val = (TD->isBigEndian()) ? RawData[e - i - 1] : RawData[i];
00604     S.emitWord64(Val);
00605   }
00606 }
00607 
00608 /// EmitSpecialLLVMGlobal - Check to see if the specified global is a
00609 /// special global used by LLVM.  If so, emit it and return true, otherwise
00610 /// do nothing and return false.
00611 bool ELFWriter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
00612   if (GV->getName() == "llvm.used")
00613     llvm_unreachable("not implemented yet");
00614 
00615   // Ignore debug and non-emitted data.  This handles llvm.compiler.used.
00616   if (GV->getSection() == "llvm.metadata" ||
00617       GV->hasAvailableExternallyLinkage())
00618     return true;
00619   
00620   if (!GV->hasAppendingLinkage()) return false;
00621 
00622   assert(GV->hasInitializer() && "Not a special LLVM global!");
00623   
00624   const TargetData *TD = TM.getTargetData();
00625   unsigned Align = TD->getPointerPrefAlignment();
00626   if (GV->getName() == "llvm.global_ctors") {
00627     ELFSection &Ctor = getCtorSection();
00628     Ctor.emitAlignment(Align);
00629     EmitXXStructorList(GV->getInitializer(), Ctor);
00630     return true;
00631   } 
00632   
00633   if (GV->getName() == "llvm.global_dtors") {
00634     ELFSection &Dtor = getDtorSection();
00635     Dtor.emitAlignment(Align);
00636     EmitXXStructorList(GV->getInitializer(), Dtor);
00637     return true;
00638   }
00639   
00640   return false;
00641 }
00642 
00643 /// EmitXXStructorList - Emit the ctor or dtor list.  This just emits out the 
00644 /// function pointers, ignoring the init priority.
00645 void ELFWriter::EmitXXStructorList(Constant *List, ELFSection &Xtor) {
00646   // Should be an array of '{ int, void ()* }' structs.  The first value is the
00647   // init priority, which we ignore.
00648   if (!isa<ConstantArray>(List)) return;
00649   ConstantArray *InitList = cast<ConstantArray>(List);
00650   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
00651     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
00652       if (CS->getNumOperands() != 2) return;  // Not array of 2-element structs.
00653 
00654       if (CS->getOperand(1)->isNullValue())
00655         return;  // Found a null terminator, exit printing.
00656       // Emit the function pointer.
00657       EmitGlobalConstant(CS->getOperand(1), Xtor);
00658     }
00659 }
00660 
00661 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
00662   // Nothing to do here, this is all done through the ElfCE object above.
00663   return false;
00664 }
00665 
00666 /// doFinalization - Now that the module has been completely processed, emit
00667 /// the ELF file to 'O'.
00668 bool ELFWriter::doFinalization(Module &M) {
00669   // Emit .data section placeholder
00670   getDataSection();
00671 
00672   // Emit .bss section placeholder
00673   getBSSSection();
00674 
00675   // Build and emit data, bss and "common" sections.
00676   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
00677        I != E; ++I)
00678     EmitGlobal(I);
00679 
00680   // Emit all pending globals
00681   for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
00682        I != E; ++I)
00683     EmitGlobal(*I);
00684 
00685   // Emit all pending externals
00686   for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
00687        I != E; ++I)
00688     SymbolList.push_back(ELFSym::getExtSym(*I));
00689 
00690   // Emit non-executable stack note
00691   if (TAI->getNonexecutableStackDirective())
00692     getNonExecStackSection();
00693 
00694   // Emit a symbol for each section created until now, skip null section
00695   for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
00696     ELFSection &ES = *SectionList[i];
00697     ELFSym *SectionSym = ELFSym::getSectionSym();
00698     SectionSym->SectionIdx = ES.SectionIdx;
00699     SymbolList.push_back(SectionSym);
00700     ES.Sym = SymbolList.back();
00701   }
00702 
00703   // Emit string table
00704   EmitStringTable(M.getModuleIdentifier());
00705 
00706   // Emit the symbol table now, if non-empty.
00707   EmitSymbolTable();
00708 
00709   // Emit the relocation sections.
00710   EmitRelocations();
00711 
00712   // Emit the sections string table.
00713   EmitSectionTableStringTable();
00714 
00715   // Dump the sections and section table to the .o file.
00716   OutputSectionsAndSectionTable();
00717 
00718   // We are done with the abstract symbols.
00719   SymbolList.clear();
00720   SectionList.clear();
00721   NumSections = 0;
00722 
00723   // Release the name mangler object.
00724   delete Mang; Mang = 0;
00725   return false;
00726 }
00727 
00728 // RelocateField - Patch relocatable field with 'Offset' in 'BO'
00729 // using a 'Value' of known 'Size'
00730 void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
00731                               int64_t Value, unsigned Size) {
00732   if (Size == 32)
00733     BO.fixWord32(Value, Offset);
00734   else if (Size == 64)
00735     BO.fixWord64(Value, Offset);
00736   else
00737     llvm_unreachable("don't know howto patch relocatable field");
00738 }
00739 
00740 /// EmitRelocations - Emit relocations
00741 void ELFWriter::EmitRelocations() {
00742 
00743   // True if the target uses the relocation entry to hold the addend,
00744   // otherwise the addend is written directly to the relocatable field.
00745   bool HasRelA = TEW->hasRelocationAddend();
00746 
00747   // Create Relocation sections for each section which needs it.
00748   for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
00749     ELFSection &S = *SectionList[i];
00750 
00751     // This section does not have relocations
00752     if (!S.hasRelocations()) continue;
00753     ELFSection &RelSec = getRelocSection(S);
00754 
00755     // 'Link' - Section hdr idx of the associated symbol table
00756     // 'Info' - Section hdr idx of the section to which the relocation applies
00757     ELFSection &SymTab = getSymbolTableSection();
00758     RelSec.Link = SymTab.SectionIdx;
00759     RelSec.Info = S.SectionIdx;
00760     RelSec.EntSize = TEW->getRelocationEntrySize();
00761 
00762     // Get the relocations from Section
00763     std::vector<MachineRelocation> Relos = S.getRelocations();
00764     for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
00765          MRE = Relos.end(); MRI != MRE; ++MRI) {
00766       MachineRelocation &MR = *MRI;
00767 
00768       // Relocatable field offset from the section start
00769       unsigned RelOffset = MR.getMachineCodeOffset();
00770 
00771       // Symbol index in the symbol table
00772       unsigned SymIdx = 0;
00773 
00774       // Target specific relocation field type and size
00775       unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
00776       unsigned RelTySize = TEW->getRelocationTySize(RelType);
00777       int64_t Addend = 0;
00778 
00779       // There are several machine relocations types, and each one of
00780       // them needs a different approach to retrieve the symbol table index.
00781       if (MR.isGlobalValue()) {
00782         const GlobalValue *G = MR.getGlobalValue();
00783         int64_t GlobalOffset = MR.getConstantVal();
00784         SymIdx = GblSymLookup[G];
00785         if (G->hasPrivateLinkage()) {
00786           // If the target uses a section offset in the relocation:
00787           // SymIdx + Addend = section sym for global + section offset
00788           unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
00789           Addend = PrivateSyms[SymIdx]->Value + GlobalOffset;
00790           SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
00791         } else {
00792           Addend = TEW->getDefaultAddendForRelTy(RelType, GlobalOffset);
00793         }
00794       } else if (MR.isExternalSymbol()) {
00795         const char *ExtSym = MR.getExternalSymbol();
00796         SymIdx = ExtSymLookup[ExtSym];
00797         Addend = TEW->getDefaultAddendForRelTy(RelType);
00798       } else {
00799         // Get the symbol index for the section symbol
00800         unsigned SectionIdx = MR.getConstantVal();
00801         SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
00802 
00803         // The symbol offset inside the section
00804         int64_t SymOffset = (int64_t)MR.getResultPointer();
00805 
00806         // For pc relative relocations where symbols are defined in the same
00807         // section they are referenced, ignore the relocation entry and patch
00808         // the relocatable field with the symbol offset directly.
00809         if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
00810           int64_t Value = TEW->computeRelocation(SymOffset, RelOffset, RelType);
00811           RelocateField(S, RelOffset, Value, RelTySize);
00812           continue;
00813         }
00814 
00815         Addend = TEW->getDefaultAddendForRelTy(RelType, SymOffset);
00816       }
00817 
00818       // The target without addend on the relocation symbol must be
00819       // patched in the relocation place itself to contain the addend
00820       // otherwise write zeros to make sure there is no garbage there
00821       RelocateField(S, RelOffset, HasRelA ? 0 : Addend, RelTySize);
00822 
00823       // Get the relocation entry and emit to the relocation section
00824       ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
00825       EmitRelocation(RelSec, Rel, HasRelA);
00826     }
00827   }
00828 }
00829 
00830 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
00831 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
00832                                bool HasRelA) {
00833   RelSec.emitWord(Rel.getOffset());
00834   RelSec.emitWord(Rel.getInfo(is64Bit));
00835   if (HasRelA)
00836     RelSec.emitWord(Rel.getAddend());
00837 }
00838 
00839 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
00840 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
00841   if (is64Bit) {
00842     SymbolTable.emitWord32(Sym.NameIdx);
00843     SymbolTable.emitByte(Sym.Info);
00844     SymbolTable.emitByte(Sym.Other);
00845     SymbolTable.emitWord16(Sym.SectionIdx);
00846     SymbolTable.emitWord64(Sym.Value);
00847     SymbolTable.emitWord64(Sym.Size);
00848   } else {
00849     SymbolTable.emitWord32(Sym.NameIdx);
00850     SymbolTable.emitWord32(Sym.Value);
00851     SymbolTable.emitWord32(Sym.Size);
00852     SymbolTable.emitByte(Sym.Info);
00853     SymbolTable.emitByte(Sym.Other);
00854     SymbolTable.emitWord16(Sym.SectionIdx);
00855   }
00856 }
00857 
00858 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
00859 /// Section Header Table
00860 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
00861                                   const ELFSection &SHdr) {
00862   SHdrTab.emitWord32(SHdr.NameIdx);
00863   SHdrTab.emitWord32(SHdr.Type);
00864   if (is64Bit) {
00865     SHdrTab.emitWord64(SHdr.Flags);
00866     SHdrTab.emitWord(SHdr.Addr);
00867     SHdrTab.emitWord(SHdr.Offset);
00868     SHdrTab.emitWord64(SHdr.Size);
00869     SHdrTab.emitWord32(SHdr.Link);
00870     SHdrTab.emitWord32(SHdr.Info);
00871     SHdrTab.emitWord64(SHdr.Align);
00872     SHdrTab.emitWord64(SHdr.EntSize);
00873   } else {
00874     SHdrTab.emitWord32(SHdr.Flags);
00875     SHdrTab.emitWord(SHdr.Addr);
00876     SHdrTab.emitWord(SHdr.Offset);
00877     SHdrTab.emitWord32(SHdr.Size);
00878     SHdrTab.emitWord32(SHdr.Link);
00879     SHdrTab.emitWord32(SHdr.Info);
00880     SHdrTab.emitWord32(SHdr.Align);
00881     SHdrTab.emitWord32(SHdr.EntSize);
00882   }
00883 }
00884 
00885 /// EmitStringTable - If the current symbol table is non-empty, emit the string
00886 /// table for it
00887 void ELFWriter::EmitStringTable(const std::string &ModuleName) {
00888   if (!SymbolList.size()) return;  // Empty symbol table.
00889   ELFSection &StrTab = getStringTableSection();
00890 
00891   // Set the zero'th symbol to a null byte, as required.
00892   StrTab.emitByte(0);
00893 
00894   // Walk on the symbol list and write symbol names into the string table.
00895   unsigned Index = 1;
00896   for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
00897     ELFSym &Sym = *(*I);
00898 
00899     std::string Name;
00900     if (Sym.isGlobalValue())
00901       Name.append(Mang->getMangledName(Sym.getGlobalValue()));
00902     else if (Sym.isExternalSym())
00903       Name.append(Sym.getExternalSymbol());
00904     else if (Sym.isFileType())
00905       Name.append(ModuleName);
00906 
00907     if (Name.empty()) {
00908       Sym.NameIdx = 0;
00909     } else {
00910       Sym.NameIdx = Index;
00911       StrTab.emitString(Name);
00912 
00913       // Keep track of the number of bytes emitted to this section.
00914       Index += Name.size()+1;
00915     }
00916   }
00917   assert(Index == StrTab.size());
00918   StrTab.Size = Index;
00919 }
00920 
00921 // SortSymbols - On the symbol table local symbols must come before
00922 // all other symbols with non-local bindings. The return value is
00923 // the position of the first non local symbol.
00924 unsigned ELFWriter::SortSymbols() {
00925   unsigned FirstNonLocalSymbol;
00926   std::vector<ELFSym*> LocalSyms, OtherSyms;
00927 
00928   for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
00929     if ((*I)->isLocalBind())
00930       LocalSyms.push_back(*I);
00931     else
00932       OtherSyms.push_back(*I);
00933   }
00934   SymbolList.clear();
00935   FirstNonLocalSymbol = LocalSyms.size();
00936 
00937   for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
00938     SymbolList.push_back(LocalSyms[i]);
00939 
00940   for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
00941     SymbolList.push_back(*I);
00942 
00943   LocalSyms.clear();
00944   OtherSyms.clear();
00945 
00946   return FirstNonLocalSymbol;
00947 }
00948 
00949 /// EmitSymbolTable - Emit the symbol table itself.
00950 void ELFWriter::EmitSymbolTable() {
00951   if (!SymbolList.size()) return;  // Empty symbol table.
00952 
00953   // Now that we have emitted the string table and know the offset into the
00954   // string table of each symbol, emit the symbol table itself.
00955   ELFSection &SymTab = getSymbolTableSection();
00956   SymTab.Align = TEW->getPrefELFAlignment();
00957 
00958   // Section Index of .strtab.
00959   SymTab.Link = getStringTableSection().SectionIdx;
00960 
00961   // Size of each symtab entry.
00962   SymTab.EntSize = TEW->getSymTabEntrySize();
00963 
00964   // Reorder the symbol table with local symbols first!
00965   unsigned FirstNonLocalSymbol = SortSymbols();
00966 
00967   // Emit all the symbols to the symbol table.
00968   for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
00969     ELFSym &Sym = *SymbolList[i];
00970 
00971     // Emit symbol to the symbol table
00972     EmitSymbol(SymTab, Sym);
00973 
00974     // Record the symbol table index for each symbol
00975     if (Sym.isGlobalValue())
00976       GblSymLookup[Sym.getGlobalValue()] = i;
00977     else if (Sym.isExternalSym())
00978       ExtSymLookup[Sym.getExternalSymbol()] = i;
00979 
00980     // Keep track on the symbol index into the symbol table
00981     Sym.SymTabIdx = i;
00982   }
00983 
00984   // One greater than the symbol table index of the last local symbol
00985   SymTab.Info = FirstNonLocalSymbol;
00986   SymTab.Size = SymTab.size();
00987 }
00988 
00989 /// EmitSectionTableStringTable - This method adds and emits a section for the
00990 /// ELF Section Table string table: the string table that holds all of the
00991 /// section names.
00992 void ELFWriter::EmitSectionTableStringTable() {
00993   // First step: add the section for the string table to the list of sections:
00994   ELFSection &SHStrTab = getSectionHeaderStringTableSection();
00995 
00996   // Now that we know which section number is the .shstrtab section, update the
00997   // e_shstrndx entry in the ELF header.
00998   ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
00999 
01000   // Set the NameIdx of each section in the string table and emit the bytes for
01001   // the string table.
01002   unsigned Index = 0;
01003 
01004   for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
01005     ELFSection &S = *(*I);
01006     // Set the index into the table.  Note if we have lots of entries with
01007     // common suffixes, we could memoize them here if we cared.
01008     S.NameIdx = Index;
01009     SHStrTab.emitString(S.getName());
01010 
01011     // Keep track of the number of bytes emitted to this section.
01012     Index += S.getName().size()+1;
01013   }
01014 
01015   // Set the size of .shstrtab now that we know what it is.
01016   assert(Index == SHStrTab.size());
01017   SHStrTab.Size = Index;
01018 }
01019 
01020 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
01021 /// and all of the sections, emit these to the ostream destination and emit the
01022 /// SectionTable.
01023 void ELFWriter::OutputSectionsAndSectionTable() {
01024   // Pass #1: Compute the file offset for each section.
01025   size_t FileOff = ElfHdr.size();   // File header first.
01026 
01027   // Adjust alignment of all section if needed, skip the null section.
01028   for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
01029     ELFSection &ES = *SectionList[i];
01030     if (!ES.size()) {
01031       ES.Offset = FileOff;
01032       continue;
01033     }
01034 
01035     // Update Section size
01036     if (!ES.Size)
01037       ES.Size = ES.size();
01038 
01039     // Align FileOff to whatever the alignment restrictions of the section are.
01040     if (ES.Align)
01041       FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
01042 
01043     ES.Offset = FileOff;
01044     FileOff += ES.Size;
01045   }
01046 
01047   // Align Section Header.
01048   unsigned TableAlign = TEW->getPrefELFAlignment();
01049   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
01050 
01051   // Now that we know where all of the sections will be emitted, set the e_shnum
01052   // entry in the ELF header.
01053   ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
01054 
01055   // Now that we know the offset in the file of the section table, update the
01056   // e_shoff address in the ELF header.
01057   ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
01058 
01059   // Now that we know all of the data in the file header, emit it and all of the
01060   // sections!
01061   O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
01062   FileOff = ElfHdr.size();
01063 
01064   // Section Header Table blob
01065   BinaryObject SHdrTable(isLittleEndian, is64Bit);
01066 
01067   // Emit all of sections to the file and build the section header table.
01068   for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
01069     ELFSection &S = *(*I);
01070     DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
01071          << ", Size: " << S.Size << ", Offset: " << S.Offset
01072          << ", SectionData Size: " << S.size() << "\n";
01073 
01074     // Align FileOff to whatever the alignment restrictions of the section are.
01075     if (S.size()) {
01076       if (S.Align)  {
01077         for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
01078              FileOff != NewFileOff; ++FileOff)
01079           O << (char)0xAB;
01080       }
01081       O.write((char *)&S.getData()[0], S.Size);
01082       FileOff += S.Size;
01083     }
01084 
01085     EmitSectionHeader(SHdrTable, S);
01086   }
01087 
01088   // Align output for the section table.
01089   for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
01090        FileOff != NewFileOff; ++FileOff)
01091     O << (char)0xAB;
01092 
01093   // Emit the section table itself.
01094   O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
01095 }