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