blob: 36f94b4184c2d282e3d35425da8652ab2a9cde8c [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
Rafael Espindola3963d612011-12-22 03:38:00 +000014#include "MCELF.h"
15#include "llvm/ADT/OwningPtr.h"
16#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallString.h"
Matt Fleming3565a062010-08-16 18:57:57 +000018#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/StringMap.h"
20#include "llvm/ADT/Twine.h"
Evan Cheng78c10ee2011-07-25 23:24:55 +000021#include "llvm/MC/MCAsmBackend.h"
Matt Fleming3565a062010-08-16 18:57:57 +000022#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola3963d612011-12-22 03:38:00 +000023#include "llvm/MC/MCAssembler.h"
Matt Fleming3565a062010-08-16 18:57:57 +000024#include "llvm/MC/MCContext.h"
Rafael Espindola3963d612011-12-22 03:38:00 +000025#include "llvm/MC/MCELFObjectWriter.h"
26#include "llvm/MC/MCELFSymbolFlags.h"
Matt Fleming3565a062010-08-16 18:57:57 +000027#include "llvm/MC/MCExpr.h"
Matt Fleming3565a062010-08-16 18:57:57 +000028#include "llvm/MC/MCSectionELF.h"
Matt Fleming3565a062010-08-16 18:57:57 +000029#include "llvm/MC/MCValue.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/ELF.h"
Jason W Kime964d112011-05-11 22:53:06 +000033#include "llvm/Support/CommandLine.h"
Evan Chenga7cfc082011-07-23 00:45:41 +000034#include "llvm/ADT/StringSwitch.h"
Matt Fleming3565a062010-08-16 18:57:57 +000035
Matt Fleming3565a062010-08-16 18:57:57 +000036#include <vector>
37using namespace llvm;
38
Jason W Kime964d112011-05-11 22:53:06 +000039#undef DEBUG_TYPE
40#define DEBUG_TYPE "reloc-info"
41
Rafael Espindola3963d612011-12-22 03:38:00 +000042namespace {
43class ELFObjectWriter : public MCObjectWriter {
44 protected:
45
46 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
47 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
48 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
49 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
50 bool Used, bool Renamed);
51 static bool isLocal(const MCSymbolData &Data, bool isSignature,
52 bool isUsedInReloc);
53 static bool IsELFMetaDataSection(const MCSectionData &SD);
54 static uint64_t DataSectionSize(const MCSectionData &SD);
55 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
56 const MCSectionData &SD);
57 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
58 const MCSectionData &SD);
59
60 void WriteDataSectionData(MCAssembler &Asm,
61 const MCAsmLayout &Layout,
62 const MCSectionELF &Section);
63
64 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
65 return Kind == X86::reloc_riprel_4byte ||
66 Kind == X86::reloc_riprel_4byte_movq_load;
67 }*/
68
69 /// ELFSymbolData - Helper struct for containing some precomputed
70 /// information on symbols.
71 struct ELFSymbolData {
72 MCSymbolData *SymbolData;
73 uint64_t StringIndex;
74 uint32_t SectionIndex;
75
76 // Support lexicographic sorting.
77 bool operator<(const ELFSymbolData &RHS) const {
78 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
79 return true;
80 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
81 return false;
82 return SymbolData->getSymbol().getName() <
83 RHS.SymbolData->getSymbol().getName();
84 }
85 };
86
87 /// @name Relocation Data
88 /// @{
89
90 struct ELFRelocationEntry {
91 // Make these big enough for both 32-bit and 64-bit
92 uint64_t r_offset;
93 int Index;
94 unsigned Type;
95 const MCSymbol *Symbol;
96 uint64_t r_addend;
97
98 ELFRelocationEntry()
99 : r_offset(0), Index(0), Type(0), Symbol(0), r_addend(0) {}
100
101 ELFRelocationEntry(uint64_t RelocOffset, int Idx,
102 unsigned RelType, const MCSymbol *Sym,
103 uint64_t Addend)
104 : r_offset(RelocOffset), Index(Idx), Type(RelType),
105 Symbol(Sym), r_addend(Addend) {}
106
107 // Support lexicographic sorting.
108 bool operator<(const ELFRelocationEntry &RE) const {
109 return RE.r_offset < r_offset;
110 }
111 };
112
113 /// The target specific ELF writer instance.
114 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
115
116 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
117 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
118 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
119
120 llvm::DenseMap<const MCSectionData*,
121 std::vector<ELFRelocationEntry> > Relocations;
122 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
123
124 /// @}
125 /// @name Symbol Table Data
126 /// @{
127
128 SmallString<256> StringTable;
129 std::vector<ELFSymbolData> LocalSymbolData;
130 std::vector<ELFSymbolData> ExternalSymbolData;
131 std::vector<ELFSymbolData> UndefinedSymbolData;
132
133 /// @}
134
135 bool NeedsGOT;
136
137 bool NeedsSymtabShndx;
138
139 // This holds the symbol table index of the last local symbol.
140 unsigned LastLocalSymbolIndex;
141 // This holds the .strtab section index.
142 unsigned StringTableIndex;
143 // This holds the .symtab section index.
144 unsigned SymbolTableIndex;
145
146 unsigned ShstrtabIndex;
147
148
149 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
150 const MCValue &Target,
151 const MCFragment &F,
152 const MCFixup &Fixup,
153 bool IsPCRel) const;
154
155 // TargetObjectWriter wrappers.
156 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
157 const MCValue &Target,
158 const MCFragment &F,
159 const MCFixup &Fixup,
160 bool IsPCRel) const {
161 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
162 }
163
164 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
165 bool hasRelocationAddend() const {
166 return TargetObjectWriter->hasRelocationAddend();
167 }
168 unsigned getEFlags() const {
169 return TargetObjectWriter->getEFlags();
170 }
171 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
172 bool IsPCRel, bool IsRelocWithSymbol,
173 int64_t Addend) const {
174 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
175 IsRelocWithSymbol, Addend);
176 }
177
178
179 public:
180 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
181 raw_ostream &_OS, bool IsLittleEndian)
182 : MCObjectWriter(_OS, IsLittleEndian),
183 TargetObjectWriter(MOTW),
184 NeedsGOT(false), NeedsSymtabShndx(false){
185 }
186
187 virtual ~ELFObjectWriter();
188
189 void WriteWord(uint64_t W) {
190 if (is64Bit())
191 Write64(W);
192 else
193 Write32(W);
194 }
195
196 void StringLE16(char *buf, uint16_t Value) {
197 buf[0] = char(Value >> 0);
198 buf[1] = char(Value >> 8);
199 }
200
201 void StringLE32(char *buf, uint32_t Value) {
202 StringLE16(buf, uint16_t(Value >> 0));
203 StringLE16(buf + 2, uint16_t(Value >> 16));
204 }
205
206 void StringLE64(char *buf, uint64_t Value) {
207 StringLE32(buf, uint32_t(Value >> 0));
208 StringLE32(buf + 4, uint32_t(Value >> 32));
209 }
210
211 void StringBE16(char *buf ,uint16_t Value) {
212 buf[0] = char(Value >> 8);
213 buf[1] = char(Value >> 0);
214 }
215
216 void StringBE32(char *buf, uint32_t Value) {
217 StringBE16(buf, uint16_t(Value >> 16));
218 StringBE16(buf + 2, uint16_t(Value >> 0));
219 }
220
221 void StringBE64(char *buf, uint64_t Value) {
222 StringBE32(buf, uint32_t(Value >> 32));
223 StringBE32(buf + 4, uint32_t(Value >> 0));
224 }
225
226 void String8(MCDataFragment &F, uint8_t Value) {
227 char buf[1];
228 buf[0] = Value;
229 F.getContents() += StringRef(buf, 1);
230 }
231
232 void String16(MCDataFragment &F, uint16_t Value) {
233 char buf[2];
234 if (isLittleEndian())
235 StringLE16(buf, Value);
236 else
237 StringBE16(buf, Value);
238 F.getContents() += StringRef(buf, 2);
239 }
240
241 void String32(MCDataFragment &F, uint32_t Value) {
242 char buf[4];
243 if (isLittleEndian())
244 StringLE32(buf, Value);
245 else
246 StringBE32(buf, Value);
247 F.getContents() += StringRef(buf, 4);
248 }
249
250 void String64(MCDataFragment &F, uint64_t Value) {
251 char buf[8];
252 if (isLittleEndian())
253 StringLE64(buf, Value);
254 else
255 StringBE64(buf, Value);
256 F.getContents() += StringRef(buf, 8);
257 }
258
259 void WriteHeader(uint64_t SectionDataSize,
260 unsigned NumberOfSections);
261
262 void WriteSymbolEntry(MCDataFragment *SymtabF,
263 MCDataFragment *ShndxF,
264 uint64_t name, uint8_t info,
265 uint64_t value, uint64_t size,
266 uint8_t other, uint32_t shndx,
267 bool Reserved);
268
269 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
270 ELFSymbolData &MSD,
271 const MCAsmLayout &Layout);
272
273 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
274 void WriteSymbolTable(MCDataFragment *SymtabF,
275 MCDataFragment *ShndxF,
276 const MCAssembler &Asm,
277 const MCAsmLayout &Layout,
278 const SectionIndexMapTy &SectionIndexMap);
279
280 virtual void RecordRelocation(const MCAssembler &Asm,
281 const MCAsmLayout &Layout,
282 const MCFragment *Fragment,
283 const MCFixup &Fixup,
284 MCValue Target, uint64_t &FixedValue);
285
286 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
287 const MCSymbol *S);
288
289 // Map from a group section to the signature symbol
290 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
291 // Map from a signature symbol to the group section
292 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
293 // Map from a section to the section with the relocations
294 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
295 // Map from a section to its offset
296 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
297
298 /// ComputeSymbolTable - Compute the symbol table data
299 ///
300 /// \param StringTable [out] - The string table data.
301 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
302 /// string table.
303 void ComputeSymbolTable(MCAssembler &Asm,
304 const SectionIndexMapTy &SectionIndexMap,
305 RevGroupMapTy RevGroupMap,
306 unsigned NumRegularSections);
307
308 void ComputeIndexMap(MCAssembler &Asm,
309 SectionIndexMapTy &SectionIndexMap,
310 const RelMapTy &RelMap);
311
312 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
313 RelMapTy &RelMap);
314
315 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
316 const RelMapTy &RelMap);
317
318 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
319 SectionIndexMapTy &SectionIndexMap,
320 const RelMapTy &RelMap);
321
322 // Create the sections that show up in the symbol table. Currently
323 // those are the .note.GNU-stack section and the group sections.
324 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
325 GroupMapTy &GroupMap,
326 RevGroupMapTy &RevGroupMap,
327 SectionIndexMapTy &SectionIndexMap,
328 const RelMapTy &RelMap);
329
330 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
331 const MCAsmLayout &Layout);
332
333 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
334 const MCAsmLayout &Layout,
335 const SectionIndexMapTy &SectionIndexMap,
336 const SectionOffsetMapTy &SectionOffsetMap);
337
338 void ComputeSectionOrder(MCAssembler &Asm,
339 std::vector<const MCSectionELF*> &Sections);
340
341 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
342 uint64_t Address, uint64_t Offset,
343 uint64_t Size, uint32_t Link, uint32_t Info,
344 uint64_t Alignment, uint64_t EntrySize);
345
346 void WriteRelocationsFragment(const MCAssembler &Asm,
347 MCDataFragment *F,
348 const MCSectionData *SD);
349
350 virtual bool
351 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
352 const MCSymbolData &DataA,
353 const MCFragment &FB,
354 bool InSet,
355 bool IsPCRel) const;
356
357 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
358 void WriteSection(MCAssembler &Asm,
359 const SectionIndexMapTy &SectionIndexMap,
360 uint32_t GroupSymbolIndex,
361 uint64_t Offset, uint64_t Size, uint64_t Alignment,
362 const MCSectionELF &Section);
363 };
364}
365
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000366bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
367 const MCFixupKindInfo &FKI =
368 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
369
370 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
371}
372
373bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
374 switch (Variant) {
375 default:
376 return false;
377 case MCSymbolRefExpr::VK_GOT:
378 case MCSymbolRefExpr::VK_PLT:
379 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola378e0ec2011-06-05 01:20:06 +0000380 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000381 case MCSymbolRefExpr::VK_TPOFF:
382 case MCSymbolRefExpr::VK_TLSGD:
383 case MCSymbolRefExpr::VK_GOTTPOFF:
384 case MCSymbolRefExpr::VK_INDNTPOFF:
385 case MCSymbolRefExpr::VK_NTPOFF:
386 case MCSymbolRefExpr::VK_GOTNTPOFF:
387 case MCSymbolRefExpr::VK_TLSLDM:
388 case MCSymbolRefExpr::VK_DTPOFF:
389 case MCSymbolRefExpr::VK_TLSLD:
390 return true;
391 }
392}
393
Jason W Kimd3443e92010-11-15 16:18:39 +0000394ELFObjectWriter::~ELFObjectWriter()
395{}
396
Matt Fleming3565a062010-08-16 18:57:57 +0000397// Emit the ELF header.
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000398void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
399 unsigned NumberOfSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000400 // ELF Header
401 // ----------
402 //
403 // Note
404 // ----
405 // emitWord method behaves differently for ELF32 and ELF64, writing
406 // 4 bytes in the former and 8 in the latter.
407
408 Write8(0x7f); // e_ident[EI_MAG0]
409 Write8('E'); // e_ident[EI_MAG1]
410 Write8('L'); // e_ident[EI_MAG2]
411 Write8('F'); // e_ident[EI_MAG3]
412
Rafael Espindolabff66a82010-12-18 03:27:34 +0000413 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming3565a062010-08-16 18:57:57 +0000414
415 // e_ident[EI_DATA]
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000416 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming3565a062010-08-16 18:57:57 +0000417
418 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000419 // e_ident[EI_OSABI]
Rafael Espindoladc9a8a32011-12-21 17:00:36 +0000420 Write8(TargetObjectWriter->getOSABI());
Matt Fleming3565a062010-08-16 18:57:57 +0000421 Write8(0); // e_ident[EI_ABIVERSION]
422
423 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
424
425 Write16(ELF::ET_REL); // e_type
426
Rafael Espindolabff66a82010-12-18 03:27:34 +0000427 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000428
429 Write32(ELF::EV_CURRENT); // e_version
430 WriteWord(0); // e_entry, no entry point in .o file
431 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolabff66a82010-12-18 03:27:34 +0000432 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramereb976772010-08-17 17:02:29 +0000433 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000434
Jason W Kim2d7a53a2011-02-04 21:41:11 +0000435 // e_flags = whatever the target wants
Rafael Espindolae8526d02011-12-21 20:09:46 +0000436 Write32(getEFlags());
Matt Fleming3565a062010-08-16 18:57:57 +0000437
438 // e_ehsize = ELF header size
Rafael Espindolabff66a82010-12-18 03:27:34 +0000439 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming3565a062010-08-16 18:57:57 +0000440
441 Write16(0); // e_phentsize = prog header entry size
442 Write16(0); // e_phnum = # prog header entries = 0
443
444 // e_shentsize = Section header entry size
Rafael Espindolabff66a82010-12-18 03:27:34 +0000445 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming3565a062010-08-16 18:57:57 +0000446
447 // e_shnum = # of section header ents
Rafael Espindola7be2c332010-10-31 00:16:26 +0000448 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewyckyaaae3f62011-10-07 20:56:23 +0000449 Write16(ELF::SHN_UNDEF);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000450 else
451 Write16(NumberOfSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000452
453 // e_shstrndx = Section # of '.shstrtab'
Nick Lewyckyb3429d32011-10-07 20:58:24 +0000454 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola7be2c332010-10-31 00:16:26 +0000455 Write16(ELF::SHN_XINDEX);
456 else
457 Write16(ShstrtabIndex);
Matt Fleming3565a062010-08-16 18:57:57 +0000458}
459
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000460void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
461 MCDataFragment *ShndxF,
462 uint64_t name,
463 uint8_t info, uint64_t value,
464 uint64_t size, uint8_t other,
465 uint32_t shndx,
466 bool Reserved) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000467 if (ShndxF) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000468 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000469 String32(*ShndxF, shndx);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000470 else
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000471 String32(*ShndxF, 0);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000472 }
473
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000474 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
475 uint16_t(ELF::SHN_XINDEX) : shndx;
476
Rafael Espindolabff66a82010-12-18 03:27:34 +0000477 if (is64Bit()) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000478 String32(*SymtabF, name); // st_name
479 String8(*SymtabF, info); // st_info
480 String8(*SymtabF, other); // st_other
481 String16(*SymtabF, Index); // st_shndx
482 String64(*SymtabF, value); // st_value
483 String64(*SymtabF, size); // st_size
Matt Fleming3565a062010-08-16 18:57:57 +0000484 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000485 String32(*SymtabF, name); // st_name
486 String32(*SymtabF, value); // st_value
487 String32(*SymtabF, size); // st_size
488 String8(*SymtabF, info); // st_info
489 String8(*SymtabF, other); // st_other
490 String16(*SymtabF, Index); // st_shndx
Matt Fleming3565a062010-08-16 18:57:57 +0000491 }
492}
493
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000494uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
495 const MCAsmLayout &Layout) {
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000496 if (Data.isCommon() && Data.isExternal())
497 return Data.getCommonAlignment();
498
499 const MCSymbol &Symbol = Data.getSymbol();
Roman Divackyd1491862010-12-20 21:14:39 +0000500
501 if (Symbol.isAbsolute() && Symbol.isVariable()) {
502 if (const MCExpr *Value = Symbol.getVariableValue()) {
503 int64_t IntValue;
504 if (Value->EvaluateAsAbsolute(IntValue, Layout))
Jim Grosbachf68a26b2011-12-06 00:13:09 +0000505 return (uint64_t)IntValue;
Roman Divackyd1491862010-12-20 21:14:39 +0000506 }
507 }
508
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000509 if (!Symbol.isInSection())
510 return 0;
511
Rafael Espindola64695402011-05-16 16:17:21 +0000512
513 if (Data.getFragment()) {
514 if (Data.getFlags() & ELF_Other_ThumbFunc)
515 return Layout.getSymbolOffset(&Data)+1;
516 else
517 return Layout.getSymbolOffset(&Data);
518 }
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000519
520 return 0;
521}
522
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000523void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
524 const MCAsmLayout &Layout) {
Rafael Espindola88182132010-10-27 15:18:17 +0000525 // The presence of symbol versions causes undefined symbols and
526 // versions declared with @@@ to be renamed.
527
528 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
529 ie = Asm.symbol_end(); it != ie; ++it) {
530 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000531 const MCSymbol &Symbol = Alias.AliasedSymbol();
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000532 MCSymbolData &SD = Asm.getSymbolData(Symbol);
533
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000534 // Not an alias.
535 if (&Symbol == &Alias)
536 continue;
537
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000538 StringRef AliasName = Alias.getName();
Rafael Espindola88182132010-10-27 15:18:17 +0000539 size_t Pos = AliasName.find('@');
540 if (Pos == StringRef::npos)
541 continue;
542
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000543 // Aliases defined with .symvar copy the binding from the symbol they alias.
544 // This is the first place we are able to copy this information.
545 it->setExternal(SD.isExternal());
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000546 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000547
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000548 StringRef Rest = AliasName.substr(Pos);
Rafael Espindola88182132010-10-27 15:18:17 +0000549 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
550 continue;
551
Rafael Espindola83ff4d22010-10-27 17:56:18 +0000552 // FIXME: produce a better error message.
553 if (Symbol.isUndefined() && Rest.startswith("@@") &&
554 !Rest.startswith("@@@"))
555 report_fatal_error("A @@ version cannot be undefined");
556
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000557 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindola88182132010-10-27 15:18:17 +0000558 }
559}
560
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000561void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
562 MCDataFragment *ShndxF,
563 ELFSymbolData &MSD,
564 const MCAsmLayout &Layout) {
Rafael Espindola152c1062010-10-06 21:02:29 +0000565 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindolade89b012010-10-15 18:25:33 +0000566 MCSymbolData &Data =
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000567 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
Rafael Espindola152c1062010-10-06 21:02:29 +0000568
Rafael Espindola7be2c332010-10-31 00:16:26 +0000569 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
570 Data.getSymbol().isVariable();
571
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000572 uint8_t Binding = MCELF::GetBinding(OrigData);
573 uint8_t Visibility = MCELF::GetVisibility(OrigData);
574 uint8_t Type = MCELF::GetType(Data);
Rafael Espindola152c1062010-10-06 21:02:29 +0000575
576 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
577 uint8_t Other = Visibility;
578
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000579 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000580 uint64_t Size = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000581
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000582 assert(!(Data.isCommon() && !Data.isExternal()));
583
Rafael Espindolaf0121242010-12-22 16:03:00 +0000584 const MCExpr *ESize = Data.getSize();
585 if (ESize) {
586 int64_t Res;
587 if (!ESize->EvaluateAsAbsolute(Res, Layout))
588 report_fatal_error("Size expression must be absolute.");
589 Size = Res;
Matt Fleming3565a062010-08-16 18:57:57 +0000590 }
591
592 // Write out the symbol table entry
Rafael Espindola7be2c332010-10-31 00:16:26 +0000593 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
594 Size, Other, MSD.SectionIndex, IsReserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000595}
596
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000597void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
598 MCDataFragment *ShndxF,
599 const MCAssembler &Asm,
600 const MCAsmLayout &Layout,
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000601 const SectionIndexMapTy &SectionIndexMap) {
Matt Fleming3565a062010-08-16 18:57:57 +0000602 // The string table must be emitted first because we need the index
603 // into the string table for all the symbol names.
604 assert(StringTable.size() && "Missing string table");
605
606 // FIXME: Make sure the start of the symbol table is aligned.
607
608 // The first entry is the undefined symbol entry.
Rafael Espindola7be2c332010-10-31 00:16:26 +0000609 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
Matt Fleming3565a062010-08-16 18:57:57 +0000610
611 // Write the symbol table entries.
612 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
613 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
614 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola7be2c332010-10-31 00:16:26 +0000615 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000616 }
617
Rafael Espindola71859c62010-09-16 19:46:31 +0000618 // Write out a symbol table entry for each regular section.
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000619 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
620 ++i) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000621 const MCSectionELF &Section =
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000622 static_cast<const MCSectionELF&>(i->getSection());
623 if (Section.getType() == ELF::SHT_RELA ||
624 Section.getType() == ELF::SHT_REL ||
625 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewyckyd2fdb4a2011-10-07 23:29:53 +0000626 Section.getType() == ELF::SHT_SYMTAB ||
627 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedmana44fa242010-08-16 21:17:09 +0000628 continue;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000629 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000630 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
631 false);
Eli Friedmana44fa242010-08-16 21:17:09 +0000632 LastLocalSymbolIndex++;
633 }
Matt Fleming3565a062010-08-16 18:57:57 +0000634
635 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
636 ELFSymbolData &MSD = ExternalSymbolData[i];
637 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola3223f192010-10-06 16:47:31 +0000638 assert(((Data.getFlags() & ELF_STB_Global) ||
639 (Data.getFlags() & ELF_STB_Weak)) &&
640 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola7be2c332010-10-31 00:16:26 +0000641 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000642 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000643 LastLocalSymbolIndex++;
644 }
645
646 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
647 ELFSymbolData &MSD = UndefinedSymbolData[i];
648 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000649 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000650 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000651 LastLocalSymbolIndex++;
652 }
653}
654
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000655const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
656 const MCValue &Target,
Jason W Kime964d112011-05-11 22:53:06 +0000657 const MCFragment &F,
658 const MCFixup &Fixup,
659 bool IsPCRel) const {
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000660 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000661 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
662 const MCSymbol *Renamed = Renames.lookup(&Symbol);
663 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000664
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000665 if (ASymbol.isUndefined()) {
666 if (Renamed)
667 return Renamed;
668 return &ASymbol;
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000669 }
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000670
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000671 if (SD.isExternal()) {
672 if (Renamed)
673 return Renamed;
674 return &Symbol;
675 }
Rafael Espindola73ffea42010-09-25 05:42:19 +0000676
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000677 const MCSectionELF &Section =
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000678 static_cast<const MCSectionELF&>(ASymbol.getSection());
Rafael Espindola25958732010-11-24 21:57:39 +0000679 const SectionKind secKind = Section.getKind();
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000680
Rafael Espindola25958732010-11-24 21:57:39 +0000681 if (secKind.isBSS())
Jason W Kime964d112011-05-11 22:53:06 +0000682 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000683
Rafael Espindola25958732010-11-24 21:57:39 +0000684 if (secKind.isThreadLocal()) {
685 if (Renamed)
686 return Renamed;
687 return &Symbol;
688 }
689
Rafael Espindola8cecf252010-10-06 16:23:36 +0000690 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindola3729d002010-10-05 23:57:26 +0000691 const MCSectionELF &Sec2 =
692 static_cast<const MCSectionELF&>(F.getParent()->getSection());
693
Rafael Espindola8cecf252010-10-06 16:23:36 +0000694 if (&Sec2 != &Section &&
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000695 (Kind == MCSymbolRefExpr::VK_PLT ||
696 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
Rafael Espindola25958732010-11-24 21:57:39 +0000697 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000698 if (Renamed)
699 return Renamed;
700 return &Symbol;
701 }
Rafael Espindola3729d002010-10-05 23:57:26 +0000702
Rafael Espindola1c130262011-01-23 04:43:11 +0000703 if (Section.getFlags() & ELF::SHF_MERGE) {
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000704 if (Target.getConstant() == 0)
Jason W Kime964d112011-05-11 22:53:06 +0000705 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000706 if (Renamed)
707 return Renamed;
708 return &Symbol;
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000709 }
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000710
Jason W Kime964d112011-05-11 22:53:06 +0000711 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
712
Rafael Espindola73ffea42010-09-25 05:42:19 +0000713}
714
Matt Fleming3565a062010-08-16 18:57:57 +0000715
Jason W Kim56a39902010-12-06 21:57:34 +0000716void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
717 const MCAsmLayout &Layout,
718 const MCFragment *Fragment,
719 const MCFixup &Fixup,
720 MCValue Target,
721 uint64_t &FixedValue) {
722 int64_t Addend = 0;
723 int Index = 0;
724 int64_t Value = Target.getConstant();
725 const MCSymbol *RelocSymbol = NULL;
726
Rafael Espindola127a6a42010-12-17 07:28:17 +0000727 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Jason W Kim56a39902010-12-06 21:57:34 +0000728 if (!Target.isAbsolute()) {
729 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
730 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
Jason W Kime964d112011-05-11 22:53:06 +0000731 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
Jason W Kim56a39902010-12-06 21:57:34 +0000732
733 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
734 const MCSymbol &SymbolB = RefB->getSymbol();
735 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
736 IsPCRel = true;
737
738 // Offset of the symbol in the section
739 int64_t a = Layout.getSymbolOffset(&SDB);
740
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000741 // Offset of the relocation in the section
Jason W Kim56a39902010-12-06 21:57:34 +0000742 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
743 Value += b - a;
744 }
745
746 if (!RelocSymbol) {
747 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
748 MCFragment *F = SD.getFragment();
749
750 Index = F->getParent()->getOrdinal() + 1;
751
752 // Offset of the symbol in the section
753 Value += Layout.getSymbolOffset(&SD);
754 } else {
755 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
756 WeakrefUsedInReloc.insert(RelocSymbol);
757 else
758 UsedInReloc.insert(RelocSymbol);
759 Index = -1;
760 }
761 Addend = Value;
762 // Compensate for the addend on i386.
Rafael Espindolabff66a82010-12-18 03:27:34 +0000763 if (is64Bit())
Jason W Kim56a39902010-12-06 21:57:34 +0000764 Value = 0;
765 }
766
767 FixedValue = Value;
768 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
769 (RelocSymbol != 0), Addend);
Rafael Espindolac677e792011-12-21 14:26:29 +0000770 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
771 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
772 if (RelocNeedsGOT(Modifier))
773 NeedsGOT = true;
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000774
Jason W Kim56a39902010-12-06 21:57:34 +0000775 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
776 Fixup.getOffset();
Roman Divacky2a66cea2011-08-04 19:08:19 +0000777
Rafael Espindolaf3a86fb2011-12-22 01:57:09 +0000778 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
779 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
Jason W Kim56a39902010-12-06 21:57:34 +0000780
Rafael Espindolabff66a82010-12-18 03:27:34 +0000781 if (!hasRelocationAddend())
782 Addend = 0;
Rafael Espindolabbf9c4a2011-08-04 13:05:26 +0000783
784 if (is64Bit())
785 assert(isInt<64>(Addend));
786 else
787 assert(isInt<32>(Addend));
788
Jason W Kim56a39902010-12-06 21:57:34 +0000789 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend);
790 Relocations[Fragment->getParent()].push_back(ERE);
791}
792
793
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000794uint64_t
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000795ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
796 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000797 MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000798 return SD.getIndex();
Matt Fleming3565a062010-08-16 18:57:57 +0000799}
800
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000801bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
802 const MCSymbolData &Data,
803 bool Used, bool Renamed) {
Rafael Espindola484291c2010-11-01 14:28:48 +0000804 if (Data.getFlags() & ELF_Other_Weakref)
805 return false;
806
Rafael Espindolabd701182010-10-19 19:31:37 +0000807 if (Used)
808 return true;
809
Rafael Espindola88182132010-10-27 15:18:17 +0000810 if (Renamed)
811 return false;
812
Rafael Espindola737cd212010-10-05 18:01:23 +0000813 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000814
Rafael Espindolad1798862010-10-29 23:09:31 +0000815 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
816 return true;
817
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000818 const MCSymbol &A = Symbol.AliasedSymbol();
Rafael Espindola21451e52011-02-23 20:22:07 +0000819 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
820 return false;
821
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000822 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola21451e52011-02-23 20:22:07 +0000823 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa6866962010-10-27 14:44:52 +0000824 return false;
825
Rafael Espindola737cd212010-10-05 18:01:23 +0000826 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
827 return false;
828
Rafael Espindolabd701182010-10-19 19:31:37 +0000829 if (Symbol.isTemporary())
Rafael Espindola737cd212010-10-05 18:01:23 +0000830 return false;
831
832 return true;
833}
834
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000835bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
836 bool isUsedInReloc) {
Rafael Espindola737cd212010-10-05 18:01:23 +0000837 if (Data.isExternal())
838 return false;
839
840 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000841 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000842
843 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
844 if (isSignature && !isUsedInReloc)
845 return true;
846
Rafael Espindola737cd212010-10-05 18:01:23 +0000847 return false;
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000848 }
Rafael Espindola737cd212010-10-05 18:01:23 +0000849
850 return true;
851}
852
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000853void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000854 SectionIndexMapTy &SectionIndexMap,
855 const RelMapTy &RelMap) {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000856 unsigned Index = 1;
857 for (MCAssembler::iterator it = Asm.begin(),
858 ie = Asm.end(); it != ie; ++it) {
859 const MCSectionELF &Section =
860 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola2ff9e832010-11-11 18:13:52 +0000861 if (Section.getType() != ELF::SHT_GROUP)
862 continue;
863 SectionIndexMap[&Section] = Index++;
864 }
865
866 for (MCAssembler::iterator it = Asm.begin(),
867 ie = Asm.end(); it != ie; ++it) {
868 const MCSectionELF &Section =
869 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000870 if (Section.getType() == ELF::SHT_GROUP ||
871 Section.getType() == ELF::SHT_REL ||
872 Section.getType() == ELF::SHT_RELA)
Rafael Espindola2ff9e832010-11-11 18:13:52 +0000873 continue;
Rafael Espindolabab2a802010-11-10 21:51:05 +0000874 SectionIndexMap[&Section] = Index++;
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000875 const MCSectionELF *RelSection = RelMap.lookup(&Section);
876 if (RelSection)
877 SectionIndexMap[RelSection] = Index++;
Rafael Espindolabab2a802010-11-10 21:51:05 +0000878 }
879}
880
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000881void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000882 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000883 RevGroupMapTy RevGroupMap,
884 unsigned NumRegularSections) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000885 // FIXME: Is this the correct place to do this?
Rafael Espindola378e0ec2011-06-05 01:20:06 +0000886 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindola5c77c162010-10-05 15:48:37 +0000887 if (NeedsGOT) {
888 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
889 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
890 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
891 Data.setExternal(true);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000892 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindola5c77c162010-10-05 15:48:37 +0000893 }
894
Matt Fleming3565a062010-08-16 18:57:57 +0000895 // Index 0 is always the empty string.
896 StringMap<uint64_t> StringIndexMap;
897 StringTable += '\x00';
898
Rafael Espindolad5321da2011-04-07 23:21:52 +0000899 // FIXME: We could optimize suffixes in strtab in the same way we
900 // optimize them in shstrtab.
901
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000902 // Add the data for the symbols.
Matt Fleming3565a062010-08-16 18:57:57 +0000903 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
904 ie = Asm.symbol_end(); it != ie; ++it) {
905 const MCSymbol &Symbol = it->getSymbol();
906
Rafael Espindola484291c2010-11-01 14:28:48 +0000907 bool Used = UsedInReloc.count(&Symbol);
908 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000909 bool isSignature = RevGroupMap.count(&Symbol);
910
911 if (!isInSymtab(Asm, *it,
912 Used || WeakrefUsed || isSignature,
Rafael Espindola88182132010-10-27 15:18:17 +0000913 Renames.count(&Symbol)))
Matt Fleming3565a062010-08-16 18:57:57 +0000914 continue;
915
Matt Fleming3565a062010-08-16 18:57:57 +0000916 ELFSymbolData MSD;
917 MSD.SymbolData = it;
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000918 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Matt Fleming3565a062010-08-16 18:57:57 +0000919
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000920 // Undefined symbols are global, but this is the first place we
921 // are able to set it.
922 bool Local = isLocal(*it, isSignature, Used);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000923 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000924 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000925 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
926 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000927 }
928
Rafael Espindola484291c2010-11-01 14:28:48 +0000929 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000930 MCELF::SetBinding(*it, ELF::STB_WEAK);
Rafael Espindola484291c2010-11-01 14:28:48 +0000931
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000932 if (it->isCommon()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000933 assert(!Local);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000934 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindolabf052ac2010-10-27 16:04:30 +0000935 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000936 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola88182132010-10-27 15:18:17 +0000937 } else if (RefSymbol.isUndefined()) {
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000938 if (isSignature && !Used)
939 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
940 else
941 MSD.SectionIndex = ELF::SHN_UNDEF;
Matt Fleming3565a062010-08-16 18:57:57 +0000942 } else {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000943 const MCSectionELF &Section =
944 static_cast<const MCSectionELF&>(RefSymbol.getSection());
945 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000946 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
947 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000948 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000949 }
950
Rafael Espindola88182132010-10-27 15:18:17 +0000951 // The @@@ in symbol version is replaced with @ in undefined symbols and
952 // @@ in defined ones.
953 StringRef Name = Symbol.getName();
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000954 SmallString<32> Buf;
955
Rafael Espindola88182132010-10-27 15:18:17 +0000956 size_t Pos = Name.find("@@@");
Rafael Espindola88182132010-10-27 15:18:17 +0000957 if (Pos != StringRef::npos) {
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000958 Buf += Name.substr(0, Pos);
959 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
960 Buf += Name.substr(Pos + Skip);
961 Name = Buf;
Rafael Espindola88182132010-10-27 15:18:17 +0000962 }
963
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000964 uint64_t &Entry = StringIndexMap[Name];
Rafael Espindolaa6866962010-10-27 14:44:52 +0000965 if (!Entry) {
966 Entry = StringTable.size();
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000967 StringTable += Name;
Rafael Espindolaa6866962010-10-27 14:44:52 +0000968 StringTable += '\x00';
Matt Fleming3565a062010-08-16 18:57:57 +0000969 }
Rafael Espindolaa6866962010-10-27 14:44:52 +0000970 MSD.StringIndex = Entry;
971 if (MSD.SectionIndex == ELF::SHN_UNDEF)
972 UndefinedSymbolData.push_back(MSD);
973 else if (Local)
974 LocalSymbolData.push_back(MSD);
975 else
976 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000977 }
978
979 // Symbols are required to be in lexicographic order.
980 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
981 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
982 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
983
984 // Set the symbol indices. Local symbols must come before all other
985 // symbols with non-local bindings.
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000986 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000987 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
988 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000989
990 Index += NumRegularSections;
991
Matt Fleming3565a062010-08-16 18:57:57 +0000992 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
993 ExternalSymbolData[i].SymbolData->setIndex(Index++);
994 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
995 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
Nick Lewycky7aabcb12011-10-11 03:54:50 +0000996
997 if (NumRegularSections > ELF::SHN_LORESERVE)
998 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000999}
1000
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001001void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1002 MCAsmLayout &Layout,
1003 RelMapTy &RelMap) {
1004 for (MCAssembler::const_iterator it = Asm.begin(),
1005 ie = Asm.end(); it != ie; ++it) {
1006 const MCSectionData &SD = *it;
1007 if (Relocations[&SD].empty())
1008 continue;
1009
Matt Fleming3565a062010-08-16 18:57:57 +00001010 MCContext &Ctx = Asm.getContext();
Matt Fleming3565a062010-08-16 18:57:57 +00001011 const MCSectionELF &Section =
1012 static_cast<const MCSectionELF&>(SD.getSection());
1013
1014 const StringRef SectionName = Section.getSectionName();
Rafael Espindolabff66a82010-12-18 03:27:34 +00001015 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +00001016 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +00001017
1018 unsigned EntrySize;
Rafael Espindolabff66a82010-12-18 03:27:34 +00001019 if (hasRelocationAddend())
1020 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramer299fbe32010-08-17 17:56:13 +00001021 else
Rafael Espindolabff66a82010-12-18 03:27:34 +00001022 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +00001023
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001024 const MCSectionELF *RelaSection =
1025 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1026 ELF::SHT_RELA : ELF::SHT_REL, 0,
1027 SectionKind::getReadOnly(),
1028 EntrySize, "");
1029 RelMap[&Section] = RelaSection;
1030 Asm.getOrCreateSectionData(*RelaSection);
1031 }
1032}
Matt Fleming3565a062010-08-16 18:57:57 +00001033
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001034void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1035 const RelMapTy &RelMap) {
1036 for (MCAssembler::const_iterator it = Asm.begin(),
1037 ie = Asm.end(); it != ie; ++it) {
1038 const MCSectionData &SD = *it;
1039 const MCSectionELF &Section =
1040 static_cast<const MCSectionELF&>(SD.getSection());
1041
1042 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1043 if (!RelaSection)
1044 continue;
Matt Fleming3565a062010-08-16 18:57:57 +00001045 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolabff66a82010-12-18 03:27:34 +00001046 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +00001047
1048 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001049 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming3565a062010-08-16 18:57:57 +00001050 }
1051}
1052
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001053void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1054 uint64_t Flags, uint64_t Address,
1055 uint64_t Offset, uint64_t Size,
1056 uint32_t Link, uint32_t Info,
1057 uint64_t Alignment,
1058 uint64_t EntrySize) {
Matt Fleming3565a062010-08-16 18:57:57 +00001059 Write32(Name); // sh_name: index into string table
1060 Write32(Type); // sh_type
1061 WriteWord(Flags); // sh_flags
1062 WriteWord(Address); // sh_addr
1063 WriteWord(Offset); // sh_offset
1064 WriteWord(Size); // sh_size
1065 Write32(Link); // sh_link
1066 Write32(Info); // sh_info
1067 WriteWord(Alignment); // sh_addralign
1068 WriteWord(EntrySize); // sh_entsize
1069}
1070
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001071void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1072 MCDataFragment *F,
1073 const MCSectionData *SD) {
Matt Fleming3565a062010-08-16 18:57:57 +00001074 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
1075 // sort by the r_offset just like gnu as does
1076 array_pod_sort(Relocs.begin(), Relocs.end());
1077
1078 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1079 ELFRelocationEntry entry = Relocs[e - i - 1];
1080
Rafael Espindola12203cc2010-11-21 00:48:25 +00001081 if (!entry.Index)
1082 ;
1083 else if (entry.Index < 0)
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001084 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1085 else
Rafael Espindola12203cc2010-11-21 00:48:25 +00001086 entry.Index += LocalSymbolData.size();
Rafael Espindolabff66a82010-12-18 03:27:34 +00001087 if (is64Bit()) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001088 String64(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001089
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001090 struct ELF::Elf64_Rela ERE64;
1091 ERE64.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001092 String64(*F, ERE64.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001093
Rafael Espindolabff66a82010-12-18 03:27:34 +00001094 if (hasRelocationAddend())
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001095 String64(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001096 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001097 String32(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001098
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001099 struct ELF::Elf32_Rela ERE32;
1100 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001101 String32(*F, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001102
Rafael Espindolabff66a82010-12-18 03:27:34 +00001103 if (hasRelocationAddend())
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001104 String32(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001105 }
Matt Fleming3565a062010-08-16 18:57:57 +00001106 }
1107}
1108
Rafael Espindolad5321da2011-04-07 23:21:52 +00001109static int compareBySuffix(const void *a, const void *b) {
1110 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1111 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1112 const StringRef &NameA = secA->getSectionName();
1113 const StringRef &NameB = secB->getSectionName();
1114 const unsigned sizeA = NameA.size();
1115 const unsigned sizeB = NameB.size();
1116 const unsigned len = std::min(sizeA, sizeB);
1117 for (unsigned int i = 0; i < len; ++i) {
1118 char ca = NameA[sizeA - i - 1];
1119 char cb = NameB[sizeB - i - 1];
1120 if (ca != cb)
1121 return cb - ca;
1122 }
1123
1124 return sizeB - sizeA;
1125}
1126
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001127void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1128 MCAsmLayout &Layout,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001129 SectionIndexMapTy &SectionIndexMap,
1130 const RelMapTy &RelMap) {
Matt Fleming3565a062010-08-16 18:57:57 +00001131 MCContext &Ctx = Asm.getContext();
1132 MCDataFragment *F;
1133
Rafael Espindolabff66a82010-12-18 03:27:34 +00001134 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming3565a062010-08-16 18:57:57 +00001135
Rafael Espindola38738bf2010-09-22 19:04:41 +00001136 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001137 const MCSectionELF *ShstrtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001138 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001139 SectionKind::getReadOnly());
Rafael Espindola71859c62010-09-16 19:46:31 +00001140 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1141 ShstrtabSD.setAlignment(1);
Rafael Espindola71859c62010-09-16 19:46:31 +00001142
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001143 const MCSectionELF *SymtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001144 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1145 SectionKind::getReadOnly(),
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001146 EntrySize, "");
Matt Fleming3565a062010-08-16 18:57:57 +00001147 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolabff66a82010-12-18 03:27:34 +00001148 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001149
1150 MCSectionData *SymtabShndxSD = NULL;
1151
1152 if (NeedsSymtabShndx) {
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001153 const MCSectionELF *SymtabShndxSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001154 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001155 SectionKind::getReadOnly(), 4, "");
Rafael Espindola7be2c332010-10-31 00:16:26 +00001156 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1157 SymtabShndxSD->setAlignment(4);
1158 }
Matt Fleming3565a062010-08-16 18:57:57 +00001159
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001160 const MCSectionELF *StrtabSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001161 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001162 SectionKind::getReadOnly());
Matt Fleming3565a062010-08-16 18:57:57 +00001163 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1164 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +00001165
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001166 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1167
1168 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1169 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1170 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola71859c62010-09-16 19:46:31 +00001171
1172 // Symbol table
1173 F = new MCDataFragment(&SymtabSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001174 MCDataFragment *ShndxF = NULL;
1175 if (NeedsSymtabShndx) {
1176 ShndxF = new MCDataFragment(SymtabShndxSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001177 }
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001178 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
Rafael Espindola71859c62010-09-16 19:46:31 +00001179
Matt Fleming3565a062010-08-16 18:57:57 +00001180 F = new MCDataFragment(&StrtabSD);
1181 F->getContents().append(StringTable.begin(), StringTable.end());
Matt Fleming3565a062010-08-16 18:57:57 +00001182
Matt Fleming3565a062010-08-16 18:57:57 +00001183 F = new MCDataFragment(&ShstrtabSD);
1184
Rafael Espindolad5321da2011-04-07 23:21:52 +00001185 std::vector<const MCSectionELF*> Sections;
1186 for (MCAssembler::const_iterator it = Asm.begin(),
1187 ie = Asm.end(); it != ie; ++it) {
1188 const MCSectionELF &Section =
1189 static_cast<const MCSectionELF&>(it->getSection());
1190 Sections.push_back(&Section);
1191 }
1192 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1193
Matt Fleming3565a062010-08-16 18:57:57 +00001194 // Section header string table.
1195 //
1196 // The first entry of a string table holds a null character so skip
1197 // section 0.
1198 uint64_t Index = 1;
1199 F->getContents() += '\x00';
1200
Rafael Espindolad5321da2011-04-07 23:21:52 +00001201 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1202 const MCSectionELF &Section = *Sections[I];
Matt Fleming3565a062010-08-16 18:57:57 +00001203
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001204 StringRef Name = Section.getSectionName();
Rafael Espindolad5321da2011-04-07 23:21:52 +00001205 if (I != 0) {
1206 StringRef PreviousName = Sections[I - 1]->getSectionName();
1207 if (PreviousName.endswith(Name)) {
1208 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1209 continue;
1210 }
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001211 }
Matt Fleming3565a062010-08-16 18:57:57 +00001212 // Remember the index into the string table so we can write it
1213 // into the sh_name field of the section header table.
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001214 SectionStringTableIndex[&Section] = Index;
Matt Fleming3565a062010-08-16 18:57:57 +00001215
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001216 Index += Name.size() + 1;
1217 F->getContents() += Name;
Matt Fleming3565a062010-08-16 18:57:57 +00001218 F->getContents() += '\x00';
1219 }
Rafael Espindola70703872010-09-30 02:22:20 +00001220}
1221
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001222void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1223 MCAsmLayout &Layout,
1224 GroupMapTy &GroupMap,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001225 RevGroupMapTy &RevGroupMap,
1226 SectionIndexMapTy &SectionIndexMap,
1227 const RelMapTy &RelMap) {
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001228 // Create the .note.GNU-stack section if needed.
1229 MCContext &Ctx = Asm.getContext();
1230 if (Asm.getNoExecStack()) {
1231 const MCSectionELF *GnuStackSection =
1232 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1233 SectionKind::getReadOnly());
1234 Asm.getOrCreateSectionData(*GnuStackSection);
1235 }
1236
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001237 // Build the groups
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001238 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1239 it != ie; ++it) {
1240 const MCSectionELF &Section =
1241 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola1c130262011-01-23 04:43:11 +00001242 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001243 continue;
1244
1245 const MCSymbol *SignatureSymbol = Section.getGroup();
1246 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +00001247 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001248 if (!Group) {
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001249 Group = Ctx.CreateELFGroupSection();
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001250 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1251 Data.setAlignment(4);
1252 MCDataFragment *F = new MCDataFragment(&Data);
1253 String32(*F, ELF::GRP_COMDAT);
1254 }
1255 GroupMap[Group] = SignatureSymbol;
1256 }
1257
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001258 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1259
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001260 // Add sections to the groups
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001261 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001262 it != ie; ++it) {
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001263 const MCSectionELF &Section =
1264 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola1c130262011-01-23 04:43:11 +00001265 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001266 continue;
Rafael Espindola1f4f9e32010-11-14 04:17:37 +00001267 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001268 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1269 // FIXME: we could use the previous fragment
1270 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001271 unsigned Index = SectionIndexMap.lookup(&Section);
1272 String32(*F, Index);
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001273 }
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001274}
1275
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001276void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1277 const SectionIndexMapTy &SectionIndexMap,
1278 uint32_t GroupSymbolIndex,
1279 uint64_t Offset, uint64_t Size,
1280 uint64_t Alignment,
1281 const MCSectionELF &Section) {
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001282 uint64_t sh_link = 0;
1283 uint64_t sh_info = 0;
1284
1285 switch(Section.getType()) {
1286 case ELF::SHT_DYNAMIC:
1287 sh_link = SectionStringTableIndex[&Section];
1288 sh_info = 0;
1289 break;
1290
1291 case ELF::SHT_REL:
1292 case ELF::SHT_RELA: {
1293 const MCSectionELF *SymtabSection;
1294 const MCSectionELF *InfoSection;
1295 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1296 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001297 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001298 sh_link = SectionIndexMap.lookup(SymtabSection);
1299 assert(sh_link && ".symtab not found");
1300
1301 // Remove ".rel" and ".rela" prefixes.
1302 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1303 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1304
1305 InfoSection = Asm.getContext().getELFSection(SectionName,
1306 ELF::SHT_PROGBITS, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001307 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001308 sh_info = SectionIndexMap.lookup(InfoSection);
1309 break;
1310 }
1311
1312 case ELF::SHT_SYMTAB:
1313 case ELF::SHT_DYNSYM:
1314 sh_link = StringTableIndex;
1315 sh_info = LastLocalSymbolIndex;
1316 break;
1317
1318 case ELF::SHT_SYMTAB_SHNDX:
1319 sh_link = SymbolTableIndex;
1320 break;
1321
1322 case ELF::SHT_PROGBITS:
1323 case ELF::SHT_STRTAB:
1324 case ELF::SHT_NOBITS:
Rafael Espindola98976612010-12-26 21:30:59 +00001325 case ELF::SHT_NOTE:
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001326 case ELF::SHT_NULL:
1327 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim86a97f22011-01-12 00:19:25 +00001328 case ELF::SHT_INIT_ARRAY:
1329 case ELF::SHT_FINI_ARRAY:
1330 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola0cf5e3d2011-01-23 05:43:40 +00001331 case ELF::SHT_X86_64_UNWIND:
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001332 // Nothing to do.
1333 break;
1334
Nick Lewycky4a8d43e2011-10-07 23:28:32 +00001335 case ELF::SHT_GROUP:
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001336 sh_link = SymbolTableIndex;
1337 sh_info = GroupSymbolIndex;
1338 break;
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001339
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001340 default:
1341 assert(0 && "FIXME: sh_type value not supported!");
1342 break;
1343 }
1344
1345 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1346 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1347 Alignment, Section.getEntrySize());
1348}
1349
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001350bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolaf8803fe2010-12-06 03:48:09 +00001351 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001352 !SD.getSection().isVirtualSection();
1353}
1354
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001355uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001356 uint64_t Ret = 0;
1357 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1358 ++i) {
1359 const MCFragment &F = *i;
1360 assert(F.getKind() == MCFragment::FT_Data);
1361 Ret += cast<MCDataFragment>(F).getContents().size();
1362 }
1363 return Ret;
1364}
1365
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001366uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1367 const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001368 if (IsELFMetaDataSection(SD))
1369 return DataSectionSize(SD);
1370 return Layout.getSectionFileSize(&SD);
1371}
1372
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001373uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1374 const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001375 if (IsELFMetaDataSection(SD))
1376 return DataSectionSize(SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001377 return Layout.getSectionAddressSize(&SD);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001378}
1379
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001380void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1381 const MCAsmLayout &Layout,
1382 const MCSectionELF &Section) {
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001383 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1384
Benjamin Kramer263109d2012-01-20 14:42:32 +00001385 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001386 WriteZeros(Padding);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001387
1388 if (IsELFMetaDataSection(SD)) {
1389 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1390 ++i) {
1391 const MCFragment &F = *i;
1392 assert(F.getKind() == MCFragment::FT_Data);
1393 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1394 }
1395 } else {
Jim Grosbachf77d5b12011-12-06 00:03:48 +00001396 Asm.writeSectionData(&SD, Layout);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001397 }
1398}
1399
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001400void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1401 const GroupMapTy &GroupMap,
1402 const MCAsmLayout &Layout,
1403 const SectionIndexMapTy &SectionIndexMap,
1404 const SectionOffsetMapTy &SectionOffsetMap) {
1405 const unsigned NumSections = Asm.size() + 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001406
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001407 std::vector<const MCSectionELF*> Sections;
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001408 Sections.resize(NumSections - 1);
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001409
1410 for (SectionIndexMapTy::const_iterator i=
1411 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1412 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001413 Sections[p.second - 1] = p.first;
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001414 }
1415
Matt Fleming3565a062010-08-16 18:57:57 +00001416 // Null section first.
Rafael Espindola7be2c332010-10-31 00:16:26 +00001417 uint64_t FirstSectionSize =
1418 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1419 uint32_t FirstSectionLink =
1420 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1421 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming3565a062010-08-16 18:57:57 +00001422
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001423 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001424 const MCSectionELF &Section = *Sections[i];
1425 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1426 uint32_t GroupSymbolIndex;
1427 if (Section.getType() != ELF::SHT_GROUP)
1428 GroupSymbolIndex = 0;
1429 else
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001430 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1431 GroupMap.lookup(&Section));
Matt Fleming3565a062010-08-16 18:57:57 +00001432
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001433 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001434
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001435 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001436 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001437 SD.getAlignment(), Section);
Matt Fleming3565a062010-08-16 18:57:57 +00001438 }
1439}
1440
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001441void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1442 std::vector<const MCSectionELF*> &Sections) {
1443 for (MCAssembler::iterator it = Asm.begin(),
1444 ie = Asm.end(); it != ie; ++it) {
1445 const MCSectionELF &Section =
1446 static_cast<const MCSectionELF &>(it->getSection());
1447 if (Section.getType() == ELF::SHT_GROUP)
1448 Sections.push_back(&Section);
1449 }
1450
1451 for (MCAssembler::iterator it = Asm.begin(),
1452 ie = Asm.end(); it != ie; ++it) {
1453 const MCSectionELF &Section =
1454 static_cast<const MCSectionELF &>(it->getSection());
1455 if (Section.getType() != ELF::SHT_GROUP &&
1456 Section.getType() != ELF::SHT_REL &&
1457 Section.getType() != ELF::SHT_RELA)
1458 Sections.push_back(&Section);
1459 }
1460
1461 for (MCAssembler::iterator it = Asm.begin(),
1462 ie = Asm.end(); it != ie; ++it) {
1463 const MCSectionELF &Section =
1464 static_cast<const MCSectionELF &>(it->getSection());
1465 if (Section.getType() == ELF::SHT_REL ||
1466 Section.getType() == ELF::SHT_RELA)
1467 Sections.push_back(&Section);
1468 }
1469}
1470
1471void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1472 const MCAsmLayout &Layout) {
1473 GroupMapTy GroupMap;
1474 RevGroupMapTy RevGroupMap;
1475 SectionIndexMapTy SectionIndexMap;
1476
1477 unsigned NumUserSections = Asm.size();
1478
1479 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1480 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1481
1482 const unsigned NumUserAndRelocSections = Asm.size();
1483 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1484 RevGroupMap, SectionIndexMap, RelMap);
1485 const unsigned AllSections = Asm.size();
1486 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1487
1488 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1489
1490 // Compute symbol table information.
1491 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1492
1493
1494 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1495
1496 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1497 const_cast<MCAsmLayout&>(Layout),
1498 SectionIndexMap,
1499 RelMap);
1500
1501 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1502 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1503 sizeof(ELF::Elf32_Ehdr);
1504 uint64_t FileOff = HeaderSize;
1505
1506 std::vector<const MCSectionELF*> Sections;
1507 ComputeSectionOrder(Asm, Sections);
1508 unsigned NumSections = Sections.size();
1509 SectionOffsetMapTy SectionOffsetMap;
1510 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1511 const MCSectionELF &Section = *Sections[i];
1512 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1513
1514 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1515
1516 // Remember the offset into the file for this section.
1517 SectionOffsetMap[&Section] = FileOff;
1518
1519 // Get the size of the section in the output file (including padding).
1520 FileOff += GetSectionFileSize(Layout, SD);
1521 }
1522
1523 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1524
1525 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1526
1527 uint64_t SectionHeaderEntrySize = is64Bit() ?
1528 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1529 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1530
1531 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1532 const MCSectionELF &Section = *Sections[i];
1533 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1534
1535 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1536
1537 // Remember the offset into the file for this section.
1538 SectionOffsetMap[&Section] = FileOff;
1539
1540 // Get the size of the section in the output file (including padding).
1541 FileOff += GetSectionFileSize(Layout, SD);
1542 }
1543
1544 // Write out the ELF header ...
1545 WriteHeader(SectionHeaderOffset, NumSections + 1);
1546
1547 // ... then the regular sections ...
1548 // + because of .shstrtab
1549 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1550 WriteDataSectionData(Asm, Layout, *Sections[i]);
1551
Benjamin Kramer263109d2012-01-20 14:42:32 +00001552 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001553 WriteZeros(Padding);
1554
1555 // ... then the section header table ...
1556 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1557 SectionOffsetMap);
1558
Nick Lewyckyaaae3f62011-10-07 20:56:23 +00001559 // ... and then the remaining sections ...
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001560 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1561 WriteDataSectionData(Asm, Layout, *Sections[i]);
1562}
1563
Eli Friedman78c1e172011-03-03 07:24:36 +00001564bool
1565ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1566 const MCSymbolData &DataA,
1567 const MCFragment &FB,
1568 bool InSet,
1569 bool IsPCRel) const {
1570 if (DataA.getFlags() & ELF_STB_Weak)
1571 return false;
1572 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1573 Asm, DataA, FB,InSet, IsPCRel);
1574}
1575
Rafael Espindola6024c972010-12-17 17:45:22 +00001576MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1577 raw_ostream &OS,
Rafael Espindolabff66a82010-12-18 03:27:34 +00001578 bool IsLittleEndian) {
Rafael Espindola7bd27802011-12-22 03:24:43 +00001579 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolaedae8e12011-12-21 17:30:17 +00001580}