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