blob: af530a2caaae71e08a861d7c5e78a1b6075a986c [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- ELFWriter.cpp - Target-independent ELF Writer code ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +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
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//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029//===----------------------------------------------------------------------===//
30
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +000031#define DEBUG_TYPE "elfwriter"
Bruno Cardoso Lopes9dcbc862009-07-02 18:29:24 +000032#include "ELF.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "ELFWriter.h"
Bruno Cardoso Lopes14582c82009-06-03 17:47:27 +000034#include "ELFCodeEmitter.h"
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +000035#include "llvm/Constants.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000036#include "llvm/Module.h"
37#include "llvm/PassManager.h"
Chris Lattnerb1528b22009-01-04 20:19:20 +000038#include "llvm/DerivedTypes.h"
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +000039#include "llvm/CodeGen/BinaryObject.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/CodeGen/FileWriters.h"
41#include "llvm/CodeGen/MachineCodeEmitter.h"
Bruno Cardoso Lopesaabb9a52009-07-06 05:09:34 +000042#include "llvm/CodeGen/ObjectCodeEmitter.h"
43#include "llvm/CodeGen/MachineCodeEmitter.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/CodeGen/MachineConstantPool.h"
Chris Lattner01316272009-07-31 17:42:42 +000045#include "llvm/MC/MCContext.h"
Bruno Cardoso Lopes26d7ecd2009-08-13 05:07:35 +000046#include "llvm/MC/MCSectionELF.h"
Chris Lattner621c44d2009-08-22 20:48:53 +000047#include "llvm/MC/MCAsmInfo.h"
Chris Lattner31a54742010-01-16 21:57:06 +000048#include "llvm/Target/Mangler.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Target/TargetData.h"
Bruno Cardoso Lopes9dcbc862009-07-02 18:29:24 +000050#include "llvm/Target/TargetELFWriterInfo.h"
Chris Lattnerc4c40a92009-07-28 03:13:23 +000051#include "llvm/Target/TargetLowering.h"
52#include "llvm/Target/TargetLoweringObjectFile.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053#include "llvm/Target/TargetMachine.h"
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +000054#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000055#include "llvm/Support/ErrorHandling.h"
Bill Wendlingf20b01e2009-08-22 20:07:03 +000056#include "llvm/Support/raw_ostream.h"
Chris Lattner47177f72010-01-16 02:16:09 +000057#include "llvm/ADT/SmallString.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000058using namespace llvm;
59
60char ELFWriter::ID = 0;
Bruno Cardoso Lopes2bcbd2e2009-07-06 09:26:48 +000061
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +000063// ELFWriter Implementation
64//===----------------------------------------------------------------------===//
65
Bruno Cardoso Lopes14582c82009-06-03 17:47:27 +000066ELFWriter::ELFWriter(raw_ostream &o, TargetMachine &tm)
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +000067 : MachineFunctionPass(&ID), O(o), TM(tm),
Chris Lattner01316272009-07-31 17:42:42 +000068 OutContext(*new MCContext()),
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +000069 TLOF(TM.getTargetLowering()->getObjFileLowering()),
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +000070 is64Bit(TM.getTargetData()->getPointerSizeInBits() == 64),
71 isLittleEndian(TM.getTargetData()->isLittleEndian()),
72 ElfHdr(isLittleEndian, is64Bit) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073
Chris Lattnera5ef4d32009-08-22 21:43:10 +000074 MAI = TM.getMCAsmInfo();
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +000075 TEW = TM.getELFWriterInfo();
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +000076
Bruno Cardoso Lopes2bcbd2e2009-07-06 09:26:48 +000077 // Create the object code emitter object for this target.
78 ElfCE = new ELFCodeEmitter(*this);
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +000079
80 // Inital number of sections
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081 NumSections = 0;
82}
83
84ELFWriter::~ELFWriter() {
Bruno Cardoso Lopes2bcbd2e2009-07-06 09:26:48 +000085 delete ElfCE;
Chris Lattner01316272009-07-31 17:42:42 +000086 delete &OutContext;
Bruno Cardoso Lopes0c971ca2009-09-01 19:25:52 +000087
88 while(!SymbolList.empty()) {
89 delete SymbolList.back();
90 SymbolList.pop_back();
91 }
92
93 while(!PrivateSyms.empty()) {
94 delete PrivateSyms.back();
95 PrivateSyms.pop_back();
96 }
97
98 while(!SectionList.empty()) {
99 delete SectionList.back();
100 SectionList.pop_back();
101 }
102
103 // Release the name mangler object.
104 delete Mang; Mang = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000105}
106
107// doInitialization - Emit the file header and all of the global variables for
108// the module to the ELF file.
109bool ELFWriter::doInitialization(Module &M) {
Chris Lattner01316272009-07-31 17:42:42 +0000110 // Initialize TargetLoweringObjectFile.
Chris Lattner01316272009-07-31 17:42:42 +0000111 const_cast<TargetLoweringObjectFile&>(TLOF).Initialize(OutContext, TM);
112
Chris Lattner63ab9bb2010-01-17 18:22:35 +0000113 Mang = new Mangler(*MAI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114
Bruno Cardoso Lopes04066de2009-06-06 03:56:29 +0000115 // ELF Header
116 // ----------
117 // Fields e_shnum e_shstrndx are only known after all section have
118 // been emitted. They locations in the ouput buffer are recorded so
119 // to be patched up later.
120 //
121 // Note
122 // ----
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000123 // emitWord method behaves differently for ELF32 and ELF64, writing
Bruno Cardoso Lopes04066de2009-06-06 03:56:29 +0000124 // 4 bytes in the former and 8 in the last for *_off and *_addr elf types
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000126 ElfHdr.emitByte(0x7f); // e_ident[EI_MAG0]
127 ElfHdr.emitByte('E'); // e_ident[EI_MAG1]
128 ElfHdr.emitByte('L'); // e_ident[EI_MAG2]
129 ElfHdr.emitByte('F'); // e_ident[EI_MAG3]
Bruno Cardoso Lopes04066de2009-06-06 03:56:29 +0000130
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000131 ElfHdr.emitByte(TEW->getEIClass()); // e_ident[EI_CLASS]
132 ElfHdr.emitByte(TEW->getEIData()); // e_ident[EI_DATA]
133 ElfHdr.emitByte(EV_CURRENT); // e_ident[EI_VERSION]
134 ElfHdr.emitAlignment(16); // e_ident[EI_NIDENT-EI_PAD]
Bruno Cardoso Lopes04066de2009-06-06 03:56:29 +0000135
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000136 ElfHdr.emitWord16(ET_REL); // e_type
137 ElfHdr.emitWord16(TEW->getEMachine()); // e_machine = target
138 ElfHdr.emitWord32(EV_CURRENT); // e_version
139 ElfHdr.emitWord(0); // e_entry, no entry point in .o file
140 ElfHdr.emitWord(0); // e_phoff, no program header for .o
141 ELFHdr_e_shoff_Offset = ElfHdr.size();
142 ElfHdr.emitWord(0); // e_shoff = sec hdr table off in bytes
143 ElfHdr.emitWord32(TEW->getEFlags()); // e_flags = whatever the target wants
144 ElfHdr.emitWord16(TEW->getHdrSize()); // e_ehsize = ELF header size
145 ElfHdr.emitWord16(0); // e_phentsize = prog header entry size
146 ElfHdr.emitWord16(0); // e_phnum = # prog header entries = 0
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000147
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +0000148 // e_shentsize = Section header entry size
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000149 ElfHdr.emitWord16(TEW->getSHdrSize());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150
Bruno Cardoso Lopes04066de2009-06-06 03:56:29 +0000151 // e_shnum = # of section header ents
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000152 ELFHdr_e_shnum_Offset = ElfHdr.size();
153 ElfHdr.emitWord16(0); // Placeholder
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154
Bruno Cardoso Lopes04066de2009-06-06 03:56:29 +0000155 // e_shstrndx = Section # of '.shstrtab'
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000156 ELFHdr_e_shstrndx_Offset = ElfHdr.size();
157 ElfHdr.emitWord16(0); // Placeholder
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158
159 // Add the null section, which is required to be first in the file.
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000160 getNullSection();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161
Bruno Cardoso Lopesf1096012009-07-28 19:25:33 +0000162 // The first entry in the symtab is the null symbol and the second
163 // is a local symbol containing the module/file name
164 SymbolList.push_back(new ELFSym());
165 SymbolList.push_back(ELFSym::getFileSym());
166
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 return false;
168}
169
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000170// AddPendingGlobalSymbol - Add a global to be processed and to
171// the global symbol lookup, use a zero index because the table
172// index will be determined later.
173void ELFWriter::AddPendingGlobalSymbol(const GlobalValue *GV,
174 bool AddToLookup /* = false */) {
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000175 PendingGlobals.insert(GV);
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000176 if (AddToLookup)
177 GblSymLookup[GV] = 0;
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000178}
179
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000180// AddPendingExternalSymbol - Add the external to be processed
181// and to the external symbol lookup, use a zero index because
182// the symbol table index will be determined later.
183void ELFWriter::AddPendingExternalSymbol(const char *External) {
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000184 PendingExternals.insert(External);
185 ExtSymLookup[External] = 0;
186}
187
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000188ELFSection &ELFWriter::getDataSection() {
189 const MCSectionELF *Data = (const MCSectionELF *)TLOF.getDataSection();
190 return getSection(Data->getSectionName(), Data->getType(),
191 Data->getFlags(), 4);
192}
193
194ELFSection &ELFWriter::getBSSSection() {
195 const MCSectionELF *BSS = (const MCSectionELF *)TLOF.getBSSSection();
196 return getSection(BSS->getSectionName(), BSS->getType(), BSS->getFlags(), 4);
197}
198
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000199// getCtorSection - Get the static constructor section
200ELFSection &ELFWriter::getCtorSection() {
Bruno Cardoso Lopes26d7ecd2009-08-13 05:07:35 +0000201 const MCSectionELF *Ctor = (const MCSectionELF *)TLOF.getStaticCtorSection();
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000202 return getSection(Ctor->getSectionName(), Ctor->getType(), Ctor->getFlags());
Bruno Cardoso Lopes2c1fe1a2009-07-18 23:24:01 +0000203}
204
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000205// getDtorSection - Get the static destructor section
206ELFSection &ELFWriter::getDtorSection() {
Bruno Cardoso Lopes26d7ecd2009-08-13 05:07:35 +0000207 const MCSectionELF *Dtor = (const MCSectionELF *)TLOF.getStaticDtorSection();
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000208 return getSection(Dtor->getSectionName(), Dtor->getType(), Dtor->getFlags());
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000209}
210
211// getTextSection - Get the text section for the specified function
212ELFSection &ELFWriter::getTextSection(Function *F) {
Bruno Cardoso Lopes26d7ecd2009-08-13 05:07:35 +0000213 const MCSectionELF *Text =
214 (const MCSectionELF *)TLOF.SectionForGlobal(F, Mang, TM);
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000215 return getSection(Text->getSectionName(), Text->getType(), Text->getFlags());
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000216}
217
218// getJumpTableSection - Get a read only section for constants when
219// emitting jump tables. TODO: add PIC support
220ELFSection &ELFWriter::getJumpTableSection() {
Bruno Cardoso Lopes26d7ecd2009-08-13 05:07:35 +0000221 const MCSectionELF *JT =
222 (const MCSectionELF *)TLOF.getSectionForConstant(SectionKind::getReadOnly());
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000223 return getSection(JT->getSectionName(), JT->getType(), JT->getFlags(),
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000224 TM.getTargetData()->getPointerABIAlignment());
225}
226
227// getConstantPoolSection - Get a constant pool section based on the machine
228// constant pool entry type and relocation info.
Bruno Cardoso Lopes2c1fe1a2009-07-18 23:24:01 +0000229ELFSection &ELFWriter::getConstantPoolSection(MachineConstantPoolEntry &CPE) {
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000230 SectionKind Kind;
231 switch (CPE.getRelocationInfo()) {
232 default: llvm_unreachable("Unknown section kind");
Chris Lattnera9453412009-08-01 23:57:16 +0000233 case 2: Kind = SectionKind::getReadOnlyWithRel(); break;
Chris Lattnered0c6762009-07-26 07:00:12 +0000234 case 1:
Chris Lattnera9453412009-08-01 23:57:16 +0000235 Kind = SectionKind::getReadOnlyWithRelLocal();
Chris Lattnered0c6762009-07-26 07:00:12 +0000236 break;
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000237 case 0:
238 switch (TM.getTargetData()->getTypeAllocSize(CPE.getType())) {
Chris Lattnera9453412009-08-01 23:57:16 +0000239 case 4: Kind = SectionKind::getMergeableConst4(); break;
240 case 8: Kind = SectionKind::getMergeableConst8(); break;
241 case 16: Kind = SectionKind::getMergeableConst16(); break;
242 default: Kind = SectionKind::getMergeableConst(); break;
Chris Lattnerfc60ba12009-07-26 06:26:55 +0000243 }
244 }
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000245
Bruno Cardoso Lopes26d7ecd2009-08-13 05:07:35 +0000246 const MCSectionELF *CPSect =
247 (const MCSectionELF *)TLOF.getSectionForConstant(Kind);
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000248 return getSection(CPSect->getSectionName(), CPSect->getType(),
249 CPSect->getFlags(), CPE.getAlignment());
Bruno Cardoso Lopes2c1fe1a2009-07-18 23:24:01 +0000250}
251
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000252// getRelocSection - Return the relocation section of section 'S'. 'RelA'
253// is true if the relocation section contains entries with addends.
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000254ELFSection &ELFWriter::getRelocSection(ELFSection &S) {
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000255 unsigned SectionType = TEW->hasRelocationAddend() ?
256 ELFSection::SHT_RELA : ELFSection::SHT_REL;
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000257
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000258 std::string SectionName(".rel");
259 if (TEW->hasRelocationAddend())
260 SectionName.append("a");
261 SectionName.append(S.getName());
262
263 return getSection(SectionName, SectionType, 0, TEW->getPrefELFAlignment());
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000264}
265
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000266// getGlobalELFVisibility - Returns the ELF specific visibility type
Bruno Cardoso Lopes9dcbc862009-07-02 18:29:24 +0000267unsigned ELFWriter::getGlobalELFVisibility(const GlobalValue *GV) {
268 switch (GV->getVisibility()) {
269 default:
Edwin Törökbd448e32009-07-14 16:55:14 +0000270 llvm_unreachable("unknown visibility type");
Bruno Cardoso Lopes9dcbc862009-07-02 18:29:24 +0000271 case GlobalValue::DefaultVisibility:
272 return ELFSym::STV_DEFAULT;
273 case GlobalValue::HiddenVisibility:
274 return ELFSym::STV_HIDDEN;
275 case GlobalValue::ProtectedVisibility:
276 return ELFSym::STV_PROTECTED;
277 }
Bruno Cardoso Lopes9dcbc862009-07-02 18:29:24 +0000278 return 0;
279}
280
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000281// getGlobalELFBinding - Returns the ELF specific binding type
282unsigned ELFWriter::getGlobalELFBinding(const GlobalValue *GV) {
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000283 if (GV->hasInternalLinkage())
284 return ELFSym::STB_LOCAL;
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000285
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000286 if (GV->isWeakForLinker() && !GV->hasCommonLinkage())
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000287 return ELFSym::STB_WEAK;
288
289 return ELFSym::STB_GLOBAL;
290}
291
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000292// getGlobalELFType - Returns the ELF specific type for a global
293unsigned ELFWriter::getGlobalELFType(const GlobalValue *GV) {
294 if (GV->isDeclaration())
295 return ELFSym::STT_NOTYPE;
296
297 if (isa<Function>(GV))
298 return ELFSym::STT_FUNC;
299
300 return ELFSym::STT_OBJECT;
301}
302
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000303// IsELFUndefSym - True if the global value must be marked as a symbol
304// which points to a SHN_UNDEF section. This means that the symbol has
305// no definition on the module.
306static bool IsELFUndefSym(const GlobalValue *GV) {
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000307 return GV->isDeclaration() || (isa<Function>(GV));
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000308}
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000309
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000310// AddToSymbolList - Update the symbol lookup and If the symbol is
311// private add it to PrivateSyms list, otherwise to SymbolList.
312void ELFWriter::AddToSymbolList(ELFSym *GblSym) {
313 assert(GblSym->isGlobalValue() && "Symbol must be a global value");
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000314
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000315 const GlobalValue *GV = GblSym->getGlobalValue();
316 if (GV->hasPrivateLinkage()) {
317 // For a private symbols, keep track of the index inside
318 // the private list since it will never go to the symbol
319 // table and won't be patched up later.
320 PrivateSyms.push_back(GblSym);
321 GblSymLookup[GV] = PrivateSyms.size()-1;
322 } else {
323 // Non private symbol are left with zero indices until
324 // they are patched up during the symbol table emition
325 // (where the indicies are created).
326 SymbolList.push_back(GblSym);
327 GblSymLookup[GV] = 0;
328 }
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000329}
330
331// EmitGlobal - Choose the right section for global and emit it
332void ELFWriter::EmitGlobal(const GlobalValue *GV) {
333
Bruno Cardoso Lopes88ac2e42009-07-21 06:51:32 +0000334 // Check if the referenced symbol is already emitted
335 if (GblSymLookup.find(GV) != GblSymLookup.end())
336 return;
337
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000338 // Handle ELF Bind, Visibility and Type for the current symbol
339 unsigned SymBind = getGlobalELFBinding(GV);
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000340 unsigned SymType = getGlobalELFType(GV);
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000341 bool IsUndefSym = IsELFUndefSym(GV);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000342
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000343 ELFSym *GblSym = IsUndefSym ? ELFSym::getUndefGV(GV, SymBind)
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000344 : ELFSym::getGV(GV, SymBind, SymType, getGlobalELFVisibility(GV));
345
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000346 if (!IsUndefSym) {
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000347 assert(isa<GlobalVariable>(GV) && "GV not a global variable!");
348 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000349
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000350 // Handle special llvm globals
351 if (EmitSpecialLLVMGlobal(GVar))
352 return;
Chris Lattnerc4c40a92009-07-28 03:13:23 +0000353
Bruno Cardoso Lopesf1096012009-07-28 19:25:33 +0000354 // Get the ELF section where this global belongs from TLOF
Bruno Cardoso Lopes26d7ecd2009-08-13 05:07:35 +0000355 const MCSectionELF *S =
356 (const MCSectionELF *)TLOF.SectionForGlobal(GV, Mang, TM);
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000357 ELFSection &ES =
358 getSection(S->getSectionName(), S->getType(), S->getFlags());
Bruno Cardoso Lopes26d7ecd2009-08-13 05:07:35 +0000359 SectionKind Kind = S->getKind();
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000360
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000361 // The symbol align should update the section alignment if needed
362 const TargetData *TD = TM.getTargetData();
363 unsigned Align = TD->getPreferredAlignment(GVar);
364 unsigned Size = TD->getTypeAllocSize(GVar->getInitializer()->getType());
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000365 GblSym->Size = Size;
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000366
Bruno Cardoso Lopes6c1789c2009-08-14 19:45:38 +0000367 if (S->HasCommonSymbols()) { // Symbol must go to a common section
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000368 GblSym->SectionIdx = ELFSection::SHN_COMMON;
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000369
370 // A new linkonce section is created for each global in the
371 // common section, the default alignment is 1 and the symbol
372 // value contains its alignment.
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000373 ES.Align = 1;
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000374 GblSym->Value = Align;
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000375
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000376 } else if (Kind.isBSS() || Kind.isThreadBSS()) { // Symbol goes to BSS.
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000377 GblSym->SectionIdx = ES.SectionIdx;
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000378
379 // Update the size with alignment and the next object can
380 // start in the right offset in the section
381 if (Align) ES.Size = (ES.Size + Align-1) & ~(Align-1);
382 ES.Align = std::max(ES.Align, Align);
383
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000384 // GblSym->Value should contain the virtual offset inside the section.
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000385 // Virtual because the BSS space is not allocated on ELF objects
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000386 GblSym->Value = ES.Size;
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000387 ES.Size += Size;
388
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000389 } else { // The symbol must go to some kind of data section
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000390 GblSym->SectionIdx = ES.SectionIdx;
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000391
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000392 // GblSym->Value should contain the symbol offset inside the section,
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000393 // and all symbols should start on their required alignment boundary
394 ES.Align = std::max(ES.Align, Align);
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000395 ES.emitAlignment(Align);
396 GblSym->Value = ES.size();
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000397
398 // Emit the global to the data section 'ES'
399 EmitGlobalConstant(GVar->getInitializer(), ES);
400 }
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000401 }
402
Bruno Cardoso Lopesdfa78d12009-08-13 21:25:27 +0000403 AddToSymbolList(GblSym);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000404}
405
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000406void ELFWriter::EmitGlobalConstantStruct(const ConstantStruct *CVS,
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000407 ELFSection &GblS) {
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000408
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.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000424 EmitGlobalConstant(field, GblS);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000425
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.
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000429 GblS.emitZeros(padSize);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000430 }
431 assert(sizeSoFar == cvsLayout->getSizeInBytes() &&
432 "Layout of constant struct may be incorrect!");
433}
434
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000435void ELFWriter::EmitGlobalConstant(const Constant *CV, ELFSection &GblS) {
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000436 const TargetData *TD = TM.getTargetData();
437 unsigned Size = TD->getTypeAllocSize(CV->getType());
438
439 if (const ConstantArray *CVA = dyn_cast<ConstantArray>(CV)) {
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000440 for (unsigned i = 0, e = CVA->getNumOperands(); i != e; ++i)
441 EmitGlobalConstant(CVA->getOperand(i), GblS);
442 return;
443 } else if (isa<ConstantAggregateZero>(CV)) {
444 GblS.emitZeros(Size);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000445 return;
446 } else if (const ConstantStruct *CVS = dyn_cast<ConstantStruct>(CV)) {
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000447 EmitGlobalConstantStruct(CVS, GblS);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000448 return;
449 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(CV)) {
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000450 APInt Val = CFP->getValueAPF().bitcastToAPInt();
Chris Lattner82cdc062009-10-05 05:54:46 +0000451 if (CFP->getType()->isDoubleTy())
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000452 GblS.emitWord64(Val.getZExtValue());
Chris Lattner82cdc062009-10-05 05:54:46 +0000453 else if (CFP->getType()->isFloatTy())
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000454 GblS.emitWord32(Val.getZExtValue());
Chris Lattner82cdc062009-10-05 05:54:46 +0000455 else if (CFP->getType()->isX86_FP80Ty()) {
456 unsigned PadSize = TD->getTypeAllocSize(CFP->getType())-
457 TD->getTypeStoreSize(CFP->getType());
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000458 GblS.emitWordFP80(Val.getRawData(), PadSize);
Chris Lattner82cdc062009-10-05 05:54:46 +0000459 } else if (CFP->getType()->isPPC_FP128Ty())
Edwin Törökbd448e32009-07-14 16:55:14 +0000460 llvm_unreachable("PPC_FP128Ty global emission not implemented");
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000461 return;
462 } else if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000463 if (Size == 1)
464 GblS.emitByte(CI->getZExtValue());
465 else if (Size == 2)
466 GblS.emitWord16(CI->getZExtValue());
467 else if (Size == 4)
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000468 GblS.emitWord32(CI->getZExtValue());
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000469 else
470 EmitGlobalConstantLargeInt(CI, GblS);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000471 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)
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000475 EmitGlobalConstant(CP->getOperand(I), GblS);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000476 return;
Bruno Cardoso Lopes88ac2e42009-07-21 06:51:32 +0000477 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
Bruno Cardoso Lopes63c4e062009-08-10 03:32:40 +0000478 // Resolve a constant expression which returns a (Constant, Offset)
479 // pair. If 'Res.first' is a GlobalValue, emit a relocation with
480 // the offset 'Res.second', otherwise emit a global constant like
481 // it is always done for not contant expression types.
482 CstExprResTy Res = ResolveConstantExpr(CE);
483 const Constant *Op = Res.first;
484
485 if (isa<GlobalValue>(Op))
486 EmitGlobalDataRelocation(cast<const GlobalValue>(Op),
487 TD->getTypeAllocSize(Op->getType()),
488 GblS, Res.second);
489 else
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000490 EmitGlobalConstant(Op, GblS);
Bruno Cardoso Lopes63c4e062009-08-10 03:32:40 +0000491
492 return;
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000493 } else if (CV->getType()->getTypeID() == Type::PointerTyID) {
494 // Fill the data entry with zeros or emit a relocation entry
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000495 if (isa<ConstantPointerNull>(CV))
496 GblS.emitZeros(Size);
497 else
498 EmitGlobalDataRelocation(cast<const GlobalValue>(CV),
499 Size, GblS);
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000500 return;
501 } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(CV)) {
502 // This is a constant address for a global variable or function and
503 // therefore must be referenced using a relocation entry.
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000504 EmitGlobalDataRelocation(GV, Size, GblS);
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000505 return;
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000506 }
Bruno Cardoso Lopes88ac2e42009-07-21 06:51:32 +0000507
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000508 std::string msg;
509 raw_string_ostream ErrorMsg(msg);
510 ErrorMsg << "Constant unimp for type: " << *CV->getType();
511 llvm_report_error(ErrorMsg.str());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512}
513
Bruno Cardoso Lopes63c4e062009-08-10 03:32:40 +0000514// ResolveConstantExpr - Resolve the constant expression until it stop
515// yielding other constant expressions.
516CstExprResTy ELFWriter::ResolveConstantExpr(const Constant *CV) {
517 const TargetData *TD = TM.getTargetData();
518
519 // There ins't constant expression inside others anymore
520 if (!isa<ConstantExpr>(CV))
521 return std::make_pair(CV, 0);
522
523 const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV);
524 switch (CE->getOpcode()) {
525 case Instruction::BitCast:
526 return ResolveConstantExpr(CE->getOperand(0));
527
528 case Instruction::GetElementPtr: {
529 const Constant *ptrVal = CE->getOperand(0);
530 SmallVector<Value*, 8> idxVec(CE->op_begin()+1, CE->op_end());
531 int64_t Offset = TD->getIndexedOffset(ptrVal->getType(), &idxVec[0],
532 idxVec.size());
533 return std::make_pair(ptrVal, Offset);
534 }
535 case Instruction::IntToPtr: {
536 Constant *Op = CE->getOperand(0);
Owen Anderson35b47072009-08-13 21:58:54 +0000537 Op = ConstantExpr::getIntegerCast(Op, TD->getIntPtrType(CV->getContext()),
538 false/*ZExt*/);
Bruno Cardoso Lopes63c4e062009-08-10 03:32:40 +0000539 return ResolveConstantExpr(Op);
540 }
541 case Instruction::PtrToInt: {
542 Constant *Op = CE->getOperand(0);
543 const Type *Ty = CE->getType();
544
545 // We can emit the pointer value into this slot if the slot is an
546 // integer slot greater or equal to the size of the pointer.
547 if (TD->getTypeAllocSize(Ty) == TD->getTypeAllocSize(Op->getType()))
548 return ResolveConstantExpr(Op);
549
550 llvm_unreachable("Integer size less then pointer size");
551 }
552 case Instruction::Add:
553 case Instruction::Sub: {
554 // Only handle cases where there's a constant expression with GlobalValue
555 // as first operand and ConstantInt as second, which are the cases we can
556 // solve direclty using a relocation entry. GlobalValue=Op0, CstInt=Op1
557 // 1) Instruction::Add => (global) + CstInt
558 // 2) Instruction::Sub => (global) + -CstInt
559 const Constant *Op0 = CE->getOperand(0);
560 const Constant *Op1 = CE->getOperand(1);
561 assert(isa<ConstantInt>(Op1) && "Op1 must be a ConstantInt");
562
563 CstExprResTy Res = ResolveConstantExpr(Op0);
564 assert(isa<GlobalValue>(Res.first) && "Op0 must be a GlobalValue");
565
566 const APInt &RHS = cast<ConstantInt>(Op1)->getValue();
567 switch (CE->getOpcode()) {
568 case Instruction::Add:
569 return std::make_pair(Res.first, RHS.getSExtValue());
570 case Instruction::Sub:
571 return std::make_pair(Res.first, (-RHS).getSExtValue());
572 }
573 }
574 }
575
576 std::string msg(CE->getOpcodeName());
577 raw_string_ostream ErrorMsg(msg);
578 ErrorMsg << ": Unsupported ConstantExpr type";
579 llvm_report_error(ErrorMsg.str());
580
581 return std::make_pair(CV, 0); // silence warning
582}
583
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000584void ELFWriter::EmitGlobalDataRelocation(const GlobalValue *GV, unsigned Size,
Bruno Cardoso Lopes63c4e062009-08-10 03:32:40 +0000585 ELFSection &GblS, int64_t Offset) {
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000586 // Create the relocation entry for the global value
587 MachineRelocation MR =
588 MachineRelocation::getGV(GblS.getCurrentPCOffset(),
589 TEW->getAbsoluteLabelMachineRelTy(),
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000590 const_cast<GlobalValue*>(GV),
591 Offset);
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000592
593 // Fill the data entry with zeros
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000594 GblS.emitZeros(Size);
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000595
596 // Add the relocation entry for the current data section
597 GblS.addRelocation(MR);
598}
599
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000600void ELFWriter::EmitGlobalConstantLargeInt(const ConstantInt *CI,
601 ELFSection &S) {
602 const TargetData *TD = TM.getTargetData();
603 unsigned BitWidth = CI->getBitWidth();
604 assert(isPowerOf2_32(BitWidth) &&
605 "Non-power-of-2-sized integers not handled!");
606
607 const uint64_t *RawData = CI->getValue().getRawData();
608 uint64_t Val = 0;
609 for (unsigned i = 0, e = BitWidth / 64; i != e; ++i) {
610 Val = (TD->isBigEndian()) ? RawData[e - i - 1] : RawData[i];
611 S.emitWord64(Val);
612 }
613}
614
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000615/// EmitSpecialLLVMGlobal - Check to see if the specified global is a
616/// special global used by LLVM. If so, emit it and return true, otherwise
617/// do nothing and return false.
618bool ELFWriter::EmitSpecialLLVMGlobal(const GlobalVariable *GV) {
619 if (GV->getName() == "llvm.used")
620 llvm_unreachable("not implemented yet");
621
622 // Ignore debug and non-emitted data. This handles llvm.compiler.used.
623 if (GV->getSection() == "llvm.metadata" ||
624 GV->hasAvailableExternallyLinkage())
625 return true;
626
627 if (!GV->hasAppendingLinkage()) return false;
628
629 assert(GV->hasInitializer() && "Not a special LLVM global!");
630
631 const TargetData *TD = TM.getTargetData();
632 unsigned Align = TD->getPointerPrefAlignment();
633 if (GV->getName() == "llvm.global_ctors") {
634 ELFSection &Ctor = getCtorSection();
635 Ctor.emitAlignment(Align);
636 EmitXXStructorList(GV->getInitializer(), Ctor);
637 return true;
638 }
639
640 if (GV->getName() == "llvm.global_dtors") {
641 ELFSection &Dtor = getDtorSection();
642 Dtor.emitAlignment(Align);
643 EmitXXStructorList(GV->getInitializer(), Dtor);
644 return true;
645 }
646
647 return false;
648}
649
650/// EmitXXStructorList - Emit the ctor or dtor list. This just emits out the
651/// function pointers, ignoring the init priority.
652void ELFWriter::EmitXXStructorList(Constant *List, ELFSection &Xtor) {
653 // Should be an array of '{ int, void ()* }' structs. The first value is the
654 // init priority, which we ignore.
655 if (!isa<ConstantArray>(List)) return;
656 ConstantArray *InitList = cast<ConstantArray>(List);
657 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
658 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(InitList->getOperand(i))){
659 if (CS->getNumOperands() != 2) return; // Not array of 2-element structs.
660
661 if (CS->getOperand(1)->isNullValue())
662 return; // Found a null terminator, exit printing.
663 // Emit the function pointer.
664 EmitGlobalConstant(CS->getOperand(1), Xtor);
665 }
666}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000667
668bool ELFWriter::runOnMachineFunction(MachineFunction &MF) {
Bruno Cardoso Lopes2bcbd2e2009-07-06 09:26:48 +0000669 // Nothing to do here, this is all done through the ElfCE object above.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 return false;
671}
672
673/// doFinalization - Now that the module has been completely processed, emit
674/// the ELF file to 'O'.
675bool ELFWriter::doFinalization(Module &M) {
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000676 // Emit .data section placeholder
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000677 getDataSection();
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000678
679 // Emit .bss section placeholder
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000680 getBSSSection();
681
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000682 // Build and emit data, bss and "common" sections.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
Bruno Cardoso Lopes88ac2e42009-07-21 06:51:32 +0000684 I != E; ++I)
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000685 EmitGlobal(I);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000686
687 // Emit all pending globals
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000688 for (PendingGblsIter I = PendingGlobals.begin(), E = PendingGlobals.end();
689 I != E; ++I)
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000690 EmitGlobal(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000692 // Emit all pending externals
693 for (PendingExtsIter I = PendingExternals.begin(), E = PendingExternals.end();
694 I != E; ++I)
695 SymbolList.push_back(ELFSym::getExtSym(*I));
696
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000697 // Emit a symbol for each section created until now, skip null section
698 for (unsigned i = 1, e = SectionList.size(); i < e; ++i) {
699 ELFSection &ES = *SectionList[i];
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000700 ELFSym *SectionSym = ELFSym::getSectionSym();
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000701 SectionSym->SectionIdx = ES.SectionIdx;
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000702 SymbolList.push_back(SectionSym);
703 ES.Sym = SymbolList.back();
Bruno Cardoso Lopes179f3a32009-06-25 07:36:24 +0000704 }
705
Bruno Cardoso Lopes5d7a1eb2009-06-22 19:29:56 +0000706 // Emit string table
Bruno Cardoso Lopes2be60ac2009-07-27 19:32:57 +0000707 EmitStringTable(M.getModuleIdentifier());
Bruno Cardoso Lopes5d7a1eb2009-06-22 19:29:56 +0000708
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709 // Emit the symbol table now, if non-empty.
710 EmitSymbolTable();
711
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +0000712 // Emit the relocation sections.
713 EmitRelocations();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000715 // Emit the sections string table.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 EmitSectionTableStringTable();
717
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000718 // Dump the sections and section table to the .o file.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000719 OutputSectionsAndSectionTable();
720
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 return false;
722}
723
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000724// RelocateField - Patch relocatable field with 'Offset' in 'BO'
725// using a 'Value' of known 'Size'
726void ELFWriter::RelocateField(BinaryObject &BO, uint32_t Offset,
727 int64_t Value, unsigned Size) {
728 if (Size == 32)
729 BO.fixWord32(Value, Offset);
730 else if (Size == 64)
731 BO.fixWord64(Value, Offset);
732 else
733 llvm_unreachable("don't know howto patch relocatable field");
734}
735
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +0000736/// EmitRelocations - Emit relocations
737void ELFWriter::EmitRelocations() {
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000738
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000739 // True if the target uses the relocation entry to hold the addend,
740 // otherwise the addend is written directly to the relocatable field.
741 bool HasRelA = TEW->hasRelocationAddend();
742
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000743 // Create Relocation sections for each section which needs it.
Bruno Cardoso Lopes65fe6942009-07-17 18:02:30 +0000744 for (unsigned i=0, e=SectionList.size(); i != e; ++i) {
745 ELFSection &S = *SectionList[i];
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000746
747 // This section does not have relocations
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000748 if (!S.hasRelocations()) continue;
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000749 ELFSection &RelSec = getRelocSection(S);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000750
751 // 'Link' - Section hdr idx of the associated symbol table
752 // 'Info' - Section hdr idx of the section to which the relocation applies
753 ELFSection &SymTab = getSymbolTableSection();
754 RelSec.Link = SymTab.SectionIdx;
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000755 RelSec.Info = S.SectionIdx;
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000756 RelSec.EntSize = TEW->getRelocationEntrySize();
757
758 // Get the relocations from Section
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000759 std::vector<MachineRelocation> Relos = S.getRelocations();
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000760 for (std::vector<MachineRelocation>::iterator MRI = Relos.begin(),
761 MRE = Relos.end(); MRI != MRE; ++MRI) {
762 MachineRelocation &MR = *MRI;
763
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000764 // Relocatable field offset from the section start
765 unsigned RelOffset = MR.getMachineCodeOffset();
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000766
767 // Symbol index in the symbol table
768 unsigned SymIdx = 0;
769
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000770 // Target specific relocation field type and size
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000771 unsigned RelType = TEW->getRelocationType(MR.getRelocationType());
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000772 unsigned RelTySize = TEW->getRelocationTySize(RelType);
Bruno Cardoso Lopes179f3a32009-06-25 07:36:24 +0000773 int64_t Addend = 0;
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000774
775 // There are several machine relocations types, and each one of
776 // them needs a different approach to retrieve the symbol table index.
777 if (MR.isGlobalValue()) {
778 const GlobalValue *G = MR.getGlobalValue();
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000779 int64_t GlobalOffset = MR.getConstantVal();
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000780 SymIdx = GblSymLookup[G];
Bruno Cardoso Lopes8c203922009-07-18 19:30:09 +0000781 if (G->hasPrivateLinkage()) {
782 // If the target uses a section offset in the relocation:
783 // SymIdx + Addend = section sym for global + section offset
784 unsigned SectionIdx = PrivateSyms[SymIdx]->SectionIdx;
Bruno Cardoso Lopesd5b21c12009-08-08 17:29:04 +0000785 Addend = PrivateSyms[SymIdx]->Value + GlobalOffset;
Bruno Cardoso Lopes8c203922009-07-18 19:30:09 +0000786 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
787 } else {
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000788 Addend = TEW->getDefaultAddendForRelTy(RelType, GlobalOffset);
Bruno Cardoso Lopes8c203922009-07-18 19:30:09 +0000789 }
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000790 } else if (MR.isExternalSymbol()) {
791 const char *ExtSym = MR.getExternalSymbol();
792 SymIdx = ExtSymLookup[ExtSym];
793 Addend = TEW->getDefaultAddendForRelTy(RelType);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000794 } else {
Bruno Cardoso Lopes2c1fe1a2009-07-18 23:24:01 +0000795 // Get the symbol index for the section symbol
Bruno Cardoso Lopes179f3a32009-06-25 07:36:24 +0000796 unsigned SectionIdx = MR.getConstantVal();
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000797 SymIdx = SectionList[SectionIdx]->getSymbolTableIndex();
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000798
799 // The symbol offset inside the section
800 int64_t SymOffset = (int64_t)MR.getResultPointer();
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000801
802 // For pc relative relocations where symbols are defined in the same
803 // section they are referenced, ignore the relocation entry and patch
804 // the relocatable field with the symbol offset directly.
805 if (S.SectionIdx == SectionIdx && TEW->isPCRelativeRel(RelType)) {
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000806 int64_t Value = TEW->computeRelocation(SymOffset, RelOffset, RelType);
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000807 RelocateField(S, RelOffset, Value, RelTySize);
808 continue;
809 }
Bruno Cardoso Lopes2c1fe1a2009-07-18 23:24:01 +0000810
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000811 Addend = TEW->getDefaultAddendForRelTy(RelType, SymOffset);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000812 }
813
Bruno Cardoso Lopes8c203922009-07-18 19:30:09 +0000814 // The target without addend on the relocation symbol must be
815 // patched in the relocation place itself to contain the addend
Bruno Cardoso Lopesb4be2152009-08-05 06:57:03 +0000816 // otherwise write zeros to make sure there is no garbage there
817 RelocateField(S, RelOffset, HasRelA ? 0 : Addend, RelTySize);
Bruno Cardoso Lopes8c203922009-07-18 19:30:09 +0000818
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000819 // Get the relocation entry and emit to the relocation section
Bruno Cardoso Lopesc4d2daf2009-07-20 08:52:02 +0000820 ELFRelocation Rel(RelOffset, SymIdx, RelType, HasRelA, Addend);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000821 EmitRelocation(RelSec, Rel, HasRelA);
822 }
823 }
824}
825
826/// EmitRelocation - Write relocation 'Rel' to the relocation section 'Rel'
827void ELFWriter::EmitRelocation(BinaryObject &RelSec, ELFRelocation &Rel,
828 bool HasRelA) {
829 RelSec.emitWord(Rel.getOffset());
830 RelSec.emitWord(Rel.getInfo(is64Bit));
831 if (HasRelA)
832 RelSec.emitWord(Rel.getAddend());
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +0000833}
834
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000835/// EmitSymbol - Write symbol 'Sym' to the symbol table 'SymbolTable'
836void ELFWriter::EmitSymbol(BinaryObject &SymbolTable, ELFSym &Sym) {
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000837 if (is64Bit) {
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000838 SymbolTable.emitWord32(Sym.NameIdx);
839 SymbolTable.emitByte(Sym.Info);
840 SymbolTable.emitByte(Sym.Other);
841 SymbolTable.emitWord16(Sym.SectionIdx);
842 SymbolTable.emitWord64(Sym.Value);
843 SymbolTable.emitWord64(Sym.Size);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000844 } else {
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000845 SymbolTable.emitWord32(Sym.NameIdx);
846 SymbolTable.emitWord32(Sym.Value);
847 SymbolTable.emitWord32(Sym.Size);
848 SymbolTable.emitByte(Sym.Info);
849 SymbolTable.emitByte(Sym.Other);
850 SymbolTable.emitWord16(Sym.SectionIdx);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000851 }
852}
853
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000854/// EmitSectionHeader - Write section 'Section' header in 'SHdrTab'
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000855/// Section Header Table
Bruno Cardoso Lopesaf939d82009-07-13 22:40:39 +0000856void ELFWriter::EmitSectionHeader(BinaryObject &SHdrTab,
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000857 const ELFSection &SHdr) {
858 SHdrTab.emitWord32(SHdr.NameIdx);
859 SHdrTab.emitWord32(SHdr.Type);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000860 if (is64Bit) {
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000861 SHdrTab.emitWord64(SHdr.Flags);
862 SHdrTab.emitWord(SHdr.Addr);
863 SHdrTab.emitWord(SHdr.Offset);
864 SHdrTab.emitWord64(SHdr.Size);
865 SHdrTab.emitWord32(SHdr.Link);
866 SHdrTab.emitWord32(SHdr.Info);
867 SHdrTab.emitWord64(SHdr.Align);
868 SHdrTab.emitWord64(SHdr.EntSize);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000869 } else {
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000870 SHdrTab.emitWord32(SHdr.Flags);
871 SHdrTab.emitWord(SHdr.Addr);
872 SHdrTab.emitWord(SHdr.Offset);
873 SHdrTab.emitWord32(SHdr.Size);
874 SHdrTab.emitWord32(SHdr.Link);
875 SHdrTab.emitWord32(SHdr.Info);
876 SHdrTab.emitWord32(SHdr.Align);
877 SHdrTab.emitWord32(SHdr.EntSize);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000878 }
879}
880
Bruno Cardoso Lopes5d7a1eb2009-06-22 19:29:56 +0000881/// EmitStringTable - If the current symbol table is non-empty, emit the string
882/// table for it
Bruno Cardoso Lopes2be60ac2009-07-27 19:32:57 +0000883void ELFWriter::EmitStringTable(const std::string &ModuleName) {
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000884 if (!SymbolList.size()) return; // Empty symbol table.
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000885 ELFSection &StrTab = getStringTableSection();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000886
887 // Set the zero'th symbol to a null byte, as required.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000888 StrTab.emitByte(0);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000889
Bruno Cardoso Lopes65fe6942009-07-17 18:02:30 +0000890 // Walk on the symbol list and write symbol names into the string table.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 unsigned Index = 1;
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +0000892 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
893 ELFSym &Sym = *(*I);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000894
Bruno Cardoso Lopes179f3a32009-06-25 07:36:24 +0000895 std::string Name;
Chris Lattner47177f72010-01-16 02:16:09 +0000896 if (Sym.isGlobalValue()) {
897 SmallString<40> NameStr;
898 Mang->getNameWithPrefix(NameStr, Sym.getGlobalValue(), false);
899 Name.append(NameStr.begin(), NameStr.end());
900 } else if (Sym.isExternalSym())
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000901 Name.append(Sym.getExternalSymbol());
Bruno Cardoso Lopes2be60ac2009-07-27 19:32:57 +0000902 else if (Sym.isFileType())
903 Name.append(ModuleName);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904
905 if (Name.empty()) {
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000906 Sym.NameIdx = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 } else {
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000908 Sym.NameIdx = Index;
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000909 StrTab.emitString(Name);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000910
911 // Keep track of the number of bytes emitted to this section.
912 Index += Name.size()+1;
913 }
914 }
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000915 assert(Index == StrTab.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000916 StrTab.Size = Index;
Bruno Cardoso Lopes5d7a1eb2009-06-22 19:29:56 +0000917}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000918
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000919// SortSymbols - On the symbol table local symbols must come before
920// all other symbols with non-local bindings. The return value is
921// the position of the first non local symbol.
922unsigned ELFWriter::SortSymbols() {
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +0000923 unsigned FirstNonLocalSymbol;
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000924 std::vector<ELFSym*> LocalSyms, OtherSyms;
925
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +0000926 for (ELFSymIter I=SymbolList.begin(), E=SymbolList.end(); I != E; ++I) {
927 if ((*I)->isLocalBind())
928 LocalSyms.push_back(*I);
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000929 else
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +0000930 OtherSyms.push_back(*I);
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000931 }
932 SymbolList.clear();
933 FirstNonLocalSymbol = LocalSyms.size();
934
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +0000935 for (unsigned i = 0; i < FirstNonLocalSymbol; ++i)
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000936 SymbolList.push_back(LocalSyms[i]);
937
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +0000938 for (ELFSymIter I=OtherSyms.begin(), E=OtherSyms.end(); I != E; ++I)
939 SymbolList.push_back(*I);
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000940
941 LocalSyms.clear();
942 OtherSyms.clear();
943
944 return FirstNonLocalSymbol;
945}
946
Bruno Cardoso Lopes5d7a1eb2009-06-22 19:29:56 +0000947/// EmitSymbolTable - Emit the symbol table itself.
948void ELFWriter::EmitSymbolTable() {
949 if (!SymbolList.size()) return; // Empty symbol table.
950
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000951 // Now that we have emitted the string table and know the offset into the
952 // string table of each symbol, emit the symbol table itself.
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000953 ELFSection &SymTab = getSymbolTableSection();
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000954 SymTab.Align = TEW->getPrefELFAlignment();
Bruno Cardoso Lopes5d7a1eb2009-06-22 19:29:56 +0000955
956 // Section Index of .strtab.
957 SymTab.Link = getStringTableSection().SectionIdx;
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000958
959 // Size of each symtab entry.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000960 SymTab.EntSize = TEW->getSymTabEntrySize();
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +0000961
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000962 // Reorder the symbol table with local symbols first!
963 unsigned FirstNonLocalSymbol = SortSymbols();
964
965 // Emit all the symbols to the symbol table.
966 for (unsigned i = 0, e = SymbolList.size(); i < e; ++i) {
967 ELFSym &Sym = *SymbolList[i];
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000968
969 // Emit symbol to the symbol table
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000970 EmitSymbol(SymTab, Sym);
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000971
Bruno Cardoso Lopes5436d9f2009-07-27 18:54:47 +0000972 // Record the symbol table index for each symbol
973 if (Sym.isGlobalValue())
974 GblSymLookup[Sym.getGlobalValue()] = i;
975 else if (Sym.isExternalSym())
976 ExtSymLookup[Sym.getExternalSymbol()] = i;
Bruno Cardoso Lopes179f3a32009-06-25 07:36:24 +0000977
978 // Keep track on the symbol index into the symbol table
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000979 Sym.SymTabIdx = i;
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000980 }
981
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +0000982 // One greater than the symbol table index of the last local symbol
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +0000983 SymTab.Info = FirstNonLocalSymbol;
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000984 SymTab.Size = SymTab.size();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985}
986
987/// EmitSectionTableStringTable - This method adds and emits a section for the
988/// ELF Section Table string table: the string table that holds all of the
989/// section names.
990void ELFWriter::EmitSectionTableStringTable() {
991 // First step: add the section for the string table to the list of sections:
Bruno Cardoso Lopesb53d5c02009-06-23 04:39:27 +0000992 ELFSection &SHStrTab = getSectionHeaderStringTableSection();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993
994 // Now that we know which section number is the .shstrtab section, update the
995 // e_shstrndx entry in the ELF header.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +0000996 ElfHdr.fixWord16(SHStrTab.SectionIdx, ELFHdr_e_shstrndx_Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997
998 // Set the NameIdx of each section in the string table and emit the bytes for
999 // the string table.
1000 unsigned Index = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +00001002 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
1003 ELFSection &S = *(*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001004 // Set the index into the table. Note if we have lots of entries with
1005 // common suffixes, we could memoize them here if we cared.
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +00001006 S.NameIdx = Index;
1007 SHStrTab.emitString(S.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001008
1009 // Keep track of the number of bytes emitted to this section.
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +00001010 Index += S.getName().size()+1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011 }
1012
1013 // Set the size of .shstrtab now that we know what it is.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001014 assert(Index == SHStrTab.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015 SHStrTab.Size = Index;
1016}
1017
1018/// OutputSectionsAndSectionTable - Now that we have constructed the file header
1019/// and all of the sections, emit these to the ostream destination and emit the
1020/// SectionTable.
1021void ELFWriter::OutputSectionsAndSectionTable() {
1022 // Pass #1: Compute the file offset for each section.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001023 size_t FileOff = ElfHdr.size(); // File header first.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001024
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +00001025 // Adjust alignment of all section if needed, skip the null section.
1026 for (unsigned i=1, e=SectionList.size(); i < e; ++i) {
1027 ELFSection &ES = *SectionList[i];
1028 if (!ES.size()) {
1029 ES.Offset = FileOff;
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +00001030 continue;
1031 }
1032
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +00001033 // Update Section size
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +00001034 if (!ES.Size)
1035 ES.Size = ES.size();
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +00001036
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 // Align FileOff to whatever the alignment restrictions of the section are.
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +00001038 if (ES.Align)
1039 FileOff = (FileOff+ES.Align-1) & ~(ES.Align-1);
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +00001040
Bruno Cardoso Lopesa412a422009-07-15 20:49:10 +00001041 ES.Offset = FileOff;
1042 FileOff += ES.Size;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 }
1044
1045 // Align Section Header.
Bruno Cardoso Lopes6d4086b2009-06-22 19:16:16 +00001046 unsigned TableAlign = TEW->getPrefELFAlignment();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001047 FileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
1048
1049 // Now that we know where all of the sections will be emitted, set the e_shnum
1050 // entry in the ELF header.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001051 ElfHdr.fixWord16(NumSections, ELFHdr_e_shnum_Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052
1053 // Now that we know the offset in the file of the section table, update the
1054 // e_shoff address in the ELF header.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001055 ElfHdr.fixWord(FileOff, ELFHdr_e_shoff_Offset);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001056
1057 // Now that we know all of the data in the file header, emit it and all of the
1058 // sections!
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001059 O.write((char *)&ElfHdr.getData()[0], ElfHdr.size());
1060 FileOff = ElfHdr.size();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001061
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001062 // Section Header Table blob
1063 BinaryObject SHdrTable(isLittleEndian, is64Bit);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001064
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001065 // Emit all of sections to the file and build the section header table.
Bruno Cardoso Lopesf4f4dcd2009-07-16 06:26:41 +00001066 for (ELFSectionIter I=SectionList.begin(), E=SectionList.end(); I != E; ++I) {
1067 ELFSection &S = *(*I);
David Greenee328bfe2010-01-04 19:57:26 +00001068 DEBUG(dbgs() << "SectionIdx: " << S.SectionIdx << ", Name: " << S.getName()
Bill Wendlingf20b01e2009-08-22 20:07:03 +00001069 << ", Size: " << S.Size << ", Offset: " << S.Offset
1070 << ", SectionData Size: " << S.size() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071
1072 // Align FileOff to whatever the alignment restrictions of the section are.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001073 if (S.size()) {
Bruno Cardoso Lopesb53d5c02009-06-23 04:39:27 +00001074 if (S.Align) {
1075 for (size_t NewFileOff = (FileOff+S.Align-1) & ~(S.Align-1);
1076 FileOff != NewFileOff; ++FileOff)
1077 O << (char)0xAB;
1078 }
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001079 O.write((char *)&S.getData()[0], S.Size);
Bruno Cardoso Lopes8c25df12009-06-11 19:16:03 +00001080 FileOff += S.Size;
1081 }
Bruno Cardoso Lopes6b5788e2009-06-07 21:22:38 +00001082
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001083 EmitSectionHeader(SHdrTable, S);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001084 }
1085
1086 // Align output for the section table.
1087 for (size_t NewFileOff = (FileOff+TableAlign-1) & ~(TableAlign-1);
1088 FileOff != NewFileOff; ++FileOff)
Owen Anderson847b99b2008-08-21 00:14:44 +00001089 O << (char)0xAB;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001090
1091 // Emit the section table itself.
Bruno Cardoso Lopesfee73a32009-06-14 07:53:21 +00001092 O.write((char *)&SHdrTable.getData()[0], SHdrTable.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093}