blob: c28f88bdba9151a12f1cfb8421b5d7039c0cb58e [file] [log] [blame]
Matt Fleming3565a062010-08-16 18:57:57 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements ELF object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/MC/ELFObjectWriter.h"
Rafael Espindola8f413fa2010-10-05 15:11:03 +000015#include "llvm/ADT/SmallPtrSet.h"
Matt Fleming3565a062010-08-16 18:57:57 +000016#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/StringMap.h"
18#include "llvm/ADT/Twine.h"
19#include "llvm/MC/MCAssembler.h"
20#include "llvm/MC/MCAsmLayout.h"
21#include "llvm/MC/MCContext.h"
22#include "llvm/MC/MCELFSymbolFlags.h"
23#include "llvm/MC/MCExpr.h"
24#include "llvm/MC/MCObjectWriter.h"
25#include "llvm/MC/MCSectionELF.h"
26#include "llvm/MC/MCSymbol.h"
27#include "llvm/MC/MCValue.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/ErrorHandling.h"
30#include "llvm/Support/ELF.h"
31#include "llvm/Target/TargetAsmBackend.h"
32
33#include "../Target/X86/X86FixupKinds.h"
34
35#include <vector>
36using namespace llvm;
37
Rafael Espindolaad49cf52010-09-18 15:03:21 +000038static unsigned GetType(const MCSymbolData &SD) {
39 uint32_t Type = (SD.getFlags() & (0xf << ELF_STT_Shift)) >> ELF_STT_Shift;
40 assert(Type == ELF::STT_NOTYPE || Type == ELF::STT_OBJECT ||
41 Type == ELF::STT_FUNC || Type == ELF::STT_SECTION ||
42 Type == ELF::STT_FILE || Type == ELF::STT_COMMON ||
43 Type == ELF::STT_TLS);
44 return Type;
45}
46
Rafael Espindolae15eb4e2010-09-23 19:55:14 +000047static unsigned GetBinding(const MCSymbolData &SD) {
48 uint32_t Binding = (SD.getFlags() & (0xf << ELF_STB_Shift)) >> ELF_STB_Shift;
49 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
50 Binding == ELF::STB_WEAK);
51 return Binding;
52}
53
54static void SetBinding(MCSymbolData &SD, unsigned Binding) {
55 assert(Binding == ELF::STB_LOCAL || Binding == ELF::STB_GLOBAL ||
56 Binding == ELF::STB_WEAK);
57 uint32_t OtherFlags = SD.getFlags() & ~(0xf << ELF_STB_Shift);
58 SD.setFlags(OtherFlags | (Binding << ELF_STB_Shift));
59}
60
Rafael Espindola152c1062010-10-06 21:02:29 +000061static unsigned GetVisibility(MCSymbolData &SD) {
62 unsigned Visibility =
63 (SD.getFlags() & (0xf << ELF_STV_Shift)) >> ELF_STV_Shift;
64 assert(Visibility == ELF::STV_DEFAULT || Visibility == ELF::STV_INTERNAL ||
65 Visibility == ELF::STV_HIDDEN || Visibility == ELF::STV_PROTECTED);
66 return Visibility;
67}
68
Rafael Espindolacebdc012010-10-04 19:46:28 +000069static bool isFixupKindX86PCRel(unsigned Kind) {
70 switch (Kind) {
71 default:
72 return false;
73 case X86::reloc_pcrel_1byte:
74 case X86::reloc_pcrel_4byte:
75 case X86::reloc_riprel_4byte:
76 case X86::reloc_riprel_4byte_movq_load:
77 return true;
78 }
79}
80
Rafael Espindolaa0a2f872010-10-28 14:22:44 +000081static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
82 switch (Variant) {
Rafael Espindola5c77c162010-10-05 15:48:37 +000083 default:
84 return false;
Rafael Espindolaa0a2f872010-10-28 14:22:44 +000085 case MCSymbolRefExpr::VK_GOT:
86 case MCSymbolRefExpr::VK_PLT:
87 case MCSymbolRefExpr::VK_GOTPCREL:
88 case MCSymbolRefExpr::VK_TPOFF:
89 case MCSymbolRefExpr::VK_TLSGD:
90 case MCSymbolRefExpr::VK_GOTTPOFF:
91 case MCSymbolRefExpr::VK_INDNTPOFF:
92 case MCSymbolRefExpr::VK_NTPOFF:
93 case MCSymbolRefExpr::VK_GOTNTPOFF:
Rafael Espindolaa264f722010-10-28 14:37:09 +000094 case MCSymbolRefExpr::VK_TLSLDM:
Rafael Espindola0cf15d62010-10-28 14:48:59 +000095 case MCSymbolRefExpr::VK_DTPOFF:
Rafael Espindolab4d17212010-10-28 15:02:40 +000096 case MCSymbolRefExpr::VK_TLSLD:
Rafael Espindola5c77c162010-10-05 15:48:37 +000097 return true;
98 }
99}
100
Matt Fleming3565a062010-08-16 18:57:57 +0000101namespace {
102
103 class ELFObjectWriterImpl {
Chris Lattnerb188a372010-08-28 03:21:03 +0000104 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +0000105 return Kind == X86::reloc_riprel_4byte ||
106 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +0000107 }*/
Matt Fleming3565a062010-08-16 18:57:57 +0000108
109
110 /// ELFSymbolData - Helper struct for containing some precomputed information
111 /// on symbols.
112 struct ELFSymbolData {
113 MCSymbolData *SymbolData;
114 uint64_t StringIndex;
115 uint32_t SectionIndex;
116
117 // Support lexicographic sorting.
118 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolaad49cf52010-09-18 15:03:21 +0000119 if (GetType(*SymbolData) == ELF::STT_FILE)
120 return true;
121 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
122 return false;
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000123 return SymbolData->getSymbol().getName() <
124 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +0000125 }
126 };
127
128 /// @name Relocation Data
129 /// @{
130
131 struct ELFRelocationEntry {
132 // Make these big enough for both 32-bit and 64-bit
133 uint64_t r_offset;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000134 int Index;
135 unsigned Type;
136 const MCSymbol *Symbol;
Matt Fleming3565a062010-08-16 18:57:57 +0000137 uint64_t r_addend;
138
139 // Support lexicographic sorting.
140 bool operator<(const ELFRelocationEntry &RE) const {
141 return RE.r_offset < r_offset;
142 }
143 };
144
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
Rafael Espindola484291c2010-11-01 14:28:48 +0000146 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
Rafael Espindola88182132010-10-27 15:18:17 +0000147 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000148
Matt Fleming3565a062010-08-16 18:57:57 +0000149 llvm::DenseMap<const MCSectionData*,
150 std::vector<ELFRelocationEntry> > Relocations;
151 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
152
153 /// @}
154 /// @name Symbol Table Data
155 /// @{
156
157 SmallString<256> StringTable;
158 std::vector<ELFSymbolData> LocalSymbolData;
159 std::vector<ELFSymbolData> ExternalSymbolData;
160 std::vector<ELFSymbolData> UndefinedSymbolData;
161
162 /// @}
163
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000164 int NumRegularSections;
165
Rafael Espindola5c77c162010-10-05 15:48:37 +0000166 bool NeedsGOT;
167
Rafael Espindola7be2c332010-10-31 00:16:26 +0000168 bool NeedsSymtabShndx;
169
Matt Fleming3565a062010-08-16 18:57:57 +0000170 ELFObjectWriter *Writer;
171
172 raw_ostream &OS;
173
Matt Fleming3565a062010-08-16 18:57:57 +0000174 unsigned Is64Bit : 1;
175
176 bool HasRelocationAddend;
177
Roman Divacky5baf79e2010-09-09 17:57:50 +0000178 Triple::OSType OSType;
179
Wesley Peckeecb8582010-10-22 15:52:49 +0000180 uint16_t EMachine;
181
Matt Fleming3565a062010-08-16 18:57:57 +0000182 // This holds the symbol table index of the last local symbol.
183 unsigned LastLocalSymbolIndex;
184 // This holds the .strtab section index.
185 unsigned StringTableIndex;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000186 // This holds the .symtab section index.
187 unsigned SymbolTableIndex;
Matt Fleming3565a062010-08-16 18:57:57 +0000188
189 unsigned ShstrtabIndex;
190
191 public:
192 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
Wesley Peckeecb8582010-10-22 15:52:49 +0000193 uint16_t _EMachine, bool _HasRelAddend,
194 Triple::OSType _OSType)
Rafael Espindola7be2c332010-10-31 00:16:26 +0000195 : NeedsGOT(false), NeedsSymtabShndx(false), Writer(_Writer),
196 OS(Writer->getStream()),
Roman Divacky5baf79e2010-09-09 17:57:50 +0000197 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
Wesley Peckeecb8582010-10-22 15:52:49 +0000198 OSType(_OSType), EMachine(_EMachine) {
Matt Fleming3565a062010-08-16 18:57:57 +0000199 }
200
201 void Write8(uint8_t Value) { Writer->Write8(Value); }
202 void Write16(uint16_t Value) { Writer->Write16(Value); }
203 void Write32(uint32_t Value) { Writer->Write32(Value); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000204 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000205 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000206 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
207 // Writer->WriteBytes(Str, ZeroFillSize);
208 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000209
210 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000211 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000212 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000213 else
Matt Fleming3565a062010-08-16 18:57:57 +0000214 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000215 }
216
Matt Fleming3565a062010-08-16 18:57:57 +0000217 void StringLE16(char *buf, uint16_t Value) {
218 buf[0] = char(Value >> 0);
219 buf[1] = char(Value >> 8);
220 }
221
222 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000223 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000224 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000225 }
226
227 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000228 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000229 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000230 }
231
232 void StringBE16(char *buf ,uint16_t Value) {
233 buf[0] = char(Value >> 8);
234 buf[1] = char(Value >> 0);
235 }
236
237 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000238 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000239 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000240 }
241
242 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000243 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000244 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000245 }
246
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000247 void String8(MCDataFragment &F, uint8_t Value) {
248 char buf[1];
249 buf[0] = Value;
250 F.getContents() += StringRef(buf, 1);
251 }
252
253 void String16(MCDataFragment &F, uint16_t Value) {
254 char buf[2];
Matt Fleming3565a062010-08-16 18:57:57 +0000255 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000256 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000257 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000258 StringBE16(buf, Value);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000259 F.getContents() += StringRef(buf, 2);
Matt Fleming3565a062010-08-16 18:57:57 +0000260 }
261
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000262 void String32(MCDataFragment &F, uint32_t Value) {
263 char buf[4];
Matt Fleming3565a062010-08-16 18:57:57 +0000264 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000265 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000266 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000267 StringBE32(buf, Value);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000268 F.getContents() += StringRef(buf, 4);
Matt Fleming3565a062010-08-16 18:57:57 +0000269 }
270
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000271 void String64(MCDataFragment &F, uint64_t Value) {
272 char buf[8];
Matt Fleming3565a062010-08-16 18:57:57 +0000273 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000274 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000275 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000276 StringBE64(buf, Value);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000277 F.getContents() += StringRef(buf, 8);
Matt Fleming3565a062010-08-16 18:57:57 +0000278 }
279
280 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
281
Rafael Espindola7be2c332010-10-31 00:16:26 +0000282 void WriteSymbolEntry(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
283 uint64_t name, uint8_t info,
Matt Fleming3565a062010-08-16 18:57:57 +0000284 uint64_t value, uint64_t size,
Rafael Espindola7be2c332010-10-31 00:16:26 +0000285 uint8_t other, uint32_t shndx,
286 bool Reserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000287
Rafael Espindola7be2c332010-10-31 00:16:26 +0000288 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
289 ELFSymbolData &MSD,
Matt Fleming3565a062010-08-16 18:57:57 +0000290 const MCAsmLayout &Layout);
291
Rafael Espindola7be2c332010-10-31 00:16:26 +0000292 void WriteSymbolTable(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
293 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000294 const MCAsmLayout &Layout,
295 unsigned NumRegularSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000296
297 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
298 const MCFragment *Fragment, const MCFixup &Fixup,
299 MCValue Target, uint64_t &FixedValue);
300
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000301 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
302 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000303
304 /// ComputeSymbolTable - Compute the symbol table data
305 ///
306 /// \param StringTable [out] - The string table data.
307 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
308 /// string table.
309 void ComputeSymbolTable(MCAssembler &Asm);
310
311 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
312 const MCSectionData &SD);
313
314 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
315 for (MCAssembler::const_iterator it = Asm.begin(),
316 ie = Asm.end(); it != ie; ++it) {
317 WriteRelocation(Asm, Layout, *it);
318 }
319 }
320
321 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
322
Rafael Espindola88182132010-10-27 15:18:17 +0000323 void ExecutePostLayoutBinding(MCAssembler &Asm);
Matt Fleming3565a062010-08-16 18:57:57 +0000324
325 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
326 uint64_t Address, uint64_t Offset,
327 uint64_t Size, uint32_t Link, uint32_t Info,
328 uint64_t Alignment, uint64_t EntrySize);
329
330 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
331 const MCSectionData *SD);
332
Rafael Espindola70703872010-09-30 02:22:20 +0000333 bool IsFixupFullyResolved(const MCAssembler &Asm,
334 const MCValue Target,
335 bool IsPCRel,
336 const MCFragment *DF) const;
337
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000338 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000339 };
340
341}
342
343// Emit the ELF header.
344void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
345 unsigned NumberOfSections) {
346 // ELF Header
347 // ----------
348 //
349 // Note
350 // ----
351 // emitWord method behaves differently for ELF32 and ELF64, writing
352 // 4 bytes in the former and 8 in the latter.
353
354 Write8(0x7f); // e_ident[EI_MAG0]
355 Write8('E'); // e_ident[EI_MAG1]
356 Write8('L'); // e_ident[EI_MAG2]
357 Write8('F'); // e_ident[EI_MAG3]
358
359 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
360
361 // e_ident[EI_DATA]
362 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
363
364 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000365 // e_ident[EI_OSABI]
366 switch (OSType) {
367 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
368 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
369 default: Write8(ELF::ELFOSABI_NONE); break;
370 }
Matt Fleming3565a062010-08-16 18:57:57 +0000371 Write8(0); // e_ident[EI_ABIVERSION]
372
373 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
374
375 Write16(ELF::ET_REL); // e_type
376
Wesley Peckeecb8582010-10-22 15:52:49 +0000377 Write16(EMachine); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000378
379 Write32(ELF::EV_CURRENT); // e_version
380 WriteWord(0); // e_entry, no entry point in .o file
381 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000382 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
383 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000384
385 // FIXME: Make this configurable.
386 Write32(0); // e_flags = whatever the target wants
387
388 // e_ehsize = ELF header size
389 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
390
391 Write16(0); // e_phentsize = prog header entry size
392 Write16(0); // e_phnum = # prog header entries = 0
393
394 // e_shentsize = Section header entry size
395 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
396
397 // e_shnum = # of section header ents
Rafael Espindola7be2c332010-10-31 00:16:26 +0000398 if (NumberOfSections >= ELF::SHN_LORESERVE)
399 Write16(0);
400 else
401 Write16(NumberOfSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000402
403 // e_shstrndx = Section # of '.shstrtab'
Rafael Espindola7be2c332010-10-31 00:16:26 +0000404 if (NumberOfSections >= ELF::SHN_LORESERVE)
405 Write16(ELF::SHN_XINDEX);
406 else
407 Write16(ShstrtabIndex);
Matt Fleming3565a062010-08-16 18:57:57 +0000408}
409
Rafael Espindola7be2c332010-10-31 00:16:26 +0000410void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *SymtabF,
411 MCDataFragment *ShndxF,
412 uint64_t name,
Matt Fleming3565a062010-08-16 18:57:57 +0000413 uint8_t info, uint64_t value,
414 uint64_t size, uint8_t other,
Rafael Espindola7be2c332010-10-31 00:16:26 +0000415 uint32_t shndx,
416 bool Reserved) {
417 if (ShndxF) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000418 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000419 String32(*ShndxF, shndx);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000420 else
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000421 String32(*ShndxF, 0);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000422 }
423
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000424 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
425 uint16_t(ELF::SHN_XINDEX) : shndx;
426
Matt Fleming3565a062010-08-16 18:57:57 +0000427 if (Is64Bit) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000428 String32(*SymtabF, name); // st_name
429 String8(*SymtabF, info); // st_info
430 String8(*SymtabF, other); // st_other
431 String16(*SymtabF, Index); // st_shndx
432 String64(*SymtabF, value); // st_value
433 String64(*SymtabF, size); // st_size
Matt Fleming3565a062010-08-16 18:57:57 +0000434 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000435 String32(*SymtabF, name); // st_name
436 String32(*SymtabF, value); // st_value
437 String32(*SymtabF, size); // st_size
438 String8(*SymtabF, info); // st_info
439 String8(*SymtabF, other); // st_other
440 String16(*SymtabF, Index); // st_shndx
Matt Fleming3565a062010-08-16 18:57:57 +0000441 }
442}
443
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000444static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
445 if (Data.isCommon() && Data.isExternal())
446 return Data.getCommonAlignment();
447
448 const MCSymbol &Symbol = Data.getSymbol();
449 if (!Symbol.isInSection())
450 return 0;
451
Rafael Espindola1973d432010-10-28 19:39:57 +0000452 if (MCFragment *FF = Data.getFragment())
453 return Layout.getSymbolAddress(&Data) -
454 Layout.getSectionAddress(FF->getParent());
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000455
456 return 0;
457}
458
Rafael Espindolade89b012010-10-15 18:25:33 +0000459static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
460 const MCSymbol *S = &Symbol;
461 while (S->isVariable()) {
462 const MCExpr *Value = S->getVariableValue();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000463 if (Value->getKind() != MCExpr::SymbolRef)
464 return *S;
Rafael Espindolade89b012010-10-15 18:25:33 +0000465 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
466 S = &Ref->getSymbol();
467 }
468 return *S;
469}
470
Rafael Espindola88182132010-10-27 15:18:17 +0000471void ELFObjectWriterImpl::ExecutePostLayoutBinding(MCAssembler &Asm) {
472 // The presence of symbol versions causes undefined symbols and
473 // versions declared with @@@ to be renamed.
474
475 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
476 ie = Asm.symbol_end(); it != ie; ++it) {
477 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola88182132010-10-27 15:18:17 +0000478 const MCSymbol &Symbol = AliasedSymbol(Alias);
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000479 MCSymbolData &SD = Asm.getSymbolData(Symbol);
480
481 // Undefined symbols are global, but this is the first place we
482 // are able to set it.
483 if (Symbol.isUndefined() && !Symbol.isVariable()) {
484 if (GetBinding(SD) == ELF::STB_LOCAL) {
485 SetBinding(SD, ELF::STB_GLOBAL);
486 SetBinding(*it, ELF::STB_GLOBAL);
487 }
488 }
489
490 // Not an alias.
491 if (&Symbol == &Alias)
492 continue;
493
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000494 StringRef AliasName = Alias.getName();
Rafael Espindola88182132010-10-27 15:18:17 +0000495 size_t Pos = AliasName.find('@');
496 if (Pos == StringRef::npos)
497 continue;
498
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000499 // Aliases defined with .symvar copy the binding from the symbol they alias.
500 // This is the first place we are able to copy this information.
501 it->setExternal(SD.isExternal());
502 SetBinding(*it, GetBinding(SD));
503
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000504 StringRef Rest = AliasName.substr(Pos);
Rafael Espindola88182132010-10-27 15:18:17 +0000505 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
506 continue;
507
Rafael Espindola83ff4d22010-10-27 17:56:18 +0000508 // FIXME: produce a better error message.
509 if (Symbol.isUndefined() && Rest.startswith("@@") &&
510 !Rest.startswith("@@@"))
511 report_fatal_error("A @@ version cannot be undefined");
512
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000513 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindola88182132010-10-27 15:18:17 +0000514 }
515}
516
Rafael Espindola7be2c332010-10-31 00:16:26 +0000517void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *SymtabF,
518 MCDataFragment *ShndxF,
519 ELFSymbolData &MSD,
Matt Fleming3565a062010-08-16 18:57:57 +0000520 const MCAsmLayout &Layout) {
Rafael Espindola152c1062010-10-06 21:02:29 +0000521 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindolade89b012010-10-15 18:25:33 +0000522 MCSymbolData &Data =
523 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
Rafael Espindola152c1062010-10-06 21:02:29 +0000524
Rafael Espindola7be2c332010-10-31 00:16:26 +0000525 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
526 Data.getSymbol().isVariable();
527
Rafael Espindola152c1062010-10-06 21:02:29 +0000528 uint8_t Binding = GetBinding(OrigData);
529 uint8_t Visibility = GetVisibility(OrigData);
530 uint8_t Type = GetType(Data);
531
532 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
533 uint8_t Other = Visibility;
534
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000535 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000536 uint64_t Size = 0;
537 const MCExpr *ESize;
538
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000539 assert(!(Data.isCommon() && !Data.isExternal()));
540
Matt Fleming3565a062010-08-16 18:57:57 +0000541 ESize = Data.getSize();
542 if (Data.getSize()) {
543 MCValue Res;
544 if (ESize->getKind() == MCExpr::Binary) {
545 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
546
547 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
Benjamin Kramer24f12062010-10-17 07:38:40 +0000548 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
549 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
Rafael Espindolaf230df92010-10-16 18:23:53 +0000550 Size = Res.getConstant();
Matt Fleming3565a062010-08-16 18:57:57 +0000551 }
552 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000553 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000554 } else {
555 assert(0 && "Unsupported size expression");
556 }
557 }
558
559 // Write out the symbol table entry
Rafael Espindola7be2c332010-10-31 00:16:26 +0000560 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
561 Size, Other, MSD.SectionIndex, IsReserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000562}
563
Rafael Espindola7be2c332010-10-31 00:16:26 +0000564void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *SymtabF,
565 MCDataFragment *ShndxF,
Matt Fleming3565a062010-08-16 18:57:57 +0000566 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000567 const MCAsmLayout &Layout,
568 unsigned NumRegularSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000569 // The string table must be emitted first because we need the index
570 // into the string table for all the symbol names.
571 assert(StringTable.size() && "Missing string table");
572
573 // FIXME: Make sure the start of the symbol table is aligned.
574
575 // The first entry is the undefined symbol entry.
Rafael Espindola7be2c332010-10-31 00:16:26 +0000576 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
Matt Fleming3565a062010-08-16 18:57:57 +0000577
578 // Write the symbol table entries.
579 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
580 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
581 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola7be2c332010-10-31 00:16:26 +0000582 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000583 }
584
Rafael Espindola71859c62010-09-16 19:46:31 +0000585 // Write out a symbol table entry for each regular section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000586 unsigned Index = 1;
Rafael Espindola71859c62010-09-16 19:46:31 +0000587 for (MCAssembler::const_iterator it = Asm.begin();
588 Index <= NumRegularSections; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000589 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000590 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000591 // Leave out relocations so we don't have indexes within
592 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000593 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000594 continue;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000595 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
596 ELF::STV_DEFAULT, Index, false);
Eli Friedmana44fa242010-08-16 21:17:09 +0000597 LastLocalSymbolIndex++;
598 }
Matt Fleming3565a062010-08-16 18:57:57 +0000599
600 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
601 ELFSymbolData &MSD = ExternalSymbolData[i];
602 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola3223f192010-10-06 16:47:31 +0000603 assert(((Data.getFlags() & ELF_STB_Global) ||
604 (Data.getFlags() & ELF_STB_Weak)) &&
605 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola7be2c332010-10-31 00:16:26 +0000606 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000607 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000608 LastLocalSymbolIndex++;
609 }
610
611 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
612 ELFSymbolData &MSD = UndefinedSymbolData[i];
613 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000614 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000615 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000616 LastLocalSymbolIndex++;
617 }
618}
619
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000620static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
Rafael Espindola3729d002010-10-05 23:57:26 +0000621 const MCValue &Target,
622 const MCFragment &F) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000623 const MCSymbol &Symbol = SD.getSymbol();
624 if (Symbol.isUndefined())
625 return true;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000626
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000627 const MCSectionELF &Section =
628 static_cast<const MCSectionELF&>(Symbol.getSection());
629
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000630 if (SD.isExternal())
631 return true;
632
Rafael Espindola8cecf252010-10-06 16:23:36 +0000633 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindola3729d002010-10-05 23:57:26 +0000634 const MCSectionELF &Sec2 =
635 static_cast<const MCSectionELF&>(F.getParent()->getSection());
636
Rafael Espindolace2d3c52010-10-18 20:25:33 +0000637 if (Section.getKind().isBSS())
638 return false;
639
Rafael Espindola8cecf252010-10-06 16:23:36 +0000640 if (&Sec2 != &Section &&
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000641 (Kind == MCSymbolRefExpr::VK_PLT ||
642 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
643 Kind == MCSymbolRefExpr::VK_GOTOFF))
Rafael Espindola3729d002010-10-05 23:57:26 +0000644 return true;
645
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000646 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
647 return Target.getConstant() != 0;
648
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000649 return false;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000650}
651
Benjamin Kramere5b57342010-08-17 18:20:28 +0000652// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000653void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
654 const MCAsmLayout &Layout,
655 const MCFragment *Fragment,
656 const MCFixup &Fixup,
657 MCValue Target,
658 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000659 int64_t Addend = 0;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000660 int Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000661 int64_t Value = Target.getConstant();
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000662 const MCSymbol *Symbol = 0;
Rafael Espindola29129722010-10-28 19:08:03 +0000663 const MCSymbol *Renamed = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000664
Rafael Espindola00074892010-09-17 22:34:41 +0000665 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000666 if (!Target.isAbsolute()) {
Rafael Espindolade89b012010-10-15 18:25:33 +0000667 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
Rafael Espindola29129722010-10-28 19:08:03 +0000668 Renamed = Renames.lookup(Symbol);
669 if (!Renamed)
Rafael Espindola484291c2010-11-01 14:28:48 +0000670 Renamed = &Target.getSymA()->getSymbol();
Matt Fleming3565a062010-08-16 18:57:57 +0000671 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000672 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000673
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000674 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
675 const MCSymbol &SymbolB = RefB->getSymbol();
676 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
677 IsPCRel = true;
Rafael Espindola55fb1022010-10-04 15:59:01 +0000678 MCSectionData *Sec = Fragment->getParent();
679
680 // Offset of the symbol in the section
681 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
682
683 // Ofeset of the relocation in the section
684 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
685 Value += b - a;
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000686 }
687
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000688 // Check that this case has already been fully resolved before we get
689 // here.
Rafael Espindola00074892010-09-17 22:34:41 +0000690 if (Symbol->isDefined() && !SD.isExternal() &&
691 IsPCRel &&
692 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000693 llvm_unreachable("We don't need a relocation in this case.");
Rafael Espindola00074892010-09-17 22:34:41 +0000694 return;
695 }
696
Rafael Espindola3729d002010-10-05 23:57:26 +0000697 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000698 if (!RelocOnSymbol) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000699 Index = F->getParent()->getOrdinal();
Rafael Espindolaa6489182010-09-24 21:19:03 +0000700
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000701 MCSectionData *FSD = F->getParent();
702 // Offset of the symbol in the section
703 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000704 } else {
Rafael Espindola29129722010-10-28 19:08:03 +0000705 UsedInReloc.insert(Renamed);
Rafael Espindola484291c2010-11-01 14:28:48 +0000706 MCSymbolData &RenamedSD = Asm.getSymbolData(*Renamed);
707 if (RenamedSD.getFlags() & ELF_Other_Weakref) {
708 WeakrefUsedInReloc.insert(Symbol);
709 }
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000710 Index = -1;
711 }
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000712 Addend = Value;
713 // Compensate for the addend on i386.
714 if (Is64Bit)
715 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000716 }
717
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000718 FixedValue = Value;
719
Matt Fleming3565a062010-08-16 18:57:57 +0000720 // determine the type of the relocation
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000721
722 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000723 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000724 if (Is64Bit) {
725 if (IsPCRel) {
Rafael Espindola92bf6682010-10-04 19:04:13 +0000726 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000727 default:
728 llvm_unreachable("Unimplemented");
Rafael Espindola92bf6682010-10-04 19:04:13 +0000729 case MCSymbolRefExpr::VK_None:
730 Type = ELF::R_X86_64_PC32;
731 break;
732 case MCSymbolRefExpr::VK_PLT:
733 Type = ELF::R_X86_64_PLT32;
734 break;
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000735 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola607d1f62010-10-04 19:51:39 +0000736 Type = ELF::R_X86_64_GOTPCREL;
737 break;
Rafael Espindolabc82d8b2010-10-27 20:28:07 +0000738 case MCSymbolRefExpr::VK_GOTTPOFF:
739 Type = ELF::R_X86_64_GOTTPOFF;
740 break;
741 case MCSymbolRefExpr::VK_TLSGD:
742 Type = ELF::R_X86_64_TLSGD;
743 break;
Rafael Espindolab4d17212010-10-28 15:02:40 +0000744 case MCSymbolRefExpr::VK_TLSLD:
745 Type = ELF::R_X86_64_TLSLD;
746 break;
Rafael Espindola92bf6682010-10-04 19:04:13 +0000747 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000748 } else {
749 switch ((unsigned)Fixup.getKind()) {
750 default: llvm_unreachable("invalid fixup kind!");
751 case FK_Data_8: Type = ELF::R_X86_64_64; break;
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000752 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000753 case X86::reloc_pcrel_4byte:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000754 assert(isInt<32>(Target.getConstant()));
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000755 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000756 default:
757 llvm_unreachable("Unimplemented");
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000758 case MCSymbolRefExpr::VK_None:
759 Type = ELF::R_X86_64_32S;
760 break;
761 case MCSymbolRefExpr::VK_GOT:
762 Type = ELF::R_X86_64_GOT32;
763 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000764 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola8cecf252010-10-06 16:23:36 +0000765 Type = ELF::R_X86_64_GOTPCREL;
766 break;
Rafael Espindolabc82d8b2010-10-27 20:28:07 +0000767 case MCSymbolRefExpr::VK_TPOFF:
768 Type = ELF::R_X86_64_TPOFF32;
769 break;
Rafael Espindolaaa8f1f02010-10-28 15:11:03 +0000770 case MCSymbolRefExpr::VK_DTPOFF:
771 Type = ELF::R_X86_64_DTPOFF32;
772 break;
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000773 }
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000774 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000775 case FK_Data_4:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000776 Type = ELF::R_X86_64_32;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000777 break;
778 case FK_Data_2: Type = ELF::R_X86_64_16; break;
779 case X86::reloc_pcrel_1byte:
780 case FK_Data_1: Type = ELF::R_X86_64_8; break;
781 }
782 }
Matt Fleming3565a062010-08-16 18:57:57 +0000783 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000784 if (IsPCRel) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000785 switch (Modifier) {
786 default:
Rafael Espindola24dc9ec2010-10-18 19:33:01 +0000787 llvm_unreachable("Unimplemented");
788 case MCSymbolRefExpr::VK_None:
Rafael Espindola9baee3b2010-10-18 18:03:28 +0000789 Type = ELF::R_386_PC32;
Rafael Espindola9baee3b2010-10-18 18:03:28 +0000790 break;
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000791 case MCSymbolRefExpr::VK_PLT:
792 Type = ELF::R_386_PLT32;
793 break;
794 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000795 } else {
796 switch ((unsigned)Fixup.getKind()) {
797 default: llvm_unreachable("invalid fixup kind!");
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000798
Rafael Espindola24ba4f72010-10-24 17:35:42 +0000799 case X86::reloc_global_offset_table:
800 Type = ELF::R_386_GOTPC;
801 break;
802
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000803 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
804 // instead?
805 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000806 case X86::reloc_pcrel_4byte:
Rafael Espindolabd701182010-10-19 19:31:37 +0000807 case FK_Data_4:
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000808 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000809 default:
810 llvm_unreachable("Unimplemented");
Rafael Espindolabd701182010-10-19 19:31:37 +0000811 case MCSymbolRefExpr::VK_None:
Rafael Espindola24ba4f72010-10-24 17:35:42 +0000812 Type = ELF::R_386_32;
Rafael Espindolabd701182010-10-19 19:31:37 +0000813 break;
Rafael Espindolaeada3042010-10-18 20:47:21 +0000814 case MCSymbolRefExpr::VK_GOT:
815 Type = ELF::R_386_GOT32;
816 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000817 case MCSymbolRefExpr::VK_GOTOFF:
818 Type = ELF::R_386_GOTOFF;
819 break;
Rafael Espindola3cede2d2010-10-27 21:23:52 +0000820 case MCSymbolRefExpr::VK_TLSGD:
821 Type = ELF::R_386_TLS_GD;
822 break;
823 case MCSymbolRefExpr::VK_TPOFF:
824 Type = ELF::R_386_TLS_LE_32;
825 break;
826 case MCSymbolRefExpr::VK_INDNTPOFF:
827 Type = ELF::R_386_TLS_IE;
828 break;
829 case MCSymbolRefExpr::VK_NTPOFF:
830 Type = ELF::R_386_TLS_LE;
831 break;
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000832 case MCSymbolRefExpr::VK_GOTNTPOFF:
833 Type = ELF::R_386_TLS_GOTIE;
834 break;
Rafael Espindolaa264f722010-10-28 14:37:09 +0000835 case MCSymbolRefExpr::VK_TLSLDM:
836 Type = ELF::R_386_TLS_LDM;
837 break;
Rafael Espindola0cf15d62010-10-28 14:48:59 +0000838 case MCSymbolRefExpr::VK_DTPOFF:
839 Type = ELF::R_386_TLS_LDO_32;
840 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000841 }
842 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000843 case FK_Data_2: Type = ELF::R_386_16; break;
844 case X86::reloc_pcrel_1byte:
845 case FK_Data_1: Type = ELF::R_386_8; break;
846 }
Matt Fleming3565a062010-08-16 18:57:57 +0000847 }
848 }
849
Rafael Espindolaa0a2f872010-10-28 14:22:44 +0000850 if (RelocNeedsGOT(Modifier))
Rafael Espindola5c77c162010-10-05 15:48:37 +0000851 NeedsGOT = true;
852
Benjamin Kramere5b57342010-08-17 18:20:28 +0000853 ELFRelocationEntry ERE;
854
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000855 ERE.Index = Index;
856 ERE.Type = Type;
Rafael Espindola29129722010-10-28 19:08:03 +0000857 ERE.Symbol = Renamed;
Matt Fleming3565a062010-08-16 18:57:57 +0000858
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000859 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000860
Matt Fleming3565a062010-08-16 18:57:57 +0000861 if (HasRelocationAddend)
862 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000863 else
864 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000865
866 Relocations[Fragment->getParent()].push_back(ERE);
867}
868
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000869uint64_t
870ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
871 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000872 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000873
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000874 // Local symbol.
875 if (!SD.isExternal() && !S->isUndefined())
876 return SD.getIndex() + /* empty symbol */ 1;
877
878 // External or undefined symbol.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000879 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000880}
881
Rafael Espindola737cd212010-10-05 18:01:23 +0000882static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
Rafael Espindola88182132010-10-27 15:18:17 +0000883 bool Used, bool Renamed) {
Rafael Espindola484291c2010-11-01 14:28:48 +0000884 if (Data.getFlags() & ELF_Other_Weakref)
885 return false;
886
Rafael Espindolabd701182010-10-19 19:31:37 +0000887 if (Used)
888 return true;
889
Rafael Espindola88182132010-10-27 15:18:17 +0000890 if (Renamed)
891 return false;
892
Rafael Espindola737cd212010-10-05 18:01:23 +0000893 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000894
Rafael Espindolad1798862010-10-29 23:09:31 +0000895 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
896 return true;
897
Rafael Espindolaa6866962010-10-27 14:44:52 +0000898 const MCSymbol &A = AliasedSymbol(Symbol);
Rafael Espindolad1798862010-10-29 23:09:31 +0000899 if (!A.isVariable() && A.isUndefined() && !Data.isCommon())
Rafael Espindolaa6866962010-10-27 14:44:52 +0000900 return false;
901
Rafael Espindola737cd212010-10-05 18:01:23 +0000902 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
903 return false;
904
Rafael Espindolabd701182010-10-19 19:31:37 +0000905 if (Symbol.isTemporary())
Rafael Espindola737cd212010-10-05 18:01:23 +0000906 return false;
907
908 return true;
909}
910
911static bool isLocal(const MCSymbolData &Data) {
912 if (Data.isExternal())
913 return false;
914
915 const MCSymbol &Symbol = Data.getSymbol();
916 if (Symbol.isUndefined() && !Symbol.isVariable())
917 return false;
918
919 return true;
920}
921
Matt Fleming3565a062010-08-16 18:57:57 +0000922void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000923 // FIXME: Is this the correct place to do this?
924 if (NeedsGOT) {
925 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
926 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
927 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
928 Data.setExternal(true);
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000929 SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindola5c77c162010-10-05 15:48:37 +0000930 }
931
Matt Fleming3565a062010-08-16 18:57:57 +0000932 // Build section lookup table.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000933 NumRegularSections = Asm.size();
Rafael Espindolaf5c347d2010-10-05 21:20:07 +0000934 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
Matt Fleming3565a062010-08-16 18:57:57 +0000935 unsigned Index = 1;
936 for (MCAssembler::iterator it = Asm.begin(),
937 ie = Asm.end(); it != ie; ++it, ++Index)
938 SectionIndexMap[&it->getSection()] = Index;
939
940 // Index 0 is always the empty string.
941 StringMap<uint64_t> StringIndexMap;
942 StringTable += '\x00';
943
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000944 // Add the data for the symbols.
Matt Fleming3565a062010-08-16 18:57:57 +0000945 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
946 ie = Asm.symbol_end(); it != ie; ++it) {
947 const MCSymbol &Symbol = it->getSymbol();
948
Rafael Espindola484291c2010-11-01 14:28:48 +0000949 bool Used = UsedInReloc.count(&Symbol);
950 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
951 if (!isInSymtab(Asm, *it, Used || WeakrefUsed,
Rafael Espindola88182132010-10-27 15:18:17 +0000952 Renames.count(&Symbol)))
Matt Fleming3565a062010-08-16 18:57:57 +0000953 continue;
954
Matt Fleming3565a062010-08-16 18:57:57 +0000955 ELFSymbolData MSD;
956 MSD.SymbolData = it;
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000957 bool Local = isLocal(*it);
Rafael Espindola88182132010-10-27 15:18:17 +0000958 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
Matt Fleming3565a062010-08-16 18:57:57 +0000959
Rafael Espindola484291c2010-11-01 14:28:48 +0000960 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
961 SetBinding(*it, ELF::STB_WEAK);
962
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000963 if (it->isCommon()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000964 assert(!Local);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000965 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindolabf052ac2010-10-27 16:04:30 +0000966 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000967 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola88182132010-10-27 15:18:17 +0000968 } else if (RefSymbol.isUndefined()) {
Matt Fleming3565a062010-08-16 18:57:57 +0000969 MSD.SectionIndex = ELF::SHN_UNDEF;
Matt Fleming3565a062010-08-16 18:57:57 +0000970 } else {
Rafael Espindolabf052ac2010-10-27 16:04:30 +0000971 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
Rafael Espindola7be2c332010-10-31 00:16:26 +0000972 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
973 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000974 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000975 }
976
Rafael Espindola88182132010-10-27 15:18:17 +0000977 // The @@@ in symbol version is replaced with @ in undefined symbols and
978 // @@ in defined ones.
979 StringRef Name = Symbol.getName();
980 size_t Pos = Name.find("@@@");
981 std::string FinalName;
982 if (Pos != StringRef::npos) {
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000983 StringRef Prefix = Name.substr(0, Pos);
Rafael Espindola88182132010-10-27 15:18:17 +0000984 unsigned n = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000985 StringRef Suffix = Name.substr(Pos + n);
Rafael Espindola88182132010-10-27 15:18:17 +0000986 FinalName = Prefix.str() + Suffix.str();
987 } else {
988 FinalName = Name.str();
989 }
990
991 uint64_t &Entry = StringIndexMap[FinalName];
Rafael Espindolaa6866962010-10-27 14:44:52 +0000992 if (!Entry) {
993 Entry = StringTable.size();
Rafael Espindola88182132010-10-27 15:18:17 +0000994 StringTable += FinalName;
Rafael Espindolaa6866962010-10-27 14:44:52 +0000995 StringTable += '\x00';
Matt Fleming3565a062010-08-16 18:57:57 +0000996 }
Rafael Espindolaa6866962010-10-27 14:44:52 +0000997 MSD.StringIndex = Entry;
998 if (MSD.SectionIndex == ELF::SHN_UNDEF)
999 UndefinedSymbolData.push_back(MSD);
1000 else if (Local)
1001 LocalSymbolData.push_back(MSD);
1002 else
1003 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +00001004 }
1005
1006 // Symbols are required to be in lexicographic order.
1007 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1008 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1009 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1010
1011 // Set the symbol indices. Local symbols must come before all other
1012 // symbols with non-local bindings.
1013 Index = 0;
1014 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1015 LocalSymbolData[i].SymbolData->setIndex(Index++);
1016 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1017 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1018 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1019 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1020}
1021
1022void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
1023 const MCSectionData &SD) {
1024 if (!Relocations[&SD].empty()) {
1025 MCContext &Ctx = Asm.getContext();
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001026 const MCSectionELF *RelaSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001027 const MCSectionELF &Section =
1028 static_cast<const MCSectionELF&>(SD.getSection());
1029
1030 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +00001031 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +00001032 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +00001033
1034 unsigned EntrySize;
1035 if (HasRelocationAddend)
1036 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1037 else
1038 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +00001039
Benjamin Kramer377a5722010-08-17 17:30:07 +00001040 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
1041 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001042 SectionKind::getReadOnly(),
Rafael Espindola34be3962010-11-09 23:42:07 +00001043 EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +00001044
1045 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001046 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +00001047
1048 MCDataFragment *F = new MCDataFragment(&RelaSD);
1049
1050 WriteRelocationsFragment(Asm, F, &SD);
1051
Rafael Espindola70703872010-09-30 02:22:20 +00001052 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +00001053 }
1054}
1055
1056void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1057 uint64_t Flags, uint64_t Address,
1058 uint64_t Offset, uint64_t Size,
1059 uint32_t Link, uint32_t Info,
1060 uint64_t Alignment,
1061 uint64_t EntrySize) {
1062 Write32(Name); // sh_name: index into string table
1063 Write32(Type); // sh_type
1064 WriteWord(Flags); // sh_flags
1065 WriteWord(Address); // sh_addr
1066 WriteWord(Offset); // sh_offset
1067 WriteWord(Size); // sh_size
1068 Write32(Link); // sh_link
1069 Write32(Info); // sh_info
1070 WriteWord(Alignment); // sh_addralign
1071 WriteWord(EntrySize); // sh_entsize
1072}
1073
1074void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
1075 MCDataFragment *F,
1076 const MCSectionData *SD) {
1077 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1078 // sort by the r_offset just like gnu as does
1079 array_pod_sort(Relocs.begin(), Relocs.end());
1080
1081 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1082 ELFRelocationEntry entry = Relocs[e - i - 1];
1083
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001084 if (entry.Index < 0)
1085 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1086 else
1087 entry.Index += LocalSymbolData.size() + 1;
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001088 if (Is64Bit) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001089 String64(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001090
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001091 struct ELF::Elf64_Rela ERE64;
1092 ERE64.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001093 String64(*F, ERE64.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001094
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001095 if (HasRelocationAddend)
1096 String64(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001097 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001098 String32(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001099
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001100 struct ELF::Elf32_Rela ERE32;
1101 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001102 String32(*F, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001103
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001104 if (HasRelocationAddend)
1105 String32(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001106 }
Matt Fleming3565a062010-08-16 18:57:57 +00001107 }
1108}
1109
1110void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
1111 MCAsmLayout &Layout) {
1112 MCContext &Ctx = Asm.getContext();
1113 MCDataFragment *F;
1114
Matt Fleming3565a062010-08-16 18:57:57 +00001115 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
1116
Rafael Espindola71859c62010-09-16 19:46:31 +00001117 unsigned NumRegularSections = Asm.size();
1118
Rafael Espindola38738bf2010-09-22 19:04:41 +00001119 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001120 const MCSectionELF *ShstrtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001121 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
1122 SectionKind::getReadOnly(), false);
Rafael Espindola71859c62010-09-16 19:46:31 +00001123 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1124 ShstrtabSD.setAlignment(1);
1125 ShstrtabIndex = Asm.size();
1126
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001127 const MCSectionELF *SymtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001128 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1129 SectionKind::getReadOnly(),
Rafael Espindola34be3962010-11-09 23:42:07 +00001130 EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +00001131 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +00001132 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001133 SymbolTableIndex = Asm.size();
1134
1135 MCSectionData *SymtabShndxSD = NULL;
1136
1137 if (NeedsSymtabShndx) {
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001138 const MCSectionELF *SymtabShndxSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001139 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
Rafael Espindola34be3962010-11-09 23:42:07 +00001140 SectionKind::getReadOnly(), 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001141 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1142 SymtabShndxSD->setAlignment(4);
1143 }
Matt Fleming3565a062010-08-16 18:57:57 +00001144
Matt Fleming3565a062010-08-16 18:57:57 +00001145 const MCSection *StrtabSection;
1146 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
1147 SectionKind::getReadOnly(), false);
Matt Fleming3565a062010-08-16 18:57:57 +00001148 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1149 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +00001150 StringTableIndex = Asm.size();
1151
Rafael Espindolac3c413f2010-09-27 22:04:54 +00001152 WriteRelocations(Asm, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +00001153
1154 // Symbol table
1155 F = new MCDataFragment(&SymtabSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001156 MCDataFragment *ShndxF = NULL;
1157 if (NeedsSymtabShndx) {
1158 ShndxF = new MCDataFragment(SymtabShndxSD);
1159 Asm.AddSectionToTheEnd(*Writer, *SymtabShndxSD, Layout);
1160 }
1161 WriteSymbolTable(F, ShndxF, Asm, Layout, NumRegularSections);
Rafael Espindola70703872010-09-30 02:22:20 +00001162 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +00001163
Matt Fleming3565a062010-08-16 18:57:57 +00001164 F = new MCDataFragment(&StrtabSD);
1165 F->getContents().append(StringTable.begin(), StringTable.end());
Rafael Espindola70703872010-09-30 02:22:20 +00001166 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +00001167
Matt Fleming3565a062010-08-16 18:57:57 +00001168 F = new MCDataFragment(&ShstrtabSD);
1169
Matt Fleming3565a062010-08-16 18:57:57 +00001170 // Section header string table.
1171 //
1172 // The first entry of a string table holds a null character so skip
1173 // section 0.
1174 uint64_t Index = 1;
1175 F->getContents() += '\x00';
1176
1177 for (MCAssembler::const_iterator it = Asm.begin(),
1178 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +00001179 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +00001180 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +00001181 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +00001182
1183 // Remember the index into the string table so we can write it
1184 // into the sh_name field of the section header table.
1185 SectionStringTableIndex[&it->getSection()] = Index;
1186
1187 Index += Section.getSectionName().size() + 1;
1188 F->getContents() += Section.getSectionName();
1189 F->getContents() += '\x00';
1190 }
1191
Rafael Espindola70703872010-09-30 02:22:20 +00001192 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1193}
1194
1195bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1196 const MCValue Target,
1197 bool IsPCRel,
1198 const MCFragment *DF) const {
1199 // If this is a PCrel relocation, find the section this fixup value is
1200 // relative to.
1201 const MCSection *BaseSection = 0;
1202 if (IsPCRel) {
1203 BaseSection = &DF->getParent()->getSection();
1204 assert(BaseSection);
1205 }
1206
1207 const MCSection *SectionA = 0;
1208 const MCSymbol *SymbolA = 0;
1209 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1210 SymbolA = &A->getSymbol();
1211 SectionA = &SymbolA->getSection();
1212 }
1213
1214 const MCSection *SectionB = 0;
1215 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1216 SectionB = &B->getSymbol().getSection();
1217 }
1218
1219 if (!BaseSection)
1220 return SectionA == SectionB;
1221
1222 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1223 if (DataA.isExternal())
1224 return false;
1225
1226 return !SectionB && BaseSection == SectionA;
Matt Fleming3565a062010-08-16 18:57:57 +00001227}
1228
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001229void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001230 const MCAsmLayout &Layout) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001231 // Compute symbol table information.
1232 ComputeSymbolTable(Asm);
1233
Matt Fleming3565a062010-08-16 18:57:57 +00001234 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1235 const_cast<MCAsmLayout&>(Layout));
1236
1237 // Add 1 for the null section.
1238 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001239 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1240 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1241 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001242
1243 for (MCAssembler::const_iterator it = Asm.begin(),
1244 ie = Asm.end(); it != ie; ++it) {
1245 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +00001246
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001247 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1248
Matt Fleming3565a062010-08-16 18:57:57 +00001249 // Get the size of the section in the output file (including padding).
1250 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001251
1252 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +00001253 }
1254
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001255 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1256
Matt Fleming3565a062010-08-16 18:57:57 +00001257 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001258 WriteHeader(FileOff - HeaderSize, NumSections);
1259
1260 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001261
1262 // ... then all of the sections ...
1263 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1264
Rafael Espindolad8e0bfe2010-10-06 22:28:19 +00001265 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001266
1267 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001268 for (MCAssembler::const_iterator it = Asm.begin(),
1269 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001270 const MCSectionData &SD = *it;
1271
1272 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1273 WriteZeros(Padding);
1274 FileOff += Padding;
1275
Matt Fleming3565a062010-08-16 18:57:57 +00001276 // Remember the offset into the file for this section.
1277 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001278 SectionIndexMap[&it->getSection()] = Index++;
1279
Matt Fleming3565a062010-08-16 18:57:57 +00001280 FileOff += Layout.getSectionFileSize(&SD);
1281
1282 Asm.WriteSectionData(it, Layout, Writer);
1283 }
1284
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001285 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1286 WriteZeros(Padding);
1287 FileOff += Padding;
1288
Matt Fleming3565a062010-08-16 18:57:57 +00001289 // ... and then the section header table.
1290 // Should we align the section header table?
1291 //
1292 // Null section first.
Rafael Espindola7be2c332010-10-31 00:16:26 +00001293 uint64_t FirstSectionSize =
1294 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1295 uint32_t FirstSectionLink =
1296 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1297 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming3565a062010-08-16 18:57:57 +00001298
1299 for (MCAssembler::const_iterator it = Asm.begin(),
1300 ie = Asm.end(); it != ie; ++it) {
1301 const MCSectionData &SD = *it;
1302 const MCSectionELF &Section =
1303 static_cast<const MCSectionELF&>(SD.getSection());
1304
1305 uint64_t sh_link = 0;
1306 uint64_t sh_info = 0;
1307
1308 switch(Section.getType()) {
1309 case ELF::SHT_DYNAMIC:
1310 sh_link = SectionStringTableIndex[&it->getSection()];
1311 sh_info = 0;
1312 break;
1313
1314 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +00001315 case ELF::SHT_RELA: {
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001316 const MCSectionELF *SymtabSection;
1317 const MCSectionELF *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001318
1319 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1320 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +00001321 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001322 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001323
Benjamin Kramer377a5722010-08-17 17:30:07 +00001324 // Remove ".rel" and ".rela" prefixes.
1325 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1326 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1327
Eli Friedmanf8020a32010-08-16 19:15:06 +00001328 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +00001329 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +00001330 SectionKind::getReadOnly(),
1331 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001332 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001333 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +00001334 }
Matt Fleming3565a062010-08-16 18:57:57 +00001335
1336 case ELF::SHT_SYMTAB:
1337 case ELF::SHT_DYNSYM:
1338 sh_link = StringTableIndex;
1339 sh_info = LastLocalSymbolIndex;
1340 break;
1341
Rafael Espindola7be2c332010-10-31 00:16:26 +00001342 case ELF::SHT_SYMTAB_SHNDX:
1343 sh_link = SymbolTableIndex;
1344 break;
1345
Matt Fleming3565a062010-08-16 18:57:57 +00001346 case ELF::SHT_PROGBITS:
1347 case ELF::SHT_STRTAB:
1348 case ELF::SHT_NOBITS:
Benjamin Kramer19dc7fa2010-08-31 17:03:33 +00001349 case ELF::SHT_NULL:
Rafael Espindolacecbc3d2010-10-25 17:50:35 +00001350 case ELF::SHT_ARM_ATTRIBUTES:
Matt Fleming3565a062010-08-16 18:57:57 +00001351 // Nothing to do.
1352 break;
1353
Matt Fleming3565a062010-08-16 18:57:57 +00001354 default:
1355 assert(0 && "FIXME: sh_type value not supported!");
1356 break;
1357 }
1358
1359 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1360 Section.getType(), Section.getFlags(),
Rafael Espindola71859c62010-09-16 19:46:31 +00001361 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001362 SectionOffsetMap.lookup(&SD.getSection()),
1363 Layout.getSectionSize(&SD), sh_link,
1364 sh_info, SD.getAlignment(),
1365 Section.getEntrySize());
1366 }
1367}
1368
1369ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1370 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001371 Triple::OSType OSType,
Wesley Peckeecb8582010-10-22 15:52:49 +00001372 uint16_t EMachine,
Matt Fleming3565a062010-08-16 18:57:57 +00001373 bool IsLittleEndian,
1374 bool HasRelocationAddend)
1375 : MCObjectWriter(OS, IsLittleEndian)
1376{
Wesley Peckeecb8582010-10-22 15:52:49 +00001377 Impl = new ELFObjectWriterImpl(this, Is64Bit, EMachine,
1378 HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001379}
1380
1381ELFObjectWriter::~ELFObjectWriter() {
1382 delete (ELFObjectWriterImpl*) Impl;
1383}
1384
1385void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1386 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1387}
1388
1389void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1390 const MCAsmLayout &Layout,
1391 const MCFragment *Fragment,
1392 const MCFixup &Fixup, MCValue Target,
1393 uint64_t &FixedValue) {
1394 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1395 Target, FixedValue);
1396}
1397
Rafael Espindola70703872010-09-30 02:22:20 +00001398bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1399 const MCValue Target,
1400 bool IsPCRel,
1401 const MCFragment *DF) const {
1402 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1403 IsPCRel, DF);
1404}
1405
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001406void ELFObjectWriter::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001407 const MCAsmLayout &Layout) {
1408 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1409}