blob: 2eb62080e16da5f555d00be971848126a3707cda [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 Espindola5c77c162010-10-05 15:48:37 +000081static bool RelocNeedsGOT(unsigned Type) {
82 switch (Type) {
83 default:
84 return false;
85 case ELF::R_X86_64_GOT32:
86 case ELF::R_X86_64_PLT32:
87 case ELF::R_X86_64_GOTPCREL:
88 return true;
89 }
90}
91
Matt Fleming3565a062010-08-16 18:57:57 +000092namespace {
93
94 class ELFObjectWriterImpl {
Chris Lattnerb188a372010-08-28 03:21:03 +000095 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
Matt Fleming3565a062010-08-16 18:57:57 +000096 return Kind == X86::reloc_riprel_4byte ||
97 Kind == X86::reloc_riprel_4byte_movq_load;
Chris Lattnerb188a372010-08-28 03:21:03 +000098 }*/
Matt Fleming3565a062010-08-16 18:57:57 +000099
100
101 /// ELFSymbolData - Helper struct for containing some precomputed information
102 /// on symbols.
103 struct ELFSymbolData {
104 MCSymbolData *SymbolData;
105 uint64_t StringIndex;
106 uint32_t SectionIndex;
107
108 // Support lexicographic sorting.
109 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolaad49cf52010-09-18 15:03:21 +0000110 if (GetType(*SymbolData) == ELF::STT_FILE)
111 return true;
112 if (GetType(*RHS.SymbolData) == ELF::STT_FILE)
113 return false;
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000114 return SymbolData->getSymbol().getName() <
115 RHS.SymbolData->getSymbol().getName();
Matt Fleming3565a062010-08-16 18:57:57 +0000116 }
117 };
118
119 /// @name Relocation Data
120 /// @{
121
122 struct ELFRelocationEntry {
123 // Make these big enough for both 32-bit and 64-bit
124 uint64_t r_offset;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000125 int Index;
126 unsigned Type;
127 const MCSymbol *Symbol;
Matt Fleming3565a062010-08-16 18:57:57 +0000128 uint64_t r_addend;
129
130 // Support lexicographic sorting.
131 bool operator<(const ELFRelocationEntry &RE) const {
132 return RE.r_offset < r_offset;
133 }
134 };
135
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000136 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
137
Matt Fleming3565a062010-08-16 18:57:57 +0000138 llvm::DenseMap<const MCSectionData*,
139 std::vector<ELFRelocationEntry> > Relocations;
140 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
141
142 /// @}
143 /// @name Symbol Table Data
144 /// @{
145
146 SmallString<256> StringTable;
147 std::vector<ELFSymbolData> LocalSymbolData;
148 std::vector<ELFSymbolData> ExternalSymbolData;
149 std::vector<ELFSymbolData> UndefinedSymbolData;
150
151 /// @}
152
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000153 int NumRegularSections;
154
Rafael Espindola5c77c162010-10-05 15:48:37 +0000155 bool NeedsGOT;
156
Matt Fleming3565a062010-08-16 18:57:57 +0000157 ELFObjectWriter *Writer;
158
159 raw_ostream &OS;
160
Matt Fleming3565a062010-08-16 18:57:57 +0000161 unsigned Is64Bit : 1;
162
163 bool HasRelocationAddend;
164
Roman Divacky5baf79e2010-09-09 17:57:50 +0000165 Triple::OSType OSType;
166
Matt Fleming3565a062010-08-16 18:57:57 +0000167 // This holds the symbol table index of the last local symbol.
168 unsigned LastLocalSymbolIndex;
169 // This holds the .strtab section index.
170 unsigned StringTableIndex;
171
172 unsigned ShstrtabIndex;
173
174 public:
175 ELFObjectWriterImpl(ELFObjectWriter *_Writer, bool _Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +0000176 bool _HasRelAddend, Triple::OSType _OSType)
Rafael Espindola5c77c162010-10-05 15:48:37 +0000177 : NeedsGOT(false), Writer(_Writer), OS(Writer->getStream()),
Roman Divacky5baf79e2010-09-09 17:57:50 +0000178 Is64Bit(_Is64Bit), HasRelocationAddend(_HasRelAddend),
179 OSType(_OSType) {
Matt Fleming3565a062010-08-16 18:57:57 +0000180 }
181
182 void Write8(uint8_t Value) { Writer->Write8(Value); }
183 void Write16(uint16_t Value) { Writer->Write16(Value); }
184 void Write32(uint32_t Value) { Writer->Write32(Value); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000185 //void Write64(uint64_t Value) { Writer->Write64(Value); }
Matt Fleming3565a062010-08-16 18:57:57 +0000186 void WriteZeros(unsigned N) { Writer->WriteZeros(N); }
Chris Lattnerb188a372010-08-28 03:21:03 +0000187 //void WriteBytes(StringRef Str, unsigned ZeroFillSize = 0) {
188 // Writer->WriteBytes(Str, ZeroFillSize);
189 //}
Matt Fleming3565a062010-08-16 18:57:57 +0000190
191 void WriteWord(uint64_t W) {
Chris Lattnerb188a372010-08-28 03:21:03 +0000192 if (Is64Bit)
Matt Fleming3565a062010-08-16 18:57:57 +0000193 Writer->Write64(W);
Chris Lattnerb188a372010-08-28 03:21:03 +0000194 else
Matt Fleming3565a062010-08-16 18:57:57 +0000195 Writer->Write32(W);
Matt Fleming3565a062010-08-16 18:57:57 +0000196 }
197
198 void String8(char *buf, uint8_t Value) {
199 buf[0] = Value;
200 }
201
202 void StringLE16(char *buf, uint16_t Value) {
203 buf[0] = char(Value >> 0);
204 buf[1] = char(Value >> 8);
205 }
206
207 void StringLE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000208 StringLE16(buf, uint16_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000209 StringLE16(buf + 2, uint16_t(Value >> 16));
Matt Fleming3565a062010-08-16 18:57:57 +0000210 }
211
212 void StringLE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000213 StringLE32(buf, uint32_t(Value >> 0));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000214 StringLE32(buf + 4, uint32_t(Value >> 32));
Matt Fleming3565a062010-08-16 18:57:57 +0000215 }
216
217 void StringBE16(char *buf ,uint16_t Value) {
218 buf[0] = char(Value >> 8);
219 buf[1] = char(Value >> 0);
220 }
221
222 void StringBE32(char *buf, uint32_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000223 StringBE16(buf, uint16_t(Value >> 16));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000224 StringBE16(buf + 2, uint16_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000225 }
226
227 void StringBE64(char *buf, uint64_t Value) {
Benjamin Kramer36c6dc22010-08-23 21:23:52 +0000228 StringBE32(buf, uint32_t(Value >> 32));
Benjamin Kramerc522f6e2010-08-23 21:32:00 +0000229 StringBE32(buf + 4, uint32_t(Value >> 0));
Matt Fleming3565a062010-08-16 18:57:57 +0000230 }
231
232 void String16(char *buf, uint16_t Value) {
233 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000234 StringLE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000235 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000236 StringBE16(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000237 }
238
239 void String32(char *buf, uint32_t Value) {
240 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000241 StringLE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000242 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000243 StringBE32(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000244 }
245
246 void String64(char *buf, uint64_t Value) {
247 if (Writer->isLittleEndian())
Eli Friedmanf8020a32010-08-16 19:15:06 +0000248 StringLE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000249 else
Eli Friedmanf8020a32010-08-16 19:15:06 +0000250 StringBE64(buf, Value);
Matt Fleming3565a062010-08-16 18:57:57 +0000251 }
252
253 void WriteHeader(uint64_t SectionDataSize, unsigned NumberOfSections);
254
255 void WriteSymbolEntry(MCDataFragment *F, uint64_t name, uint8_t info,
256 uint64_t value, uint64_t size,
257 uint8_t other, uint16_t shndx);
258
259 void WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
260 const MCAsmLayout &Layout);
261
262 void WriteSymbolTable(MCDataFragment *F, const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000263 const MCAsmLayout &Layout,
264 unsigned NumRegularSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000265
266 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
267 const MCFragment *Fragment, const MCFixup &Fixup,
268 MCValue Target, uint64_t &FixedValue);
269
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000270 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
271 const MCSymbol *S);
Matt Fleming3565a062010-08-16 18:57:57 +0000272
273 /// ComputeSymbolTable - Compute the symbol table data
274 ///
275 /// \param StringTable [out] - The string table data.
276 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
277 /// string table.
278 void ComputeSymbolTable(MCAssembler &Asm);
279
280 void WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
281 const MCSectionData &SD);
282
283 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
284 for (MCAssembler::const_iterator it = Asm.begin(),
285 ie = Asm.end(); it != ie; ++it) {
286 WriteRelocation(Asm, Layout, *it);
287 }
288 }
289
290 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout);
291
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000292 void ExecutePostLayoutBinding(MCAssembler &Asm) {
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000293 }
Matt Fleming3565a062010-08-16 18:57:57 +0000294
295 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
296 uint64_t Address, uint64_t Offset,
297 uint64_t Size, uint32_t Link, uint32_t Info,
298 uint64_t Alignment, uint64_t EntrySize);
299
300 void WriteRelocationsFragment(const MCAssembler &Asm, MCDataFragment *F,
301 const MCSectionData *SD);
302
Rafael Espindola70703872010-09-30 02:22:20 +0000303 bool IsFixupFullyResolved(const MCAssembler &Asm,
304 const MCValue Target,
305 bool IsPCRel,
306 const MCFragment *DF) const;
307
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000308 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000309 };
310
311}
312
313// Emit the ELF header.
314void ELFObjectWriterImpl::WriteHeader(uint64_t SectionDataSize,
315 unsigned NumberOfSections) {
316 // ELF Header
317 // ----------
318 //
319 // Note
320 // ----
321 // emitWord method behaves differently for ELF32 and ELF64, writing
322 // 4 bytes in the former and 8 in the latter.
323
324 Write8(0x7f); // e_ident[EI_MAG0]
325 Write8('E'); // e_ident[EI_MAG1]
326 Write8('L'); // e_ident[EI_MAG2]
327 Write8('F'); // e_ident[EI_MAG3]
328
329 Write8(Is64Bit ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
330
331 // e_ident[EI_DATA]
332 Write8(Writer->isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
333
334 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000335 // e_ident[EI_OSABI]
336 switch (OSType) {
337 case Triple::FreeBSD: Write8(ELF::ELFOSABI_FREEBSD); break;
338 case Triple::Linux: Write8(ELF::ELFOSABI_LINUX); break;
339 default: Write8(ELF::ELFOSABI_NONE); break;
340 }
Matt Fleming3565a062010-08-16 18:57:57 +0000341 Write8(0); // e_ident[EI_ABIVERSION]
342
343 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
344
345 Write16(ELF::ET_REL); // e_type
346
347 // FIXME: Make this configurable
Benjamin Kramereb976772010-08-17 17:02:29 +0000348 Write16(Is64Bit ? ELF::EM_X86_64 : ELF::EM_386); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000349
350 Write32(ELF::EV_CURRENT); // e_version
351 WriteWord(0); // e_entry, no entry point in .o file
352 WriteWord(0); // e_phoff, no program header for .o
Benjamin Kramereb976772010-08-17 17:02:29 +0000353 WriteWord(SectionDataSize + (Is64Bit ? sizeof(ELF::Elf64_Ehdr) :
354 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000355
356 // FIXME: Make this configurable.
357 Write32(0); // e_flags = whatever the target wants
358
359 // e_ehsize = ELF header size
360 Write16(Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
361
362 Write16(0); // e_phentsize = prog header entry size
363 Write16(0); // e_phnum = # prog header entries = 0
364
365 // e_shentsize = Section header entry size
366 Write16(Is64Bit ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
367
368 // e_shnum = # of section header ents
369 Write16(NumberOfSections);
370
371 // e_shstrndx = Section # of '.shstrtab'
372 Write16(ShstrtabIndex);
373}
374
375void ELFObjectWriterImpl::WriteSymbolEntry(MCDataFragment *F, uint64_t name,
376 uint8_t info, uint64_t value,
377 uint64_t size, uint8_t other,
378 uint16_t shndx) {
379 if (Is64Bit) {
380 char buf[8];
381
382 String32(buf, name);
383 F->getContents() += StringRef(buf, 4); // st_name
384
385 String8(buf, info);
386 F->getContents() += StringRef(buf, 1); // st_info
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000387
Matt Fleming3565a062010-08-16 18:57:57 +0000388 String8(buf, other);
389 F->getContents() += StringRef(buf, 1); // st_other
390
391 String16(buf, shndx);
392 F->getContents() += StringRef(buf, 2); // st_shndx
393
394 String64(buf, value);
395 F->getContents() += StringRef(buf, 8); // st_value
396
397 String64(buf, size);
398 F->getContents() += StringRef(buf, 8); // st_size
399 } else {
400 char buf[4];
401
402 String32(buf, name);
403 F->getContents() += StringRef(buf, 4); // st_name
404
405 String32(buf, value);
406 F->getContents() += StringRef(buf, 4); // st_value
407
408 String32(buf, size);
409 F->getContents() += StringRef(buf, 4); // st_size
410
411 String8(buf, info);
412 F->getContents() += StringRef(buf, 1); // st_info
413
414 String8(buf, other);
415 F->getContents() += StringRef(buf, 1); // st_other
416
417 String16(buf, shndx);
418 F->getContents() += StringRef(buf, 2); // st_shndx
419 }
420}
421
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000422static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout) {
423 if (Data.isCommon() && Data.isExternal())
424 return Data.getCommonAlignment();
425
426 const MCSymbol &Symbol = Data.getSymbol();
427 if (!Symbol.isInSection())
428 return 0;
429
430 if (!Data.isCommon() && !(Data.getFlags() & ELF_STB_Weak))
431 if (MCFragment *FF = Data.getFragment())
432 return Layout.getSymbolAddress(&Data) -
433 Layout.getSectionAddress(FF->getParent());
434
435 return 0;
436}
437
Rafael Espindolade89b012010-10-15 18:25:33 +0000438static const MCSymbol &AliasedSymbol(const MCSymbol &Symbol) {
439 const MCSymbol *S = &Symbol;
440 while (S->isVariable()) {
441 const MCExpr *Value = S->getVariableValue();
442 assert (Value->getKind() == MCExpr::SymbolRef && "Unimplemented");
443 const MCSymbolRefExpr *Ref = static_cast<const MCSymbolRefExpr*>(Value);
444 S = &Ref->getSymbol();
445 }
446 return *S;
447}
448
Matt Fleming3565a062010-08-16 18:57:57 +0000449void ELFObjectWriterImpl::WriteSymbol(MCDataFragment *F, ELFSymbolData &MSD,
450 const MCAsmLayout &Layout) {
Rafael Espindola152c1062010-10-06 21:02:29 +0000451 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindolade89b012010-10-15 18:25:33 +0000452 MCSymbolData &Data =
453 Layout.getAssembler().getSymbolData(AliasedSymbol(OrigData.getSymbol()));
Rafael Espindola152c1062010-10-06 21:02:29 +0000454
455 uint8_t Binding = GetBinding(OrigData);
456 uint8_t Visibility = GetVisibility(OrigData);
457 uint8_t Type = GetType(Data);
458
459 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
460 uint8_t Other = Visibility;
461
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000462 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000463 uint64_t Size = 0;
464 const MCExpr *ESize;
465
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000466 assert(!(Data.isCommon() && !Data.isExternal()));
467
Matt Fleming3565a062010-08-16 18:57:57 +0000468 ESize = Data.getSize();
469 if (Data.getSize()) {
470 MCValue Res;
471 if (ESize->getKind() == MCExpr::Binary) {
472 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(ESize);
473
474 if (BE->EvaluateAsRelocatable(Res, &Layout)) {
Benjamin Kramer24f12062010-10-17 07:38:40 +0000475 assert(!Res.getSymA() || !Res.getSymA()->getSymbol().isDefined());
476 assert(!Res.getSymB() || !Res.getSymB()->getSymbol().isDefined());
Rafael Espindolaf230df92010-10-16 18:23:53 +0000477 Size = Res.getConstant();
Matt Fleming3565a062010-08-16 18:57:57 +0000478 }
479 } else if (ESize->getKind() == MCExpr::Constant) {
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000480 Size = static_cast<const MCConstantExpr *>(ESize)->getValue();
Matt Fleming3565a062010-08-16 18:57:57 +0000481 } else {
482 assert(0 && "Unsupported size expression");
483 }
484 }
485
486 // Write out the symbol table entry
487 WriteSymbolEntry(F, MSD.StringIndex, Info, Value,
488 Size, Other, MSD.SectionIndex);
489}
490
491void ELFObjectWriterImpl::WriteSymbolTable(MCDataFragment *F,
492 const MCAssembler &Asm,
Rafael Espindola71859c62010-09-16 19:46:31 +0000493 const MCAsmLayout &Layout,
494 unsigned NumRegularSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000495 // The string table must be emitted first because we need the index
496 // into the string table for all the symbol names.
497 assert(StringTable.size() && "Missing string table");
498
499 // FIXME: Make sure the start of the symbol table is aligned.
500
501 // The first entry is the undefined symbol entry.
502 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000503 F->getContents().append(EntrySize, '\x00');
Matt Fleming3565a062010-08-16 18:57:57 +0000504
505 // Write the symbol table entries.
506 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
507 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
508 ELFSymbolData &MSD = LocalSymbolData[i];
509 WriteSymbol(F, MSD, Layout);
510 }
511
Rafael Espindola71859c62010-09-16 19:46:31 +0000512 // Write out a symbol table entry for each regular section.
Eli Friedmana44fa242010-08-16 21:17:09 +0000513 unsigned Index = 1;
Rafael Espindola71859c62010-09-16 19:46:31 +0000514 for (MCAssembler::const_iterator it = Asm.begin();
515 Index <= NumRegularSections; ++it, ++Index) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000516 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +0000517 static_cast<const MCSectionELF&>(it->getSection());
Eli Friedmana44fa242010-08-16 21:17:09 +0000518 // Leave out relocations so we don't have indexes within
519 // the relocations messed up
Benjamin Kramer377a5722010-08-17 17:30:07 +0000520 if (Section.getType() == ELF::SHT_RELA || Section.getType() == ELF::SHT_REL)
Eli Friedmana44fa242010-08-16 21:17:09 +0000521 continue;
Matt Fleming3565a062010-08-16 18:57:57 +0000522 WriteSymbolEntry(F, 0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT, Index);
Eli Friedmana44fa242010-08-16 21:17:09 +0000523 LastLocalSymbolIndex++;
524 }
Matt Fleming3565a062010-08-16 18:57:57 +0000525
526 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
527 ELFSymbolData &MSD = ExternalSymbolData[i];
528 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola3223f192010-10-06 16:47:31 +0000529 assert(((Data.getFlags() & ELF_STB_Global) ||
530 (Data.getFlags() & ELF_STB_Weak)) &&
531 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Matt Fleming3565a062010-08-16 18:57:57 +0000532 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000533 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000534 LastLocalSymbolIndex++;
535 }
536
537 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
538 ELFSymbolData &MSD = UndefinedSymbolData[i];
539 MCSymbolData &Data = *MSD.SymbolData;
Matt Fleming3565a062010-08-16 18:57:57 +0000540 WriteSymbol(F, MSD, Layout);
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000541 if (GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000542 LastLocalSymbolIndex++;
543 }
544}
545
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000546static bool ShouldRelocOnSymbol(const MCSymbolData &SD,
Rafael Espindola3729d002010-10-05 23:57:26 +0000547 const MCValue &Target,
548 const MCFragment &F) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000549 const MCSymbol &Symbol = SD.getSymbol();
550 if (Symbol.isUndefined())
551 return true;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000552
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000553 const MCSectionELF &Section =
554 static_cast<const MCSectionELF&>(Symbol.getSection());
555
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000556 if (SD.isExternal())
557 return true;
558
Rafael Espindola8cecf252010-10-06 16:23:36 +0000559 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindola3729d002010-10-05 23:57:26 +0000560 const MCSectionELF &Sec2 =
561 static_cast<const MCSectionELF&>(F.getParent()->getSection());
562
Rafael Espindola8cecf252010-10-06 16:23:36 +0000563 if (&Sec2 != &Section &&
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000564 (Kind == MCSymbolRefExpr::VK_PLT ||
565 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
566 Kind == MCSymbolRefExpr::VK_GOTOFF))
Rafael Espindola3729d002010-10-05 23:57:26 +0000567 return true;
568
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000569 if (Section.getFlags() & MCSectionELF::SHF_MERGE)
570 return Target.getConstant() != 0;
571
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000572 return false;
Rafael Espindola73ffea42010-09-25 05:42:19 +0000573}
574
Benjamin Kramere5b57342010-08-17 18:20:28 +0000575// FIXME: this is currently X86/X86_64 only
Matt Fleming3565a062010-08-16 18:57:57 +0000576void ELFObjectWriterImpl::RecordRelocation(const MCAssembler &Asm,
577 const MCAsmLayout &Layout,
578 const MCFragment *Fragment,
579 const MCFixup &Fixup,
580 MCValue Target,
581 uint64_t &FixedValue) {
Matt Fleming3565a062010-08-16 18:57:57 +0000582 int64_t Addend = 0;
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000583 int Index = 0;
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000584 int64_t Value = Target.getConstant();
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000585 const MCSymbol *Symbol = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000586
Rafael Espindola00074892010-09-17 22:34:41 +0000587 bool IsPCRel = isFixupKindX86PCRel(Fixup.getKind());
Benjamin Kramer81cfb852010-08-17 19:45:05 +0000588 if (!Target.isAbsolute()) {
Rafael Espindolade89b012010-10-15 18:25:33 +0000589 Symbol = &AliasedSymbol(Target.getSymA()->getSymbol());
Matt Fleming3565a062010-08-16 18:57:57 +0000590 MCSymbolData &SD = Asm.getSymbolData(*Symbol);
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000591 MCFragment *F = SD.getFragment();
Matt Fleming3565a062010-08-16 18:57:57 +0000592
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000593 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
594 const MCSymbol &SymbolB = RefB->getSymbol();
595 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
596 IsPCRel = true;
Rafael Espindola55fb1022010-10-04 15:59:01 +0000597 MCSectionData *Sec = Fragment->getParent();
598
599 // Offset of the symbol in the section
600 int64_t a = Layout.getSymbolAddress(&SDB) - Layout.getSectionAddress(Sec);
601
602 // Ofeset of the relocation in the section
603 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
604 Value += b - a;
Rafael Espindola9d8b7552010-10-03 00:46:57 +0000605 }
606
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000607 // Check that this case has already been fully resolved before we get
608 // here.
Rafael Espindola00074892010-09-17 22:34:41 +0000609 if (Symbol->isDefined() && !SD.isExternal() &&
610 IsPCRel &&
611 &Fragment->getParent()->getSection() == &Symbol->getSection()) {
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000612 llvm_unreachable("We don't need a relocation in this case.");
Rafael Espindola00074892010-09-17 22:34:41 +0000613 return;
614 }
615
Rafael Espindola3729d002010-10-05 23:57:26 +0000616 bool RelocOnSymbol = ShouldRelocOnSymbol(SD, Target, *Fragment);
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000617 if (!RelocOnSymbol) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000618 Index = F->getParent()->getOrdinal();
Rafael Espindolaa6489182010-09-24 21:19:03 +0000619
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000620 MCSectionData *FSD = F->getParent();
621 // Offset of the symbol in the section
622 Value += Layout.getSymbolAddress(&SD) - Layout.getSectionAddress(FSD);
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000623 } else {
624 UsedInReloc.insert(Symbol);
625 Index = -1;
626 }
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000627 Addend = Value;
628 // Compensate for the addend on i386.
629 if (Is64Bit)
630 Value = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000631 }
632
Benjamin Kramer95c602a2010-08-27 10:38:39 +0000633 FixedValue = Value;
634
Matt Fleming3565a062010-08-16 18:57:57 +0000635 // determine the type of the relocation
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000636
637 MCSymbolRefExpr::VariantKind Modifier = Target.getSymA()->getKind();
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000638 unsigned Type;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000639 if (Is64Bit) {
640 if (IsPCRel) {
Rafael Espindola92bf6682010-10-04 19:04:13 +0000641 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000642 default:
643 llvm_unreachable("Unimplemented");
Rafael Espindola92bf6682010-10-04 19:04:13 +0000644 case MCSymbolRefExpr::VK_None:
645 Type = ELF::R_X86_64_PC32;
646 break;
647 case MCSymbolRefExpr::VK_PLT:
648 Type = ELF::R_X86_64_PLT32;
649 break;
Rafael Espindola607d1f62010-10-04 19:51:39 +0000650 case llvm::MCSymbolRefExpr::VK_GOTPCREL:
651 Type = ELF::R_X86_64_GOTPCREL;
652 break;
Rafael Espindola92bf6682010-10-04 19:04:13 +0000653 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000654 } else {
655 switch ((unsigned)Fixup.getKind()) {
656 default: llvm_unreachable("invalid fixup kind!");
657 case FK_Data_8: Type = ELF::R_X86_64_64; break;
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000658 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000659 case X86::reloc_pcrel_4byte:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000660 assert(isInt<32>(Target.getConstant()));
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000661 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000662 default:
663 llvm_unreachable("Unimplemented");
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000664 case MCSymbolRefExpr::VK_None:
665 Type = ELF::R_X86_64_32S;
666 break;
667 case MCSymbolRefExpr::VK_GOT:
668 Type = ELF::R_X86_64_GOT32;
669 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000670 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola8cecf252010-10-06 16:23:36 +0000671 Type = ELF::R_X86_64_GOTPCREL;
672 break;
Rafael Espindola28f9ac82010-10-04 18:44:25 +0000673 }
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000674 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000675 case FK_Data_4:
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000676 Type = ELF::R_X86_64_32;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000677 break;
678 case FK_Data_2: Type = ELF::R_X86_64_16; break;
679 case X86::reloc_pcrel_1byte:
680 case FK_Data_1: Type = ELF::R_X86_64_8; break;
681 }
682 }
Matt Fleming3565a062010-08-16 18:57:57 +0000683 } else {
Benjamin Kramere5b57342010-08-17 18:20:28 +0000684 if (IsPCRel) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000685 switch (Modifier) {
686 default:
Rafael Espindola9baee3b2010-10-18 18:03:28 +0000687 Type = ELF::R_386_PC32;
688 //llvm_unreachable("Unimplemented");
689 break;
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000690 case MCSymbolRefExpr::VK_PLT:
691 Type = ELF::R_386_PLT32;
692 break;
693 }
Benjamin Kramere5b57342010-08-17 18:20:28 +0000694 } else {
695 switch ((unsigned)Fixup.getKind()) {
696 default: llvm_unreachable("invalid fixup kind!");
Rafael Espindolaa8c02c32010-09-30 03:11:42 +0000697
698 // FIXME: Should we avoid selecting reloc_signed_4byte in 32 bit mode
699 // instead?
700 case X86::reloc_signed_4byte:
Benjamin Kramere5b57342010-08-17 18:20:28 +0000701 case X86::reloc_pcrel_4byte:
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000702 switch (Modifier) {
Rafael Espindola9edab3a2010-10-18 16:58:03 +0000703 default:
704 llvm_unreachable("Unimplemented");
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000705 case MCSymbolRefExpr::VK_GOTOFF:
706 Type = ELF::R_386_GOTOFF;
707 break;
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000708 }
709 break;
Rafael Espindolaaa85c212010-10-18 18:36:12 +0000710 case FK_Data_4:
711 if (Symbol->getName() == "_GLOBAL_OFFSET_TABLE_")
712 Type = ELF::R_386_GOTPC;
713 else
714 Type = ELF::R_386_32;
715 break;
Benjamin Kramere5b57342010-08-17 18:20:28 +0000716 case FK_Data_2: Type = ELF::R_386_16; break;
717 case X86::reloc_pcrel_1byte:
718 case FK_Data_1: Type = ELF::R_386_8; break;
719 }
Matt Fleming3565a062010-08-16 18:57:57 +0000720 }
721 }
722
Rafael Espindola5c77c162010-10-05 15:48:37 +0000723 if (RelocNeedsGOT(Type))
724 NeedsGOT = true;
725
Benjamin Kramere5b57342010-08-17 18:20:28 +0000726 ELFRelocationEntry ERE;
727
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000728 ERE.Index = Index;
729 ERE.Type = Type;
730 ERE.Symbol = Symbol;
Matt Fleming3565a062010-08-16 18:57:57 +0000731
Benjamin Kramer63d37b92010-08-26 17:23:02 +0000732 ERE.r_offset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Benjamin Kramere5b57342010-08-17 18:20:28 +0000733
Matt Fleming3565a062010-08-16 18:57:57 +0000734 if (HasRelocationAddend)
735 ERE.r_addend = Addend;
Benjamin Kramer172d7d62010-08-17 00:33:24 +0000736 else
737 ERE.r_addend = 0; // Silence compiler warning.
Matt Fleming3565a062010-08-16 18:57:57 +0000738
739 Relocations[Fragment->getParent()].push_back(ERE);
740}
741
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000742uint64_t
743ELFObjectWriterImpl::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
744 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000745 MCSymbolData &SD = Asm.getSymbolData(*S);
Eli Friedmanf8020a32010-08-16 19:15:06 +0000746
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000747 // Local symbol.
748 if (!SD.isExternal() && !S->isUndefined())
749 return SD.getIndex() + /* empty symbol */ 1;
750
751 // External or undefined symbol.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000752 return SD.getIndex() + NumRegularSections + /* empty symbol */ 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000753}
754
Rafael Espindola737cd212010-10-05 18:01:23 +0000755static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
756 bool Used) {
757 const MCSymbol &Symbol = Data.getSymbol();
758 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
759 return false;
760
761 if (!Used && Symbol.isTemporary())
762 return false;
763
764 return true;
765}
766
767static bool isLocal(const MCSymbolData &Data) {
768 if (Data.isExternal())
769 return false;
770
771 const MCSymbol &Symbol = Data.getSymbol();
772 if (Symbol.isUndefined() && !Symbol.isVariable())
773 return false;
774
775 return true;
776}
777
Matt Fleming3565a062010-08-16 18:57:57 +0000778void ELFObjectWriterImpl::ComputeSymbolTable(MCAssembler &Asm) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000779 // FIXME: Is this the correct place to do this?
780 if (NeedsGOT) {
781 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
782 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
783 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
784 Data.setExternal(true);
785 }
786
Matt Fleming3565a062010-08-16 18:57:57 +0000787 // Build section lookup table.
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000788 NumRegularSections = Asm.size();
Rafael Espindolaf5c347d2010-10-05 21:20:07 +0000789 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
Matt Fleming3565a062010-08-16 18:57:57 +0000790 unsigned Index = 1;
791 for (MCAssembler::iterator it = Asm.begin(),
792 ie = Asm.end(); it != ie; ++it, ++Index)
793 SectionIndexMap[&it->getSection()] = Index;
794
795 // Index 0 is always the empty string.
796 StringMap<uint64_t> StringIndexMap;
797 StringTable += '\x00';
798
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000799 // Add the data for the symbols.
Matt Fleming3565a062010-08-16 18:57:57 +0000800 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
801 ie = Asm.symbol_end(); it != ie; ++it) {
802 const MCSymbol &Symbol = it->getSymbol();
803
Rafael Espindola737cd212010-10-05 18:01:23 +0000804 if (!isInSymtab(Asm, *it, UsedInReloc.count(&Symbol)))
Matt Fleming3565a062010-08-16 18:57:57 +0000805 continue;
806
Matt Fleming3565a062010-08-16 18:57:57 +0000807 ELFSymbolData MSD;
808 MSD.SymbolData = it;
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000809 bool Local = isLocal(*it);
Matt Fleming3565a062010-08-16 18:57:57 +0000810
Rafael Espindola5df0b652010-10-15 15:39:06 +0000811 bool Add = false;
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000812 if (it->isCommon()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000813 assert(!Local);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000814 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola5df0b652010-10-15 15:39:06 +0000815 Add = true;
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000816 } else if (Symbol.isAbsolute()) {
817 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola5df0b652010-10-15 15:39:06 +0000818 Add = true;
Rafael Espindola01f9ea32010-10-05 22:26:43 +0000819 } else if (Symbol.isVariable()) {
Rafael Espindolade89b012010-10-15 18:25:33 +0000820 const MCSymbol &RefSymbol = AliasedSymbol(Symbol);
Rafael Espindola01f9ea32010-10-05 22:26:43 +0000821 if (RefSymbol.isDefined()) {
822 MSD.SectionIndex = SectionIndexMap.lookup(&RefSymbol.getSection());
823 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000824 Add = true;
Rafael Espindola01f9ea32010-10-05 22:26:43 +0000825 }
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000826 } else if (Symbol.isUndefined()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000827 assert(!Local);
Matt Fleming3565a062010-08-16 18:57:57 +0000828 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindolae15eb4e2010-09-23 19:55:14 +0000829 // FIXME: Undefined symbols are global, but this is the first place we
830 // are able to set it.
831 if (GetBinding(*it) == ELF::STB_LOCAL)
832 SetBinding(*it, ELF::STB_GLOBAL);
Rafael Espindola5df0b652010-10-15 15:39:06 +0000833 Add = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000834 } else {
835 MSD.SectionIndex = SectionIndexMap.lookup(&Symbol.getSection());
836 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000837 Add = true;
838 }
839
840 if (Add) {
841 uint64_t &Entry = StringIndexMap[Symbol.getName()];
842 if (!Entry) {
843 Entry = StringTable.size();
844 StringTable += Symbol.getName();
845 StringTable += '\x00';
846 }
847 MSD.StringIndex = Entry;
848 if (MSD.SectionIndex == ELF::SHN_UNDEF)
849 UndefinedSymbolData.push_back(MSD);
850 else if (Local)
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000851 LocalSymbolData.push_back(MSD);
852 else
853 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000854 }
855 }
856
857 // Symbols are required to be in lexicographic order.
858 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
859 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
860 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
861
862 // Set the symbol indices. Local symbols must come before all other
863 // symbols with non-local bindings.
864 Index = 0;
865 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
866 LocalSymbolData[i].SymbolData->setIndex(Index++);
867 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
868 ExternalSymbolData[i].SymbolData->setIndex(Index++);
869 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
870 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
871}
872
873void ELFObjectWriterImpl::WriteRelocation(MCAssembler &Asm, MCAsmLayout &Layout,
874 const MCSectionData &SD) {
875 if (!Relocations[&SD].empty()) {
876 MCContext &Ctx = Asm.getContext();
877 const MCSection *RelaSection;
878 const MCSectionELF &Section =
879 static_cast<const MCSectionELF&>(SD.getSection());
880
881 const StringRef SectionName = Section.getSectionName();
Benjamin Kramer377a5722010-08-17 17:30:07 +0000882 std::string RelaSectionName = HasRelocationAddend ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000883 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000884
885 unsigned EntrySize;
886 if (HasRelocationAddend)
887 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
888 else
889 EntrySize = Is64Bit ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000890
Benjamin Kramer377a5722010-08-17 17:30:07 +0000891 RelaSection = Ctx.getELFSection(RelaSectionName, HasRelocationAddend ?
892 ELF::SHT_RELA : ELF::SHT_REL, 0,
Matt Fleming3565a062010-08-16 18:57:57 +0000893 SectionKind::getReadOnly(),
894 false, EntrySize);
895
896 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Benjamin Kramera9eadca2010-09-06 16:11:52 +0000897 RelaSD.setAlignment(Is64Bit ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +0000898
899 MCDataFragment *F = new MCDataFragment(&RelaSD);
900
901 WriteRelocationsFragment(Asm, F, &SD);
902
Rafael Espindola70703872010-09-30 02:22:20 +0000903 Asm.AddSectionToTheEnd(*Writer, RelaSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000904 }
905}
906
907void ELFObjectWriterImpl::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
908 uint64_t Flags, uint64_t Address,
909 uint64_t Offset, uint64_t Size,
910 uint32_t Link, uint32_t Info,
911 uint64_t Alignment,
912 uint64_t EntrySize) {
913 Write32(Name); // sh_name: index into string table
914 Write32(Type); // sh_type
915 WriteWord(Flags); // sh_flags
916 WriteWord(Address); // sh_addr
917 WriteWord(Offset); // sh_offset
918 WriteWord(Size); // sh_size
919 Write32(Link); // sh_link
920 Write32(Info); // sh_info
921 WriteWord(Alignment); // sh_addralign
922 WriteWord(EntrySize); // sh_entsize
923}
924
925void ELFObjectWriterImpl::WriteRelocationsFragment(const MCAssembler &Asm,
926 MCDataFragment *F,
927 const MCSectionData *SD) {
928 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
929 // sort by the r_offset just like gnu as does
930 array_pod_sort(Relocs.begin(), Relocs.end());
931
932 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
933 ELFRelocationEntry entry = Relocs[e - i - 1];
934
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000935 if (entry.Index < 0)
936 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
937 else
938 entry.Index += LocalSymbolData.size() + 1;
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000939 if (Is64Bit) {
940 char buf[8];
Matt Fleming3565a062010-08-16 18:57:57 +0000941
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000942 String64(buf, entry.r_offset);
943 F->getContents() += StringRef(buf, 8);
944
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000945 struct ELF::Elf64_Rela ERE64;
946 ERE64.setSymbolAndType(entry.Index, entry.Type);
947 String64(buf, ERE64.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000948 F->getContents() += StringRef(buf, 8);
949
950 if (HasRelocationAddend) {
951 String64(buf, entry.r_addend);
952 F->getContents() += StringRef(buf, 8);
953 }
954 } else {
955 char buf[4];
956
957 String32(buf, entry.r_offset);
958 F->getContents() += StringRef(buf, 4);
959
Rafael Espindola8f413fa2010-10-05 15:11:03 +0000960 struct ELF::Elf32_Rela ERE32;
961 ERE32.setSymbolAndType(entry.Index, entry.Type);
962 String32(buf, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +0000963 F->getContents() += StringRef(buf, 4);
964
965 if (HasRelocationAddend) {
966 String32(buf, entry.r_addend);
967 F->getContents() += StringRef(buf, 4);
968 }
969 }
Matt Fleming3565a062010-08-16 18:57:57 +0000970 }
971}
972
973void ELFObjectWriterImpl::CreateMetadataSections(MCAssembler &Asm,
974 MCAsmLayout &Layout) {
975 MCContext &Ctx = Asm.getContext();
976 MCDataFragment *F;
977
Matt Fleming3565a062010-08-16 18:57:57 +0000978 const MCSection *SymtabSection;
979 unsigned EntrySize = Is64Bit ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
980
Rafael Espindola71859c62010-09-16 19:46:31 +0000981 unsigned NumRegularSections = Asm.size();
982
Rafael Espindola38738bf2010-09-22 19:04:41 +0000983 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola71859c62010-09-16 19:46:31 +0000984 const MCSection *ShstrtabSection;
985 ShstrtabSection = Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
986 SectionKind::getReadOnly(), false);
987 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
988 ShstrtabSD.setAlignment(1);
989 ShstrtabIndex = Asm.size();
990
Matt Fleming3565a062010-08-16 18:57:57 +0000991 SymtabSection = Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
992 SectionKind::getReadOnly(),
993 false, EntrySize);
Matt Fleming3565a062010-08-16 18:57:57 +0000994 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Matt Fleming3565a062010-08-16 18:57:57 +0000995 SymtabSD.setAlignment(Is64Bit ? 8 : 4);
996
Matt Fleming3565a062010-08-16 18:57:57 +0000997 const MCSection *StrtabSection;
998 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
999 SectionKind::getReadOnly(), false);
Matt Fleming3565a062010-08-16 18:57:57 +00001000 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1001 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +00001002 StringTableIndex = Asm.size();
1003
Rafael Espindolac3c413f2010-09-27 22:04:54 +00001004 WriteRelocations(Asm, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +00001005
1006 // Symbol table
1007 F = new MCDataFragment(&SymtabSD);
1008 WriteSymbolTable(F, Asm, Layout, NumRegularSections);
Rafael Espindola70703872010-09-30 02:22:20 +00001009 Asm.AddSectionToTheEnd(*Writer, SymtabSD, Layout);
Rafael Espindola71859c62010-09-16 19:46:31 +00001010
Matt Fleming3565a062010-08-16 18:57:57 +00001011 F = new MCDataFragment(&StrtabSD);
1012 F->getContents().append(StringTable.begin(), StringTable.end());
Rafael Espindola70703872010-09-30 02:22:20 +00001013 Asm.AddSectionToTheEnd(*Writer, StrtabSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +00001014
Matt Fleming3565a062010-08-16 18:57:57 +00001015 F = new MCDataFragment(&ShstrtabSD);
1016
Matt Fleming3565a062010-08-16 18:57:57 +00001017 // Section header string table.
1018 //
1019 // The first entry of a string table holds a null character so skip
1020 // section 0.
1021 uint64_t Index = 1;
1022 F->getContents() += '\x00';
1023
1024 for (MCAssembler::const_iterator it = Asm.begin(),
1025 ie = Asm.end(); it != ie; ++it) {
Matt Fleming3565a062010-08-16 18:57:57 +00001026 const MCSectionELF &Section =
Benjamin Kramer368ae7e2010-08-17 00:00:46 +00001027 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola51efe7a2010-09-23 14:14:56 +00001028 // FIXME: We could merge suffixes like in .text and .rela.text.
Matt Fleming3565a062010-08-16 18:57:57 +00001029
1030 // Remember the index into the string table so we can write it
1031 // into the sh_name field of the section header table.
1032 SectionStringTableIndex[&it->getSection()] = Index;
1033
1034 Index += Section.getSectionName().size() + 1;
1035 F->getContents() += Section.getSectionName();
1036 F->getContents() += '\x00';
1037 }
1038
Rafael Espindola70703872010-09-30 02:22:20 +00001039 Asm.AddSectionToTheEnd(*Writer, ShstrtabSD, Layout);
1040}
1041
1042bool ELFObjectWriterImpl::IsFixupFullyResolved(const MCAssembler &Asm,
1043 const MCValue Target,
1044 bool IsPCRel,
1045 const MCFragment *DF) const {
1046 // If this is a PCrel relocation, find the section this fixup value is
1047 // relative to.
1048 const MCSection *BaseSection = 0;
1049 if (IsPCRel) {
1050 BaseSection = &DF->getParent()->getSection();
1051 assert(BaseSection);
1052 }
1053
1054 const MCSection *SectionA = 0;
1055 const MCSymbol *SymbolA = 0;
1056 if (const MCSymbolRefExpr *A = Target.getSymA()) {
1057 SymbolA = &A->getSymbol();
1058 SectionA = &SymbolA->getSection();
1059 }
1060
1061 const MCSection *SectionB = 0;
1062 if (const MCSymbolRefExpr *B = Target.getSymB()) {
1063 SectionB = &B->getSymbol().getSection();
1064 }
1065
1066 if (!BaseSection)
1067 return SectionA == SectionB;
1068
1069 const MCSymbolData &DataA = Asm.getSymbolData(*SymbolA);
1070 if (DataA.isExternal())
1071 return false;
1072
1073 return !SectionB && BaseSection == SectionA;
Matt Fleming3565a062010-08-16 18:57:57 +00001074}
1075
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001076void ELFObjectWriterImpl::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001077 const MCAsmLayout &Layout) {
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001078 // Compute symbol table information.
1079 ComputeSymbolTable(Asm);
1080
Matt Fleming3565a062010-08-16 18:57:57 +00001081 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1082 const_cast<MCAsmLayout&>(Layout));
1083
1084 // Add 1 for the null section.
1085 unsigned NumSections = Asm.size() + 1;
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001086 uint64_t NaturalAlignment = Is64Bit ? 8 : 4;
1087 uint64_t HeaderSize = Is64Bit ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr);
1088 uint64_t FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001089
1090 for (MCAssembler::const_iterator it = Asm.begin(),
1091 ie = Asm.end(); it != ie; ++it) {
1092 const MCSectionData &SD = *it;
Matt Fleming3565a062010-08-16 18:57:57 +00001093
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001094 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1095
Matt Fleming3565a062010-08-16 18:57:57 +00001096 // Get the size of the section in the output file (including padding).
1097 uint64_t Size = Layout.getSectionFileSize(&SD);
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001098
1099 FileOff += Size;
Matt Fleming3565a062010-08-16 18:57:57 +00001100 }
1101
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001102 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1103
Matt Fleming3565a062010-08-16 18:57:57 +00001104 // Write out the ELF header ...
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001105 WriteHeader(FileOff - HeaderSize, NumSections);
1106
1107 FileOff = HeaderSize;
Matt Fleming3565a062010-08-16 18:57:57 +00001108
1109 // ... then all of the sections ...
1110 DenseMap<const MCSection*, uint64_t> SectionOffsetMap;
1111
Rafael Espindolad8e0bfe2010-10-06 22:28:19 +00001112 DenseMap<const MCSection*, uint32_t> SectionIndexMap;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001113
1114 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001115 for (MCAssembler::const_iterator it = Asm.begin(),
1116 ie = Asm.end(); it != ie; ++it) {
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001117 const MCSectionData &SD = *it;
1118
1119 uint64_t Padding = OffsetToAlignment(FileOff, SD.getAlignment());
1120 WriteZeros(Padding);
1121 FileOff += Padding;
1122
Matt Fleming3565a062010-08-16 18:57:57 +00001123 // Remember the offset into the file for this section.
1124 SectionOffsetMap[&it->getSection()] = FileOff;
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001125 SectionIndexMap[&it->getSection()] = Index++;
1126
Matt Fleming3565a062010-08-16 18:57:57 +00001127 FileOff += Layout.getSectionFileSize(&SD);
1128
1129 Asm.WriteSectionData(it, Layout, Writer);
1130 }
1131
Benjamin Kramera9eadca2010-09-06 16:11:52 +00001132 uint64_t Padding = OffsetToAlignment(FileOff, NaturalAlignment);
1133 WriteZeros(Padding);
1134 FileOff += Padding;
1135
Matt Fleming3565a062010-08-16 18:57:57 +00001136 // ... and then the section header table.
1137 // Should we align the section header table?
1138 //
1139 // Null section first.
1140 WriteSecHdrEntry(0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
1141
1142 for (MCAssembler::const_iterator it = Asm.begin(),
1143 ie = Asm.end(); it != ie; ++it) {
1144 const MCSectionData &SD = *it;
1145 const MCSectionELF &Section =
1146 static_cast<const MCSectionELF&>(SD.getSection());
1147
1148 uint64_t sh_link = 0;
1149 uint64_t sh_info = 0;
1150
1151 switch(Section.getType()) {
1152 case ELF::SHT_DYNAMIC:
1153 sh_link = SectionStringTableIndex[&it->getSection()];
1154 sh_info = 0;
1155 break;
1156
1157 case ELF::SHT_REL:
Eli Friedmanf8020a32010-08-16 19:15:06 +00001158 case ELF::SHT_RELA: {
Matt Fleming3565a062010-08-16 18:57:57 +00001159 const MCSection *SymtabSection;
1160 const MCSection *InfoSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001161
1162 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1163 SectionKind::getReadOnly(),
Eli Friedmanf8020a32010-08-16 19:15:06 +00001164 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001165 sh_link = SectionIndexMap[SymtabSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001166
Benjamin Kramer377a5722010-08-17 17:30:07 +00001167 // Remove ".rel" and ".rela" prefixes.
1168 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1169 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1170
Eli Friedmanf8020a32010-08-16 19:15:06 +00001171 InfoSection = Asm.getContext().getELFSection(SectionName,
Matt Fleming3565a062010-08-16 18:57:57 +00001172 ELF::SHT_PROGBITS, 0,
Eli Friedmanf8020a32010-08-16 19:15:06 +00001173 SectionKind::getReadOnly(),
1174 false);
Benjamin Kramer44cbde82010-08-19 13:44:49 +00001175 sh_info = SectionIndexMap[InfoSection];
Matt Fleming3565a062010-08-16 18:57:57 +00001176 break;
Eli Friedmanf8020a32010-08-16 19:15:06 +00001177 }
Matt Fleming3565a062010-08-16 18:57:57 +00001178
1179 case ELF::SHT_SYMTAB:
1180 case ELF::SHT_DYNSYM:
1181 sh_link = StringTableIndex;
1182 sh_info = LastLocalSymbolIndex;
1183 break;
1184
1185 case ELF::SHT_PROGBITS:
1186 case ELF::SHT_STRTAB:
1187 case ELF::SHT_NOBITS:
Benjamin Kramer19dc7fa2010-08-31 17:03:33 +00001188 case ELF::SHT_NULL:
Matt Fleming3565a062010-08-16 18:57:57 +00001189 // Nothing to do.
1190 break;
1191
1192 case ELF::SHT_HASH:
1193 case ELF::SHT_GROUP:
1194 case ELF::SHT_SYMTAB_SHNDX:
1195 default:
1196 assert(0 && "FIXME: sh_type value not supported!");
1197 break;
1198 }
1199
1200 WriteSecHdrEntry(SectionStringTableIndex[&it->getSection()],
1201 Section.getType(), Section.getFlags(),
Rafael Espindola71859c62010-09-16 19:46:31 +00001202 0,
Matt Fleming3565a062010-08-16 18:57:57 +00001203 SectionOffsetMap.lookup(&SD.getSection()),
1204 Layout.getSectionSize(&SD), sh_link,
1205 sh_info, SD.getAlignment(),
1206 Section.getEntrySize());
1207 }
1208}
1209
1210ELFObjectWriter::ELFObjectWriter(raw_ostream &OS,
1211 bool Is64Bit,
Roman Divacky5baf79e2010-09-09 17:57:50 +00001212 Triple::OSType OSType,
Matt Fleming3565a062010-08-16 18:57:57 +00001213 bool IsLittleEndian,
1214 bool HasRelocationAddend)
1215 : MCObjectWriter(OS, IsLittleEndian)
1216{
Roman Divacky5baf79e2010-09-09 17:57:50 +00001217 Impl = new ELFObjectWriterImpl(this, Is64Bit, HasRelocationAddend, OSType);
Matt Fleming3565a062010-08-16 18:57:57 +00001218}
1219
1220ELFObjectWriter::~ELFObjectWriter() {
1221 delete (ELFObjectWriterImpl*) Impl;
1222}
1223
1224void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm) {
1225 ((ELFObjectWriterImpl*) Impl)->ExecutePostLayoutBinding(Asm);
1226}
1227
1228void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
1229 const MCAsmLayout &Layout,
1230 const MCFragment *Fragment,
1231 const MCFixup &Fixup, MCValue Target,
1232 uint64_t &FixedValue) {
1233 ((ELFObjectWriterImpl*) Impl)->RecordRelocation(Asm, Layout, Fragment, Fixup,
1234 Target, FixedValue);
1235}
1236
Rafael Espindola70703872010-09-30 02:22:20 +00001237bool ELFObjectWriter::IsFixupFullyResolved(const MCAssembler &Asm,
1238 const MCValue Target,
1239 bool IsPCRel,
1240 const MCFragment *DF) const {
1241 return ((ELFObjectWriterImpl*) Impl)->IsFixupFullyResolved(Asm, Target,
1242 IsPCRel, DF);
1243}
1244
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001245void ELFObjectWriter::WriteObject(MCAssembler &Asm,
Matt Fleming3565a062010-08-16 18:57:57 +00001246 const MCAsmLayout &Layout) {
1247 ((ELFObjectWriterImpl*) Impl)->WriteObject(Asm, Layout);
1248}