blob: 9fc33b6b3e5eda125f5624a69fcfbb0863963795 [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"
Evan Cheng78c10ee2011-07-25 23:24:55 +000020#include "llvm/MC/MCAsmBackend.h"
Matt Fleming3565a062010-08-16 18:57:57 +000021#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola3963d612011-12-22 03:38:00 +000022#include "llvm/MC/MCAssembler.h"
Matt Fleming3565a062010-08-16 18:57:57 +000023#include "llvm/MC/MCContext.h"
Rafael Espindola3963d612011-12-22 03:38:00 +000024#include "llvm/MC/MCELFObjectWriter.h"
25#include "llvm/MC/MCELFSymbolFlags.h"
Matt Fleming3565a062010-08-16 18:57:57 +000026#include "llvm/MC/MCExpr.h"
Craig Topperf1d0f772012-03-26 06:58:25 +000027#include "llvm/MC/MCFixupKindInfo.h"
28#include "llvm/MC/MCObjectWriter.h"
Matt Fleming3565a062010-08-16 18:57:57 +000029#include "llvm/MC/MCSectionELF.h"
Matt Fleming3565a062010-08-16 18:57:57 +000030#include "llvm/MC/MCValue.h"
31#include "llvm/Support/Debug.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/ELF.h"
Matt Fleming3565a062010-08-16 18:57:57 +000034
Matt Fleming3565a062010-08-16 18:57:57 +000035#include <vector>
36using namespace llvm;
37
Jason W Kime964d112011-05-11 22:53:06 +000038#undef DEBUG_TYPE
39#define DEBUG_TYPE "reloc-info"
40
Rafael Espindola3963d612011-12-22 03:38:00 +000041namespace {
42class ELFObjectWriter : public MCObjectWriter {
43 protected:
44
45 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
46 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
47 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
48 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
49 bool Used, bool Renamed);
50 static bool isLocal(const MCSymbolData &Data, bool isSignature,
51 bool isUsedInReloc);
52 static bool IsELFMetaDataSection(const MCSectionData &SD);
53 static uint64_t DataSectionSize(const MCSectionData &SD);
54 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
55 const MCSectionData &SD);
56 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
57 const MCSectionData &SD);
58
59 void WriteDataSectionData(MCAssembler &Asm,
60 const MCAsmLayout &Layout,
61 const MCSectionELF &Section);
62
63 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
64 return Kind == X86::reloc_riprel_4byte ||
65 Kind == X86::reloc_riprel_4byte_movq_load;
66 }*/
67
68 /// ELFSymbolData - Helper struct for containing some precomputed
69 /// information on symbols.
70 struct ELFSymbolData {
71 MCSymbolData *SymbolData;
72 uint64_t StringIndex;
73 uint32_t SectionIndex;
74
75 // Support lexicographic sorting.
76 bool operator<(const ELFSymbolData &RHS) const {
77 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
78 return true;
79 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
80 return false;
81 return SymbolData->getSymbol().getName() <
82 RHS.SymbolData->getSymbol().getName();
83 }
84 };
85
Rafael Espindola3963d612011-12-22 03:38:00 +000086 /// The target specific ELF writer instance.
87 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
88
89 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
90 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
91 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
92
93 llvm::DenseMap<const MCSectionData*,
94 std::vector<ELFRelocationEntry> > Relocations;
95 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
96
97 /// @}
98 /// @name Symbol Table Data
99 /// @{
100
101 SmallString<256> StringTable;
102 std::vector<ELFSymbolData> LocalSymbolData;
103 std::vector<ELFSymbolData> ExternalSymbolData;
104 std::vector<ELFSymbolData> UndefinedSymbolData;
105
106 /// @}
107
108 bool NeedsGOT;
109
110 bool NeedsSymtabShndx;
111
112 // This holds the symbol table index of the last local symbol.
113 unsigned LastLocalSymbolIndex;
114 // This holds the .strtab section index.
115 unsigned StringTableIndex;
116 // This holds the .symtab section index.
117 unsigned SymbolTableIndex;
118
119 unsigned ShstrtabIndex;
120
121
122 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
123 const MCValue &Target,
124 const MCFragment &F,
125 const MCFixup &Fixup,
126 bool IsPCRel) const;
127
128 // TargetObjectWriter wrappers.
129 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
130 const MCValue &Target,
131 const MCFragment &F,
132 const MCFixup &Fixup,
133 bool IsPCRel) const {
134 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
135 }
136
137 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
138 bool hasRelocationAddend() const {
139 return TargetObjectWriter->hasRelocationAddend();
140 }
141 unsigned getEFlags() const {
142 return TargetObjectWriter->getEFlags();
143 }
144 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
145 bool IsPCRel, bool IsRelocWithSymbol,
146 int64_t Addend) const {
147 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
148 IsRelocWithSymbol, Addend);
149 }
150
151
152 public:
153 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
154 raw_ostream &_OS, bool IsLittleEndian)
155 : MCObjectWriter(_OS, IsLittleEndian),
156 TargetObjectWriter(MOTW),
157 NeedsGOT(false), NeedsSymtabShndx(false){
158 }
159
160 virtual ~ELFObjectWriter();
161
162 void WriteWord(uint64_t W) {
163 if (is64Bit())
164 Write64(W);
165 else
166 Write32(W);
167 }
168
169 void StringLE16(char *buf, uint16_t Value) {
170 buf[0] = char(Value >> 0);
171 buf[1] = char(Value >> 8);
172 }
173
174 void StringLE32(char *buf, uint32_t Value) {
175 StringLE16(buf, uint16_t(Value >> 0));
176 StringLE16(buf + 2, uint16_t(Value >> 16));
177 }
178
179 void StringLE64(char *buf, uint64_t Value) {
180 StringLE32(buf, uint32_t(Value >> 0));
181 StringLE32(buf + 4, uint32_t(Value >> 32));
182 }
183
184 void StringBE16(char *buf ,uint16_t Value) {
185 buf[0] = char(Value >> 8);
186 buf[1] = char(Value >> 0);
187 }
188
189 void StringBE32(char *buf, uint32_t Value) {
190 StringBE16(buf, uint16_t(Value >> 16));
191 StringBE16(buf + 2, uint16_t(Value >> 0));
192 }
193
194 void StringBE64(char *buf, uint64_t Value) {
195 StringBE32(buf, uint32_t(Value >> 32));
196 StringBE32(buf + 4, uint32_t(Value >> 0));
197 }
198
199 void String8(MCDataFragment &F, uint8_t Value) {
200 char buf[1];
201 buf[0] = Value;
202 F.getContents() += StringRef(buf, 1);
203 }
204
205 void String16(MCDataFragment &F, uint16_t Value) {
206 char buf[2];
207 if (isLittleEndian())
208 StringLE16(buf, Value);
209 else
210 StringBE16(buf, Value);
211 F.getContents() += StringRef(buf, 2);
212 }
213
214 void String32(MCDataFragment &F, uint32_t Value) {
215 char buf[4];
216 if (isLittleEndian())
217 StringLE32(buf, Value);
218 else
219 StringBE32(buf, Value);
220 F.getContents() += StringRef(buf, 4);
221 }
222
223 void String64(MCDataFragment &F, uint64_t Value) {
224 char buf[8];
225 if (isLittleEndian())
226 StringLE64(buf, Value);
227 else
228 StringBE64(buf, Value);
229 F.getContents() += StringRef(buf, 8);
230 }
231
232 void WriteHeader(uint64_t SectionDataSize,
233 unsigned NumberOfSections);
234
235 void WriteSymbolEntry(MCDataFragment *SymtabF,
236 MCDataFragment *ShndxF,
237 uint64_t name, uint8_t info,
238 uint64_t value, uint64_t size,
239 uint8_t other, uint32_t shndx,
240 bool Reserved);
241
242 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
243 ELFSymbolData &MSD,
244 const MCAsmLayout &Layout);
245
246 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
247 void WriteSymbolTable(MCDataFragment *SymtabF,
248 MCDataFragment *ShndxF,
249 const MCAssembler &Asm,
250 const MCAsmLayout &Layout,
251 const SectionIndexMapTy &SectionIndexMap);
252
253 virtual void RecordRelocation(const MCAssembler &Asm,
254 const MCAsmLayout &Layout,
255 const MCFragment *Fragment,
256 const MCFixup &Fixup,
257 MCValue Target, uint64_t &FixedValue);
258
259 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
260 const MCSymbol *S);
261
262 // Map from a group section to the signature symbol
263 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
264 // Map from a signature symbol to the group section
265 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
266 // Map from a section to the section with the relocations
267 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
268 // Map from a section to its offset
269 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
270
271 /// ComputeSymbolTable - Compute the symbol table data
272 ///
273 /// \param StringTable [out] - The string table data.
274 /// \param StringIndexMap [out] - Map from symbol names to offsets in the
275 /// string table.
276 void ComputeSymbolTable(MCAssembler &Asm,
277 const SectionIndexMapTy &SectionIndexMap,
278 RevGroupMapTy RevGroupMap,
279 unsigned NumRegularSections);
280
281 void ComputeIndexMap(MCAssembler &Asm,
282 SectionIndexMapTy &SectionIndexMap,
283 const RelMapTy &RelMap);
284
285 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
286 RelMapTy &RelMap);
287
288 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
289 const RelMapTy &RelMap);
290
291 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
292 SectionIndexMapTy &SectionIndexMap,
293 const RelMapTy &RelMap);
294
295 // Create the sections that show up in the symbol table. Currently
296 // those are the .note.GNU-stack section and the group sections.
297 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
298 GroupMapTy &GroupMap,
299 RevGroupMapTy &RevGroupMap,
300 SectionIndexMapTy &SectionIndexMap,
301 const RelMapTy &RelMap);
302
303 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
304 const MCAsmLayout &Layout);
305
306 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
307 const MCAsmLayout &Layout,
308 const SectionIndexMapTy &SectionIndexMap,
309 const SectionOffsetMapTy &SectionOffsetMap);
310
311 void ComputeSectionOrder(MCAssembler &Asm,
312 std::vector<const MCSectionELF*> &Sections);
313
314 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
315 uint64_t Address, uint64_t Offset,
316 uint64_t Size, uint32_t Link, uint32_t Info,
317 uint64_t Alignment, uint64_t EntrySize);
318
319 void WriteRelocationsFragment(const MCAssembler &Asm,
320 MCDataFragment *F,
321 const MCSectionData *SD);
322
323 virtual bool
324 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
325 const MCSymbolData &DataA,
326 const MCFragment &FB,
327 bool InSet,
328 bool IsPCRel) const;
329
330 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
331 void WriteSection(MCAssembler &Asm,
332 const SectionIndexMapTy &SectionIndexMap,
333 uint32_t GroupSymbolIndex,
334 uint64_t Offset, uint64_t Size, uint64_t Alignment,
335 const MCSectionELF &Section);
336 };
337}
338
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000339bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
340 const MCFixupKindInfo &FKI =
341 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
342
343 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
344}
345
346bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
347 switch (Variant) {
348 default:
349 return false;
350 case MCSymbolRefExpr::VK_GOT:
351 case MCSymbolRefExpr::VK_PLT:
352 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola378e0ec2011-06-05 01:20:06 +0000353 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000354 case MCSymbolRefExpr::VK_TPOFF:
355 case MCSymbolRefExpr::VK_TLSGD:
356 case MCSymbolRefExpr::VK_GOTTPOFF:
357 case MCSymbolRefExpr::VK_INDNTPOFF:
358 case MCSymbolRefExpr::VK_NTPOFF:
359 case MCSymbolRefExpr::VK_GOTNTPOFF:
360 case MCSymbolRefExpr::VK_TLSLDM:
361 case MCSymbolRefExpr::VK_DTPOFF:
362 case MCSymbolRefExpr::VK_TLSLD:
363 return true;
364 }
365}
366
Jason W Kimd3443e92010-11-15 16:18:39 +0000367ELFObjectWriter::~ELFObjectWriter()
368{}
369
Matt Fleming3565a062010-08-16 18:57:57 +0000370// Emit the ELF header.
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000371void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
372 unsigned NumberOfSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000373 // ELF Header
374 // ----------
375 //
376 // Note
377 // ----
378 // emitWord method behaves differently for ELF32 and ELF64, writing
379 // 4 bytes in the former and 8 in the latter.
380
381 Write8(0x7f); // e_ident[EI_MAG0]
382 Write8('E'); // e_ident[EI_MAG1]
383 Write8('L'); // e_ident[EI_MAG2]
384 Write8('F'); // e_ident[EI_MAG3]
385
Rafael Espindolabff66a82010-12-18 03:27:34 +0000386 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming3565a062010-08-16 18:57:57 +0000387
388 // e_ident[EI_DATA]
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000389 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming3565a062010-08-16 18:57:57 +0000390
391 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000392 // e_ident[EI_OSABI]
Rafael Espindoladc9a8a32011-12-21 17:00:36 +0000393 Write8(TargetObjectWriter->getOSABI());
Matt Fleming3565a062010-08-16 18:57:57 +0000394 Write8(0); // e_ident[EI_ABIVERSION]
395
396 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
397
398 Write16(ELF::ET_REL); // e_type
399
Rafael Espindolabff66a82010-12-18 03:27:34 +0000400 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000401
402 Write32(ELF::EV_CURRENT); // e_version
403 WriteWord(0); // e_entry, no entry point in .o file
404 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolabff66a82010-12-18 03:27:34 +0000405 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramereb976772010-08-17 17:02:29 +0000406 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000407
Jason W Kim2d7a53a2011-02-04 21:41:11 +0000408 // e_flags = whatever the target wants
Rafael Espindolae8526d02011-12-21 20:09:46 +0000409 Write32(getEFlags());
Matt Fleming3565a062010-08-16 18:57:57 +0000410
411 // e_ehsize = ELF header size
Rafael Espindolabff66a82010-12-18 03:27:34 +0000412 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming3565a062010-08-16 18:57:57 +0000413
414 Write16(0); // e_phentsize = prog header entry size
415 Write16(0); // e_phnum = # prog header entries = 0
416
417 // e_shentsize = Section header entry size
Rafael Espindolabff66a82010-12-18 03:27:34 +0000418 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming3565a062010-08-16 18:57:57 +0000419
420 // e_shnum = # of section header ents
Rafael Espindola7be2c332010-10-31 00:16:26 +0000421 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewyckyaaae3f62011-10-07 20:56:23 +0000422 Write16(ELF::SHN_UNDEF);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000423 else
424 Write16(NumberOfSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000425
426 // e_shstrndx = Section # of '.shstrtab'
Nick Lewyckyb3429d32011-10-07 20:58:24 +0000427 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola7be2c332010-10-31 00:16:26 +0000428 Write16(ELF::SHN_XINDEX);
429 else
430 Write16(ShstrtabIndex);
Matt Fleming3565a062010-08-16 18:57:57 +0000431}
432
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000433void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
434 MCDataFragment *ShndxF,
435 uint64_t name,
436 uint8_t info, uint64_t value,
437 uint64_t size, uint8_t other,
438 uint32_t shndx,
439 bool Reserved) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000440 if (ShndxF) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000441 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000442 String32(*ShndxF, shndx);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000443 else
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000444 String32(*ShndxF, 0);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000445 }
446
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000447 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
448 uint16_t(ELF::SHN_XINDEX) : shndx;
449
Rafael Espindolabff66a82010-12-18 03:27:34 +0000450 if (is64Bit()) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000451 String32(*SymtabF, name); // st_name
452 String8(*SymtabF, info); // st_info
453 String8(*SymtabF, other); // st_other
454 String16(*SymtabF, Index); // st_shndx
455 String64(*SymtabF, value); // st_value
456 String64(*SymtabF, size); // st_size
Matt Fleming3565a062010-08-16 18:57:57 +0000457 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000458 String32(*SymtabF, name); // st_name
459 String32(*SymtabF, value); // st_value
460 String32(*SymtabF, size); // st_size
461 String8(*SymtabF, info); // st_info
462 String8(*SymtabF, other); // st_other
463 String16(*SymtabF, Index); // st_shndx
Matt Fleming3565a062010-08-16 18:57:57 +0000464 }
465}
466
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000467uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
468 const MCAsmLayout &Layout) {
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000469 if (Data.isCommon() && Data.isExternal())
470 return Data.getCommonAlignment();
471
472 const MCSymbol &Symbol = Data.getSymbol();
Roman Divackyd1491862010-12-20 21:14:39 +0000473
474 if (Symbol.isAbsolute() && Symbol.isVariable()) {
475 if (const MCExpr *Value = Symbol.getVariableValue()) {
476 int64_t IntValue;
477 if (Value->EvaluateAsAbsolute(IntValue, Layout))
Jim Grosbachf68a26b2011-12-06 00:13:09 +0000478 return (uint64_t)IntValue;
Roman Divackyd1491862010-12-20 21:14:39 +0000479 }
480 }
481
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000482 if (!Symbol.isInSection())
483 return 0;
484
Rafael Espindola64695402011-05-16 16:17:21 +0000485
486 if (Data.getFragment()) {
487 if (Data.getFlags() & ELF_Other_ThumbFunc)
488 return Layout.getSymbolOffset(&Data)+1;
489 else
490 return Layout.getSymbolOffset(&Data);
491 }
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000492
493 return 0;
494}
495
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000496void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
497 const MCAsmLayout &Layout) {
Rafael Espindola88182132010-10-27 15:18:17 +0000498 // The presence of symbol versions causes undefined symbols and
499 // versions declared with @@@ to be renamed.
500
501 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
502 ie = Asm.symbol_end(); it != ie; ++it) {
503 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000504 const MCSymbol &Symbol = Alias.AliasedSymbol();
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000505 MCSymbolData &SD = Asm.getSymbolData(Symbol);
506
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000507 // Not an alias.
508 if (&Symbol == &Alias)
509 continue;
510
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000511 StringRef AliasName = Alias.getName();
Rafael Espindola88182132010-10-27 15:18:17 +0000512 size_t Pos = AliasName.find('@');
513 if (Pos == StringRef::npos)
514 continue;
515
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000516 // Aliases defined with .symvar copy the binding from the symbol they alias.
517 // This is the first place we are able to copy this information.
518 it->setExternal(SD.isExternal());
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000519 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000520
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000521 StringRef Rest = AliasName.substr(Pos);
Rafael Espindola88182132010-10-27 15:18:17 +0000522 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
523 continue;
524
Rafael Espindola83ff4d22010-10-27 17:56:18 +0000525 // FIXME: produce a better error message.
526 if (Symbol.isUndefined() && Rest.startswith("@@") &&
527 !Rest.startswith("@@@"))
528 report_fatal_error("A @@ version cannot be undefined");
529
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000530 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindola88182132010-10-27 15:18:17 +0000531 }
532}
533
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000534void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
535 MCDataFragment *ShndxF,
536 ELFSymbolData &MSD,
537 const MCAsmLayout &Layout) {
Rafael Espindola152c1062010-10-06 21:02:29 +0000538 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindolade89b012010-10-15 18:25:33 +0000539 MCSymbolData &Data =
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000540 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
Rafael Espindola152c1062010-10-06 21:02:29 +0000541
Rafael Espindola7be2c332010-10-31 00:16:26 +0000542 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
543 Data.getSymbol().isVariable();
544
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000545 uint8_t Binding = MCELF::GetBinding(OrigData);
546 uint8_t Visibility = MCELF::GetVisibility(OrigData);
547 uint8_t Type = MCELF::GetType(Data);
Rafael Espindola152c1062010-10-06 21:02:29 +0000548
549 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
550 uint8_t Other = Visibility;
551
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000552 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000553 uint64_t Size = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000554
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000555 assert(!(Data.isCommon() && !Data.isExternal()));
556
Rafael Espindolaf0121242010-12-22 16:03:00 +0000557 const MCExpr *ESize = Data.getSize();
558 if (ESize) {
559 int64_t Res;
560 if (!ESize->EvaluateAsAbsolute(Res, Layout))
561 report_fatal_error("Size expression must be absolute.");
562 Size = Res;
Matt Fleming3565a062010-08-16 18:57:57 +0000563 }
564
565 // Write out the symbol table entry
Rafael Espindola7be2c332010-10-31 00:16:26 +0000566 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
567 Size, Other, MSD.SectionIndex, IsReserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000568}
569
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000570void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
571 MCDataFragment *ShndxF,
572 const MCAssembler &Asm,
573 const MCAsmLayout &Layout,
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000574 const SectionIndexMapTy &SectionIndexMap) {
Matt Fleming3565a062010-08-16 18:57:57 +0000575 // The string table must be emitted first because we need the index
576 // into the string table for all the symbol names.
577 assert(StringTable.size() && "Missing string table");
578
579 // FIXME: Make sure the start of the symbol table is aligned.
580
581 // The first entry is the undefined symbol entry.
Rafael Espindola7be2c332010-10-31 00:16:26 +0000582 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
Matt Fleming3565a062010-08-16 18:57:57 +0000583
584 // Write the symbol table entries.
585 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
586 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
587 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola7be2c332010-10-31 00:16:26 +0000588 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000589 }
590
Rafael Espindola71859c62010-09-16 19:46:31 +0000591 // Write out a symbol table entry for each regular section.
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000592 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
593 ++i) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000594 const MCSectionELF &Section =
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000595 static_cast<const MCSectionELF&>(i->getSection());
596 if (Section.getType() == ELF::SHT_RELA ||
597 Section.getType() == ELF::SHT_REL ||
598 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewyckyd2fdb4a2011-10-07 23:29:53 +0000599 Section.getType() == ELF::SHT_SYMTAB ||
600 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedmana44fa242010-08-16 21:17:09 +0000601 continue;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000602 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000603 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
604 false);
Eli Friedmana44fa242010-08-16 21:17:09 +0000605 LastLocalSymbolIndex++;
606 }
Matt Fleming3565a062010-08-16 18:57:57 +0000607
608 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
609 ELFSymbolData &MSD = ExternalSymbolData[i];
610 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola3223f192010-10-06 16:47:31 +0000611 assert(((Data.getFlags() & ELF_STB_Global) ||
612 (Data.getFlags() & ELF_STB_Weak)) &&
613 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola7be2c332010-10-31 00:16:26 +0000614 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000615 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000616 LastLocalSymbolIndex++;
617 }
618
619 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
620 ELFSymbolData &MSD = UndefinedSymbolData[i];
621 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000622 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000623 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000624 LastLocalSymbolIndex++;
625 }
626}
627
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000628const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
629 const MCValue &Target,
Jason W Kime964d112011-05-11 22:53:06 +0000630 const MCFragment &F,
631 const MCFixup &Fixup,
632 bool IsPCRel) const {
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000633 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000634 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
635 const MCSymbol *Renamed = Renames.lookup(&Symbol);
636 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000637
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000638 if (ASymbol.isUndefined()) {
639 if (Renamed)
640 return Renamed;
641 return &ASymbol;
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000642 }
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000643
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000644 if (SD.isExternal()) {
645 if (Renamed)
646 return Renamed;
647 return &Symbol;
648 }
Rafael Espindola73ffea42010-09-25 05:42:19 +0000649
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000650 const MCSectionELF &Section =
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000651 static_cast<const MCSectionELF&>(ASymbol.getSection());
Rafael Espindola25958732010-11-24 21:57:39 +0000652 const SectionKind secKind = Section.getKind();
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000653
Rafael Espindola25958732010-11-24 21:57:39 +0000654 if (secKind.isBSS())
Jason W Kime964d112011-05-11 22:53:06 +0000655 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000656
Rafael Espindola25958732010-11-24 21:57:39 +0000657 if (secKind.isThreadLocal()) {
658 if (Renamed)
659 return Renamed;
660 return &Symbol;
661 }
662
Rafael Espindola8cecf252010-10-06 16:23:36 +0000663 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindola3729d002010-10-05 23:57:26 +0000664 const MCSectionELF &Sec2 =
665 static_cast<const MCSectionELF&>(F.getParent()->getSection());
666
Rafael Espindola8cecf252010-10-06 16:23:36 +0000667 if (&Sec2 != &Section &&
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000668 (Kind == MCSymbolRefExpr::VK_PLT ||
669 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
Rafael Espindola25958732010-11-24 21:57:39 +0000670 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000671 if (Renamed)
672 return Renamed;
673 return &Symbol;
674 }
Rafael Espindola3729d002010-10-05 23:57:26 +0000675
Rafael Espindola1c130262011-01-23 04:43:11 +0000676 if (Section.getFlags() & ELF::SHF_MERGE) {
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000677 if (Target.getConstant() == 0)
Jason W Kime964d112011-05-11 22:53:06 +0000678 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000679 if (Renamed)
680 return Renamed;
681 return &Symbol;
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000682 }
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000683
Jason W Kime964d112011-05-11 22:53:06 +0000684 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
685
Rafael Espindola73ffea42010-09-25 05:42:19 +0000686}
687
Matt Fleming3565a062010-08-16 18:57:57 +0000688
Jason W Kim56a39902010-12-06 21:57:34 +0000689void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
690 const MCAsmLayout &Layout,
691 const MCFragment *Fragment,
692 const MCFixup &Fixup,
693 MCValue Target,
694 uint64_t &FixedValue) {
695 int64_t Addend = 0;
696 int Index = 0;
697 int64_t Value = Target.getConstant();
698 const MCSymbol *RelocSymbol = NULL;
699
Rafael Espindola127a6a42010-12-17 07:28:17 +0000700 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Jason W Kim56a39902010-12-06 21:57:34 +0000701 if (!Target.isAbsolute()) {
702 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
703 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
Jason W Kime964d112011-05-11 22:53:06 +0000704 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
Jason W Kim56a39902010-12-06 21:57:34 +0000705
706 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
707 const MCSymbol &SymbolB = RefB->getSymbol();
708 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
709 IsPCRel = true;
710
711 // Offset of the symbol in the section
712 int64_t a = Layout.getSymbolOffset(&SDB);
713
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000714 // Offset of the relocation in the section
Jason W Kim56a39902010-12-06 21:57:34 +0000715 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
716 Value += b - a;
717 }
718
719 if (!RelocSymbol) {
720 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
721 MCFragment *F = SD.getFragment();
722
723 Index = F->getParent()->getOrdinal() + 1;
724
725 // Offset of the symbol in the section
726 Value += Layout.getSymbolOffset(&SD);
727 } else {
728 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
729 WeakrefUsedInReloc.insert(RelocSymbol);
730 else
731 UsedInReloc.insert(RelocSymbol);
732 Index = -1;
733 }
734 Addend = Value;
735 // Compensate for the addend on i386.
Rafael Espindolabff66a82010-12-18 03:27:34 +0000736 if (is64Bit())
Jason W Kim56a39902010-12-06 21:57:34 +0000737 Value = 0;
738 }
739
740 FixedValue = Value;
741 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
742 (RelocSymbol != 0), Addend);
Rafael Espindolac677e792011-12-21 14:26:29 +0000743 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
744 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
745 if (RelocNeedsGOT(Modifier))
746 NeedsGOT = true;
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000747
Jason W Kim56a39902010-12-06 21:57:34 +0000748 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
749 Fixup.getOffset();
Roman Divacky2a66cea2011-08-04 19:08:19 +0000750
Rafael Espindolaf3a86fb2011-12-22 01:57:09 +0000751 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
752 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
Jason W Kim56a39902010-12-06 21:57:34 +0000753
Rafael Espindolabff66a82010-12-18 03:27:34 +0000754 if (!hasRelocationAddend())
755 Addend = 0;
Rafael Espindolabbf9c4a2011-08-04 13:05:26 +0000756
757 if (is64Bit())
758 assert(isInt<64>(Addend));
759 else
760 assert(isInt<32>(Addend));
761
Akira Hatanaka00ca8882012-03-23 23:06:45 +0000762 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
Jason W Kim56a39902010-12-06 21:57:34 +0000763 Relocations[Fragment->getParent()].push_back(ERE);
764}
765
766
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000767uint64_t
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000768ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
769 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000770 MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000771 return SD.getIndex();
Matt Fleming3565a062010-08-16 18:57:57 +0000772}
773
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000774bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
775 const MCSymbolData &Data,
776 bool Used, bool Renamed) {
Rafael Espindola484291c2010-11-01 14:28:48 +0000777 if (Data.getFlags() & ELF_Other_Weakref)
778 return false;
779
Rafael Espindolabd701182010-10-19 19:31:37 +0000780 if (Used)
781 return true;
782
Rafael Espindola88182132010-10-27 15:18:17 +0000783 if (Renamed)
784 return false;
785
Rafael Espindola737cd212010-10-05 18:01:23 +0000786 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000787
Rafael Espindolad1798862010-10-29 23:09:31 +0000788 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
789 return true;
790
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000791 const MCSymbol &A = Symbol.AliasedSymbol();
Rafael Espindola21451e52011-02-23 20:22:07 +0000792 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
793 return false;
794
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000795 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola21451e52011-02-23 20:22:07 +0000796 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa6866962010-10-27 14:44:52 +0000797 return false;
798
Rafael Espindola737cd212010-10-05 18:01:23 +0000799 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
800 return false;
801
Rafael Espindolabd701182010-10-19 19:31:37 +0000802 if (Symbol.isTemporary())
Rafael Espindola737cd212010-10-05 18:01:23 +0000803 return false;
804
805 return true;
806}
807
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000808bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
809 bool isUsedInReloc) {
Rafael Espindola737cd212010-10-05 18:01:23 +0000810 if (Data.isExternal())
811 return false;
812
813 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000814 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000815
816 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
817 if (isSignature && !isUsedInReloc)
818 return true;
819
Rafael Espindola737cd212010-10-05 18:01:23 +0000820 return false;
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000821 }
Rafael Espindola737cd212010-10-05 18:01:23 +0000822
823 return true;
824}
825
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000826void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000827 SectionIndexMapTy &SectionIndexMap,
828 const RelMapTy &RelMap) {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000829 unsigned Index = 1;
830 for (MCAssembler::iterator it = Asm.begin(),
831 ie = Asm.end(); it != ie; ++it) {
832 const MCSectionELF &Section =
833 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola2ff9e832010-11-11 18:13:52 +0000834 if (Section.getType() != ELF::SHT_GROUP)
835 continue;
836 SectionIndexMap[&Section] = Index++;
837 }
838
839 for (MCAssembler::iterator it = Asm.begin(),
840 ie = Asm.end(); it != ie; ++it) {
841 const MCSectionELF &Section =
842 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000843 if (Section.getType() == ELF::SHT_GROUP ||
844 Section.getType() == ELF::SHT_REL ||
845 Section.getType() == ELF::SHT_RELA)
Rafael Espindola2ff9e832010-11-11 18:13:52 +0000846 continue;
Rafael Espindolabab2a802010-11-10 21:51:05 +0000847 SectionIndexMap[&Section] = Index++;
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000848 const MCSectionELF *RelSection = RelMap.lookup(&Section);
849 if (RelSection)
850 SectionIndexMap[RelSection] = Index++;
Rafael Espindolabab2a802010-11-10 21:51:05 +0000851 }
852}
853
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000854void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000855 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000856 RevGroupMapTy RevGroupMap,
857 unsigned NumRegularSections) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000858 // FIXME: Is this the correct place to do this?
Rafael Espindola378e0ec2011-06-05 01:20:06 +0000859 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindola5c77c162010-10-05 15:48:37 +0000860 if (NeedsGOT) {
861 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
862 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
863 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
864 Data.setExternal(true);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000865 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindola5c77c162010-10-05 15:48:37 +0000866 }
867
Matt Fleming3565a062010-08-16 18:57:57 +0000868 // Index 0 is always the empty string.
869 StringMap<uint64_t> StringIndexMap;
870 StringTable += '\x00';
871
Rafael Espindolad5321da2011-04-07 23:21:52 +0000872 // FIXME: We could optimize suffixes in strtab in the same way we
873 // optimize them in shstrtab.
874
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000875 // Add the data for the symbols.
Matt Fleming3565a062010-08-16 18:57:57 +0000876 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
877 ie = Asm.symbol_end(); it != ie; ++it) {
878 const MCSymbol &Symbol = it->getSymbol();
879
Rafael Espindola484291c2010-11-01 14:28:48 +0000880 bool Used = UsedInReloc.count(&Symbol);
881 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000882 bool isSignature = RevGroupMap.count(&Symbol);
883
884 if (!isInSymtab(Asm, *it,
885 Used || WeakrefUsed || isSignature,
Rafael Espindola88182132010-10-27 15:18:17 +0000886 Renames.count(&Symbol)))
Matt Fleming3565a062010-08-16 18:57:57 +0000887 continue;
888
Matt Fleming3565a062010-08-16 18:57:57 +0000889 ELFSymbolData MSD;
890 MSD.SymbolData = it;
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000891 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Matt Fleming3565a062010-08-16 18:57:57 +0000892
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000893 // Undefined symbols are global, but this is the first place we
894 // are able to set it.
895 bool Local = isLocal(*it, isSignature, Used);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000896 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000897 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000898 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
899 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000900 }
901
Rafael Espindola484291c2010-11-01 14:28:48 +0000902 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000903 MCELF::SetBinding(*it, ELF::STB_WEAK);
Rafael Espindola484291c2010-11-01 14:28:48 +0000904
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000905 if (it->isCommon()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000906 assert(!Local);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000907 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindolabf052ac2010-10-27 16:04:30 +0000908 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000909 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola88182132010-10-27 15:18:17 +0000910 } else if (RefSymbol.isUndefined()) {
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000911 if (isSignature && !Used)
912 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
913 else
914 MSD.SectionIndex = ELF::SHN_UNDEF;
Matt Fleming3565a062010-08-16 18:57:57 +0000915 } else {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000916 const MCSectionELF &Section =
917 static_cast<const MCSectionELF&>(RefSymbol.getSection());
918 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000919 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
920 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000921 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000922 }
923
Rafael Espindola88182132010-10-27 15:18:17 +0000924 // The @@@ in symbol version is replaced with @ in undefined symbols and
925 // @@ in defined ones.
926 StringRef Name = Symbol.getName();
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000927 SmallString<32> Buf;
928
Rafael Espindola88182132010-10-27 15:18:17 +0000929 size_t Pos = Name.find("@@@");
Rafael Espindola88182132010-10-27 15:18:17 +0000930 if (Pos != StringRef::npos) {
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000931 Buf += Name.substr(0, Pos);
932 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
933 Buf += Name.substr(Pos + Skip);
934 Name = Buf;
Rafael Espindola88182132010-10-27 15:18:17 +0000935 }
936
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000937 uint64_t &Entry = StringIndexMap[Name];
Rafael Espindolaa6866962010-10-27 14:44:52 +0000938 if (!Entry) {
939 Entry = StringTable.size();
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000940 StringTable += Name;
Rafael Espindolaa6866962010-10-27 14:44:52 +0000941 StringTable += '\x00';
Matt Fleming3565a062010-08-16 18:57:57 +0000942 }
Rafael Espindolaa6866962010-10-27 14:44:52 +0000943 MSD.StringIndex = Entry;
944 if (MSD.SectionIndex == ELF::SHN_UNDEF)
945 UndefinedSymbolData.push_back(MSD);
946 else if (Local)
947 LocalSymbolData.push_back(MSD);
948 else
949 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000950 }
951
952 // Symbols are required to be in lexicographic order.
953 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
954 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
955 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
956
957 // Set the symbol indices. Local symbols must come before all other
958 // symbols with non-local bindings.
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000959 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000960 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
961 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000962
963 Index += NumRegularSections;
964
Matt Fleming3565a062010-08-16 18:57:57 +0000965 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
966 ExternalSymbolData[i].SymbolData->setIndex(Index++);
967 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
968 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
Nick Lewycky7aabcb12011-10-11 03:54:50 +0000969
970 if (NumRegularSections > ELF::SHN_LORESERVE)
971 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000972}
973
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000974void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
975 MCAsmLayout &Layout,
976 RelMapTy &RelMap) {
977 for (MCAssembler::const_iterator it = Asm.begin(),
978 ie = Asm.end(); it != ie; ++it) {
979 const MCSectionData &SD = *it;
980 if (Relocations[&SD].empty())
981 continue;
982
Matt Fleming3565a062010-08-16 18:57:57 +0000983 MCContext &Ctx = Asm.getContext();
Matt Fleming3565a062010-08-16 18:57:57 +0000984 const MCSectionELF &Section =
985 static_cast<const MCSectionELF&>(SD.getSection());
986
987 const StringRef SectionName = Section.getSectionName();
Rafael Espindolabff66a82010-12-18 03:27:34 +0000988 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000989 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000990
991 unsigned EntrySize;
Rafael Espindolabff66a82010-12-18 03:27:34 +0000992 if (hasRelocationAddend())
993 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000994 else
Rafael Espindolabff66a82010-12-18 03:27:34 +0000995 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +0000996
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000997 const MCSectionELF *RelaSection =
998 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
999 ELF::SHT_RELA : ELF::SHT_REL, 0,
1000 SectionKind::getReadOnly(),
1001 EntrySize, "");
1002 RelMap[&Section] = RelaSection;
1003 Asm.getOrCreateSectionData(*RelaSection);
1004 }
1005}
Matt Fleming3565a062010-08-16 18:57:57 +00001006
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001007void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1008 const RelMapTy &RelMap) {
1009 for (MCAssembler::const_iterator it = Asm.begin(),
1010 ie = Asm.end(); it != ie; ++it) {
1011 const MCSectionData &SD = *it;
1012 const MCSectionELF &Section =
1013 static_cast<const MCSectionELF&>(SD.getSection());
1014
1015 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1016 if (!RelaSection)
1017 continue;
Matt Fleming3565a062010-08-16 18:57:57 +00001018 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolabff66a82010-12-18 03:27:34 +00001019 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +00001020
1021 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001022 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming3565a062010-08-16 18:57:57 +00001023 }
1024}
1025
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001026void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1027 uint64_t Flags, uint64_t Address,
1028 uint64_t Offset, uint64_t Size,
1029 uint32_t Link, uint32_t Info,
1030 uint64_t Alignment,
1031 uint64_t EntrySize) {
Matt Fleming3565a062010-08-16 18:57:57 +00001032 Write32(Name); // sh_name: index into string table
1033 Write32(Type); // sh_type
1034 WriteWord(Flags); // sh_flags
1035 WriteWord(Address); // sh_addr
1036 WriteWord(Offset); // sh_offset
1037 WriteWord(Size); // sh_size
1038 Write32(Link); // sh_link
1039 Write32(Info); // sh_info
1040 WriteWord(Alignment); // sh_addralign
1041 WriteWord(EntrySize); // sh_entsize
1042}
1043
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001044void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1045 MCDataFragment *F,
1046 const MCSectionData *SD) {
Matt Fleming3565a062010-08-16 18:57:57 +00001047 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka00ca8882012-03-23 23:06:45 +00001048
1049 // Sort the relocation entries. Most targets just sort by r_offset, but some
1050 // (e.g., MIPS) have additional constraints.
1051 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming3565a062010-08-16 18:57:57 +00001052
1053 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1054 ELFRelocationEntry entry = Relocs[e - i - 1];
1055
Rafael Espindola12203cc2010-11-21 00:48:25 +00001056 if (!entry.Index)
1057 ;
1058 else if (entry.Index < 0)
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001059 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1060 else
Rafael Espindola12203cc2010-11-21 00:48:25 +00001061 entry.Index += LocalSymbolData.size();
Rafael Espindolabff66a82010-12-18 03:27:34 +00001062 if (is64Bit()) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001063 String64(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001064
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001065 struct ELF::Elf64_Rela ERE64;
1066 ERE64.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001067 String64(*F, ERE64.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001068
Rafael Espindolabff66a82010-12-18 03:27:34 +00001069 if (hasRelocationAddend())
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001070 String64(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001071 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001072 String32(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001073
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001074 struct ELF::Elf32_Rela ERE32;
1075 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001076 String32(*F, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001077
Rafael Espindolabff66a82010-12-18 03:27:34 +00001078 if (hasRelocationAddend())
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001079 String32(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001080 }
Matt Fleming3565a062010-08-16 18:57:57 +00001081 }
1082}
1083
Rafael Espindolad5321da2011-04-07 23:21:52 +00001084static int compareBySuffix(const void *a, const void *b) {
1085 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1086 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1087 const StringRef &NameA = secA->getSectionName();
1088 const StringRef &NameB = secB->getSectionName();
1089 const unsigned sizeA = NameA.size();
1090 const unsigned sizeB = NameB.size();
1091 const unsigned len = std::min(sizeA, sizeB);
1092 for (unsigned int i = 0; i < len; ++i) {
1093 char ca = NameA[sizeA - i - 1];
1094 char cb = NameB[sizeB - i - 1];
1095 if (ca != cb)
1096 return cb - ca;
1097 }
1098
1099 return sizeB - sizeA;
1100}
1101
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001102void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1103 MCAsmLayout &Layout,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001104 SectionIndexMapTy &SectionIndexMap,
1105 const RelMapTy &RelMap) {
Matt Fleming3565a062010-08-16 18:57:57 +00001106 MCContext &Ctx = Asm.getContext();
1107 MCDataFragment *F;
1108
Rafael Espindolabff66a82010-12-18 03:27:34 +00001109 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming3565a062010-08-16 18:57:57 +00001110
Rafael Espindola38738bf2010-09-22 19:04:41 +00001111 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001112 const MCSectionELF *ShstrtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001113 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001114 SectionKind::getReadOnly());
Rafael Espindola71859c62010-09-16 19:46:31 +00001115 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1116 ShstrtabSD.setAlignment(1);
Rafael Espindola71859c62010-09-16 19:46:31 +00001117
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001118 const MCSectionELF *SymtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001119 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1120 SectionKind::getReadOnly(),
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001121 EntrySize, "");
Matt Fleming3565a062010-08-16 18:57:57 +00001122 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolabff66a82010-12-18 03:27:34 +00001123 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001124
1125 MCSectionData *SymtabShndxSD = NULL;
1126
1127 if (NeedsSymtabShndx) {
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001128 const MCSectionELF *SymtabShndxSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001129 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001130 SectionKind::getReadOnly(), 4, "");
Rafael Espindola7be2c332010-10-31 00:16:26 +00001131 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1132 SymtabShndxSD->setAlignment(4);
1133 }
Matt Fleming3565a062010-08-16 18:57:57 +00001134
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001135 const MCSectionELF *StrtabSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001136 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001137 SectionKind::getReadOnly());
Matt Fleming3565a062010-08-16 18:57:57 +00001138 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1139 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +00001140
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001141 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1142
1143 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1144 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1145 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola71859c62010-09-16 19:46:31 +00001146
1147 // Symbol table
1148 F = new MCDataFragment(&SymtabSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001149 MCDataFragment *ShndxF = NULL;
1150 if (NeedsSymtabShndx) {
1151 ShndxF = new MCDataFragment(SymtabShndxSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001152 }
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001153 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
Rafael Espindola71859c62010-09-16 19:46:31 +00001154
Matt Fleming3565a062010-08-16 18:57:57 +00001155 F = new MCDataFragment(&StrtabSD);
1156 F->getContents().append(StringTable.begin(), StringTable.end());
Matt Fleming3565a062010-08-16 18:57:57 +00001157
Matt Fleming3565a062010-08-16 18:57:57 +00001158 F = new MCDataFragment(&ShstrtabSD);
1159
Rafael Espindolad5321da2011-04-07 23:21:52 +00001160 std::vector<const MCSectionELF*> Sections;
1161 for (MCAssembler::const_iterator it = Asm.begin(),
1162 ie = Asm.end(); it != ie; ++it) {
1163 const MCSectionELF &Section =
1164 static_cast<const MCSectionELF&>(it->getSection());
1165 Sections.push_back(&Section);
1166 }
1167 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1168
Matt Fleming3565a062010-08-16 18:57:57 +00001169 // Section header string table.
1170 //
1171 // The first entry of a string table holds a null character so skip
1172 // section 0.
1173 uint64_t Index = 1;
1174 F->getContents() += '\x00';
1175
Rafael Espindolad5321da2011-04-07 23:21:52 +00001176 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1177 const MCSectionELF &Section = *Sections[I];
Matt Fleming3565a062010-08-16 18:57:57 +00001178
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001179 StringRef Name = Section.getSectionName();
Rafael Espindolad5321da2011-04-07 23:21:52 +00001180 if (I != 0) {
1181 StringRef PreviousName = Sections[I - 1]->getSectionName();
1182 if (PreviousName.endswith(Name)) {
1183 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1184 continue;
1185 }
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001186 }
Matt Fleming3565a062010-08-16 18:57:57 +00001187 // Remember the index into the string table so we can write it
1188 // into the sh_name field of the section header table.
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001189 SectionStringTableIndex[&Section] = Index;
Matt Fleming3565a062010-08-16 18:57:57 +00001190
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001191 Index += Name.size() + 1;
1192 F->getContents() += Name;
Matt Fleming3565a062010-08-16 18:57:57 +00001193 F->getContents() += '\x00';
1194 }
Rafael Espindola70703872010-09-30 02:22:20 +00001195}
1196
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001197void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1198 MCAsmLayout &Layout,
1199 GroupMapTy &GroupMap,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001200 RevGroupMapTy &RevGroupMap,
1201 SectionIndexMapTy &SectionIndexMap,
1202 const RelMapTy &RelMap) {
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001203 // Create the .note.GNU-stack section if needed.
1204 MCContext &Ctx = Asm.getContext();
1205 if (Asm.getNoExecStack()) {
1206 const MCSectionELF *GnuStackSection =
1207 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1208 SectionKind::getReadOnly());
1209 Asm.getOrCreateSectionData(*GnuStackSection);
1210 }
1211
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001212 // Build the groups
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001213 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1214 it != ie; ++it) {
1215 const MCSectionELF &Section =
1216 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola1c130262011-01-23 04:43:11 +00001217 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001218 continue;
1219
1220 const MCSymbol *SignatureSymbol = Section.getGroup();
1221 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +00001222 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001223 if (!Group) {
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001224 Group = Ctx.CreateELFGroupSection();
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001225 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1226 Data.setAlignment(4);
1227 MCDataFragment *F = new MCDataFragment(&Data);
1228 String32(*F, ELF::GRP_COMDAT);
1229 }
1230 GroupMap[Group] = SignatureSymbol;
1231 }
1232
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001233 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1234
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001235 // Add sections to the groups
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001236 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001237 it != ie; ++it) {
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001238 const MCSectionELF &Section =
1239 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola1c130262011-01-23 04:43:11 +00001240 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001241 continue;
Rafael Espindola1f4f9e32010-11-14 04:17:37 +00001242 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001243 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1244 // FIXME: we could use the previous fragment
1245 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001246 unsigned Index = SectionIndexMap.lookup(&Section);
1247 String32(*F, Index);
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001248 }
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001249}
1250
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001251void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1252 const SectionIndexMapTy &SectionIndexMap,
1253 uint32_t GroupSymbolIndex,
1254 uint64_t Offset, uint64_t Size,
1255 uint64_t Alignment,
1256 const MCSectionELF &Section) {
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001257 uint64_t sh_link = 0;
1258 uint64_t sh_info = 0;
1259
1260 switch(Section.getType()) {
1261 case ELF::SHT_DYNAMIC:
1262 sh_link = SectionStringTableIndex[&Section];
1263 sh_info = 0;
1264 break;
1265
1266 case ELF::SHT_REL:
1267 case ELF::SHT_RELA: {
1268 const MCSectionELF *SymtabSection;
1269 const MCSectionELF *InfoSection;
1270 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1271 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001272 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001273 sh_link = SectionIndexMap.lookup(SymtabSection);
1274 assert(sh_link && ".symtab not found");
1275
1276 // Remove ".rel" and ".rela" prefixes.
1277 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1278 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1279
1280 InfoSection = Asm.getContext().getELFSection(SectionName,
1281 ELF::SHT_PROGBITS, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001282 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001283 sh_info = SectionIndexMap.lookup(InfoSection);
1284 break;
1285 }
1286
1287 case ELF::SHT_SYMTAB:
1288 case ELF::SHT_DYNSYM:
1289 sh_link = StringTableIndex;
1290 sh_info = LastLocalSymbolIndex;
1291 break;
1292
1293 case ELF::SHT_SYMTAB_SHNDX:
1294 sh_link = SymbolTableIndex;
1295 break;
1296
1297 case ELF::SHT_PROGBITS:
1298 case ELF::SHT_STRTAB:
1299 case ELF::SHT_NOBITS:
Rafael Espindola98976612010-12-26 21:30:59 +00001300 case ELF::SHT_NOTE:
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001301 case ELF::SHT_NULL:
1302 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim86a97f22011-01-12 00:19:25 +00001303 case ELF::SHT_INIT_ARRAY:
1304 case ELF::SHT_FINI_ARRAY:
1305 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola0cf5e3d2011-01-23 05:43:40 +00001306 case ELF::SHT_X86_64_UNWIND:
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001307 // Nothing to do.
1308 break;
1309
Nick Lewycky4a8d43e2011-10-07 23:28:32 +00001310 case ELF::SHT_GROUP:
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001311 sh_link = SymbolTableIndex;
1312 sh_info = GroupSymbolIndex;
1313 break;
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001314
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001315 default:
1316 assert(0 && "FIXME: sh_type value not supported!");
1317 break;
1318 }
1319
1320 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1321 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1322 Alignment, Section.getEntrySize());
1323}
1324
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001325bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolaf8803fe2010-12-06 03:48:09 +00001326 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001327 !SD.getSection().isVirtualSection();
1328}
1329
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001330uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001331 uint64_t Ret = 0;
1332 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1333 ++i) {
1334 const MCFragment &F = *i;
1335 assert(F.getKind() == MCFragment::FT_Data);
1336 Ret += cast<MCDataFragment>(F).getContents().size();
1337 }
1338 return Ret;
1339}
1340
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001341uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1342 const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001343 if (IsELFMetaDataSection(SD))
1344 return DataSectionSize(SD);
1345 return Layout.getSectionFileSize(&SD);
1346}
1347
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001348uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1349 const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001350 if (IsELFMetaDataSection(SD))
1351 return DataSectionSize(SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001352 return Layout.getSectionAddressSize(&SD);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001353}
1354
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001355void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1356 const MCAsmLayout &Layout,
1357 const MCSectionELF &Section) {
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001358 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1359
Benjamin Kramer263109d2012-01-20 14:42:32 +00001360 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001361 WriteZeros(Padding);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001362
1363 if (IsELFMetaDataSection(SD)) {
1364 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1365 ++i) {
1366 const MCFragment &F = *i;
1367 assert(F.getKind() == MCFragment::FT_Data);
1368 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1369 }
1370 } else {
Jim Grosbachf77d5b12011-12-06 00:03:48 +00001371 Asm.writeSectionData(&SD, Layout);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001372 }
1373}
1374
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001375void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1376 const GroupMapTy &GroupMap,
1377 const MCAsmLayout &Layout,
1378 const SectionIndexMapTy &SectionIndexMap,
1379 const SectionOffsetMapTy &SectionOffsetMap) {
1380 const unsigned NumSections = Asm.size() + 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001381
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001382 std::vector<const MCSectionELF*> Sections;
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001383 Sections.resize(NumSections - 1);
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001384
1385 for (SectionIndexMapTy::const_iterator i=
1386 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1387 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001388 Sections[p.second - 1] = p.first;
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001389 }
1390
Matt Fleming3565a062010-08-16 18:57:57 +00001391 // Null section first.
Rafael Espindola7be2c332010-10-31 00:16:26 +00001392 uint64_t FirstSectionSize =
1393 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1394 uint32_t FirstSectionLink =
1395 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1396 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming3565a062010-08-16 18:57:57 +00001397
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001398 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001399 const MCSectionELF &Section = *Sections[i];
1400 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1401 uint32_t GroupSymbolIndex;
1402 if (Section.getType() != ELF::SHT_GROUP)
1403 GroupSymbolIndex = 0;
1404 else
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001405 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1406 GroupMap.lookup(&Section));
Matt Fleming3565a062010-08-16 18:57:57 +00001407
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001408 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001409
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001410 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001411 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001412 SD.getAlignment(), Section);
Matt Fleming3565a062010-08-16 18:57:57 +00001413 }
1414}
1415
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001416void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1417 std::vector<const MCSectionELF*> &Sections) {
1418 for (MCAssembler::iterator it = Asm.begin(),
1419 ie = Asm.end(); it != ie; ++it) {
1420 const MCSectionELF &Section =
1421 static_cast<const MCSectionELF &>(it->getSection());
1422 if (Section.getType() == ELF::SHT_GROUP)
1423 Sections.push_back(&Section);
1424 }
1425
1426 for (MCAssembler::iterator it = Asm.begin(),
1427 ie = Asm.end(); it != ie; ++it) {
1428 const MCSectionELF &Section =
1429 static_cast<const MCSectionELF &>(it->getSection());
1430 if (Section.getType() != ELF::SHT_GROUP &&
1431 Section.getType() != ELF::SHT_REL &&
1432 Section.getType() != ELF::SHT_RELA)
1433 Sections.push_back(&Section);
1434 }
1435
1436 for (MCAssembler::iterator it = Asm.begin(),
1437 ie = Asm.end(); it != ie; ++it) {
1438 const MCSectionELF &Section =
1439 static_cast<const MCSectionELF &>(it->getSection());
1440 if (Section.getType() == ELF::SHT_REL ||
1441 Section.getType() == ELF::SHT_RELA)
1442 Sections.push_back(&Section);
1443 }
1444}
1445
1446void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1447 const MCAsmLayout &Layout) {
1448 GroupMapTy GroupMap;
1449 RevGroupMapTy RevGroupMap;
1450 SectionIndexMapTy SectionIndexMap;
1451
1452 unsigned NumUserSections = Asm.size();
1453
1454 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1455 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1456
1457 const unsigned NumUserAndRelocSections = Asm.size();
1458 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1459 RevGroupMap, SectionIndexMap, RelMap);
1460 const unsigned AllSections = Asm.size();
1461 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1462
1463 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1464
1465 // Compute symbol table information.
1466 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1467
1468
1469 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1470
1471 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1472 const_cast<MCAsmLayout&>(Layout),
1473 SectionIndexMap,
1474 RelMap);
1475
1476 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1477 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1478 sizeof(ELF::Elf32_Ehdr);
1479 uint64_t FileOff = HeaderSize;
1480
1481 std::vector<const MCSectionELF*> Sections;
1482 ComputeSectionOrder(Asm, Sections);
1483 unsigned NumSections = Sections.size();
1484 SectionOffsetMapTy SectionOffsetMap;
1485 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1486 const MCSectionELF &Section = *Sections[i];
1487 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1488
1489 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1490
1491 // Remember the offset into the file for this section.
1492 SectionOffsetMap[&Section] = FileOff;
1493
1494 // Get the size of the section in the output file (including padding).
1495 FileOff += GetSectionFileSize(Layout, SD);
1496 }
1497
1498 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1499
1500 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1501
1502 uint64_t SectionHeaderEntrySize = is64Bit() ?
1503 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1504 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1505
1506 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1507 const MCSectionELF &Section = *Sections[i];
1508 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1509
1510 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1511
1512 // Remember the offset into the file for this section.
1513 SectionOffsetMap[&Section] = FileOff;
1514
1515 // Get the size of the section in the output file (including padding).
1516 FileOff += GetSectionFileSize(Layout, SD);
1517 }
1518
1519 // Write out the ELF header ...
1520 WriteHeader(SectionHeaderOffset, NumSections + 1);
1521
1522 // ... then the regular sections ...
1523 // + because of .shstrtab
1524 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1525 WriteDataSectionData(Asm, Layout, *Sections[i]);
1526
Benjamin Kramer263109d2012-01-20 14:42:32 +00001527 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001528 WriteZeros(Padding);
1529
1530 // ... then the section header table ...
1531 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1532 SectionOffsetMap);
1533
Nick Lewyckyaaae3f62011-10-07 20:56:23 +00001534 // ... and then the remaining sections ...
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001535 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1536 WriteDataSectionData(Asm, Layout, *Sections[i]);
1537}
1538
Eli Friedman78c1e172011-03-03 07:24:36 +00001539bool
1540ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1541 const MCSymbolData &DataA,
1542 const MCFragment &FB,
1543 bool InSet,
1544 bool IsPCRel) const {
1545 if (DataA.getFlags() & ELF_STB_Weak)
1546 return false;
1547 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1548 Asm, DataA, FB,InSet, IsPCRel);
1549}
1550
Rafael Espindola6024c972010-12-17 17:45:22 +00001551MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1552 raw_ostream &OS,
Rafael Espindolabff66a82010-12-18 03:27:34 +00001553 bool IsLittleEndian) {
Rafael Espindola7bd27802011-12-22 03:24:43 +00001554 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolaedae8e12011-12-21 17:30:17 +00001555}