Support Constant Pool Sections
[oota-llvm.git] / lib / CodeGen / ELFWriter.cpp
1 //===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the target-independent ELF writer.  This file writes out
11 // the ELF file in the following order:
12 //
13 //  #1. ELF Header
14 //  #2. '.text' section
15 //  #3. '.data' section
16 //  #4. '.bss' section  (conceptual position in file)
17 //  ...
18 //  #X. '.shstrtab' section
19 //  #Y. Section Table
20 //
21 // The entries in the section table are laid out as:
22 //  #0. Null entry [required]
23 //  #1. ".text" entry - the program code
24 //  #2. ".data" entry - global variables with initializers.     [ if needed ]
25 //  #3. ".bss" entry  - global variables without initializers.  [ if needed ]
26 //  ...
27 //  #N. ".shstrtab" entry - String table for the section names.
28 //
29 //===----------------------------------------------------------------------===//
30
31 #define DEBUG_TYPE "elfwriter"
32
33 #include "ELFWriter.h"
34 #include "ELFCodeEmitter.h"
35 #include "ELF.h"
36 #include "llvm/Constants.h"
37 #include "llvm/Module.h"
38 #include "llvm/PassManager.h"
39 #include "llvm/DerivedTypes.h"
40 #include "llvm/CodeGen/BinaryObject.h"
41 #include "llvm/CodeGen/FileWriters.h"
42 #include "llvm/CodeGen/MachineCodeEmitter.h"
43 #include "llvm/CodeGen/MachineConstantPool.h"
44 #include "llvm/CodeGen/MachineFunctionPass.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Support/Mangler.h"
48 #include "llvm/Support/Streams.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/Support/Debug.h"
51 #include <list>
52 using namespace llvm;
53
54 char ELFWriter::ID = 0;
55 /// AddELFWriter - Concrete function to add the ELF writer to the function pass
56 /// manager.
57 MachineCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
58                                        raw_ostream &O,
59                                        TargetMachine &TM) {
60   ELFWriter *EW = new ELFWriter(O, TM);
61   PM.add(EW);
62   return &EW->getMachineCodeEmitter();
63 }
64
65 //===----------------------------------------------------------------------===//
66 //                          ELFWriter Implementation
67 //===----------------------------------------------------------------------===//
68
69 ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
70   : MachineFunctionPass(&ID), O(o), TM(tm),
71     is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
72     isLittleEndian(TM.getTargetData()->isLittleEndian()),
73     ElfHdr(isLittleEndian, is64Bit) {
74
75   TAI = TM.getTargetAsmInfo();
76   TEW = TM.getELFWriterInfo();
77
78   // Create the machine code emitter object for this target.
79   MCE = new ELFCodeEmitter(*this);
80
81   // Inital number of sections
82   NumSections = 0;
83 }
84
85 ELFWriter::~ELFWriter() {
86   delete MCE;
87 }
88
89 // doInitialization - Emit the file header and all of the global variables for
90 // the module to the ELF file.
91 bool ELFWriter::doInitialization(Module &M) {
92   Mang = new Mangler(M);
93
94   // ELF Header
95   // ----------
96   // Fields e_shnum e_shstrndx are only known after all section have
97   // been emitted. They locations in the ouput buffer are recorded so
98   // to be patched up later.
99   //
100   // Note
101   // ----
102   // emitWord method behaves differently for ELF32 and ELF64, writing
103   // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
104
105   ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
106   ElfHdr.emitByte('E');  // e_ident[EI_MAG1]
107   ElfHdr.emitByte('L');  // e_ident[EI_MAG2]
108   ElfHdr.emitByte('F');  // e_ident[EI_MAG3]
109
110   ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
111   ElfHdr.emitByte(TEW->getEIData());  // e_ident[EI_DATA]
112   ElfHdr.emitByte(EV_CURRENT);        // e_ident[EI_VERSION]
113   ElfHdr.emitAlignment(16);           // e_ident[EI_NIDENT-EI_PAD]
114
115   ElfHdr.emitWord16(ET_REL);             // e_type
116   ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
117   ElfHdr.emitWord32(EV_CURRENT);         // e_version
118   ElfHdr.emitWord(0);                    // e_entry, no entry point in .o file
119   ElfHdr.emitWord(0);                    // e_phoff, no program header for .o
120   ELFHdr_e_shoff_Offset = ElfHdr.size();
121   ElfHdr.emitWord(0);                    // e_shoff = sec hdr table off in bytes
122   ElfHdr.emitWord32(TEW->getEFlags());   // e_flags = whatever the target wants
123   ElfHdr.emitWord16(TEW->getHdrSize());  // e_ehsize = ELF header size
124   ElfHdr.emitWord16(0);                  // e_phentsize = prog header entry size
125   ElfHdr.emitWord16(0);                  // e_phnum = # prog header entries = 0
126
127   // e_shentsize = Section header entry size
128   ElfHdr.emitWord16(TEW->getSHdrSize());
129
130   // e_shnum     = # of section header ents
131   ELFHdr_e_shnum_Offset = ElfHdr.size();
132   ElfHdr.emitWord16(0); // Placeholder
133
134   // e_shstrndx  = Section # of '.shstrtab'
135   ELFHdr_e_shstrndx_Offset = ElfHdr.size();
136   ElfHdr.emitWord16(0); // Placeholder
137
138   // Add the null section, which is required to be first in the file.
139   getNullSection();
140
141   return false;
142 }
143
144 unsigned ELFWriter::getGlobalELFLinkage(const GlobalVariable *GV) {
145   if (GV->hasInternalLinkage())
146     return ELFSym::STB_LOCAL;
147
148   if (GV->hasWeakLinkage())
149     return ELFSym::STB_WEAK;
150
151   return ELFSym::STB_GLOBAL;
152 }
153
154 // For global symbols without a section, return the Null section as a
155 // placeholder
156 ELFSection &ELFWriter::getGlobalSymELFSection(const GlobalVariable *GV,
157                                               ELFSym &Sym) {
158   const Section *S = TAI->SectionForGlobal(GV);
159   unsigned Flags = S->getFlags();
160   unsigned SectionType = ELFSection::SHT_PROGBITS;
161   unsigned SHdrFlags = ELFSection::SHF_ALLOC;
162   DOUT << "Section " << S->getName() << " for global " << GV->getName() << "\n";
163
164   // If this is an external global, the symbol does not have a section.
165   if (!GV->hasInitializer()) {
166     Sym.SectionIdx = ELFSection::SHN_UNDEF;
167     return getNullSection();
168   }
169
170   const TargetData *TD = TM.getTargetData();
171   unsigned Align = TD->getPreferredAlignment(GV);
172   Constant *CV = GV->getInitializer();
173
174   if (Flags & SectionFlags::Code)
175     SHdrFlags |= ELFSection::SHF_EXECINSTR;
176   if (Flags & SectionFlags::Writeable)
177     SHdrFlags |= ELFSection::SHF_WRITE;
178   if (Flags & SectionFlags::Mergeable)
179     SHdrFlags |= ELFSection::SHF_MERGE;
180   if (Flags & SectionFlags::TLS)
181     SHdrFlags |= ELFSection::SHF_TLS;
182   if (Flags & SectionFlags::Strings)
183     SHdrFlags |= ELFSection::SHF_STRINGS;
184
185   // If this global has a zero initializer, go to .bss or common section.
186   // Variables are part of the common block if they are zero initialized
187   // and allowed to be merged with other symbols.
188   if (CV->isNullValue() || isa<UndefValue>(CV)) {
189     SectionType = ELFSection::SHT_NOBITS;
190     ELFSection &ElfS = getSection(S->getName(), SectionType, SHdrFlags);
191     if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
192         GV->hasCommonLinkage()) {
193       Sym.SectionIdx = ELFSection::SHN_COMMON;
194       Sym.IsCommon = true;
195       ElfS.Align = 1;
196       return ElfS;
197     }
198     Sym.IsBss = true;
199     Sym.SectionIdx = ElfS.SectionIdx;
200     if (Align) ElfS.Size = (ElfS.Size + Align-1) & ~(Align-1);
201     ElfS.Align = std::max(ElfS.Align, Align);
202     return ElfS;
203   }
204
205   Sym.IsConstant = true;
206   ELFSection &ElfS = getSection(S->getName(), SectionType, SHdrFlags);
207   Sym.SectionIdx = ElfS.SectionIdx;
208   ElfS.Align = std::max(ElfS.Align, Align);
209   return ElfS;
210 }
211
212 void ELFWriter::EmitFunctionDeclaration(const Function *F) {
213   ELFSym GblSym(F);
214   GblSym.setBind(ELFSym::STB_GLOBAL);
215   GblSym.setType(ELFSym::STT_NOTYPE);
216   GblSym.SectionIdx = ELFSection::SHN_UNDEF;
217   SymbolList.push_back(GblSym);
218 }
219
220 void ELFWriter::EmitGlobalVar(const GlobalVariable *GV) {
221   unsigned SymBind = getGlobalELFLinkage(GV);
222   unsigned Align=0, Size=0;
223   ELFSym GblSym(GV);
224   GblSym.setBind(SymBind);
225
226   if (GV->hasInitializer()) {
227     GblSym.setType(ELFSym::STT_OBJECT);
228     const TargetData *TD = TM.getTargetData();
229     Align = TD->getPreferredAlignment(GV);
230     Size = TD->getTypeAllocSize(GV->getInitializer()->getType());
231     GblSym.Size = Size;
232   } else {
233     GblSym.setType(ELFSym::STT_NOTYPE);
234   }
235
236   ELFSection &GblSection = getGlobalSymELFSection(GV, GblSym);
237
238   if (GblSym.IsCommon) {
239     GblSym.Value = Align;
240   } else if (GblSym.IsBss) {
241     GblSym.Value = GblSection.Size;
242     GblSection.Size += Size;
243   } else if (GblSym.IsConstant){
244     // GblSym.Value should contain the symbol index inside the section,
245     // and all symbols should start on their required alignment boundary
246     GblSym.Value = (GblSection.size() + (Align-1)) & (-Align);
247     GblSection.emitAlignment(Align);
248     EmitGlobalConstant(GV->getInitializer(), GblSection);
249   }
250
251   // Local symbols should come first on the symbol table.
252   if (!GV->hasPrivateLinkage()) {
253     if (SymBind == ELFSym::STB_LOCAL)
254       SymbolList.push_front(GblSym);
255     else
256       SymbolList.push_back(GblSym);
257   }
258 }
259
260 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
261                                          ELFSection &GblS) {
262
263   // Print the fields in successive locations. Pad to align if needed!
264   const TargetData *TD = TM.getTargetData();
265   unsigned Size = TD->getTypeAllocSize(CVS->getType());
266   const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
267   uint64_t sizeSoFar = 0;
268   for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
269     const Constant* field = CVS->getOperand(i);
270
271     // Check if padding is needed and insert one or more 0s.
272     uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
273     uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
274                         - cvsLayout->getElementOffset(i)) - fieldSize;
275     sizeSoFar += fieldSize + padSize;
276
277     // Now print the actual field value.
278     EmitGlobalConstant(field, GblS);
279
280     // Insert padding - this may include padding to increase the size of the
281     // current field up to the ABI size (if the struct is not packed) as well
282     // as padding to ensure that the next field starts at the right offset.
283     for (unsigned p=0; p < padSize; p++)
284       GblS.emitByte(0);
285   }
286   assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
287          "Layout of constant struct may be incorrect!");
288 }
289
290 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
291   const TargetData *TD = TM.getTargetData();
292   unsigned Size = TD->getTypeAllocSize(CV->getType());
293
294   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
295     if (CVA->isString()) {
296       std::string GblStr = CVA->getAsString();
297       GblStr.resize(GblStr.size()-1);
298       GblS.emitString(GblStr);
299     } else { // Not a string.  Print the values in successive locations
300       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
301         EmitGlobalConstant(CVA->getOperand(i), GblS);
302     }
303     return;
304   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
305     EmitGlobalConstantStruct(CVS, GblS);
306     return;
307   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
308     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
309     if (CFP->getType() == Type::DoubleTy)
310       GblS.emitWord64(Val);
311     else if (CFP->getType() == Type::FloatTy)
312       GblS.emitWord32(Val);
313     else if (CFP->getType() == Type::X86_FP80Ty) {
314       assert(0 && "X86_FP80Ty global emission not implemented");
315     } else if (CFP->getType() == Type::PPC_FP128Ty)
316       assert(0 && "PPC_FP128Ty global emission not implemented");
317     return;
318   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
319     if (Size == 4)
320       GblS.emitWord32(CI->getZExtValue());
321     else if (Size == 8)
322       GblS.emitWord64(CI->getZExtValue());
323     else
324       assert(0 && "LargeInt global emission not implemented");
325     return;
326   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
327     const VectorType *PTy = CP->getType();
328     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
329       EmitGlobalConstant(CP->getOperand(I), GblS);
330     return;
331   }
332   assert(0 && "unknown global constant");
333 }
334
335
336 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
337   // Nothing to do here, this is all done through the MCE object above.
338   return false;
339 }
340
341 /// doFinalization - Now that the module has been completely processed, emit
342 /// the ELF file to 'O'.
343 bool ELFWriter::doFinalization(Module &M) {
344   /// FIXME: This should be removed when moving to ObjectCodeEmiter. Since the
345   /// current ELFCodeEmiter uses CurrBuff, ... it doesn't update S.Data
346   /// vector size for .text sections, so this is a quick dirty fix
347   ELFSection &TS = getTextSection();
348   if (TS.Size) {
349     BinaryData &BD = TS.getData();
350     for (unsigned e=0; e<TS.Size; ++e)
351       BD.push_back(BD[e]);
352   }
353
354   // Emit .data section placeholder
355   getDataSection();
356
357   // Emit .bss section placeholder
358   getBSSSection();
359
360   // Build and emit data, bss and "common" sections.
361   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
362        I != E; ++I) {
363     EmitGlobalVar(I);
364     GblSymLookup[I] = 0;
365   }
366
367   // Emit all pending globals
368   // TODO: this should be done only for referenced symbols
369   for (SetVector<GlobalValue*>::const_iterator I = PendingGlobals.begin(),
370        E = PendingGlobals.end(); I != E; ++I) {
371
372     // No need to emit the symbol again
373     if (GblSymLookup.find(*I) != GblSymLookup.end())
374       continue;
375
376     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
377       EmitGlobalVar(GV);
378     } else if (Function *F = dyn_cast<Function>(*I)) {
379       // If function is not in GblSymLookup, it doesn't have a body,
380       // so emit the symbol as a function declaration (no section associated)
381       EmitFunctionDeclaration(F);
382     } else {
383       assert("unknown howto handle pending global");
384     }
385     GblSymLookup[*I] = 0;
386   }
387
388   // Emit non-executable stack note
389   if (TAI->getNonexecutableStackDirective())
390     getNonExecStackSection();
391
392   // Emit a symbol for each section created until now
393   for (std::map<std::string, ELFSection*>::iterator I = SectionLookup.begin(),
394        E = SectionLookup.end(); I != E; ++I) {
395     ELFSection *ES = I->second;
396
397     // Skip null section
398     if (ES->SectionIdx == 0) continue;
399
400     ELFSym SectionSym(0);
401     SectionSym.SectionIdx = ES->SectionIdx;
402     SectionSym.Size = 0;
403     SectionSym.setBind(ELFSym::STB_LOCAL);
404     SectionSym.setType(ELFSym::STT_SECTION);
405
406     // Local symbols go in the list front
407     SymbolList.push_front(SectionSym);
408   }
409
410   // Emit string table
411   EmitStringTable();
412
413   // Emit the symbol table now, if non-empty.
414   EmitSymbolTable();
415
416   // Emit the relocation sections.
417   EmitRelocations();
418
419   // Emit the sections string table.
420   EmitSectionTableStringTable();
421
422   // Dump the sections and section table to the .o file.
423   OutputSectionsAndSectionTable();
424
425   // We are done with the abstract symbols.
426   SectionList.clear();
427   NumSections = 0;
428
429   // Release the name mangler object.
430   delete Mang; Mang = 0;
431   return false;
432 }
433
434 /// EmitRelocations - Emit relocations
435 void ELFWriter::EmitRelocations() {
436
437   // Create Relocation sections for each section which needs it.
438   for (std::list<ELFSection>::iterator I = SectionList.begin(),
439        E = SectionList.end(); I != E; ++I) {
440
441     // This section does not have relocations
442     if (!I->hasRelocations()) continue;
443
444     // Get the relocation section for section 'I'
445     bool HasRelA = TEW->hasRelocationAddend();
446     ELFSection &RelSec = getRelocSection(I->getName(), HasRelA);
447
448     // 'Link' - Section hdr idx of the associated symbol table
449     // 'Info' - Section hdr idx of the section to which the relocation applies
450     ELFSection &SymTab = getSymbolTableSection();
451     RelSec.Link = SymTab.SectionIdx;
452     RelSec.Info = I->SectionIdx;
453     RelSec.EntSize = TEW->getRelocationEntrySize();
454
455     // Get the relocations from Section
456     std::vector<MachineRelocation> Relos = I->getRelocations();
457     for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
458          MRE = Relos.end(); MRI != MRE; ++MRI) {
459       MachineRelocation &MR = *MRI;
460
461       // Offset from the start of the section containing the symbol
462       unsigned Offset = MR.getMachineCodeOffset();
463
464       // Symbol index in the symbol table
465       unsigned SymIdx = 0;
466
467       // Target specific ELF relocation type
468       unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
469
470       // Constant addend used to compute the value to be stored 
471       // into the relocatable field
472       int64_t Addend = 0;
473
474       // There are several machine relocations types, and each one of
475       // them needs a different approach to retrieve the symbol table index.
476       if (MR.isGlobalValue()) {
477         const GlobalValue *G = MR.getGlobalValue();
478         SymIdx = GblSymLookup[G];
479         Addend = TEW->getAddendForRelTy(RelType);
480       } else {
481         unsigned SectionIdx = MR.getConstantVal();
482         // TODO: use a map for this.
483         for (std::list<ELFSym>::iterator I = SymbolList.begin(),
484              E = SymbolList.end(); I != E; ++I)
485           if ((SectionIdx == I->SectionIdx) &&
486               (I->getType() == ELFSym::STT_SECTION)) {
487             SymIdx = I->SymTabIdx;
488             break;
489           }
490         Addend = (uint64_t)MR.getResultPointer();
491       }
492
493       // Get the relocation entry and emit to the relocation section
494       ELFRelocation Rel(Offset, SymIdx, RelType, HasRelA, Addend);
495       EmitRelocation(RelSec, Rel, HasRelA);
496     }
497   }
498 }
499
500 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
501 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
502                                bool HasRelA) {
503   RelSec.emitWord(Rel.getOffset());
504   RelSec.emitWord(Rel.getInfo(is64Bit));
505   if (HasRelA)
506     RelSec.emitWord(Rel.getAddend());
507 }
508
509 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
510 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
511   if (is64Bit) {
512     SymbolTable.emitWord32(Sym.NameIdx);
513     SymbolTable.emitByte(Sym.Info);
514     SymbolTable.emitByte(Sym.Other);
515     SymbolTable.emitWord16(Sym.SectionIdx);
516     SymbolTable.emitWord64(Sym.Value);
517     SymbolTable.emitWord64(Sym.Size);
518   } else {
519     SymbolTable.emitWord32(Sym.NameIdx);
520     SymbolTable.emitWord32(Sym.Value);
521     SymbolTable.emitWord32(Sym.Size);
522     SymbolTable.emitByte(Sym.Info);
523     SymbolTable.emitByte(Sym.Other);
524     SymbolTable.emitWord16(Sym.SectionIdx);
525   }
526 }
527
528 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
529 /// Section Header Table
530 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab, 
531                                   const ELFSection &SHdr) {
532   SHdrTab.emitWord32(SHdr.NameIdx);
533   SHdrTab.emitWord32(SHdr.Type);
534   if (is64Bit) {
535     SHdrTab.emitWord64(SHdr.Flags);
536     SHdrTab.emitWord(SHdr.Addr);
537     SHdrTab.emitWord(SHdr.Offset);
538     SHdrTab.emitWord64(SHdr.Size);
539     SHdrTab.emitWord32(SHdr.Link);
540     SHdrTab.emitWord32(SHdr.Info);
541     SHdrTab.emitWord64(SHdr.Align);
542     SHdrTab.emitWord64(SHdr.EntSize);
543   } else {
544     SHdrTab.emitWord32(SHdr.Flags);
545     SHdrTab.emitWord(SHdr.Addr);
546     SHdrTab.emitWord(SHdr.Offset);
547     SHdrTab.emitWord32(SHdr.Size);
548     SHdrTab.emitWord32(SHdr.Link);
549     SHdrTab.emitWord32(SHdr.Info);
550     SHdrTab.emitWord32(SHdr.Align);
551     SHdrTab.emitWord32(SHdr.EntSize);
552   }
553 }
554
555 /// EmitStringTable - If the current symbol table is non-empty, emit the string
556 /// table for it
557 void ELFWriter::EmitStringTable() {
558   if (!SymbolList.size()) return;  // Empty symbol table.
559   ELFSection &StrTab = getStringTableSection();
560
561   // Set the zero'th symbol to a null byte, as required.
562   StrTab.emitByte(0);
563
564   // Walk on the symbol list and write symbol names into the
565   // string table.
566   unsigned Index = 1;
567   for (std::list<ELFSym>::iterator I = SymbolList.begin(),
568        E = SymbolList.end(); I != E; ++I) {
569
570     // Use the name mangler to uniquify the LLVM symbol.
571     std::string Name;
572     if (I->GV) Name.append(Mang->getValueName(I->GV));
573
574     if (Name.empty()) {
575       I->NameIdx = 0;
576     } else {
577       I->NameIdx = Index;
578       StrTab.emitString(Name);
579
580       // Keep track of the number of bytes emitted to this section.
581       Index += Name.size()+1;
582     }
583   }
584   assert(Index == StrTab.size());
585   StrTab.Size = Index;
586 }
587
588 /// EmitSymbolTable - Emit the symbol table itself.
589 void ELFWriter::EmitSymbolTable() {
590   if (!SymbolList.size()) return;  // Empty symbol table.
591
592   unsigned FirstNonLocalSymbol = 1;
593   // Now that we have emitted the string table and know the offset into the
594   // string table of each symbol, emit the symbol table itself.
595   ELFSection &SymTab = getSymbolTableSection();
596   SymTab.Align = TEW->getPrefELFAlignment();
597
598   // Section Index of .strtab.
599   SymTab.Link = getStringTableSection().SectionIdx;
600
601   // Size of each symtab entry.
602   SymTab.EntSize = TEW->getSymTabEntrySize();
603
604   // The first entry in the symtab is the null symbol
605   ELFSym NullSym = ELFSym(0);
606   EmitSymbol(SymTab, NullSym);
607
608   // Emit all the symbols to the symbol table. Skip the null
609   // symbol, cause it's emitted already
610   unsigned Index = 1;
611   for (std::list<ELFSym>::iterator I = SymbolList.begin(),
612        E = SymbolList.end(); I != E; ++I, ++Index) {
613     // Keep track of the first non-local symbol
614     if (I->getBind() == ELFSym::STB_LOCAL)
615       FirstNonLocalSymbol++;
616
617     // Emit symbol to the symbol table
618     EmitSymbol(SymTab, *I);
619
620     // Record the symbol table index for each global value
621     if (I->GV)
622       GblSymLookup[I->GV] = Index;
623
624     // Keep track on the symbol index into the symbol table
625     I->SymTabIdx = Index;
626   }
627
628   SymTab.Info = FirstNonLocalSymbol;
629   SymTab.Size = SymTab.size();
630 }
631
632 /// EmitSectionTableStringTable - This method adds and emits a section for the
633 /// ELF Section Table string table: the string table that holds all of the
634 /// section names.
635 void ELFWriter::EmitSectionTableStringTable() {
636   // First step: add the section for the string table to the list of sections:
637   ELFSection &SHStrTab = getSectionHeaderStringTableSection();
638
639   // Now that we know which section number is the .shstrtab section, update the
640   // e_shstrndx entry in the ELF header.
641   ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
642
643   // Set the NameIdx of each section in the string table and emit the bytes for
644   // the string table.
645   unsigned Index = 0;
646
647   for (std::list<ELFSection>::iterator I = SectionList.begin(),
648          E = SectionList.end(); I != E; ++I) {
649     // Set the index into the table.  Note if we have lots of entries with
650     // common suffixes, we could memoize them here if we cared.
651     I->NameIdx = Index;
652     SHStrTab.emitString(I->getName());
653
654     // Keep track of the number of bytes emitted to this section.
655     Index += I->getName().size()+1;
656   }
657
658   // Set the size of .shstrtab now that we know what it is.
659   assert(Index == SHStrTab.size());
660   SHStrTab.Size = Index;
661 }
662
663 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
664 /// and all of the sections, emit these to the ostream destination and emit the
665 /// SectionTable.
666 void ELFWriter::OutputSectionsAndSectionTable() {
667   // Pass #1: Compute the file offset for each section.
668   size_t FileOff = ElfHdr.size();   // File header first.
669
670   // Adjust alignment of all section if needed.
671   for (std::list<ELFSection>::iterator I = SectionList.begin(),
672          E = SectionList.end(); I != E; ++I) {
673
674     // Section idx 0 has 0 offset
675     if (!I->SectionIdx)
676       continue;
677
678     if (!I->size()) {
679       I->Offset = FileOff;
680       continue;
681     }
682
683     // Update Section size
684     if (!I->Size)
685       I->Size = I->size();
686
687     // Align FileOff to whatever the alignment restrictions of the section are.
688     if (I->Align)
689       FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
690
691     I->Offset = FileOff;
692     FileOff += I->Size;
693   }
694
695   // Align Section Header.
696   unsigned TableAlign = TEW->getPrefELFAlignment();
697   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
698
699   // Now that we know where all of the sections will be emitted, set the e_shnum
700   // entry in the ELF header.
701   ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
702
703   // Now that we know the offset in the file of the section table, update the
704   // e_shoff address in the ELF header.
705   ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
706
707   // Now that we know all of the data in the file header, emit it and all of the
708   // sections!
709   O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
710   FileOff = ElfHdr.size();
711
712   // Section Header Table blob
713   BinaryObject SHdrTable(isLittleEndian, is64Bit);
714
715   // Emit all of sections to the file and build the section header table.
716   while (!SectionList.empty()) {
717     ELFSection &S = *SectionList.begin();
718     DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
719          << ", Size: " << S.Size << ", Offset: " << S.Offset
720          << ", SectionData Size: " << S.size() << "\n";
721
722     // Align FileOff to whatever the alignment restrictions of the section are.
723     if (S.size()) {
724       if (S.Align)  {
725         for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
726              FileOff != NewFileOff; ++FileOff)
727           O << (char)0xAB;
728       }
729       O.write((char *)&S.getData()[0], S.Size);
730       FileOff += S.Size;
731     }
732
733     EmitSectionHeader(SHdrTable, S);
734     SectionList.pop_front();
735   }
736
737   // Align output for the section table.
738   for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
739        FileOff != NewFileOff; ++FileOff)
740     O << (char)0xAB;
741
742   // Emit the section table itself.
743   O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
744 }