blob: 8dd4aab3f0a32f246099cbc5365209ddb317f387 [file] [log] [blame]
Chris Lattner35f0a4f2005-06-27 06:29:00 +00001//===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner35f0a4f2005-06-27 06:29:00 +00007//
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
Chris Lattner80ed8fa2005-07-07 07:02:20 +000014// #2. '.text' section
15// #3. '.data' section
16// #4. '.bss' section (conceptual position in file)
Chris Lattner35f0a4f2005-06-27 06:29:00 +000017// ...
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]
Chris Lattner80ed8fa2005-07-07 07:02:20 +000023// #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 ]
Chris Lattner35f0a4f2005-06-27 06:29:00 +000026// ...
27// #N. ".shstrtab" entry - String table for the section names.
Chris Lattner35f0a4f2005-06-27 06:29:00 +000028//
Chris Lattner35f0a4f2005-06-27 06:29:00 +000029//===----------------------------------------------------------------------===//
30
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +000031#define DEBUG_TYPE "elfwriter"
32
Bill Wendling8f84f1f2007-02-08 01:35:27 +000033#include "ELFWriter.h"
Bruno Cardoso Lopes4cb31432009-06-03 17:47:27 +000034#include "ELFCodeEmitter.h"
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +000035#include "ELF.h"
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +000036#include "llvm/Constants.h"
Chris Lattner35f0a4f2005-06-27 06:29:00 +000037#include "llvm/Module.h"
Bill Wendling8f84f1f2007-02-08 01:35:27 +000038#include "llvm/PassManager.h"
Chris Lattner02b73ab2009-01-04 20:19:20 +000039#include "llvm/DerivedTypes.h"
Bill Wendling8f84f1f2007-02-08 01:35:27 +000040#include "llvm/CodeGen/FileWriters.h"
Chris Lattneraa507db2005-07-11 05:17:18 +000041#include "llvm/CodeGen/MachineCodeEmitter.h"
42#include "llvm/CodeGen/MachineConstantPool.h"
Bill Wendling8f84f1f2007-02-08 01:35:27 +000043#include "llvm/CodeGen/MachineFunctionPass.h"
Owen Anderson07000c62006-05-12 06:33:49 +000044#include "llvm/Target/TargetData.h"
Chris Lattner35f0a4f2005-06-27 06:29:00 +000045#include "llvm/Target/TargetMachine.h"
Chris Lattner5acd1202005-07-11 03:11:47 +000046#include "llvm/Support/Mangler.h"
Bill Wendlingbdc679d2006-11-29 00:39:47 +000047#include "llvm/Support/Streams.h"
Owen Andersoncb371882008-08-21 00:14:44 +000048#include "llvm/Support/raw_ostream.h"
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +000049#include "llvm/Support/Debug.h"
Bill Wendling8f84f1f2007-02-08 01:35:27 +000050#include <list>
Chris Lattner35f0a4f2005-06-27 06:29:00 +000051using namespace llvm;
52
Devang Patel19974732007-05-03 01:11:54 +000053char ELFWriter::ID = 0;
Bill Wendling8f84f1f2007-02-08 01:35:27 +000054/// AddELFWriter - Concrete function to add the ELF writer to the function pass
55/// manager.
Dan Gohmanbfae8312008-03-11 22:29:46 +000056MachineCodeEmitter *llvm::AddELFWriter(PassManagerBase &PM,
Owen Andersoncb371882008-08-21 00:14:44 +000057 raw_ostream &O,
Bill Wendling8f84f1f2007-02-08 01:35:27 +000058 TargetMachine &TM) {
59 ELFWriter *EW = new ELFWriter(O, TM);
Dan Gohmanbfae8312008-03-11 22:29:46 +000060 PM.add(EW);
Bill Wendling8f84f1f2007-02-08 01:35:27 +000061 return &EW->getMachineCodeEmitter();
62}
63
Chris Lattner0e180502005-07-11 06:34:30 +000064//===----------------------------------------------------------------------===//
Chris Lattner0e180502005-07-11 06:34:30 +000065// ELFWriter Implementation
66//===----------------------------------------------------------------------===//
Chris Lattneraa507db2005-07-11 05:17:18 +000067
Bruno Cardoso Lopes4cb31432009-06-03 17:47:27 +000068ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +000069 : MachineFunctionPass(&ID), O(o), TM(tm), ElfHdr() {
Owen Andersona69571c2006-05-03 01:29:57 +000070 is64Bit = TM.getTargetData()->getPointerSizeInBits() == 64;
71 isLittleEndian = TM.getTargetData()->isLittleEndian();
Chris Lattneraa507db2005-07-11 05:17:18 +000072
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +000073 ElfHdr = new ELFHeader(TM.getELFWriterInfo()->getEMachine(), 0,
74 is64Bit, isLittleEndian);
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +000075 TAI = TM.getTargetAsmInfo();
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +000076
Chris Lattneraa507db2005-07-11 05:17:18 +000077 // Create the machine code emitter object for this target.
Bill Wendlinge9116152007-01-17 09:06:13 +000078 MCE = new ELFCodeEmitter(*this);
Chris Lattner5f48ff72005-07-16 08:01:13 +000079 NumSections = 0;
Chris Lattneraa507db2005-07-11 05:17:18 +000080}
81
82ELFWriter::~ELFWriter() {
83 delete MCE;
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +000084 delete ElfHdr;
Chris Lattner35f0a4f2005-06-27 06:29:00 +000085}
86
87// doInitialization - Emit the file header and all of the global variables for
88// the module to the ELF file.
89bool ELFWriter::doInitialization(Module &M) {
Chris Lattner5acd1202005-07-11 03:11:47 +000090 Mang = new Mangler(M);
91
Chris Lattner5f48ff72005-07-16 08:01:13 +000092 // Local alias to shortenify coming code.
93 std::vector<unsigned char> &FH = FileHeader;
Bill Wendlingc904a5b2007-01-18 01:23:11 +000094 OutputBuffer FHOut(FH, is64Bit, isLittleEndian);
Jeff Cohen00b168892005-07-27 06:12:32 +000095
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +000096 // ELF Header
97 // ----------
98 // Fields e_shnum e_shstrndx are only known after all section have
99 // been emitted. They locations in the ouput buffer are recorded so
100 // to be patched up later.
101 //
102 // Note
103 // ----
104 // FHOut.outaddr method behaves differently for ELF32 and ELF64 writing
105 // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000106
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000107 FHOut.outbyte(0x7f); // e_ident[EI_MAG0]
108 FHOut.outbyte('E'); // e_ident[EI_MAG1]
109 FHOut.outbyte('L'); // e_ident[EI_MAG2]
110 FHOut.outbyte('F'); // e_ident[EI_MAG3]
111
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000112 FHOut.outbyte(ElfHdr->getElfClass()); // e_ident[EI_CLASS]
113 FHOut.outbyte(ElfHdr->getByteOrder()); // e_ident[EI_DATA]
114 FHOut.outbyte(EV_CURRENT); // e_ident[EI_VERSION]
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000115
116 FH.resize(16); // e_ident[EI_NIDENT-EI_PAD]
117
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000118 FHOut.outhalf(ET_REL); // e_type
119 FHOut.outhalf(ElfHdr->getMachine()); // e_machine = target
120 FHOut.outword(EV_CURRENT); // e_version
121 FHOut.outaddr(0); // e_entry = 0, no entry point in .o file
122 FHOut.outaddr(0); // e_phoff = 0, no program header for .o
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000123 ELFHdr_e_shoff_Offset = FH.size();
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000124 FHOut.outaddr(0); // e_shoff = sec hdr table off in bytes
125 FHOut.outword(ElfHdr->getFlags()); // e_flags = whatever the target wants
126 FHOut.outhalf(ElfHdr->getSize()); // e_ehsize = ELF header size
127 FHOut.outhalf(0); // e_phentsize = prog header entry size
128 FHOut.outhalf(0); // e_phnum = # prog header entries = 0
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000129
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000130 // e_shentsize = Section header entry size
131 FHOut.outhalf(ELFSection::getSectionHdrSize(is64Bit));
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000132
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000133 // e_shnum = # of section header ents
134 ELFHdr_e_shnum_Offset = FH.size();
135 FHOut.outhalf(0);
Jeff Cohen00b168892005-07-27 06:12:32 +0000136
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000137 // e_shstrndx = Section # of '.shstrtab'
138 ELFHdr_e_shstrndx_Offset = FH.size();
139 FHOut.outhalf(0);
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000140
Chris Lattner5f48ff72005-07-16 08:01:13 +0000141 // Add the null section, which is required to be first in the file.
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000142 getSection("", ELFSection::SHT_NULL, 0);
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000143
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000144 // Start up the symbol table. The first entry in the symtab is the null
145 // entry.
146 SymbolTable.push_back(ELFSym(0));
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000147
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000148 return false;
149}
150
Chris Lattner05895232005-07-16 17:41:06 +0000151void ELFWriter::EmitGlobal(GlobalVariable *GV) {
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000152
153 // XXX: put local symbols *before* global ones!
154 const Section *S = TAI->SectionForGlobal(GV);
155 DOUT << "Section " << S->getName() << " for global " << GV->getName() << "\n";
156
Chris Lattner4c47e3a2005-07-08 05:47:00 +0000157 // If this is an external global, emit it now. TODO: Note that it would be
158 // better to ignore the symbol here and only add it to the symbol table if
159 // referenced.
160 if (!GV->hasInitializer()) {
161 ELFSym ExternalSym(GV);
162 ExternalSym.SetBind(ELFSym::STB_GLOBAL);
163 ExternalSym.SetType(ELFSym::STT_NOTYPE);
164 ExternalSym.SectionIdx = ELFSection::SHN_UNDEF;
165 SymbolTable.push_back(ExternalSym);
166 return;
167 }
Jeff Cohen00b168892005-07-27 06:12:32 +0000168
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000169 const TargetData *TD = TM.getTargetData();
170 unsigned Align = TD->getPreferredAlignment(GV);
171 Constant *CV = GV->getInitializer();
172 unsigned Size = TD->getTypeAllocSize(CV->getType());
Chris Lattner4c47e3a2005-07-08 05:47:00 +0000173
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000174 // If this global has a zero initializer, go to .bss or common section.
175 if (CV->isNullValue() || isa<UndefValue>(CV)) {
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000176 // If this global is part of the common block, add it now. Variables are
177 // part of the common block if they are zero initialized and allowed to be
178 // merged with other symbols.
Dale Johannesenaafce772008-05-14 20:12:51 +0000179 if (GV->hasLinkOnceLinkage() || GV->hasWeakLinkage() ||
180 GV->hasCommonLinkage()) {
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000181 ELFSym CommonSym(GV);
182 // Value for common symbols is the alignment required.
Chris Lattner4c47e3a2005-07-08 05:47:00 +0000183 CommonSym.Value = Align;
184 CommonSym.Size = Size;
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000185 CommonSym.SetBind(ELFSym::STB_GLOBAL);
186 CommonSym.SetType(ELFSym::STT_OBJECT);
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000187 CommonSym.SectionIdx = ELFSection::SHN_COMMON;
188 SymbolTable.push_back(CommonSym);
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000189 getSection(S->getName(), ELFSection::SHT_NOBITS,
190 ELFSection::SHF_WRITE | ELFSection::SHF_ALLOC, 1);
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000191 return;
192 }
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000193
Chris Lattner4c47e3a2005-07-08 05:47:00 +0000194 // Otherwise, this symbol is part of the .bss section. Emit it now.
Chris Lattner4c47e3a2005-07-08 05:47:00 +0000195 // Handle alignment. Ensure section is aligned at least as much as required
196 // by this symbol.
Chris Lattner05895232005-07-16 17:41:06 +0000197 ELFSection &BSSSection = getBSSSection();
Chris Lattner4c47e3a2005-07-08 05:47:00 +0000198 BSSSection.Align = std::max(BSSSection.Align, Align);
199
200 // Within the section, emit enough virtual padding to get us to an alignment
201 // boundary.
202 if (Align)
203 BSSSection.Size = (BSSSection.Size + Align - 1) & ~(Align-1);
204
205 ELFSym BSSSym(GV);
206 BSSSym.Value = BSSSection.Size;
207 BSSSym.Size = Size;
208 BSSSym.SetType(ELFSym::STT_OBJECT);
209
210 switch (GV->getLinkage()) {
Dale Johannesenaafce772008-05-14 20:12:51 +0000211 default: // weak/linkonce/common handled above
Chris Lattner4c47e3a2005-07-08 05:47:00 +0000212 assert(0 && "Unexpected linkage type!");
213 case GlobalValue::AppendingLinkage: // FIXME: This should be improved!
214 case GlobalValue::ExternalLinkage:
215 BSSSym.SetBind(ELFSym::STB_GLOBAL);
216 break;
217 case GlobalValue::InternalLinkage:
218 BSSSym.SetBind(ELFSym::STB_LOCAL);
219 break;
220 }
221
222 // Set the idx of the .bss section
Chris Lattner5f48ff72005-07-16 08:01:13 +0000223 BSSSym.SectionIdx = BSSSection.SectionIdx;
Rafael Espindolabb46f522009-01-15 20:18:42 +0000224 if (!GV->hasPrivateLinkage())
225 SymbolTable.push_back(BSSSym);
Chris Lattner4c47e3a2005-07-08 05:47:00 +0000226
227 // Reserve space in the .bss section for this symbol.
228 BSSSection.Size += Size;
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000229 return;
230 }
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000231
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000232 /// Emit the Global symbol to the right ELF section
233 ELFSym GblSym(GV);
234 GblSym.Size = Size;
235 GblSym.SetType(ELFSym::STT_OBJECT);
236 GblSym.SetBind(ELFSym::STB_GLOBAL);
237 unsigned Flags = S->getFlags();
238 unsigned SectType = ELFSection::SHT_PROGBITS;
239 unsigned SHdrFlags = ELFSection::SHF_ALLOC;
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000240
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000241 if (Flags & SectionFlags::Code)
242 SHdrFlags |= ELFSection::SHF_EXECINSTR;
243 if (Flags & SectionFlags::Writeable)
244 SHdrFlags |= ELFSection::SHF_WRITE;
245 if (Flags & SectionFlags::Mergeable)
246 SHdrFlags |= ELFSection::SHF_MERGE;
247 if (Flags & SectionFlags::TLS)
248 SHdrFlags |= ELFSection::SHF_TLS;
249 if (Flags & SectionFlags::Strings)
250 SHdrFlags |= ELFSection::SHF_STRINGS;
251
252 // Remove tab from section name prefix
253 std::string SectionName(S->getName());
254 size_t Pos = SectionName.find("\t");
255 if (Pos != std::string::npos)
256 SectionName.erase(Pos, 1);
257
258 // The section alignment should be bound to the element with
259 // the largest alignment
260 ELFSection &ElfS = getSection(SectionName, SectType, SHdrFlags);
261 GblSym.SectionIdx = ElfS.SectionIdx;
262 if (Align > ElfS.Align)
263 ElfS.Align = Align;
264
265 DataBuffer &GblCstBuf = ElfS.SectionData;
266 OutputBuffer GblCstTab(GblCstBuf, is64Bit, isLittleEndian);
267
268 // S.Value should contain the symbol index inside the section,
269 // and all symbols should start on their required alignment boundary
270 GblSym.Value = (GblCstBuf.size() + (Align-1)) & (-Align);
271 GblCstBuf.insert(GblCstBuf.end(), GblSym.Value-GblCstBuf.size(), 0);
272
273 // Emit the constant symbol to its section
274 EmitGlobalConstant(CV, GblCstTab);
275 SymbolTable.push_back(GblSym);
276}
277
278void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
279 OutputBuffer &GblCstTab) {
280
281 // Print the fields in successive locations. Pad to align if needed!
282 const TargetData *TD = TM.getTargetData();
283 unsigned Size = TD->getTypeAllocSize(CVS->getType());
284 const StructLayout *cvsLayout = TD->getStructLayout(CVS->getType());
285 uint64_t sizeSoFar = 0;
286 for (unsigned i = 0, e = CVS->getNumOperands(); i != e; ++i) {
287 const Constant* field = CVS->getOperand(i);
288
289 // Check if padding is needed and insert one or more 0s.
290 uint64_t fieldSize = TD->getTypeAllocSize(field->getType());
291 uint64_t padSize = ((i == e-1 ? Size : cvsLayout->getElementOffset(i+1))
292 - cvsLayout->getElementOffset(i)) - fieldSize;
293 sizeSoFar += fieldSize + padSize;
294
295 // Now print the actual field value.
296 EmitGlobalConstant(field, GblCstTab);
297
298 // Insert padding - this may include padding to increase the size of the
299 // current field up to the ABI size (if the struct is not packed) as well
300 // as padding to ensure that the next field starts at the right offset.
301 for (unsigned p=0; p < padSize; p++)
302 GblCstTab.outbyte(0);
303 }
304 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
305 "Layout of constant struct may be incorrect!");
306}
307
308void ELFWriter::EmitGlobalConstant(const Constant *CV, OutputBuffer &GblCstTab) {
309 const TargetData *TD = TM.getTargetData();
310 unsigned Size = TD->getTypeAllocSize(CV->getType());
311
312 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
313 if (CVA->isString()) {
314 std::string GblStr = CVA->getAsString();
315 GblCstTab.outstring(GblStr, GblStr.length());
316 } else { // Not a string. Print the values in successive locations
317 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
318 EmitGlobalConstant(CVA->getOperand(i), GblCstTab);
319 }
320 return;
321 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
322 EmitGlobalConstantStruct(CVS, GblCstTab);
323 return;
324 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
325 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
326 if (CFP->getType() == Type::DoubleTy)
327 GblCstTab.outxword(Val);
328 else if (CFP->getType() == Type::FloatTy)
329 GblCstTab.outword(Val);
330 else if (CFP->getType() == Type::X86_FP80Ty) {
331 assert(0 && "X86_FP80Ty global emission not implemented");
332 } else if (CFP->getType() == Type::PPC_FP128Ty)
333 assert(0 && "PPC_FP128Ty global emission not implemented");
334 return;
335 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
336 if (Size == 4)
337 GblCstTab.outword(CI->getZExtValue());
338 else if (Size == 8)
339 GblCstTab.outxword(CI->getZExtValue());
340 else
341 assert(0 && "LargeInt global emission not implemented");
342 return;
343 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CV)) {
344 const VectorType *PTy = CP->getType();
345 for (unsigned I = 0, E = PTy->getNumElements(); I < E; ++I)
346 EmitGlobalConstant(CP->getOperand(I), GblCstTab);
347 return;
348 }
349 assert(0 && "unknown global constant");
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000350}
351
352
353bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
Chris Lattneraa507db2005-07-11 05:17:18 +0000354 // Nothing to do here, this is all done through the MCE object above.
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000355 return false;
356}
357
358/// doFinalization - Now that the module has been completely processed, emit
359/// the ELF file to 'O'.
360bool ELFWriter::doFinalization(Module &M) {
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000361 /// FIXME: This should be removed when moving to BinaryObjects. Since the
362 /// current ELFCodeEmiter uses CurrBuff, ... it doesn't update S.SectionData
363 /// vector size for .text sections, so this is a quick dirty fix
364 ELFSection &TS = getTextSection();
365 if (TS.Size)
366 for (unsigned e=0; e<TS.Size; ++e)
367 TS.SectionData.push_back(TS.SectionData[e]);
368
369 // Get .data and .bss section, they should always be present in the binary
370 getDataSection();
371 getBSSSection();
372
373 // build data, bss and "common" sections.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000374 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
375 I != E; ++I)
Chris Lattner05895232005-07-16 17:41:06 +0000376 EmitGlobal(I);
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000377
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000378 // Emit non-executable stack note
379 if (TAI->getNonexecutableStackDirective())
380 getSection(".note.GNU-stack", ELFSection::SHT_PROGBITS, 0, 1);
381
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000382 // Emit the symbol table now, if non-empty.
383 EmitSymbolTable();
384
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000385 // Emit the relocation sections.
386 EmitRelocations();
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000387
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000388 // Emit the string table for the sections in the ELF file.
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000389 EmitSectionTableStringTable();
390
Chris Lattner5f48ff72005-07-16 08:01:13 +0000391 // Emit the sections to the .o file, and emit the section table for the file.
392 OutputSectionsAndSectionTable();
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000393
Chris Lattner5f48ff72005-07-16 08:01:13 +0000394 // We are done with the abstract symbols.
395 SectionList.clear();
396 NumSections = 0;
Chris Lattner5acd1202005-07-11 03:11:47 +0000397
398 // Release the name mangler object.
399 delete Mang; Mang = 0;
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000400 return false;
401}
402
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000403/// EmitRelocations - Emit relocations
404void ELFWriter::EmitRelocations() {
405}
406
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000407/// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymTabOut'
408void ELFWriter::EmitSymbol(OutputBuffer &SymTabOut, ELFSym &Sym) {
409 if (is64Bit) {
410 SymTabOut.outword(Sym.NameIdx);
411 SymTabOut.outbyte(Sym.Info);
412 SymTabOut.outbyte(Sym.Other);
413 SymTabOut.outhalf(Sym.SectionIdx);
414 SymTabOut.outaddr64(Sym.Value);
415 SymTabOut.outxword(Sym.Size);
416 } else {
417 SymTabOut.outword(Sym.NameIdx);
418 SymTabOut.outaddr32(Sym.Value);
419 SymTabOut.outword(Sym.Size);
420 SymTabOut.outbyte(Sym.Info);
421 SymTabOut.outbyte(Sym.Other);
422 SymTabOut.outhalf(Sym.SectionIdx);
423 }
424}
425
426/// EmitSectionHeader - Write section 'Section' header in 'TableOut'
427/// Section Header Table
428void ELFWriter::EmitSectionHeader(OutputBuffer &TableOut, const ELFSection &S) {
429 TableOut.outword(S.NameIdx);
430 TableOut.outword(S.Type);
431 if (is64Bit) {
432 TableOut.outxword(S.Flags);
433 TableOut.outaddr(S.Addr);
434 TableOut.outaddr(S.Offset);
435 TableOut.outxword(S.Size);
436 TableOut.outword(S.Link);
437 TableOut.outword(S.Info);
438 TableOut.outxword(S.Align);
439 TableOut.outxword(S.EntSize);
440 } else {
441 TableOut.outword(S.Flags);
442 TableOut.outaddr(S.Addr);
443 TableOut.outaddr(S.Offset);
444 TableOut.outword(S.Size);
445 TableOut.outword(S.Link);
446 TableOut.outword(S.Info);
447 TableOut.outword(S.Align);
448 TableOut.outword(S.EntSize);
449 }
450}
451
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000452/// EmitSymbolTable - If the current symbol table is non-empty, emit the string
453/// table for it and then the symbol table itself.
454void ELFWriter::EmitSymbolTable() {
455 if (SymbolTable.size() == 1) return; // Only the null entry.
456
457 // FIXME: compact all local symbols to the start of the symtab.
458 unsigned FirstNonLocalSymbol = 1;
459
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000460 ELFSection &StrTab = getStringTableSection();
Chris Lattner5f48ff72005-07-16 08:01:13 +0000461 DataBuffer &StrTabBuf = StrTab.SectionData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000462 OutputBuffer StrTabOut(StrTabBuf, is64Bit, isLittleEndian);
Chris Lattner5f48ff72005-07-16 08:01:13 +0000463
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000464 // Set the zero'th symbol to a null byte, as required.
Bill Wendling203d3e42007-01-17 22:22:31 +0000465 StrTabOut.outbyte(0);
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000466
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000467 unsigned Index = 1;
468 for (unsigned i = 1, e = SymbolTable.size(); i != e; ++i) {
Chris Lattner5acd1202005-07-11 03:11:47 +0000469 // Use the name mangler to uniquify the LLVM symbol.
470 std::string Name = Mang->getValueName(SymbolTable[i].GV);
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000471
472 if (Name.empty()) {
473 SymbolTable[i].NameIdx = 0;
474 } else {
475 SymbolTable[i].NameIdx = Index;
476
477 // Add the name to the output buffer, including the null terminator.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000478 StrTabBuf.insert(StrTabBuf.end(), Name.begin(), Name.end());
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000479
480 // Add a null terminator.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000481 StrTabBuf.push_back(0);
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000482
483 // Keep track of the number of bytes emitted to this section.
484 Index += Name.size()+1;
485 }
486 }
Chris Lattner5f48ff72005-07-16 08:01:13 +0000487 assert(Index == StrTabBuf.size());
488 StrTab.Size = Index;
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000489
490 // Now that we have emitted the string table and know the offset into the
491 // string table of each symbol, emit the symbol table itself.
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000492 ELFSection &SymTab = getSymbolTableSection();
Chris Lattner46c53052005-07-12 06:57:52 +0000493 SymTab.Align = is64Bit ? 8 : 4;
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000494 SymTab.Link = StrTab.SectionIdx; // Section Index of .strtab.
495 SymTab.Info = FirstNonLocalSymbol; // First non-STB_LOCAL symbol.
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000496
497 // Size of each symtab entry.
498 SymTab.EntSize = ELFSym::getEntrySize(is64Bit);
499
Chris Lattner5f48ff72005-07-16 08:01:13 +0000500 DataBuffer &SymTabBuf = SymTab.SectionData;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000501 OutputBuffer SymTabOut(SymTabBuf, is64Bit, isLittleEndian);
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000502
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000503 for (unsigned i = 0, e = SymbolTable.size(); i != e; ++i)
504 EmitSymbol(SymTabOut, SymbolTable[i]);
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000505
Chris Lattner5f48ff72005-07-16 08:01:13 +0000506 SymTab.Size = SymTabBuf.size();
Chris Lattner80ed8fa2005-07-07 07:02:20 +0000507}
508
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000509/// EmitSectionTableStringTable - This method adds and emits a section for the
510/// ELF Section Table string table: the string table that holds all of the
511/// section names.
512void ELFWriter::EmitSectionTableStringTable() {
513 // First step: add the section for the string table to the list of sections:
Chris Lattner00033952005-07-16 17:36:04 +0000514 ELFSection &SHStrTab = getSection(".shstrtab", ELFSection::SHT_STRTAB, 0);
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000515
516 // Now that we know which section number is the .shstrtab section, update the
517 // e_shstrndx entry in the ELF header.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000518 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000519 FHOut.fixhalf(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000520
521 // Set the NameIdx of each section in the string table and emit the bytes for
522 // the string table.
523 unsigned Index = 0;
Chris Lattner5f48ff72005-07-16 08:01:13 +0000524 DataBuffer &Buf = SHStrTab.SectionData;
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000525
Chris Lattner5f48ff72005-07-16 08:01:13 +0000526 for (std::list<ELFSection>::iterator I = SectionList.begin(),
527 E = SectionList.end(); I != E; ++I) {
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000528 // Set the index into the table. Note if we have lots of entries with
529 // common suffixes, we could memoize them here if we cared.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000530 I->NameIdx = Index;
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000531
532 // Add the name to the output buffer, including the null terminator.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000533 Buf.insert(Buf.end(), I->Name.begin(), I->Name.end());
534
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000535 // Add a null terminator.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000536 Buf.push_back(0);
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000537
538 // Keep track of the number of bytes emitted to this section.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000539 Index += I->Name.size()+1;
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000540 }
541
542 // Set the size of .shstrtab now that we know what it is.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000543 assert(Index == Buf.size());
544 SHStrTab.Size = Index;
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000545}
546
Chris Lattner5f48ff72005-07-16 08:01:13 +0000547/// OutputSectionsAndSectionTable - Now that we have constructed the file header
548/// and all of the sections, emit these to the ostream destination and emit the
549/// SectionTable.
550void ELFWriter::OutputSectionsAndSectionTable() {
551 // Pass #1: Compute the file offset for each section.
552 size_t FileOff = FileHeader.size(); // File header first.
553
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000554 // Adjust alignment of all section if needed.
Chris Lattner5f48ff72005-07-16 08:01:13 +0000555 for (std::list<ELFSection>::iterator I = SectionList.begin(),
556 E = SectionList.end(); I != E; ++I) {
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000557
558 // Section idx 0 has 0 offset
559 if (!I->SectionIdx)
560 continue;
561
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000562 if (!I->SectionData.size()) {
563 I->Offset = FileOff;
564 continue;
565 }
566
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000567 // Update Section size
568 if (!I->Size)
569 I->Size = I->SectionData.size();
570
Chris Lattner5f48ff72005-07-16 08:01:13 +0000571 // Align FileOff to whatever the alignment restrictions of the section are.
572 if (I->Align)
573 FileOff = (FileOff+I->Align-1) & ~(I->Align-1);
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000574
Chris Lattner5f48ff72005-07-16 08:01:13 +0000575 I->Offset = FileOff;
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000576 FileOff += I->Size;
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000577 }
578
Chris Lattner5f48ff72005-07-16 08:01:13 +0000579 // Align Section Header.
580 unsigned TableAlign = is64Bit ? 8 : 4;
581 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
582
583 // Now that we know where all of the sections will be emitted, set the e_shnum
584 // entry in the ELF header.
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000585 OutputBuffer FHOut(FileHeader, is64Bit, isLittleEndian);
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000586 FHOut.fixhalf(NumSections, ELFHdr_e_shnum_Offset);
Jeff Cohen00b168892005-07-27 06:12:32 +0000587
Chris Lattner5f48ff72005-07-16 08:01:13 +0000588 // Now that we know the offset in the file of the section table, update the
589 // e_shoff address in the ELF header.
Bruno Cardoso Lopesf5b0c5a2009-06-06 03:56:29 +0000590 FHOut.fixaddr(FileOff, ELFHdr_e_shoff_Offset);
Jeff Cohen00b168892005-07-27 06:12:32 +0000591
Chris Lattner5f48ff72005-07-16 08:01:13 +0000592 // Now that we know all of the data in the file header, emit it and all of the
593 // sections!
594 O.write((char*)&FileHeader[0], FileHeader.size());
595 FileOff = FileHeader.size();
596 DataBuffer().swap(FileHeader);
597
598 DataBuffer Table;
Bill Wendlingc904a5b2007-01-18 01:23:11 +0000599 OutputBuffer TableOut(Table, is64Bit, isLittleEndian);
Chris Lattner5f48ff72005-07-16 08:01:13 +0000600
601 // Emit all of the section data and build the section table itself.
602 while (!SectionList.empty()) {
603 const ELFSection &S = *SectionList.begin();
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000604 DOUT << "SectionIdx: " << S.SectionIdx << ", Name: " << S.Name
605 << ", Size: " << S.Size << ", Offset: " << S.Offset
606 << ", SectionData Size: " << S.SectionData.size() << "\n";
607
Chris Lattner5f48ff72005-07-16 08:01:13 +0000608
609 // Align FileOff to whatever the alignment restrictions of the section are.
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000610 if (S.Align) {
Chris Lattner5f48ff72005-07-16 08:01:13 +0000611 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
612 FileOff != NewFileOff; ++FileOff)
Owen Andersoncb371882008-08-21 00:14:44 +0000613 O << (char)0xAB;
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000614 }
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000615
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000616 if (S.SectionData.size()) {
617 O.write((char*)&S.SectionData[0], S.Size);
618 FileOff += S.Size;
619 }
Bruno Cardoso Lopesa029a272009-06-07 21:22:38 +0000620
Bruno Cardoso Lopesc997d452009-06-11 19:16:03 +0000621 EmitSectionHeader(TableOut, S);
Chris Lattner5f48ff72005-07-16 08:01:13 +0000622 SectionList.pop_front();
623 }
624
625 // Align output for the section table.
626 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
627 FileOff != NewFileOff; ++FileOff)
Owen Andersoncb371882008-08-21 00:14:44 +0000628 O << (char)0xAB;
Jeff Cohen00b168892005-07-27 06:12:32 +0000629
Chris Lattner5f48ff72005-07-16 08:01:13 +0000630 // Emit the section table itself.
631 O.write((char*)&Table[0], Table.size());
Chris Lattner35f0a4f2005-06-27 06:29:00 +0000632}