9e915245525a3800bf1ac217babd19efc7182bd3
[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 "ELF.h"
34 #include "ELFWriter.h"
35 #include "ELFCodeEmitter.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/Target/TargetAsmInfo.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Target/TargetELFWriterInfo.h"
47 #include "llvm/Target/TargetMachine.h"
48 #include "llvm/Support/Mangler.h"
49 #include "llvm/Support/Streams.h"
50 #include "llvm/Support/raw_ostream.h"
51 #include "llvm/Support/Debug.h"
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::getGlobalELFVisibility(const GlobalValue *GV) {
145   switch (GV->getVisibility()) {
146   default:
147     assert(0 && "unknown visibility type");
148   case GlobalValue::DefaultVisibility:
149     return ELFSym::STV_DEFAULT;
150   case GlobalValue::HiddenVisibility:
151     return ELFSym::STV_HIDDEN;
152   case GlobalValue::ProtectedVisibility:
153     return ELFSym::STV_PROTECTED;
154   }
155
156   return 0;
157 }
158
159 unsigned ELFWriter::getGlobalELFLinkage(const GlobalValue *GV) {
160   if (GV->hasInternalLinkage())
161     return ELFSym::STB_LOCAL;
162
163   if (GV->hasWeakLinkage())
164     return ELFSym::STB_WEAK;
165
166   return ELFSym::STB_GLOBAL;
167 }
168
169 // getElfSectionFlags - Get the ELF Section Header based on the
170 // flags defined in ELFTargetAsmInfo.
171 unsigned ELFWriter::getElfSectionFlags(unsigned Flags) {
172   unsigned ElfSectionFlags = ELFSection::SHF_ALLOC;
173
174   if (Flags & SectionFlags::Code)
175     ElfSectionFlags |= ELFSection::SHF_EXECINSTR;
176   if (Flags & SectionFlags::Writeable)
177     ElfSectionFlags |= ELFSection::SHF_WRITE;
178   if (Flags & SectionFlags::Mergeable)
179     ElfSectionFlags |= ELFSection::SHF_MERGE;
180   if (Flags & SectionFlags::TLS)
181     ElfSectionFlags |= ELFSection::SHF_TLS;
182   if (Flags & SectionFlags::Strings)
183     ElfSectionFlags |= ELFSection::SHF_STRINGS;
184
185   return ElfSectionFlags;
186 }
187
188 // For global symbols without a section, return the Null section as a
189 // placeholder
190 ELFSection &ELFWriter::getGlobalSymELFSection(const GlobalVariable *GV,
191                                               ELFSym &Sym) {
192   // If this is a declaration, the symbol does not have a section.
193   if (!GV->hasInitializer()) {
194     Sym.SectionIdx = ELFSection::SHN_UNDEF;
195     return getNullSection();
196   }
197
198   // Get the name and flags of the section for the global
199   const Section *S = TAI->SectionForGlobal(GV);
200   unsigned SectionType = ELFSection::SHT_PROGBITS;
201   unsigned SectionFlags = getElfSectionFlags(S->getFlags());
202   DOUT << "Section " << S->getName() << " for global " << GV->getName() << "\n";
203
204   const TargetData *TD = TM.getTargetData();
205   unsigned Align = TD->getPreferredAlignment(GV);
206   Constant *CV = GV->getInitializer();
207
208   // If this global has a zero initializer, go to .bss or common section.
209   // Variables are part of the common block if they are zero initialized
210   // and allowed to be merged with other symbols.
211   if (CV->isNullValue() || isa<UndefValue>(CV)) {
212     SectionType = ELFSection::SHT_NOBITS;
213     ELFSection &ElfS = getSection(S->getName(), SectionType, SectionFlags);
214     if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
215         GV->hasCommonLinkage()) {
216       Sym.SectionIdx = ELFSection::SHN_COMMON;
217       Sym.IsCommon = true;
218       ElfS.Align = 1;
219       return ElfS;
220     }
221     Sym.IsBss = true;
222     Sym.SectionIdx = ElfS.SectionIdx;
223     if (Align) ElfS.Size = (ElfS.Size + Align-1) & ~(Align-1);
224     ElfS.Align = std::max(ElfS.Align, Align);
225     return ElfS;
226   }
227
228   Sym.IsConstant = true;
229   ELFSection &ElfS = getSection(S->getName(), SectionType, SectionFlags);
230   Sym.SectionIdx = ElfS.SectionIdx;
231   ElfS.Align = std::max(ElfS.Align, Align);
232   return ElfS;
233 }
234
235 void ELFWriter::EmitFunctionDeclaration(const Function *F) {
236   ELFSym GblSym(F);
237   GblSym.setBind(ELFSym::STB_GLOBAL);
238   GblSym.setType(ELFSym::STT_NOTYPE);
239   GblSym.setVisibility(ELFSym::STV_DEFAULT);
240   GblSym.SectionIdx = ELFSection::SHN_UNDEF;
241   SymbolList.push_back(GblSym);
242 }
243
244 void ELFWriter::EmitGlobalVar(const GlobalVariable *GV) {
245   unsigned SymBind = getGlobalELFLinkage(GV);
246   unsigned Align=0, Size=0;
247   ELFSym GblSym(GV);
248   GblSym.setBind(SymBind);
249   GblSym.setVisibility(getGlobalELFVisibility(GV));
250
251   if (GV->hasInitializer()) {
252     GblSym.setType(ELFSym::STT_OBJECT);
253     const TargetData *TD = TM.getTargetData();
254     Align = TD->getPreferredAlignment(GV);
255     Size = TD->getTypeAllocSize(GV->getInitializer()->getType());
256     GblSym.Size = Size;
257   } else {
258     GblSym.setType(ELFSym::STT_NOTYPE);
259   }
260
261   ELFSection &GblSection = getGlobalSymELFSection(GV, GblSym);
262
263   if (GblSym.IsCommon) {
264     GblSym.Value = Align;
265   } else if (GblSym.IsBss) {
266     GblSym.Value = GblSection.Size;
267     GblSection.Size += Size;
268   } else if (GblSym.IsConstant){
269     // GblSym.Value should contain the symbol index inside the section,
270     // and all symbols should start on their required alignment boundary
271     GblSym.Value = (GblSection.size() + (Align-1)) & (-Align);
272     GblSection.emitAlignment(Align);
273     EmitGlobalConstant(GV->getInitializer(), GblSection);
274   }
275
276   // Local symbols should come first on the symbol table.
277   if (!GV->hasPrivateLinkage()) {
278     if (SymBind == ELFSym::STB_LOCAL)
279       SymbolList.push_front(GblSym);
280     else
281       SymbolList.push_back(GblSym);
282   }
283 }
284
285 void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
286                                          ELFSection &GblS) {
287
288   // Print the fields in successive locations. Pad to align if needed!
289   const TargetData *TD = TM.getTargetData();
290   unsigned Size = TD->getTypeAllocSize(CVS->getType());
291   const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
292   uint64_t sizeSoFar = 0;
293   for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
294     const Constant* field = CVS->getOperand(i);
295
296     // Check if padding is needed and insert one or more 0s.
297     uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
298     uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
299                         - cvsLayout->getElementOffset(i)) - fieldSize;
300     sizeSoFar += fieldSize + padSize;
301
302     // Now print the actual field value.
303     EmitGlobalConstant(field, GblS);
304
305     // Insert padding - this may include padding to increase the size of the
306     // current field up to the ABI size (if the struct is not packed) as well
307     // as padding to ensure that the next field starts at the right offset.
308     for (unsigned p=0; p < padSize; p++)
309       GblS.emitByte(0);
310   }
311   assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
312          "Layout of constant struct may be incorrect!");
313 }
314
315 void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
316   const TargetData *TD = TM.getTargetData();
317   unsigned Size = TD->getTypeAllocSize(CV->getType());
318
319   if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
320     if (CVA->isString()) {
321       std::string GblStr = CVA->getAsString();
322       GblStr.resize(GblStr.size()-1);
323       GblS.emitString(GblStr);
324     } else { // Not a string.  Print the values in successive locations
325       for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
326         EmitGlobalConstant(CVA->getOperand(i), GblS);
327     }
328     return;
329   } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
330     EmitGlobalConstantStruct(CVS, GblS);
331     return;
332   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
333     uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
334     if (CFP->getType() == Type::DoubleTy)
335       GblS.emitWord64(Val);
336     else if (CFP->getType() == Type::FloatTy)
337       GblS.emitWord32(Val);
338     else if (CFP->getType() == Type::X86_FP80Ty) {
339       assert(0 && "X86_FP80Ty global emission not implemented");
340     } else if (CFP->getType() == Type::PPC_FP128Ty)
341       assert(0 && "PPC_FP128Ty global emission not implemented");
342     return;
343   } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
344     if (Size == 4)
345       GblS.emitWord32(CI->getZExtValue());
346     else if (Size == 8)
347       GblS.emitWord64(CI->getZExtValue());
348     else
349       assert(0 && "LargeInt global emission not implemented");
350     return;
351   } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
352     const VectorType *PTy = CP->getType();
353     for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
354       EmitGlobalConstant(CP->getOperand(I), GblS);
355     return;
356   }
357   assert(0 && "unknown global constant");
358 }
359
360
361 bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
362   // Nothing to do here, this is all done through the MCE object above.
363   return false;
364 }
365
366 /// doFinalization - Now that the module has been completely processed, emit
367 /// the ELF file to 'O'.
368 bool ELFWriter::doFinalization(Module &M) {
369   /// FIXME: This should be removed when moving to ObjectCodeEmiter. Since the
370   /// current ELFCodeEmiter uses CurrBuff, ... it doesn't update S.Data
371   /// vector size for .text sections, so this is a quick dirty fix
372   ELFSection &TS = getTextSection();
373   if (TS.Size) {
374     BinaryData &BD = TS.getData();
375     for (unsigned e=0; e<TS.Size; ++e)
376       BD.push_back(BD[e]);
377   }
378
379   // Emit .data section placeholder
380   getDataSection();
381
382   // Emit .bss section placeholder
383   getBSSSection();
384
385   // Build and emit data, bss and "common" sections.
386   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
387        I != E; ++I) {
388     EmitGlobalVar(I);
389     GblSymLookup[I] = 0;
390   }
391
392   // Emit all pending globals
393   // TODO: this should be done only for referenced symbols
394   for (SetVector<GlobalValue*>::const_iterator I = PendingGlobals.begin(),
395        E = PendingGlobals.end(); I != E; ++I) {
396
397     // No need to emit the symbol again
398     if (GblSymLookup.find(*I) != GblSymLookup.end())
399       continue;
400
401     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I)) {
402       EmitGlobalVar(GV);
403     } else if (Function *F = dyn_cast<Function>(*I)) {
404       // If function is not in GblSymLookup, it doesn't have a body,
405       // so emit the symbol as a function declaration (no section associated)
406       EmitFunctionDeclaration(F);
407     } else {
408       assert("unknown howto handle pending global");
409     }
410     GblSymLookup[*I] = 0;
411   }
412
413   // Emit non-executable stack note
414   if (TAI->getNonexecutableStackDirective())
415     getNonExecStackSection();
416
417   // Emit a symbol for each section created until now
418   for (std::map<std::string, ELFSection*>::iterator I = SectionLookup.begin(),
419        E = SectionLookup.end(); I != E; ++I) {
420     ELFSection *ES = I->second;
421
422     // Skip null section
423     if (ES->SectionIdx == 0) continue;
424
425     ELFSym SectionSym(0);
426     SectionSym.SectionIdx = ES->SectionIdx;
427     SectionSym.Size = 0;
428     SectionSym.setBind(ELFSym::STB_LOCAL);
429     SectionSym.setType(ELFSym::STT_SECTION);
430     SectionSym.setVisibility(ELFSym::STV_DEFAULT);
431
432     // Local symbols go in the list front
433     SymbolList.push_front(SectionSym);
434   }
435
436   // Emit string table
437   EmitStringTable();
438
439   // Emit the symbol table now, if non-empty.
440   EmitSymbolTable();
441
442   // Emit the relocation sections.
443   EmitRelocations();
444
445   // Emit the sections string table.
446   EmitSectionTableStringTable();
447
448   // Dump the sections and section table to the .o file.
449   OutputSectionsAndSectionTable();
450
451   // We are done with the abstract symbols.
452   SectionList.clear();
453   NumSections = 0;
454
455   // Release the name mangler object.
456   delete Mang; Mang = 0;
457   return false;
458 }
459
460 /// EmitRelocations - Emit relocations
461 void ELFWriter::EmitRelocations() {
462
463   // Create Relocation sections for each section which needs it.
464   for (std::list<ELFSection>::iterator I = SectionList.begin(),
465        E = SectionList.end(); I != E; ++I) {
466
467     // This section does not have relocations
468     if (!I->hasRelocations()) continue;
469
470     // Get the relocation section for section 'I'
471     bool HasRelA = TEW->hasRelocationAddend();
472     ELFSection &RelSec = getRelocSection(I->getName(), HasRelA,
473                                          TEW->getPrefELFAlignment());
474
475     // 'Link' - Section hdr idx of the associated symbol table
476     // 'Info' - Section hdr idx of the section to which the relocation applies
477     ELFSection &SymTab = getSymbolTableSection();
478     RelSec.Link = SymTab.SectionIdx;
479     RelSec.Info = I->SectionIdx;
480     RelSec.EntSize = TEW->getRelocationEntrySize();
481
482     // Get the relocations from Section
483     std::vector<MachineRelocation> Relos = I->getRelocations();
484     for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
485          MRE = Relos.end(); MRI != MRE; ++MRI) {
486       MachineRelocation &MR = *MRI;
487
488       // Offset from the start of the section containing the symbol
489       unsigned Offset = MR.getMachineCodeOffset();
490
491       // Symbol index in the symbol table
492       unsigned SymIdx = 0;
493
494       // Target specific ELF relocation type
495       unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
496
497       // Constant addend used to compute the value to be stored 
498       // into the relocatable field
499       int64_t Addend = 0;
500
501       // There are several machine relocations types, and each one of
502       // them needs a different approach to retrieve the symbol table index.
503       if (MR.isGlobalValue()) {
504         const GlobalValue *G = MR.getGlobalValue();
505         SymIdx = GblSymLookup[G];
506         Addend = TEW->getAddendForRelTy(RelType);
507       } else {
508         unsigned SectionIdx = MR.getConstantVal();
509         // TODO: use a map for this.
510         for (std::list<ELFSym>::iterator I = SymbolList.begin(),
511              E = SymbolList.end(); I != E; ++I)
512           if ((SectionIdx == I->SectionIdx) &&
513               (I->getType() == ELFSym::STT_SECTION)) {
514             SymIdx = I->SymTabIdx;
515             break;
516           }
517         Addend = (uint64_t)MR.getResultPointer();
518       }
519
520       // Get the relocation entry and emit to the relocation section
521       ELFRelocation Rel(Offset, SymIdx, RelType, HasRelA, Addend);
522       EmitRelocation(RelSec, Rel, HasRelA);
523     }
524   }
525 }
526
527 /// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
528 void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
529                                bool HasRelA) {
530   RelSec.emitWord(Rel.getOffset());
531   RelSec.emitWord(Rel.getInfo(is64Bit));
532   if (HasRelA)
533     RelSec.emitWord(Rel.getAddend());
534 }
535
536 /// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
537 void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
538   if (is64Bit) {
539     SymbolTable.emitWord32(Sym.NameIdx);
540     SymbolTable.emitByte(Sym.Info);
541     SymbolTable.emitByte(Sym.Other);
542     SymbolTable.emitWord16(Sym.SectionIdx);
543     SymbolTable.emitWord64(Sym.Value);
544     SymbolTable.emitWord64(Sym.Size);
545   } else {
546     SymbolTable.emitWord32(Sym.NameIdx);
547     SymbolTable.emitWord32(Sym.Value);
548     SymbolTable.emitWord32(Sym.Size);
549     SymbolTable.emitByte(Sym.Info);
550     SymbolTable.emitByte(Sym.Other);
551     SymbolTable.emitWord16(Sym.SectionIdx);
552   }
553 }
554
555 /// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
556 /// Section Header Table
557 void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab, 
558                                   const ELFSection &SHdr) {
559   SHdrTab.emitWord32(SHdr.NameIdx);
560   SHdrTab.emitWord32(SHdr.Type);
561   if (is64Bit) {
562     SHdrTab.emitWord64(SHdr.Flags);
563     SHdrTab.emitWord(SHdr.Addr);
564     SHdrTab.emitWord(SHdr.Offset);
565     SHdrTab.emitWord64(SHdr.Size);
566     SHdrTab.emitWord32(SHdr.Link);
567     SHdrTab.emitWord32(SHdr.Info);
568     SHdrTab.emitWord64(SHdr.Align);
569     SHdrTab.emitWord64(SHdr.EntSize);
570   } else {
571     SHdrTab.emitWord32(SHdr.Flags);
572     SHdrTab.emitWord(SHdr.Addr);
573     SHdrTab.emitWord(SHdr.Offset);
574     SHdrTab.emitWord32(SHdr.Size);
575     SHdrTab.emitWord32(SHdr.Link);
576     SHdrTab.emitWord32(SHdr.Info);
577     SHdrTab.emitWord32(SHdr.Align);
578     SHdrTab.emitWord32(SHdr.EntSize);
579   }
580 }
581
582 /// EmitStringTable - If the current symbol table is non-empty, emit the string
583 /// table for it
584 void ELFWriter::EmitStringTable() {
585   if (!SymbolList.size()) return;  // Empty symbol table.
586   ELFSection &StrTab = getStringTableSection();
587
588   // Set the zero'th symbol to a null byte, as required.
589   StrTab.emitByte(0);
590
591   // Walk on the symbol list and write symbol names into the
592   // string table.
593   unsigned Index = 1;
594   for (std::list<ELFSym>::iterator I = SymbolList.begin(),
595        E = SymbolList.end(); I != E; ++I) {
596
597     // Use the name mangler to uniquify the LLVM symbol.
598     std::string Name;
599     if (I->GV) Name.append(Mang->getValueName(I->GV));
600
601     if (Name.empty()) {
602       I->NameIdx = 0;
603     } else {
604       I->NameIdx = Index;
605       StrTab.emitString(Name);
606
607       // Keep track of the number of bytes emitted to this section.
608       Index += Name.size()+1;
609     }
610   }
611   assert(Index == StrTab.size());
612   StrTab.Size = Index;
613 }
614
615 /// EmitSymbolTable - Emit the symbol table itself.
616 void ELFWriter::EmitSymbolTable() {
617   if (!SymbolList.size()) return;  // Empty symbol table.
618
619   unsigned FirstNonLocalSymbol = 1;
620   // Now that we have emitted the string table and know the offset into the
621   // string table of each symbol, emit the symbol table itself.
622   ELFSection &SymTab = getSymbolTableSection();
623   SymTab.Align = TEW->getPrefELFAlignment();
624
625   // Section Index of .strtab.
626   SymTab.Link = getStringTableSection().SectionIdx;
627
628   // Size of each symtab entry.
629   SymTab.EntSize = TEW->getSymTabEntrySize();
630
631   // The first entry in the symtab is the null symbol
632   ELFSym NullSym = ELFSym(0);
633   EmitSymbol(SymTab, NullSym);
634
635   // Emit all the symbols to the symbol table. Skip the null
636   // symbol, cause it's emitted already
637   unsigned Index = 1;
638   for (std::list<ELFSym>::iterator I = SymbolList.begin(),
639        E = SymbolList.end(); I != E; ++I, ++Index) {
640     // Keep track of the first non-local symbol
641     if (I->getBind() == ELFSym::STB_LOCAL)
642       FirstNonLocalSymbol++;
643
644     // Emit symbol to the symbol table
645     EmitSymbol(SymTab, *I);
646
647     // Record the symbol table index for each global value
648     if (I->GV)
649       GblSymLookup[I->GV] = Index;
650
651     // Keep track on the symbol index into the symbol table
652     I->SymTabIdx = Index;
653   }
654
655   SymTab.Info = FirstNonLocalSymbol;
656   SymTab.Size = SymTab.size();
657 }
658
659 /// EmitSectionTableStringTable - This method adds and emits a section for the
660 /// ELF Section Table string table: the string table that holds all of the
661 /// section names.
662 void ELFWriter::EmitSectionTableStringTable() {
663   // First step: add the section for the string table to the list of sections:
664   ELFSection &SHStrTab = getSectionHeaderStringTableSection();
665
666   // Now that we know which section number is the .shstrtab section, update the
667   // e_shstrndx entry in the ELF header.
668   ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
669
670   // Set the NameIdx of each section in the string table and emit the bytes for
671   // the string table.
672   unsigned Index = 0;
673
674   for (std::list<ELFSection>::iterator I = SectionList.begin(),
675          E = SectionList.end(); I != E; ++I) {
676     // Set the index into the table.  Note if we have lots of entries with
677     // common suffixes, we could memoize them here if we cared.
678     I->NameIdx = Index;
679     SHStrTab.emitString(I->getName());
680
681     // Keep track of the number of bytes emitted to this section.
682     Index += I->getName().size()+1;
683   }
684
685   // Set the size of .shstrtab now that we know what it is.
686   assert(Index == SHStrTab.size());
687   SHStrTab.Size = Index;
688 }
689
690 /// OutputSectionsAndSectionTable - Now that we have constructed the file header
691 /// and all of the sections, emit these to the ostream destination and emit the
692 /// SectionTable.
693 void ELFWriter::OutputSectionsAndSectionTable() {
694   // Pass #1: Compute the file offset for each section.
695   size_t FileOff = ElfHdr.size();   // File header first.
696
697   // Adjust alignment of all section if needed.
698   for (std::list<ELFSection>::iterator I = SectionList.begin(),
699          E = SectionList.end(); I != E; ++I) {
700
701     // Section idx 0 has 0 offset
702     if (!I->SectionIdx)
703       continue;
704
705     if (!I->size()) {
706       I->Offset = FileOff;
707       continue;
708     }
709
710     // Update Section size
711     if (!I->Size)
712       I->Size = I->size();
713
714     // Align FileOff to whatever the alignment restrictions of the section are.
715     if (I->Align)
716       FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
717
718     I->Offset = FileOff;
719     FileOff += I->Size;
720   }
721
722   // Align Section Header.
723   unsigned TableAlign = TEW->getPrefELFAlignment();
724   FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
725
726   // Now that we know where all of the sections will be emitted, set the e_shnum
727   // entry in the ELF header.
728   ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
729
730   // Now that we know the offset in the file of the section table, update the
731   // e_shoff address in the ELF header.
732   ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
733
734   // Now that we know all of the data in the file header, emit it and all of the
735   // sections!
736   O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
737   FileOff = ElfHdr.size();
738
739   // Section Header Table blob
740   BinaryObject SHdrTable(isLittleEndian, is64Bit);
741
742   // Emit all of sections to the file and build the section header table.
743   while (!SectionList.empty()) {
744     ELFSection &S = *SectionList.begin();
745     DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
746          << ", Size: " << S.Size << ", Offset: " << S.Offset
747          << ", SectionData Size: " << S.size() << "\n";
748
749     // Align FileOff to whatever the alignment restrictions of the section are.
750     if (S.size()) {
751       if (S.Align)  {
752         for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
753              FileOff != NewFileOff; ++FileOff)
754           O << (char)0xAB;
755       }
756       O.write((char *)&S.getData()[0], S.Size);
757       FileOff += S.Size;
758     }
759
760     EmitSectionHeader(SHdrTable, S);
761     SectionList.pop_front();
762   }
763
764   // Align output for the section table.
765   for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
766        FileOff != NewFileOff; ++FileOff)
767     O << (char)0xAB;
768
769   // Emit the section table itself.
770   O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
771 }