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