blob: eda062376edc365584c2892b62657b08bd8217af [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 }
Adhemerval Zanellaaa714282012-10-25 12:27:42 +0000136 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
137 const MCFixup &Fixup,
138 bool IsPCRel) const {
139 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup, IsPCRel);
140 }
Rafael Espindola3963d612011-12-22 03:38:00 +0000141
142 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
143 bool hasRelocationAddend() const {
144 return TargetObjectWriter->hasRelocationAddend();
145 }
146 unsigned getEFlags() const {
147 return TargetObjectWriter->getEFlags();
148 }
149 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
150 bool IsPCRel, bool IsRelocWithSymbol,
151 int64_t Addend) const {
152 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
153 IsRelocWithSymbol, Addend);
154 }
155
156
157 public:
158 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
159 raw_ostream &_OS, bool IsLittleEndian)
160 : MCObjectWriter(_OS, IsLittleEndian),
161 TargetObjectWriter(MOTW),
162 NeedsGOT(false), NeedsSymtabShndx(false){
163 }
164
165 virtual ~ELFObjectWriter();
166
167 void WriteWord(uint64_t W) {
168 if (is64Bit())
169 Write64(W);
170 else
171 Write32(W);
172 }
173
174 void StringLE16(char *buf, uint16_t Value) {
175 buf[0] = char(Value >> 0);
176 buf[1] = char(Value >> 8);
177 }
178
179 void StringLE32(char *buf, uint32_t Value) {
180 StringLE16(buf, uint16_t(Value >> 0));
181 StringLE16(buf + 2, uint16_t(Value >> 16));
182 }
183
184 void StringLE64(char *buf, uint64_t Value) {
185 StringLE32(buf, uint32_t(Value >> 0));
186 StringLE32(buf + 4, uint32_t(Value >> 32));
187 }
188
189 void StringBE16(char *buf ,uint16_t Value) {
190 buf[0] = char(Value >> 8);
191 buf[1] = char(Value >> 0);
192 }
193
194 void StringBE32(char *buf, uint32_t Value) {
195 StringBE16(buf, uint16_t(Value >> 16));
196 StringBE16(buf + 2, uint16_t(Value >> 0));
197 }
198
199 void StringBE64(char *buf, uint64_t Value) {
200 StringBE32(buf, uint32_t(Value >> 32));
201 StringBE32(buf + 4, uint32_t(Value >> 0));
202 }
203
204 void String8(MCDataFragment &F, uint8_t Value) {
205 char buf[1];
206 buf[0] = Value;
207 F.getContents() += StringRef(buf, 1);
208 }
209
210 void String16(MCDataFragment &F, uint16_t Value) {
211 char buf[2];
212 if (isLittleEndian())
213 StringLE16(buf, Value);
214 else
215 StringBE16(buf, Value);
216 F.getContents() += StringRef(buf, 2);
217 }
218
219 void String32(MCDataFragment &F, uint32_t Value) {
220 char buf[4];
221 if (isLittleEndian())
222 StringLE32(buf, Value);
223 else
224 StringBE32(buf, Value);
225 F.getContents() += StringRef(buf, 4);
226 }
227
228 void String64(MCDataFragment &F, uint64_t Value) {
229 char buf[8];
230 if (isLittleEndian())
231 StringLE64(buf, Value);
232 else
233 StringBE64(buf, Value);
234 F.getContents() += StringRef(buf, 8);
235 }
236
237 void WriteHeader(uint64_t SectionDataSize,
238 unsigned NumberOfSections);
239
240 void WriteSymbolEntry(MCDataFragment *SymtabF,
241 MCDataFragment *ShndxF,
242 uint64_t name, uint8_t info,
243 uint64_t value, uint64_t size,
244 uint8_t other, uint32_t shndx,
245 bool Reserved);
246
247 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
248 ELFSymbolData &MSD,
249 const MCAsmLayout &Layout);
250
251 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
252 void WriteSymbolTable(MCDataFragment *SymtabF,
253 MCDataFragment *ShndxF,
254 const MCAssembler &Asm,
255 const MCAsmLayout &Layout,
256 const SectionIndexMapTy &SectionIndexMap);
257
258 virtual void RecordRelocation(const MCAssembler &Asm,
259 const MCAsmLayout &Layout,
260 const MCFragment *Fragment,
261 const MCFixup &Fixup,
262 MCValue Target, uint64_t &FixedValue);
263
264 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
265 const MCSymbol *S);
266
267 // Map from a group section to the signature symbol
268 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
269 // Map from a signature symbol to the group section
270 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
271 // Map from a section to the section with the relocations
272 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
273 // Map from a section to its offset
274 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
275
276 /// ComputeSymbolTable - Compute the symbol table data
277 ///
Rafael Espindola828ea382012-08-27 16:04:24 +0000278 /// \param Asm - The assembler.
279 /// \param SectionIndexMap - Maps a section to its index.
280 /// \param RevGroupMap - Maps a signature symbol to the group section.
281 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola3963d612011-12-22 03:38:00 +0000282 void ComputeSymbolTable(MCAssembler &Asm,
283 const SectionIndexMapTy &SectionIndexMap,
284 RevGroupMapTy RevGroupMap,
285 unsigned NumRegularSections);
286
287 void ComputeIndexMap(MCAssembler &Asm,
288 SectionIndexMapTy &SectionIndexMap,
289 const RelMapTy &RelMap);
290
291 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
292 RelMapTy &RelMap);
293
294 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
295 const RelMapTy &RelMap);
296
297 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
298 SectionIndexMapTy &SectionIndexMap,
299 const RelMapTy &RelMap);
300
301 // Create the sections that show up in the symbol table. Currently
302 // those are the .note.GNU-stack section and the group sections.
303 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
304 GroupMapTy &GroupMap,
305 RevGroupMapTy &RevGroupMap,
306 SectionIndexMapTy &SectionIndexMap,
307 const RelMapTy &RelMap);
308
309 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
310 const MCAsmLayout &Layout);
311
312 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
313 const MCAsmLayout &Layout,
314 const SectionIndexMapTy &SectionIndexMap,
315 const SectionOffsetMapTy &SectionOffsetMap);
316
317 void ComputeSectionOrder(MCAssembler &Asm,
318 std::vector<const MCSectionELF*> &Sections);
319
320 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
321 uint64_t Address, uint64_t Offset,
322 uint64_t Size, uint32_t Link, uint32_t Info,
323 uint64_t Alignment, uint64_t EntrySize);
324
325 void WriteRelocationsFragment(const MCAssembler &Asm,
326 MCDataFragment *F,
327 const MCSectionData *SD);
328
329 virtual bool
330 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
331 const MCSymbolData &DataA,
332 const MCFragment &FB,
333 bool InSet,
334 bool IsPCRel) const;
335
336 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
337 void WriteSection(MCAssembler &Asm,
338 const SectionIndexMapTy &SectionIndexMap,
339 uint32_t GroupSymbolIndex,
340 uint64_t Offset, uint64_t Size, uint64_t Alignment,
341 const MCSectionELF &Section);
342 };
343}
344
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000345bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
346 const MCFixupKindInfo &FKI =
347 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
348
349 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
350}
351
352bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
353 switch (Variant) {
354 default:
355 return false;
356 case MCSymbolRefExpr::VK_GOT:
357 case MCSymbolRefExpr::VK_PLT:
358 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola378e0ec2011-06-05 01:20:06 +0000359 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000360 case MCSymbolRefExpr::VK_TPOFF:
361 case MCSymbolRefExpr::VK_TLSGD:
362 case MCSymbolRefExpr::VK_GOTTPOFF:
363 case MCSymbolRefExpr::VK_INDNTPOFF:
364 case MCSymbolRefExpr::VK_NTPOFF:
365 case MCSymbolRefExpr::VK_GOTNTPOFF:
366 case MCSymbolRefExpr::VK_TLSLDM:
367 case MCSymbolRefExpr::VK_DTPOFF:
368 case MCSymbolRefExpr::VK_TLSLD:
369 return true;
370 }
371}
372
Jason W Kimd3443e92010-11-15 16:18:39 +0000373ELFObjectWriter::~ELFObjectWriter()
374{}
375
Matt Fleming3565a062010-08-16 18:57:57 +0000376// Emit the ELF header.
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000377void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
378 unsigned NumberOfSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000379 // ELF Header
380 // ----------
381 //
382 // Note
383 // ----
384 // emitWord method behaves differently for ELF32 and ELF64, writing
385 // 4 bytes in the former and 8 in the latter.
386
387 Write8(0x7f); // e_ident[EI_MAG0]
388 Write8('E'); // e_ident[EI_MAG1]
389 Write8('L'); // e_ident[EI_MAG2]
390 Write8('F'); // e_ident[EI_MAG3]
391
Rafael Espindolabff66a82010-12-18 03:27:34 +0000392 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming3565a062010-08-16 18:57:57 +0000393
394 // e_ident[EI_DATA]
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000395 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming3565a062010-08-16 18:57:57 +0000396
397 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000398 // e_ident[EI_OSABI]
Rafael Espindoladc9a8a32011-12-21 17:00:36 +0000399 Write8(TargetObjectWriter->getOSABI());
Matt Fleming3565a062010-08-16 18:57:57 +0000400 Write8(0); // e_ident[EI_ABIVERSION]
401
402 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
403
404 Write16(ELF::ET_REL); // e_type
405
Rafael Espindolabff66a82010-12-18 03:27:34 +0000406 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000407
408 Write32(ELF::EV_CURRENT); // e_version
409 WriteWord(0); // e_entry, no entry point in .o file
410 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolabff66a82010-12-18 03:27:34 +0000411 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramereb976772010-08-17 17:02:29 +0000412 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000413
Jason W Kim2d7a53a2011-02-04 21:41:11 +0000414 // e_flags = whatever the target wants
Rafael Espindolae8526d02011-12-21 20:09:46 +0000415 Write32(getEFlags());
Matt Fleming3565a062010-08-16 18:57:57 +0000416
417 // e_ehsize = ELF header size
Rafael Espindolabff66a82010-12-18 03:27:34 +0000418 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming3565a062010-08-16 18:57:57 +0000419
420 Write16(0); // e_phentsize = prog header entry size
421 Write16(0); // e_phnum = # prog header entries = 0
422
423 // e_shentsize = Section header entry size
Rafael Espindolabff66a82010-12-18 03:27:34 +0000424 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming3565a062010-08-16 18:57:57 +0000425
426 // e_shnum = # of section header ents
Rafael Espindola7be2c332010-10-31 00:16:26 +0000427 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewyckyaaae3f62011-10-07 20:56:23 +0000428 Write16(ELF::SHN_UNDEF);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000429 else
430 Write16(NumberOfSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000431
432 // e_shstrndx = Section # of '.shstrtab'
Nick Lewyckyb3429d32011-10-07 20:58:24 +0000433 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola7be2c332010-10-31 00:16:26 +0000434 Write16(ELF::SHN_XINDEX);
435 else
436 Write16(ShstrtabIndex);
Matt Fleming3565a062010-08-16 18:57:57 +0000437}
438
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000439void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
440 MCDataFragment *ShndxF,
441 uint64_t name,
442 uint8_t info, uint64_t value,
443 uint64_t size, uint8_t other,
444 uint32_t shndx,
445 bool Reserved) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000446 if (ShndxF) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000447 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000448 String32(*ShndxF, shndx);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000449 else
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000450 String32(*ShndxF, 0);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000451 }
452
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000453 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
454 uint16_t(ELF::SHN_XINDEX) : shndx;
455
Rafael Espindolabff66a82010-12-18 03:27:34 +0000456 if (is64Bit()) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000457 String32(*SymtabF, name); // st_name
458 String8(*SymtabF, info); // st_info
459 String8(*SymtabF, other); // st_other
460 String16(*SymtabF, Index); // st_shndx
461 String64(*SymtabF, value); // st_value
462 String64(*SymtabF, size); // st_size
Matt Fleming3565a062010-08-16 18:57:57 +0000463 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000464 String32(*SymtabF, name); // st_name
465 String32(*SymtabF, value); // st_value
466 String32(*SymtabF, size); // st_size
467 String8(*SymtabF, info); // st_info
468 String8(*SymtabF, other); // st_other
469 String16(*SymtabF, Index); // st_shndx
Matt Fleming3565a062010-08-16 18:57:57 +0000470 }
471}
472
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000473uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
474 const MCAsmLayout &Layout) {
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000475 if (Data.isCommon() && Data.isExternal())
476 return Data.getCommonAlignment();
477
478 const MCSymbol &Symbol = Data.getSymbol();
Roman Divackyd1491862010-12-20 21:14:39 +0000479
480 if (Symbol.isAbsolute() && Symbol.isVariable()) {
481 if (const MCExpr *Value = Symbol.getVariableValue()) {
482 int64_t IntValue;
483 if (Value->EvaluateAsAbsolute(IntValue, Layout))
Jim Grosbachf68a26b2011-12-06 00:13:09 +0000484 return (uint64_t)IntValue;
Roman Divackyd1491862010-12-20 21:14:39 +0000485 }
486 }
487
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000488 if (!Symbol.isInSection())
489 return 0;
490
Rafael Espindola64695402011-05-16 16:17:21 +0000491
492 if (Data.getFragment()) {
493 if (Data.getFlags() & ELF_Other_ThumbFunc)
494 return Layout.getSymbolOffset(&Data)+1;
495 else
496 return Layout.getSymbolOffset(&Data);
497 }
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000498
499 return 0;
500}
501
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000502void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
503 const MCAsmLayout &Layout) {
Rafael Espindola88182132010-10-27 15:18:17 +0000504 // The presence of symbol versions causes undefined symbols and
505 // versions declared with @@@ to be renamed.
506
507 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
508 ie = Asm.symbol_end(); it != ie; ++it) {
509 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000510 const MCSymbol &Symbol = Alias.AliasedSymbol();
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000511 MCSymbolData &SD = Asm.getSymbolData(Symbol);
512
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000513 // Not an alias.
514 if (&Symbol == &Alias)
515 continue;
516
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000517 StringRef AliasName = Alias.getName();
Rafael Espindola88182132010-10-27 15:18:17 +0000518 size_t Pos = AliasName.find('@');
519 if (Pos == StringRef::npos)
520 continue;
521
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000522 // Aliases defined with .symvar copy the binding from the symbol they alias.
523 // This is the first place we are able to copy this information.
524 it->setExternal(SD.isExternal());
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000525 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000526
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000527 StringRef Rest = AliasName.substr(Pos);
Rafael Espindola88182132010-10-27 15:18:17 +0000528 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
529 continue;
530
Rafael Espindola83ff4d22010-10-27 17:56:18 +0000531 // FIXME: produce a better error message.
532 if (Symbol.isUndefined() && Rest.startswith("@@") &&
533 !Rest.startswith("@@@"))
534 report_fatal_error("A @@ version cannot be undefined");
535
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000536 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindola88182132010-10-27 15:18:17 +0000537 }
538}
539
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000540void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
541 MCDataFragment *ShndxF,
542 ELFSymbolData &MSD,
543 const MCAsmLayout &Layout) {
Rafael Espindola152c1062010-10-06 21:02:29 +0000544 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindolade89b012010-10-15 18:25:33 +0000545 MCSymbolData &Data =
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000546 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
Rafael Espindola152c1062010-10-06 21:02:29 +0000547
Rafael Espindola7be2c332010-10-31 00:16:26 +0000548 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
549 Data.getSymbol().isVariable();
550
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000551 uint8_t Binding = MCELF::GetBinding(OrigData);
552 uint8_t Visibility = MCELF::GetVisibility(OrigData);
553 uint8_t Type = MCELF::GetType(Data);
Rafael Espindola152c1062010-10-06 21:02:29 +0000554
555 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
556 uint8_t Other = Visibility;
557
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000558 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000559 uint64_t Size = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000560
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000561 assert(!(Data.isCommon() && !Data.isExternal()));
562
Rafael Espindolaf0121242010-12-22 16:03:00 +0000563 const MCExpr *ESize = Data.getSize();
564 if (ESize) {
565 int64_t Res;
566 if (!ESize->EvaluateAsAbsolute(Res, Layout))
567 report_fatal_error("Size expression must be absolute.");
568 Size = Res;
Matt Fleming3565a062010-08-16 18:57:57 +0000569 }
570
571 // Write out the symbol table entry
Rafael Espindola7be2c332010-10-31 00:16:26 +0000572 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
573 Size, Other, MSD.SectionIndex, IsReserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000574}
575
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000576void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
577 MCDataFragment *ShndxF,
578 const MCAssembler &Asm,
579 const MCAsmLayout &Layout,
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000580 const SectionIndexMapTy &SectionIndexMap) {
Matt Fleming3565a062010-08-16 18:57:57 +0000581 // The string table must be emitted first because we need the index
582 // into the string table for all the symbol names.
583 assert(StringTable.size() && "Missing string table");
584
585 // FIXME: Make sure the start of the symbol table is aligned.
586
587 // The first entry is the undefined symbol entry.
Rafael Espindola7be2c332010-10-31 00:16:26 +0000588 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
Matt Fleming3565a062010-08-16 18:57:57 +0000589
590 // Write the symbol table entries.
591 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
592 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
593 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola7be2c332010-10-31 00:16:26 +0000594 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000595 }
596
Rafael Espindola71859c62010-09-16 19:46:31 +0000597 // Write out a symbol table entry for each regular section.
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000598 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
599 ++i) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000600 const MCSectionELF &Section =
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000601 static_cast<const MCSectionELF&>(i->getSection());
602 if (Section.getType() == ELF::SHT_RELA ||
603 Section.getType() == ELF::SHT_REL ||
604 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewyckyd2fdb4a2011-10-07 23:29:53 +0000605 Section.getType() == ELF::SHT_SYMTAB ||
606 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedmana44fa242010-08-16 21:17:09 +0000607 continue;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000608 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000609 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
610 false);
Eli Friedmana44fa242010-08-16 21:17:09 +0000611 LastLocalSymbolIndex++;
612 }
Matt Fleming3565a062010-08-16 18:57:57 +0000613
614 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
615 ELFSymbolData &MSD = ExternalSymbolData[i];
616 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola3223f192010-10-06 16:47:31 +0000617 assert(((Data.getFlags() & ELF_STB_Global) ||
618 (Data.getFlags() & ELF_STB_Weak)) &&
619 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola7be2c332010-10-31 00:16:26 +0000620 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000621 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000622 LastLocalSymbolIndex++;
623 }
624
625 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
626 ELFSymbolData &MSD = UndefinedSymbolData[i];
627 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000628 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000629 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000630 LastLocalSymbolIndex++;
631 }
632}
633
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000634const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
635 const MCValue &Target,
Jim Grosbach2684d9e2012-05-11 01:41:30 +0000636 const MCFragment &F,
Jason W Kime964d112011-05-11 22:53:06 +0000637 const MCFixup &Fixup,
638 bool IsPCRel) const {
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000639 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000640 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
641 const MCSymbol *Renamed = Renames.lookup(&Symbol);
642 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000643
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000644 if (ASymbol.isUndefined()) {
645 if (Renamed)
646 return Renamed;
Adhemerval Zanellaaa714282012-10-25 12:27:42 +0000647 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000648 }
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000649
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000650 if (SD.isExternal()) {
651 if (Renamed)
652 return Renamed;
653 return &Symbol;
654 }
Rafael Espindola73ffea42010-09-25 05:42:19 +0000655
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000656 const MCSectionELF &Section =
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000657 static_cast<const MCSectionELF&>(ASymbol.getSection());
Rafael Espindola25958732010-11-24 21:57:39 +0000658 const SectionKind secKind = Section.getKind();
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000659
Rafael Espindola25958732010-11-24 21:57:39 +0000660 if (secKind.isBSS())
Jason W Kime964d112011-05-11 22:53:06 +0000661 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000662
Rafael Espindola25958732010-11-24 21:57:39 +0000663 if (secKind.isThreadLocal()) {
664 if (Renamed)
665 return Renamed;
666 return &Symbol;
667 }
668
Rafael Espindola8cecf252010-10-06 16:23:36 +0000669 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindola3729d002010-10-05 23:57:26 +0000670 const MCSectionELF &Sec2 =
671 static_cast<const MCSectionELF&>(F.getParent()->getSection());
672
Rafael Espindola8cecf252010-10-06 16:23:36 +0000673 if (&Sec2 != &Section &&
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000674 (Kind == MCSymbolRefExpr::VK_PLT ||
675 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
Rafael Espindola25958732010-11-24 21:57:39 +0000676 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000677 if (Renamed)
678 return Renamed;
679 return &Symbol;
680 }
Rafael Espindola3729d002010-10-05 23:57:26 +0000681
Rafael Espindola1c130262011-01-23 04:43:11 +0000682 if (Section.getFlags() & ELF::SHF_MERGE) {
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000683 if (Target.getConstant() == 0)
Jason W Kime964d112011-05-11 22:53:06 +0000684 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000685 if (Renamed)
686 return Renamed;
687 return &Symbol;
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000688 }
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000689
Jason W Kime964d112011-05-11 22:53:06 +0000690 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
691
Rafael Espindola73ffea42010-09-25 05:42:19 +0000692}
693
Matt Fleming3565a062010-08-16 18:57:57 +0000694
Jason W Kim56a39902010-12-06 21:57:34 +0000695void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
696 const MCAsmLayout &Layout,
697 const MCFragment *Fragment,
698 const MCFixup &Fixup,
699 MCValue Target,
700 uint64_t &FixedValue) {
701 int64_t Addend = 0;
702 int Index = 0;
703 int64_t Value = Target.getConstant();
704 const MCSymbol *RelocSymbol = NULL;
705
Rafael Espindola127a6a42010-12-17 07:28:17 +0000706 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Jason W Kim56a39902010-12-06 21:57:34 +0000707 if (!Target.isAbsolute()) {
708 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
709 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
Jason W Kime964d112011-05-11 22:53:06 +0000710 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
Jason W Kim56a39902010-12-06 21:57:34 +0000711
712 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
713 const MCSymbol &SymbolB = RefB->getSymbol();
714 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
715 IsPCRel = true;
716
717 // Offset of the symbol in the section
718 int64_t a = Layout.getSymbolOffset(&SDB);
719
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000720 // Offset of the relocation in the section
Jason W Kim56a39902010-12-06 21:57:34 +0000721 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
722 Value += b - a;
723 }
724
725 if (!RelocSymbol) {
726 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
727 MCFragment *F = SD.getFragment();
728
Adhemerval Zanellaaa714282012-10-25 12:27:42 +0000729 if (F) {
730 Index = F->getParent()->getOrdinal() + 1;
731 // Offset of the symbol in the section
732 Value += Layout.getSymbolOffset(&SD);
733 } else {
734 Index = 0;
735 }
Jason W Kim56a39902010-12-06 21:57:34 +0000736 } else {
737 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
738 WeakrefUsedInReloc.insert(RelocSymbol);
739 else
740 UsedInReloc.insert(RelocSymbol);
741 Index = -1;
742 }
743 Addend = Value;
Michael Liaob21d9ae2012-10-16 19:49:51 +0000744 if (hasRelocationAddend())
Jason W Kim56a39902010-12-06 21:57:34 +0000745 Value = 0;
746 }
747
748 FixedValue = Value;
749 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
750 (RelocSymbol != 0), Addend);
Rafael Espindolac677e792011-12-21 14:26:29 +0000751 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
752 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
753 if (RelocNeedsGOT(Modifier))
754 NeedsGOT = true;
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000755
Jason W Kim56a39902010-12-06 21:57:34 +0000756 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
757 Fixup.getOffset();
Roman Divacky2a66cea2011-08-04 19:08:19 +0000758
Rafael Espindolaf3a86fb2011-12-22 01:57:09 +0000759 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
760 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
Jason W Kim56a39902010-12-06 21:57:34 +0000761
Rafael Espindolabff66a82010-12-18 03:27:34 +0000762 if (!hasRelocationAddend())
763 Addend = 0;
Rafael Espindolabbf9c4a2011-08-04 13:05:26 +0000764
765 if (is64Bit())
766 assert(isInt<64>(Addend));
767 else
768 assert(isInt<32>(Addend));
769
Akira Hatanaka00ca8882012-03-23 23:06:45 +0000770 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
Jason W Kim56a39902010-12-06 21:57:34 +0000771 Relocations[Fragment->getParent()].push_back(ERE);
772}
773
774
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000775uint64_t
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000776ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
777 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000778 MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000779 return SD.getIndex();
Matt Fleming3565a062010-08-16 18:57:57 +0000780}
781
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000782bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
783 const MCSymbolData &Data,
784 bool Used, bool Renamed) {
Rafael Espindola484291c2010-11-01 14:28:48 +0000785 if (Data.getFlags() & ELF_Other_Weakref)
786 return false;
787
Rafael Espindolabd701182010-10-19 19:31:37 +0000788 if (Used)
789 return true;
790
Rafael Espindola88182132010-10-27 15:18:17 +0000791 if (Renamed)
792 return false;
793
Rafael Espindola737cd212010-10-05 18:01:23 +0000794 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000795
Rafael Espindolad1798862010-10-29 23:09:31 +0000796 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
797 return true;
798
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000799 const MCSymbol &A = Symbol.AliasedSymbol();
Rafael Espindola21451e52011-02-23 20:22:07 +0000800 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
801 return false;
802
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000803 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola21451e52011-02-23 20:22:07 +0000804 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa6866962010-10-27 14:44:52 +0000805 return false;
806
Rafael Espindola737cd212010-10-05 18:01:23 +0000807 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
808 return false;
809
Rafael Espindolabd701182010-10-19 19:31:37 +0000810 if (Symbol.isTemporary())
Rafael Espindola737cd212010-10-05 18:01:23 +0000811 return false;
812
813 return true;
814}
815
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000816bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
817 bool isUsedInReloc) {
Rafael Espindola737cd212010-10-05 18:01:23 +0000818 if (Data.isExternal())
819 return false;
820
821 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000822 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000823
824 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
825 if (isSignature && !isUsedInReloc)
826 return true;
827
Rafael Espindola737cd212010-10-05 18:01:23 +0000828 return false;
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000829 }
Rafael Espindola737cd212010-10-05 18:01:23 +0000830
831 return true;
832}
833
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000834void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000835 SectionIndexMapTy &SectionIndexMap,
836 const RelMapTy &RelMap) {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000837 unsigned Index = 1;
838 for (MCAssembler::iterator it = Asm.begin(),
839 ie = Asm.end(); it != ie; ++it) {
840 const MCSectionELF &Section =
841 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola2ff9e832010-11-11 18:13:52 +0000842 if (Section.getType() != ELF::SHT_GROUP)
843 continue;
844 SectionIndexMap[&Section] = Index++;
845 }
846
847 for (MCAssembler::iterator it = Asm.begin(),
848 ie = Asm.end(); it != ie; ++it) {
849 const MCSectionELF &Section =
850 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000851 if (Section.getType() == ELF::SHT_GROUP ||
852 Section.getType() == ELF::SHT_REL ||
853 Section.getType() == ELF::SHT_RELA)
Rafael Espindola2ff9e832010-11-11 18:13:52 +0000854 continue;
Rafael Espindolabab2a802010-11-10 21:51:05 +0000855 SectionIndexMap[&Section] = Index++;
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000856 const MCSectionELF *RelSection = RelMap.lookup(&Section);
857 if (RelSection)
858 SectionIndexMap[RelSection] = Index++;
Rafael Espindolabab2a802010-11-10 21:51:05 +0000859 }
860}
861
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000862void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000863 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000864 RevGroupMapTy RevGroupMap,
865 unsigned NumRegularSections) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000866 // FIXME: Is this the correct place to do this?
Rafael Espindola378e0ec2011-06-05 01:20:06 +0000867 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindola5c77c162010-10-05 15:48:37 +0000868 if (NeedsGOT) {
869 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
870 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
871 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
872 Data.setExternal(true);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000873 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindola5c77c162010-10-05 15:48:37 +0000874 }
875
Matt Fleming3565a062010-08-16 18:57:57 +0000876 // Index 0 is always the empty string.
877 StringMap<uint64_t> StringIndexMap;
878 StringTable += '\x00';
879
Rafael Espindolad5321da2011-04-07 23:21:52 +0000880 // FIXME: We could optimize suffixes in strtab in the same way we
881 // optimize them in shstrtab.
882
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000883 // Add the data for the symbols.
Matt Fleming3565a062010-08-16 18:57:57 +0000884 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
885 ie = Asm.symbol_end(); it != ie; ++it) {
886 const MCSymbol &Symbol = it->getSymbol();
887
Rafael Espindola484291c2010-11-01 14:28:48 +0000888 bool Used = UsedInReloc.count(&Symbol);
889 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000890 bool isSignature = RevGroupMap.count(&Symbol);
891
892 if (!isInSymtab(Asm, *it,
893 Used || WeakrefUsed || isSignature,
Rafael Espindola88182132010-10-27 15:18:17 +0000894 Renames.count(&Symbol)))
Matt Fleming3565a062010-08-16 18:57:57 +0000895 continue;
896
Matt Fleming3565a062010-08-16 18:57:57 +0000897 ELFSymbolData MSD;
898 MSD.SymbolData = it;
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000899 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Matt Fleming3565a062010-08-16 18:57:57 +0000900
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000901 // Undefined symbols are global, but this is the first place we
902 // are able to set it.
903 bool Local = isLocal(*it, isSignature, Used);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000904 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000905 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000906 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
907 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000908 }
909
Rafael Espindola484291c2010-11-01 14:28:48 +0000910 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000911 MCELF::SetBinding(*it, ELF::STB_WEAK);
Rafael Espindola484291c2010-11-01 14:28:48 +0000912
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000913 if (it->isCommon()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000914 assert(!Local);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000915 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindolabf052ac2010-10-27 16:04:30 +0000916 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000917 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola88182132010-10-27 15:18:17 +0000918 } else if (RefSymbol.isUndefined()) {
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000919 if (isSignature && !Used)
920 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
921 else
922 MSD.SectionIndex = ELF::SHN_UNDEF;
Matt Fleming3565a062010-08-16 18:57:57 +0000923 } else {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000924 const MCSectionELF &Section =
925 static_cast<const MCSectionELF&>(RefSymbol.getSection());
926 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000927 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
928 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000929 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000930 }
931
Rafael Espindola88182132010-10-27 15:18:17 +0000932 // The @@@ in symbol version is replaced with @ in undefined symbols and
933 // @@ in defined ones.
934 StringRef Name = Symbol.getName();
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000935 SmallString<32> Buf;
936
Rafael Espindola88182132010-10-27 15:18:17 +0000937 size_t Pos = Name.find("@@@");
Rafael Espindola88182132010-10-27 15:18:17 +0000938 if (Pos != StringRef::npos) {
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000939 Buf += Name.substr(0, Pos);
940 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
941 Buf += Name.substr(Pos + Skip);
942 Name = Buf;
Rafael Espindola88182132010-10-27 15:18:17 +0000943 }
944
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000945 uint64_t &Entry = StringIndexMap[Name];
Rafael Espindolaa6866962010-10-27 14:44:52 +0000946 if (!Entry) {
947 Entry = StringTable.size();
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000948 StringTable += Name;
Rafael Espindolaa6866962010-10-27 14:44:52 +0000949 StringTable += '\x00';
Matt Fleming3565a062010-08-16 18:57:57 +0000950 }
Rafael Espindolaa6866962010-10-27 14:44:52 +0000951 MSD.StringIndex = Entry;
952 if (MSD.SectionIndex == ELF::SHN_UNDEF)
953 UndefinedSymbolData.push_back(MSD);
954 else if (Local)
955 LocalSymbolData.push_back(MSD);
956 else
957 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000958 }
959
960 // Symbols are required to be in lexicographic order.
961 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
962 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
963 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
964
965 // Set the symbol indices. Local symbols must come before all other
966 // symbols with non-local bindings.
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000967 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000968 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
969 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000970
971 Index += NumRegularSections;
972
Matt Fleming3565a062010-08-16 18:57:57 +0000973 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
974 ExternalSymbolData[i].SymbolData->setIndex(Index++);
975 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
976 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
Nick Lewycky7aabcb12011-10-11 03:54:50 +0000977
978 if (NumRegularSections > ELF::SHN_LORESERVE)
979 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000980}
981
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000982void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
983 MCAsmLayout &Layout,
984 RelMapTy &RelMap) {
985 for (MCAssembler::const_iterator it = Asm.begin(),
986 ie = Asm.end(); it != ie; ++it) {
987 const MCSectionData &SD = *it;
988 if (Relocations[&SD].empty())
989 continue;
990
Matt Fleming3565a062010-08-16 18:57:57 +0000991 MCContext &Ctx = Asm.getContext();
Matt Fleming3565a062010-08-16 18:57:57 +0000992 const MCSectionELF &Section =
993 static_cast<const MCSectionELF&>(SD.getSection());
994
995 const StringRef SectionName = Section.getSectionName();
Rafael Espindolabff66a82010-12-18 03:27:34 +0000996 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000997 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000998
999 unsigned EntrySize;
Rafael Espindolabff66a82010-12-18 03:27:34 +00001000 if (hasRelocationAddend())
1001 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramer299fbe32010-08-17 17:56:13 +00001002 else
Rafael Espindolabff66a82010-12-18 03:27:34 +00001003 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +00001004
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001005 const MCSectionELF *RelaSection =
1006 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1007 ELF::SHT_RELA : ELF::SHT_REL, 0,
1008 SectionKind::getReadOnly(),
1009 EntrySize, "");
1010 RelMap[&Section] = RelaSection;
1011 Asm.getOrCreateSectionData(*RelaSection);
1012 }
1013}
Matt Fleming3565a062010-08-16 18:57:57 +00001014
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001015void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1016 const RelMapTy &RelMap) {
1017 for (MCAssembler::const_iterator it = Asm.begin(),
1018 ie = Asm.end(); it != ie; ++it) {
1019 const MCSectionData &SD = *it;
1020 const MCSectionELF &Section =
1021 static_cast<const MCSectionELF&>(SD.getSection());
1022
1023 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1024 if (!RelaSection)
1025 continue;
Matt Fleming3565a062010-08-16 18:57:57 +00001026 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolabff66a82010-12-18 03:27:34 +00001027 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +00001028
1029 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001030 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming3565a062010-08-16 18:57:57 +00001031 }
1032}
1033
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001034void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1035 uint64_t Flags, uint64_t Address,
1036 uint64_t Offset, uint64_t Size,
1037 uint32_t Link, uint32_t Info,
1038 uint64_t Alignment,
1039 uint64_t EntrySize) {
Matt Fleming3565a062010-08-16 18:57:57 +00001040 Write32(Name); // sh_name: index into string table
1041 Write32(Type); // sh_type
1042 WriteWord(Flags); // sh_flags
1043 WriteWord(Address); // sh_addr
1044 WriteWord(Offset); // sh_offset
1045 WriteWord(Size); // sh_size
1046 Write32(Link); // sh_link
1047 Write32(Info); // sh_info
1048 WriteWord(Alignment); // sh_addralign
1049 WriteWord(EntrySize); // sh_entsize
1050}
1051
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001052void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1053 MCDataFragment *F,
1054 const MCSectionData *SD) {
Matt Fleming3565a062010-08-16 18:57:57 +00001055 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka00ca8882012-03-23 23:06:45 +00001056
1057 // Sort the relocation entries. Most targets just sort by r_offset, but some
1058 // (e.g., MIPS) have additional constraints.
1059 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming3565a062010-08-16 18:57:57 +00001060
1061 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1062 ELFRelocationEntry entry = Relocs[e - i - 1];
1063
Rafael Espindola12203cc2010-11-21 00:48:25 +00001064 if (!entry.Index)
1065 ;
1066 else if (entry.Index < 0)
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001067 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1068 else
Rafael Espindola12203cc2010-11-21 00:48:25 +00001069 entry.Index += LocalSymbolData.size();
Rafael Espindolabff66a82010-12-18 03:27:34 +00001070 if (is64Bit()) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001071 String64(*F, entry.r_offset);
Jack Carter93ee2862012-06-27 22:28:30 +00001072 if (TargetObjectWriter->isN64()) {
1073 String32(*F, entry.Index);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001074
Jack Carter93ee2862012-06-27 22:28:30 +00001075 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1076 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1077 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1078 String8(*F, TargetObjectWriter->getRType(entry.Type));
1079 }
1080 else {
1081 struct ELF::Elf64_Rela ERE64;
1082 ERE64.setSymbolAndType(entry.Index, entry.Type);
1083 String64(*F, ERE64.r_info);
1084 }
Rafael Espindolabff66a82010-12-18 03:27:34 +00001085 if (hasRelocationAddend())
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001086 String64(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001087 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001088 String32(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001089
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001090 struct ELF::Elf32_Rela ERE32;
1091 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001092 String32(*F, ERE32.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 String32(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001096 }
Matt Fleming3565a062010-08-16 18:57:57 +00001097 }
1098}
1099
Rafael Espindolad5321da2011-04-07 23:21:52 +00001100static int compareBySuffix(const void *a, const void *b) {
1101 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1102 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1103 const StringRef &NameA = secA->getSectionName();
1104 const StringRef &NameB = secB->getSectionName();
1105 const unsigned sizeA = NameA.size();
1106 const unsigned sizeB = NameB.size();
1107 const unsigned len = std::min(sizeA, sizeB);
1108 for (unsigned int i = 0; i < len; ++i) {
1109 char ca = NameA[sizeA - i - 1];
1110 char cb = NameB[sizeB - i - 1];
1111 if (ca != cb)
1112 return cb - ca;
1113 }
1114
1115 return sizeB - sizeA;
1116}
1117
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001118void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1119 MCAsmLayout &Layout,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001120 SectionIndexMapTy &SectionIndexMap,
1121 const RelMapTy &RelMap) {
Matt Fleming3565a062010-08-16 18:57:57 +00001122 MCContext &Ctx = Asm.getContext();
1123 MCDataFragment *F;
1124
Rafael Espindolabff66a82010-12-18 03:27:34 +00001125 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming3565a062010-08-16 18:57:57 +00001126
Rafael Espindola38738bf2010-09-22 19:04:41 +00001127 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001128 const MCSectionELF *ShstrtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001129 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001130 SectionKind::getReadOnly());
Rafael Espindola71859c62010-09-16 19:46:31 +00001131 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1132 ShstrtabSD.setAlignment(1);
Rafael Espindola71859c62010-09-16 19:46:31 +00001133
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001134 const MCSectionELF *SymtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001135 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1136 SectionKind::getReadOnly(),
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001137 EntrySize, "");
Matt Fleming3565a062010-08-16 18:57:57 +00001138 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolabff66a82010-12-18 03:27:34 +00001139 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001140
1141 MCSectionData *SymtabShndxSD = NULL;
1142
1143 if (NeedsSymtabShndx) {
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001144 const MCSectionELF *SymtabShndxSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001145 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001146 SectionKind::getReadOnly(), 4, "");
Rafael Espindola7be2c332010-10-31 00:16:26 +00001147 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1148 SymtabShndxSD->setAlignment(4);
1149 }
Matt Fleming3565a062010-08-16 18:57:57 +00001150
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001151 const MCSectionELF *StrtabSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001152 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001153 SectionKind::getReadOnly());
Matt Fleming3565a062010-08-16 18:57:57 +00001154 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1155 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +00001156
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001157 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1158
1159 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1160 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1161 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola71859c62010-09-16 19:46:31 +00001162
1163 // Symbol table
1164 F = new MCDataFragment(&SymtabSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001165 MCDataFragment *ShndxF = NULL;
1166 if (NeedsSymtabShndx) {
1167 ShndxF = new MCDataFragment(SymtabShndxSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001168 }
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001169 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
Rafael Espindola71859c62010-09-16 19:46:31 +00001170
Matt Fleming3565a062010-08-16 18:57:57 +00001171 F = new MCDataFragment(&StrtabSD);
1172 F->getContents().append(StringTable.begin(), StringTable.end());
Matt Fleming3565a062010-08-16 18:57:57 +00001173
Matt Fleming3565a062010-08-16 18:57:57 +00001174 F = new MCDataFragment(&ShstrtabSD);
1175
Rafael Espindolad5321da2011-04-07 23:21:52 +00001176 std::vector<const MCSectionELF*> Sections;
1177 for (MCAssembler::const_iterator it = Asm.begin(),
1178 ie = Asm.end(); it != ie; ++it) {
1179 const MCSectionELF &Section =
1180 static_cast<const MCSectionELF&>(it->getSection());
1181 Sections.push_back(&Section);
1182 }
1183 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1184
Matt Fleming3565a062010-08-16 18:57:57 +00001185 // Section header string table.
1186 //
1187 // The first entry of a string table holds a null character so skip
1188 // section 0.
1189 uint64_t Index = 1;
1190 F->getContents() += '\x00';
1191
Rafael Espindolad5321da2011-04-07 23:21:52 +00001192 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1193 const MCSectionELF &Section = *Sections[I];
Matt Fleming3565a062010-08-16 18:57:57 +00001194
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001195 StringRef Name = Section.getSectionName();
Rafael Espindolad5321da2011-04-07 23:21:52 +00001196 if (I != 0) {
1197 StringRef PreviousName = Sections[I - 1]->getSectionName();
1198 if (PreviousName.endswith(Name)) {
1199 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1200 continue;
1201 }
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001202 }
Matt Fleming3565a062010-08-16 18:57:57 +00001203 // Remember the index into the string table so we can write it
1204 // into the sh_name field of the section header table.
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001205 SectionStringTableIndex[&Section] = Index;
Matt Fleming3565a062010-08-16 18:57:57 +00001206
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001207 Index += Name.size() + 1;
1208 F->getContents() += Name;
Matt Fleming3565a062010-08-16 18:57:57 +00001209 F->getContents() += '\x00';
1210 }
Rafael Espindola70703872010-09-30 02:22:20 +00001211}
1212
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001213void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1214 MCAsmLayout &Layout,
1215 GroupMapTy &GroupMap,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001216 RevGroupMapTy &RevGroupMap,
1217 SectionIndexMapTy &SectionIndexMap,
1218 const RelMapTy &RelMap) {
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001219 // Create the .note.GNU-stack section if needed.
1220 MCContext &Ctx = Asm.getContext();
1221 if (Asm.getNoExecStack()) {
1222 const MCSectionELF *GnuStackSection =
1223 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1224 SectionKind::getReadOnly());
1225 Asm.getOrCreateSectionData(*GnuStackSection);
1226 }
1227
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001228 // Build the groups
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001229 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1230 it != ie; ++it) {
1231 const MCSectionELF &Section =
1232 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola1c130262011-01-23 04:43:11 +00001233 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001234 continue;
1235
1236 const MCSymbol *SignatureSymbol = Section.getGroup();
1237 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +00001238 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001239 if (!Group) {
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001240 Group = Ctx.CreateELFGroupSection();
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001241 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1242 Data.setAlignment(4);
1243 MCDataFragment *F = new MCDataFragment(&Data);
1244 String32(*F, ELF::GRP_COMDAT);
1245 }
1246 GroupMap[Group] = SignatureSymbol;
1247 }
1248
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001249 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1250
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001251 // Add sections to the groups
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001252 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001253 it != ie; ++it) {
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001254 const MCSectionELF &Section =
1255 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola1c130262011-01-23 04:43:11 +00001256 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001257 continue;
Rafael Espindola1f4f9e32010-11-14 04:17:37 +00001258 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001259 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1260 // FIXME: we could use the previous fragment
1261 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001262 unsigned Index = SectionIndexMap.lookup(&Section);
1263 String32(*F, Index);
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001264 }
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001265}
1266
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001267void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1268 const SectionIndexMapTy &SectionIndexMap,
1269 uint32_t GroupSymbolIndex,
1270 uint64_t Offset, uint64_t Size,
1271 uint64_t Alignment,
1272 const MCSectionELF &Section) {
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001273 uint64_t sh_link = 0;
1274 uint64_t sh_info = 0;
1275
1276 switch(Section.getType()) {
1277 case ELF::SHT_DYNAMIC:
1278 sh_link = SectionStringTableIndex[&Section];
1279 sh_info = 0;
1280 break;
1281
1282 case ELF::SHT_REL:
1283 case ELF::SHT_RELA: {
1284 const MCSectionELF *SymtabSection;
1285 const MCSectionELF *InfoSection;
1286 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1287 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001288 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001289 sh_link = SectionIndexMap.lookup(SymtabSection);
1290 assert(sh_link && ".symtab not found");
1291
1292 // Remove ".rel" and ".rela" prefixes.
1293 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1294 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1295
1296 InfoSection = Asm.getContext().getELFSection(SectionName,
1297 ELF::SHT_PROGBITS, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001298 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001299 sh_info = SectionIndexMap.lookup(InfoSection);
1300 break;
1301 }
1302
1303 case ELF::SHT_SYMTAB:
1304 case ELF::SHT_DYNSYM:
1305 sh_link = StringTableIndex;
1306 sh_info = LastLocalSymbolIndex;
1307 break;
1308
1309 case ELF::SHT_SYMTAB_SHNDX:
1310 sh_link = SymbolTableIndex;
1311 break;
1312
1313 case ELF::SHT_PROGBITS:
1314 case ELF::SHT_STRTAB:
1315 case ELF::SHT_NOBITS:
Rafael Espindola98976612010-12-26 21:30:59 +00001316 case ELF::SHT_NOTE:
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001317 case ELF::SHT_NULL:
1318 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim86a97f22011-01-12 00:19:25 +00001319 case ELF::SHT_INIT_ARRAY:
1320 case ELF::SHT_FINI_ARRAY:
1321 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola0cf5e3d2011-01-23 05:43:40 +00001322 case ELF::SHT_X86_64_UNWIND:
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001323 // Nothing to do.
1324 break;
1325
Nick Lewycky4a8d43e2011-10-07 23:28:32 +00001326 case ELF::SHT_GROUP:
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001327 sh_link = SymbolTableIndex;
1328 sh_info = GroupSymbolIndex;
1329 break;
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001330
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001331 default:
1332 assert(0 && "FIXME: sh_type value not supported!");
1333 break;
1334 }
1335
1336 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1337 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1338 Alignment, Section.getEntrySize());
1339}
1340
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001341bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolaf8803fe2010-12-06 03:48:09 +00001342 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001343 !SD.getSection().isVirtualSection();
1344}
1345
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001346uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001347 uint64_t Ret = 0;
1348 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1349 ++i) {
1350 const MCFragment &F = *i;
1351 assert(F.getKind() == MCFragment::FT_Data);
1352 Ret += cast<MCDataFragment>(F).getContents().size();
1353 }
1354 return Ret;
1355}
1356
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001357uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1358 const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001359 if (IsELFMetaDataSection(SD))
1360 return DataSectionSize(SD);
1361 return Layout.getSectionFileSize(&SD);
1362}
1363
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001364uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1365 const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001366 if (IsELFMetaDataSection(SD))
1367 return DataSectionSize(SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001368 return Layout.getSectionAddressSize(&SD);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001369}
1370
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001371void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1372 const MCAsmLayout &Layout,
1373 const MCSectionELF &Section) {
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001374 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1375
Benjamin Kramer263109d2012-01-20 14:42:32 +00001376 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001377 WriteZeros(Padding);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001378
1379 if (IsELFMetaDataSection(SD)) {
1380 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1381 ++i) {
1382 const MCFragment &F = *i;
1383 assert(F.getKind() == MCFragment::FT_Data);
1384 WriteBytes(cast<MCDataFragment>(F).getContents().str());
1385 }
1386 } else {
Jim Grosbachf77d5b12011-12-06 00:03:48 +00001387 Asm.writeSectionData(&SD, Layout);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001388 }
1389}
1390
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001391void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1392 const GroupMapTy &GroupMap,
1393 const MCAsmLayout &Layout,
1394 const SectionIndexMapTy &SectionIndexMap,
1395 const SectionOffsetMapTy &SectionOffsetMap) {
1396 const unsigned NumSections = Asm.size() + 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001397
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001398 std::vector<const MCSectionELF*> Sections;
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001399 Sections.resize(NumSections - 1);
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001400
1401 for (SectionIndexMapTy::const_iterator i=
1402 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1403 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001404 Sections[p.second - 1] = p.first;
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001405 }
1406
Matt Fleming3565a062010-08-16 18:57:57 +00001407 // Null section first.
Rafael Espindola7be2c332010-10-31 00:16:26 +00001408 uint64_t FirstSectionSize =
1409 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1410 uint32_t FirstSectionLink =
1411 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1412 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming3565a062010-08-16 18:57:57 +00001413
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001414 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001415 const MCSectionELF &Section = *Sections[i];
1416 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1417 uint32_t GroupSymbolIndex;
1418 if (Section.getType() != ELF::SHT_GROUP)
1419 GroupSymbolIndex = 0;
1420 else
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001421 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1422 GroupMap.lookup(&Section));
Matt Fleming3565a062010-08-16 18:57:57 +00001423
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001424 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001425
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001426 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001427 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001428 SD.getAlignment(), Section);
Matt Fleming3565a062010-08-16 18:57:57 +00001429 }
1430}
1431
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001432void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1433 std::vector<const MCSectionELF*> &Sections) {
1434 for (MCAssembler::iterator it = Asm.begin(),
1435 ie = Asm.end(); it != ie; ++it) {
1436 const MCSectionELF &Section =
1437 static_cast<const MCSectionELF &>(it->getSection());
1438 if (Section.getType() == ELF::SHT_GROUP)
1439 Sections.push_back(&Section);
1440 }
1441
1442 for (MCAssembler::iterator it = Asm.begin(),
1443 ie = Asm.end(); it != ie; ++it) {
1444 const MCSectionELF &Section =
1445 static_cast<const MCSectionELF &>(it->getSection());
1446 if (Section.getType() != ELF::SHT_GROUP &&
1447 Section.getType() != ELF::SHT_REL &&
1448 Section.getType() != ELF::SHT_RELA)
1449 Sections.push_back(&Section);
1450 }
1451
1452 for (MCAssembler::iterator it = Asm.begin(),
1453 ie = Asm.end(); it != ie; ++it) {
1454 const MCSectionELF &Section =
1455 static_cast<const MCSectionELF &>(it->getSection());
1456 if (Section.getType() == ELF::SHT_REL ||
1457 Section.getType() == ELF::SHT_RELA)
1458 Sections.push_back(&Section);
1459 }
1460}
1461
1462void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1463 const MCAsmLayout &Layout) {
1464 GroupMapTy GroupMap;
1465 RevGroupMapTy RevGroupMap;
1466 SectionIndexMapTy SectionIndexMap;
1467
1468 unsigned NumUserSections = Asm.size();
1469
1470 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1471 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1472
1473 const unsigned NumUserAndRelocSections = Asm.size();
1474 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1475 RevGroupMap, SectionIndexMap, RelMap);
1476 const unsigned AllSections = Asm.size();
1477 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1478
1479 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1480
1481 // Compute symbol table information.
1482 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1483
1484
1485 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1486
1487 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1488 const_cast<MCAsmLayout&>(Layout),
1489 SectionIndexMap,
1490 RelMap);
1491
1492 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1493 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1494 sizeof(ELF::Elf32_Ehdr);
1495 uint64_t FileOff = HeaderSize;
1496
1497 std::vector<const MCSectionELF*> Sections;
1498 ComputeSectionOrder(Asm, Sections);
1499 unsigned NumSections = Sections.size();
1500 SectionOffsetMapTy SectionOffsetMap;
1501 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1502 const MCSectionELF &Section = *Sections[i];
1503 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1504
1505 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1506
1507 // Remember the offset into the file for this section.
1508 SectionOffsetMap[&Section] = FileOff;
1509
1510 // Get the size of the section in the output file (including padding).
1511 FileOff += GetSectionFileSize(Layout, SD);
1512 }
1513
1514 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1515
1516 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1517
1518 uint64_t SectionHeaderEntrySize = is64Bit() ?
1519 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1520 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1521
1522 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1523 const MCSectionELF &Section = *Sections[i];
1524 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1525
1526 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1527
1528 // Remember the offset into the file for this section.
1529 SectionOffsetMap[&Section] = FileOff;
1530
1531 // Get the size of the section in the output file (including padding).
1532 FileOff += GetSectionFileSize(Layout, SD);
1533 }
1534
1535 // Write out the ELF header ...
1536 WriteHeader(SectionHeaderOffset, NumSections + 1);
1537
1538 // ... then the regular sections ...
1539 // + because of .shstrtab
1540 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1541 WriteDataSectionData(Asm, Layout, *Sections[i]);
1542
Benjamin Kramer263109d2012-01-20 14:42:32 +00001543 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001544 WriteZeros(Padding);
1545
1546 // ... then the section header table ...
1547 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1548 SectionOffsetMap);
1549
Nick Lewyckyaaae3f62011-10-07 20:56:23 +00001550 // ... and then the remaining sections ...
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001551 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1552 WriteDataSectionData(Asm, Layout, *Sections[i]);
1553}
1554
Eli Friedman78c1e172011-03-03 07:24:36 +00001555bool
1556ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1557 const MCSymbolData &DataA,
1558 const MCFragment &FB,
1559 bool InSet,
1560 bool IsPCRel) const {
1561 if (DataA.getFlags() & ELF_STB_Weak)
1562 return false;
1563 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1564 Asm, DataA, FB,InSet, IsPCRel);
1565}
1566
Rafael Espindola6024c972010-12-17 17:45:22 +00001567MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1568 raw_ostream &OS,
Rafael Espindolabff66a82010-12-18 03:27:34 +00001569 bool IsLittleEndian) {
Rafael Espindola7bd27802011-12-22 03:24:43 +00001570 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolaedae8e12011-12-21 17:30:17 +00001571}