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