blob: bfe17094628b0b690a3ef9f1e4ee9eafe993e806 [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
Chandler Carruthd04a8d42012-12-03 16:50:05 +000014#include "llvm/MC/MCELFObjectWriter.h"
Rafael Espindola3963d612011-12-22 03:38:00 +000015#include "llvm/ADT/OwningPtr.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000016#include "llvm/ADT/STLExtras.h"
Rafael Espindola3963d612011-12-22 03:38:00 +000017#include "llvm/ADT/SmallPtrSet.h"
18#include "llvm/ADT/SmallString.h"
Matt Fleming3565a062010-08-16 18:57:57 +000019#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"
Tim Northover6eb3e872012-12-07 16:50:23 +000024#include "llvm/MC/MCELF.h"
Rafael Espindola3963d612011-12-22 03:38:00 +000025#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"
Matt Fleming3565a062010-08-16 18:57:57 +000032#include "llvm/Support/ELF.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000033#include "llvm/Support/ErrorHandling.h"
Matt Fleming3565a062010-08-16 18:57:57 +000034#include <vector>
35using namespace llvm;
36
Jason W Kime964d112011-05-11 22:53:06 +000037#undef DEBUG_TYPE
38#define DEBUG_TYPE "reloc-info"
39
Rafael Espindola3963d612011-12-22 03:38:00 +000040namespace {
41class ELFObjectWriter : public MCObjectWriter {
42 protected:
43
44 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
45 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
46 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
47 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
48 bool Used, bool Renamed);
49 static bool isLocal(const MCSymbolData &Data, bool isSignature,
50 bool isUsedInReloc);
51 static bool IsELFMetaDataSection(const MCSectionData &SD);
52 static uint64_t DataSectionSize(const MCSectionData &SD);
53 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
54 const MCSectionData &SD);
55 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
56 const MCSectionData &SD);
57
58 void WriteDataSectionData(MCAssembler &Asm,
59 const MCAsmLayout &Layout,
60 const MCSectionELF &Section);
61
62 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
63 return Kind == X86::reloc_riprel_4byte ||
64 Kind == X86::reloc_riprel_4byte_movq_load;
65 }*/
66
67 /// ELFSymbolData - Helper struct for containing some precomputed
68 /// information on symbols.
69 struct ELFSymbolData {
70 MCSymbolData *SymbolData;
71 uint64_t StringIndex;
72 uint32_t SectionIndex;
73
74 // Support lexicographic sorting.
75 bool operator<(const ELFSymbolData &RHS) const {
76 if (MCELF::GetType(*SymbolData) == ELF::STT_FILE)
77 return true;
78 if (MCELF::GetType(*RHS.SymbolData) == ELF::STT_FILE)
79 return false;
80 return SymbolData->getSymbol().getName() <
81 RHS.SymbolData->getSymbol().getName();
82 }
83 };
84
Rafael Espindola3963d612011-12-22 03:38:00 +000085 /// The target specific ELF writer instance.
86 llvm::OwningPtr<MCELFObjectTargetWriter> TargetObjectWriter;
87
88 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
89 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
90 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
91
92 llvm::DenseMap<const MCSectionData*,
93 std::vector<ELFRelocationEntry> > Relocations;
94 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
95
96 /// @}
97 /// @name Symbol Table Data
98 /// @{
99
100 SmallString<256> StringTable;
101 std::vector<ELFSymbolData> LocalSymbolData;
102 std::vector<ELFSymbolData> ExternalSymbolData;
103 std::vector<ELFSymbolData> UndefinedSymbolData;
104
105 /// @}
106
107 bool NeedsGOT;
108
109 bool NeedsSymtabShndx;
110
111 // This holds the symbol table index of the last local symbol.
112 unsigned LastLocalSymbolIndex;
113 // This holds the .strtab section index.
114 unsigned StringTableIndex;
115 // This holds the .symtab section index.
116 unsigned SymbolTableIndex;
117
118 unsigned ShstrtabIndex;
119
120
121 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
122 const MCValue &Target,
123 const MCFragment &F,
124 const MCFixup &Fixup,
125 bool IsPCRel) const;
126
127 // TargetObjectWriter wrappers.
128 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
129 const MCValue &Target,
130 const MCFragment &F,
131 const MCFixup &Fixup,
132 bool IsPCRel) const {
133 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
134 }
Adhemerval Zanellaaa714282012-10-25 12:27:42 +0000135 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
136 const MCFixup &Fixup,
137 bool IsPCRel) const {
138 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup, IsPCRel);
139 }
Rafael Espindola3963d612011-12-22 03:38:00 +0000140
141 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
142 bool hasRelocationAddend() const {
143 return TargetObjectWriter->hasRelocationAddend();
144 }
145 unsigned getEFlags() const {
146 return TargetObjectWriter->getEFlags();
147 }
148 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
149 bool IsPCRel, bool IsRelocWithSymbol,
150 int64_t Addend) const {
151 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
152 IsRelocWithSymbol, Addend);
153 }
154
155
156 public:
157 ELFObjectWriter(MCELFObjectTargetWriter *MOTW,
158 raw_ostream &_OS, bool IsLittleEndian)
159 : MCObjectWriter(_OS, IsLittleEndian),
160 TargetObjectWriter(MOTW),
161 NeedsGOT(false), NeedsSymtabShndx(false){
162 }
163
164 virtual ~ELFObjectWriter();
165
166 void WriteWord(uint64_t W) {
167 if (is64Bit())
168 Write64(W);
169 else
170 Write32(W);
171 }
172
173 void StringLE16(char *buf, uint16_t Value) {
174 buf[0] = char(Value >> 0);
175 buf[1] = char(Value >> 8);
176 }
177
178 void StringLE32(char *buf, uint32_t Value) {
179 StringLE16(buf, uint16_t(Value >> 0));
180 StringLE16(buf + 2, uint16_t(Value >> 16));
181 }
182
183 void StringLE64(char *buf, uint64_t Value) {
184 StringLE32(buf, uint32_t(Value >> 0));
185 StringLE32(buf + 4, uint32_t(Value >> 32));
186 }
187
188 void StringBE16(char *buf ,uint16_t Value) {
189 buf[0] = char(Value >> 8);
190 buf[1] = char(Value >> 0);
191 }
192
193 void StringBE32(char *buf, uint32_t Value) {
194 StringBE16(buf, uint16_t(Value >> 16));
195 StringBE16(buf + 2, uint16_t(Value >> 0));
196 }
197
198 void StringBE64(char *buf, uint64_t Value) {
199 StringBE32(buf, uint32_t(Value >> 32));
200 StringBE32(buf + 4, uint32_t(Value >> 0));
201 }
202
203 void String8(MCDataFragment &F, uint8_t Value) {
204 char buf[1];
205 buf[0] = Value;
Eli Bendersky550f0ad2012-12-07 22:06:56 +0000206 F.getContents().append(&buf[0], &buf[1]);
Rafael Espindola3963d612011-12-22 03:38:00 +0000207 }
208
209 void String16(MCDataFragment &F, uint16_t Value) {
210 char buf[2];
211 if (isLittleEndian())
212 StringLE16(buf, Value);
213 else
214 StringBE16(buf, Value);
Eli Bendersky550f0ad2012-12-07 22:06:56 +0000215 F.getContents().append(&buf[0], &buf[2]);
Rafael Espindola3963d612011-12-22 03:38:00 +0000216 }
217
218 void String32(MCDataFragment &F, uint32_t Value) {
219 char buf[4];
220 if (isLittleEndian())
221 StringLE32(buf, Value);
222 else
223 StringBE32(buf, Value);
Eli Bendersky550f0ad2012-12-07 22:06:56 +0000224 F.getContents().append(&buf[0], &buf[4]);
Rafael Espindola3963d612011-12-22 03:38:00 +0000225 }
226
227 void String64(MCDataFragment &F, uint64_t Value) {
228 char buf[8];
229 if (isLittleEndian())
230 StringLE64(buf, Value);
231 else
232 StringBE64(buf, Value);
Eli Bendersky550f0ad2012-12-07 22:06:56 +0000233 F.getContents().append(&buf[0], &buf[8]);
Rafael Espindola3963d612011-12-22 03:38:00 +0000234 }
235
236 void WriteHeader(uint64_t SectionDataSize,
237 unsigned NumberOfSections);
238
239 void WriteSymbolEntry(MCDataFragment *SymtabF,
240 MCDataFragment *ShndxF,
241 uint64_t name, uint8_t info,
242 uint64_t value, uint64_t size,
243 uint8_t other, uint32_t shndx,
244 bool Reserved);
245
246 void WriteSymbol(MCDataFragment *SymtabF, MCDataFragment *ShndxF,
247 ELFSymbolData &MSD,
248 const MCAsmLayout &Layout);
249
250 typedef DenseMap<const MCSectionELF*, uint32_t> SectionIndexMapTy;
251 void WriteSymbolTable(MCDataFragment *SymtabF,
252 MCDataFragment *ShndxF,
253 const MCAssembler &Asm,
254 const MCAsmLayout &Layout,
255 const SectionIndexMapTy &SectionIndexMap);
256
257 virtual void RecordRelocation(const MCAssembler &Asm,
258 const MCAsmLayout &Layout,
259 const MCFragment *Fragment,
260 const MCFixup &Fixup,
261 MCValue Target, uint64_t &FixedValue);
262
263 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
264 const MCSymbol *S);
265
266 // Map from a group section to the signature symbol
267 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
268 // Map from a signature symbol to the group section
269 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
270 // Map from a section to the section with the relocations
271 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
272 // Map from a section to its offset
273 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
274
275 /// ComputeSymbolTable - Compute the symbol table data
276 ///
Rafael Espindola828ea382012-08-27 16:04:24 +0000277 /// \param Asm - The assembler.
278 /// \param SectionIndexMap - Maps a section to its index.
279 /// \param RevGroupMap - Maps a signature symbol to the group section.
280 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola3963d612011-12-22 03:38:00 +0000281 void ComputeSymbolTable(MCAssembler &Asm,
282 const SectionIndexMapTy &SectionIndexMap,
283 RevGroupMapTy RevGroupMap,
284 unsigned NumRegularSections);
285
286 void ComputeIndexMap(MCAssembler &Asm,
287 SectionIndexMapTy &SectionIndexMap,
288 const RelMapTy &RelMap);
289
290 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
291 RelMapTy &RelMap);
292
293 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
294 const RelMapTy &RelMap);
295
296 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
297 SectionIndexMapTy &SectionIndexMap,
298 const RelMapTy &RelMap);
299
300 // Create the sections that show up in the symbol table. Currently
301 // those are the .note.GNU-stack section and the group sections.
302 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
303 GroupMapTy &GroupMap,
304 RevGroupMapTy &RevGroupMap,
305 SectionIndexMapTy &SectionIndexMap,
306 const RelMapTy &RelMap);
307
308 virtual void ExecutePostLayoutBinding(MCAssembler &Asm,
309 const MCAsmLayout &Layout);
310
311 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
312 const MCAsmLayout &Layout,
313 const SectionIndexMapTy &SectionIndexMap,
314 const SectionOffsetMapTy &SectionOffsetMap);
315
316 void ComputeSectionOrder(MCAssembler &Asm,
317 std::vector<const MCSectionELF*> &Sections);
318
319 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
320 uint64_t Address, uint64_t Offset,
321 uint64_t Size, uint32_t Link, uint32_t Info,
322 uint64_t Alignment, uint64_t EntrySize);
323
324 void WriteRelocationsFragment(const MCAssembler &Asm,
325 MCDataFragment *F,
326 const MCSectionData *SD);
327
328 virtual bool
329 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
330 const MCSymbolData &DataA,
331 const MCFragment &FB,
332 bool InSet,
333 bool IsPCRel) const;
334
335 virtual void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout);
336 void WriteSection(MCAssembler &Asm,
337 const SectionIndexMapTy &SectionIndexMap,
338 uint32_t GroupSymbolIndex,
339 uint64_t Offset, uint64_t Size, uint64_t Alignment,
340 const MCSectionELF &Section);
341 };
342}
343
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000344bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
345 const MCFixupKindInfo &FKI =
346 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
347
348 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
349}
350
351bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
352 switch (Variant) {
353 default:
354 return false;
355 case MCSymbolRefExpr::VK_GOT:
356 case MCSymbolRefExpr::VK_PLT:
357 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola378e0ec2011-06-05 01:20:06 +0000358 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000359 case MCSymbolRefExpr::VK_TPOFF:
360 case MCSymbolRefExpr::VK_TLSGD:
361 case MCSymbolRefExpr::VK_GOTTPOFF:
362 case MCSymbolRefExpr::VK_INDNTPOFF:
363 case MCSymbolRefExpr::VK_NTPOFF:
364 case MCSymbolRefExpr::VK_GOTNTPOFF:
365 case MCSymbolRefExpr::VK_TLSLDM:
366 case MCSymbolRefExpr::VK_DTPOFF:
367 case MCSymbolRefExpr::VK_TLSLD:
368 return true;
369 }
370}
371
Jason W Kimd3443e92010-11-15 16:18:39 +0000372ELFObjectWriter::~ELFObjectWriter()
373{}
374
Matt Fleming3565a062010-08-16 18:57:57 +0000375// Emit the ELF header.
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000376void ELFObjectWriter::WriteHeader(uint64_t SectionDataSize,
377 unsigned NumberOfSections) {
Matt Fleming3565a062010-08-16 18:57:57 +0000378 // ELF Header
379 // ----------
380 //
381 // Note
382 // ----
383 // emitWord method behaves differently for ELF32 and ELF64, writing
384 // 4 bytes in the former and 8 in the latter.
385
386 Write8(0x7f); // e_ident[EI_MAG0]
387 Write8('E'); // e_ident[EI_MAG1]
388 Write8('L'); // e_ident[EI_MAG2]
389 Write8('F'); // e_ident[EI_MAG3]
390
Rafael Espindolabff66a82010-12-18 03:27:34 +0000391 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming3565a062010-08-16 18:57:57 +0000392
393 // e_ident[EI_DATA]
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000394 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming3565a062010-08-16 18:57:57 +0000395
396 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky5baf79e2010-09-09 17:57:50 +0000397 // e_ident[EI_OSABI]
Rafael Espindoladc9a8a32011-12-21 17:00:36 +0000398 Write8(TargetObjectWriter->getOSABI());
Matt Fleming3565a062010-08-16 18:57:57 +0000399 Write8(0); // e_ident[EI_ABIVERSION]
400
401 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
402
403 Write16(ELF::ET_REL); // e_type
404
Rafael Espindolabff66a82010-12-18 03:27:34 +0000405 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming3565a062010-08-16 18:57:57 +0000406
407 Write32(ELF::EV_CURRENT); // e_version
408 WriteWord(0); // e_entry, no entry point in .o file
409 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolabff66a82010-12-18 03:27:34 +0000410 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramereb976772010-08-17 17:02:29 +0000411 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming3565a062010-08-16 18:57:57 +0000412
Jason W Kim2d7a53a2011-02-04 21:41:11 +0000413 // e_flags = whatever the target wants
Rafael Espindolae8526d02011-12-21 20:09:46 +0000414 Write32(getEFlags());
Matt Fleming3565a062010-08-16 18:57:57 +0000415
416 // e_ehsize = ELF header size
Rafael Espindolabff66a82010-12-18 03:27:34 +0000417 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming3565a062010-08-16 18:57:57 +0000418
419 Write16(0); // e_phentsize = prog header entry size
420 Write16(0); // e_phnum = # prog header entries = 0
421
422 // e_shentsize = Section header entry size
Rafael Espindolabff66a82010-12-18 03:27:34 +0000423 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming3565a062010-08-16 18:57:57 +0000424
425 // e_shnum = # of section header ents
Rafael Espindola7be2c332010-10-31 00:16:26 +0000426 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewyckyaaae3f62011-10-07 20:56:23 +0000427 Write16(ELF::SHN_UNDEF);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000428 else
429 Write16(NumberOfSections);
Matt Fleming3565a062010-08-16 18:57:57 +0000430
431 // e_shstrndx = Section # of '.shstrtab'
Nick Lewyckyb3429d32011-10-07 20:58:24 +0000432 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola7be2c332010-10-31 00:16:26 +0000433 Write16(ELF::SHN_XINDEX);
434 else
435 Write16(ShstrtabIndex);
Matt Fleming3565a062010-08-16 18:57:57 +0000436}
437
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000438void ELFObjectWriter::WriteSymbolEntry(MCDataFragment *SymtabF,
439 MCDataFragment *ShndxF,
440 uint64_t name,
441 uint8_t info, uint64_t value,
442 uint64_t size, uint8_t other,
443 uint32_t shndx,
444 bool Reserved) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000445 if (ShndxF) {
Rafael Espindola7be2c332010-10-31 00:16:26 +0000446 if (shndx >= ELF::SHN_LORESERVE && !Reserved)
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000447 String32(*ShndxF, shndx);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000448 else
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000449 String32(*ShndxF, 0);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000450 }
451
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000452 uint16_t Index = (shndx >= ELF::SHN_LORESERVE && !Reserved) ?
453 uint16_t(ELF::SHN_XINDEX) : shndx;
454
Rafael Espindolabff66a82010-12-18 03:27:34 +0000455 if (is64Bit()) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000456 String32(*SymtabF, name); // st_name
457 String8(*SymtabF, info); // st_info
458 String8(*SymtabF, other); // st_other
459 String16(*SymtabF, Index); // st_shndx
460 String64(*SymtabF, value); // st_value
461 String64(*SymtabF, size); // st_size
Matt Fleming3565a062010-08-16 18:57:57 +0000462 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +0000463 String32(*SymtabF, name); // st_name
464 String32(*SymtabF, value); // st_value
465 String32(*SymtabF, size); // st_size
466 String8(*SymtabF, info); // st_info
467 String8(*SymtabF, other); // st_other
468 String16(*SymtabF, Index); // st_shndx
Matt Fleming3565a062010-08-16 18:57:57 +0000469 }
470}
471
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000472uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
473 const MCAsmLayout &Layout) {
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000474 if (Data.isCommon() && Data.isExternal())
475 return Data.getCommonAlignment();
476
477 const MCSymbol &Symbol = Data.getSymbol();
Roman Divackyd1491862010-12-20 21:14:39 +0000478
479 if (Symbol.isAbsolute() && Symbol.isVariable()) {
480 if (const MCExpr *Value = Symbol.getVariableValue()) {
481 int64_t IntValue;
482 if (Value->EvaluateAsAbsolute(IntValue, Layout))
Jim Grosbachf68a26b2011-12-06 00:13:09 +0000483 return (uint64_t)IntValue;
Roman Divackyd1491862010-12-20 21:14:39 +0000484 }
485 }
486
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000487 if (!Symbol.isInSection())
488 return 0;
489
Rafael Espindola64695402011-05-16 16:17:21 +0000490
491 if (Data.getFragment()) {
492 if (Data.getFlags() & ELF_Other_ThumbFunc)
493 return Layout.getSymbolOffset(&Data)+1;
494 else
495 return Layout.getSymbolOffset(&Data);
496 }
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000497
498 return 0;
499}
500
Rafael Espindola85f2ecc2010-12-07 00:27:36 +0000501void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
502 const MCAsmLayout &Layout) {
Rafael Espindola88182132010-10-27 15:18:17 +0000503 // The presence of symbol versions causes undefined symbols and
504 // versions declared with @@@ to be renamed.
505
506 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
507 ie = Asm.symbol_end(); it != ie; ++it) {
508 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000509 const MCSymbol &Symbol = Alias.AliasedSymbol();
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000510 MCSymbolData &SD = Asm.getSymbolData(Symbol);
511
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000512 // Not an alias.
513 if (&Symbol == &Alias)
514 continue;
515
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000516 StringRef AliasName = Alias.getName();
Rafael Espindola88182132010-10-27 15:18:17 +0000517 size_t Pos = AliasName.find('@');
518 if (Pos == StringRef::npos)
519 continue;
520
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000521 // Aliases defined with .symvar copy the binding from the symbol they alias.
522 // This is the first place we are able to copy this information.
523 it->setExternal(SD.isExternal());
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000524 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
Rafael Espindolaf571f9a2010-10-28 18:33:03 +0000525
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000526 StringRef Rest = AliasName.substr(Pos);
Rafael Espindola88182132010-10-27 15:18:17 +0000527 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
528 continue;
529
Rafael Espindola83ff4d22010-10-27 17:56:18 +0000530 // FIXME: produce a better error message.
531 if (Symbol.isUndefined() && Rest.startswith("@@") &&
532 !Rest.startswith("@@@"))
533 report_fatal_error("A @@ version cannot be undefined");
534
Benjamin Kramer07ee6322010-10-27 19:53:52 +0000535 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindola88182132010-10-27 15:18:17 +0000536 }
537}
538
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000539void ELFObjectWriter::WriteSymbol(MCDataFragment *SymtabF,
540 MCDataFragment *ShndxF,
541 ELFSymbolData &MSD,
542 const MCAsmLayout &Layout) {
Rafael Espindola152c1062010-10-06 21:02:29 +0000543 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindolade89b012010-10-15 18:25:33 +0000544 MCSymbolData &Data =
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000545 Layout.getAssembler().getSymbolData(OrigData.getSymbol().AliasedSymbol());
Rafael Espindola152c1062010-10-06 21:02:29 +0000546
Rafael Espindola7be2c332010-10-31 00:16:26 +0000547 bool IsReserved = Data.isCommon() || Data.getSymbol().isAbsolute() ||
548 Data.getSymbol().isVariable();
549
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000550 uint8_t Binding = MCELF::GetBinding(OrigData);
551 uint8_t Visibility = MCELF::GetVisibility(OrigData);
552 uint8_t Type = MCELF::GetType(Data);
Rafael Espindola152c1062010-10-06 21:02:29 +0000553
554 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
555 uint8_t Other = Visibility;
556
Rafael Espindola2c6ec312010-09-27 21:23:02 +0000557 uint64_t Value = SymbolValue(Data, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000558 uint64_t Size = 0;
Matt Fleming3565a062010-08-16 18:57:57 +0000559
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000560 assert(!(Data.isCommon() && !Data.isExternal()));
561
Rafael Espindolaf0121242010-12-22 16:03:00 +0000562 const MCExpr *ESize = Data.getSize();
563 if (ESize) {
564 int64_t Res;
565 if (!ESize->EvaluateAsAbsolute(Res, Layout))
566 report_fatal_error("Size expression must be absolute.");
567 Size = Res;
Matt Fleming3565a062010-08-16 18:57:57 +0000568 }
569
570 // Write out the symbol table entry
Rafael Espindola7be2c332010-10-31 00:16:26 +0000571 WriteSymbolEntry(SymtabF, ShndxF, MSD.StringIndex, Info, Value,
572 Size, Other, MSD.SectionIndex, IsReserved);
Matt Fleming3565a062010-08-16 18:57:57 +0000573}
574
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000575void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
576 MCDataFragment *ShndxF,
577 const MCAssembler &Asm,
578 const MCAsmLayout &Layout,
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000579 const SectionIndexMapTy &SectionIndexMap) {
Matt Fleming3565a062010-08-16 18:57:57 +0000580 // The string table must be emitted first because we need the index
581 // into the string table for all the symbol names.
582 assert(StringTable.size() && "Missing string table");
583
584 // FIXME: Make sure the start of the symbol table is aligned.
585
586 // The first entry is the undefined symbol entry.
Rafael Espindola7be2c332010-10-31 00:16:26 +0000587 WriteSymbolEntry(SymtabF, ShndxF, 0, 0, 0, 0, 0, 0, false);
Matt Fleming3565a062010-08-16 18:57:57 +0000588
589 // Write the symbol table entries.
590 LastLocalSymbolIndex = LocalSymbolData.size() + 1;
591 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
592 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola7be2c332010-10-31 00:16:26 +0000593 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Matt Fleming3565a062010-08-16 18:57:57 +0000594 }
595
Rafael Espindola71859c62010-09-16 19:46:31 +0000596 // Write out a symbol table entry for each regular section.
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000597 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
598 ++i) {
Eli Friedmana44fa242010-08-16 21:17:09 +0000599 const MCSectionELF &Section =
Rafael Espindola4beee3d2010-11-10 22:16:43 +0000600 static_cast<const MCSectionELF&>(i->getSection());
601 if (Section.getType() == ELF::SHT_RELA ||
602 Section.getType() == ELF::SHT_REL ||
603 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewyckyd2fdb4a2011-10-07 23:29:53 +0000604 Section.getType() == ELF::SHT_SYMTAB ||
605 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedmana44fa242010-08-16 21:17:09 +0000606 continue;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000607 WriteSymbolEntry(SymtabF, ShndxF, 0, ELF::STT_SECTION, 0, 0,
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000608 ELF::STV_DEFAULT, SectionIndexMap.lookup(&Section),
609 false);
Eli Friedmana44fa242010-08-16 21:17:09 +0000610 LastLocalSymbolIndex++;
611 }
Matt Fleming3565a062010-08-16 18:57:57 +0000612
613 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
614 ELFSymbolData &MSD = ExternalSymbolData[i];
615 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola3223f192010-10-06 16:47:31 +0000616 assert(((Data.getFlags() & ELF_STB_Global) ||
617 (Data.getFlags() & ELF_STB_Weak)) &&
618 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola7be2c332010-10-31 00:16:26 +0000619 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000620 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000621 LastLocalSymbolIndex++;
622 }
623
624 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
625 ELFSymbolData &MSD = UndefinedSymbolData[i];
626 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola7be2c332010-10-31 00:16:26 +0000627 WriteSymbol(SymtabF, ShndxF, MSD, Layout);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000628 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming3565a062010-08-16 18:57:57 +0000629 LastLocalSymbolIndex++;
630 }
631}
632
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000633const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
634 const MCValue &Target,
Jim Grosbach2684d9e2012-05-11 01:41:30 +0000635 const MCFragment &F,
Jason W Kime964d112011-05-11 22:53:06 +0000636 const MCFixup &Fixup,
637 bool IsPCRel) const {
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000638 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000639 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
640 const MCSymbol *Renamed = Renames.lookup(&Symbol);
641 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000642
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000643 if (ASymbol.isUndefined()) {
644 if (Renamed)
645 return Renamed;
Adhemerval Zanellaaa714282012-10-25 12:27:42 +0000646 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000647 }
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000648
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000649 if (SD.isExternal()) {
650 if (Renamed)
651 return Renamed;
652 return &Symbol;
653 }
Rafael Espindola73ffea42010-09-25 05:42:19 +0000654
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000655 const MCSectionELF &Section =
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000656 static_cast<const MCSectionELF&>(ASymbol.getSection());
Rafael Espindola25958732010-11-24 21:57:39 +0000657 const SectionKind secKind = Section.getKind();
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000658
Rafael Espindola25958732010-11-24 21:57:39 +0000659 if (secKind.isBSS())
Jason W Kime964d112011-05-11 22:53:06 +0000660 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola7eae36b2010-09-30 20:18:35 +0000661
Rafael Espindola25958732010-11-24 21:57:39 +0000662 if (secKind.isThreadLocal()) {
663 if (Renamed)
664 return Renamed;
665 return &Symbol;
666 }
667
Rafael Espindola8cecf252010-10-06 16:23:36 +0000668 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindola3729d002010-10-05 23:57:26 +0000669 const MCSectionELF &Sec2 =
670 static_cast<const MCSectionELF&>(F.getParent()->getSection());
671
Rafael Espindola8cecf252010-10-06 16:23:36 +0000672 if (&Sec2 != &Section &&
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000673 (Kind == MCSymbolRefExpr::VK_PLT ||
674 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
Rafael Espindola25958732010-11-24 21:57:39 +0000675 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000676 if (Renamed)
677 return Renamed;
678 return &Symbol;
679 }
Rafael Espindola3729d002010-10-05 23:57:26 +0000680
Rafael Espindola1c130262011-01-23 04:43:11 +0000681 if (Section.getFlags() & ELF::SHF_MERGE) {
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000682 if (Target.getConstant() == 0)
Jason W Kime964d112011-05-11 22:53:06 +0000683 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000684 if (Renamed)
685 return Renamed;
686 return &Symbol;
Rafael Espindola1f52dfe2010-11-14 23:53:26 +0000687 }
Rafael Espindolac97f80e2010-10-18 16:38:04 +0000688
Jason W Kime964d112011-05-11 22:53:06 +0000689 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
690
Rafael Espindola73ffea42010-09-25 05:42:19 +0000691}
692
Matt Fleming3565a062010-08-16 18:57:57 +0000693
Jason W Kim56a39902010-12-06 21:57:34 +0000694void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
695 const MCAsmLayout &Layout,
696 const MCFragment *Fragment,
697 const MCFixup &Fixup,
698 MCValue Target,
699 uint64_t &FixedValue) {
700 int64_t Addend = 0;
701 int Index = 0;
702 int64_t Value = Target.getConstant();
703 const MCSymbol *RelocSymbol = NULL;
704
Rafael Espindola127a6a42010-12-17 07:28:17 +0000705 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Jason W Kim56a39902010-12-06 21:57:34 +0000706 if (!Target.isAbsolute()) {
707 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
708 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
Jason W Kime964d112011-05-11 22:53:06 +0000709 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
Jason W Kim56a39902010-12-06 21:57:34 +0000710
711 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
712 const MCSymbol &SymbolB = RefB->getSymbol();
713 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
714 IsPCRel = true;
715
716 // Offset of the symbol in the section
717 int64_t a = Layout.getSymbolOffset(&SDB);
718
Bruno Cardoso Lopesa0dd4cb2011-11-04 22:24:36 +0000719 // Offset of the relocation in the section
Jason W Kim56a39902010-12-06 21:57:34 +0000720 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
721 Value += b - a;
722 }
723
724 if (!RelocSymbol) {
725 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
726 MCFragment *F = SD.getFragment();
727
Adhemerval Zanellaaa714282012-10-25 12:27:42 +0000728 if (F) {
729 Index = F->getParent()->getOrdinal() + 1;
730 // Offset of the symbol in the section
731 Value += Layout.getSymbolOffset(&SD);
732 } else {
733 Index = 0;
734 }
Jason W Kim56a39902010-12-06 21:57:34 +0000735 } else {
736 if (Asm.getSymbolData(Symbol).getFlags() & ELF_Other_Weakref)
737 WeakrefUsedInReloc.insert(RelocSymbol);
738 else
739 UsedInReloc.insert(RelocSymbol);
740 Index = -1;
741 }
742 Addend = Value;
Michael Liaob21d9ae2012-10-16 19:49:51 +0000743 if (hasRelocationAddend())
Jason W Kim56a39902010-12-06 21:57:34 +0000744 Value = 0;
745 }
746
747 FixedValue = Value;
748 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
749 (RelocSymbol != 0), Addend);
Rafael Espindolac677e792011-12-21 14:26:29 +0000750 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
751 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
752 if (RelocNeedsGOT(Modifier))
753 NeedsGOT = true;
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000754
Jason W Kim56a39902010-12-06 21:57:34 +0000755 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
756 Fixup.getOffset();
Roman Divacky2a66cea2011-08-04 19:08:19 +0000757
Rafael Espindolaf3a86fb2011-12-22 01:57:09 +0000758 // FIXME: no tests cover this. Is adjustFixupOffset dead code?
759 TargetObjectWriter->adjustFixupOffset(Fixup, RelocOffset);
Jason W Kim56a39902010-12-06 21:57:34 +0000760
Rafael Espindolabff66a82010-12-18 03:27:34 +0000761 if (!hasRelocationAddend())
762 Addend = 0;
Rafael Espindolabbf9c4a2011-08-04 13:05:26 +0000763
764 if (is64Bit())
765 assert(isInt<64>(Addend));
766 else
767 assert(isInt<32>(Addend));
768
Akira Hatanaka00ca8882012-03-23 23:06:45 +0000769 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
Jason W Kim56a39902010-12-06 21:57:34 +0000770 Relocations[Fragment->getParent()].push_back(ERE);
771}
772
773
Benjamin Kramer0b6cbfe2010-08-23 21:19:37 +0000774uint64_t
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000775ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
776 const MCSymbol *S) {
Benjamin Kramer7b83c262010-08-25 20:09:43 +0000777 MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000778 return SD.getIndex();
Matt Fleming3565a062010-08-16 18:57:57 +0000779}
780
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000781bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
782 const MCSymbolData &Data,
783 bool Used, bool Renamed) {
Rafael Espindola484291c2010-11-01 14:28:48 +0000784 if (Data.getFlags() & ELF_Other_Weakref)
785 return false;
786
Rafael Espindolabd701182010-10-19 19:31:37 +0000787 if (Used)
788 return true;
789
Rafael Espindola88182132010-10-27 15:18:17 +0000790 if (Renamed)
791 return false;
792
Rafael Espindola737cd212010-10-05 18:01:23 +0000793 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindolaa6866962010-10-27 14:44:52 +0000794
Rafael Espindolad1798862010-10-29 23:09:31 +0000795 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
796 return true;
797
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000798 const MCSymbol &A = Symbol.AliasedSymbol();
Rafael Espindola21451e52011-02-23 20:22:07 +0000799 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
800 return false;
801
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000802 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola21451e52011-02-23 20:22:07 +0000803 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa6866962010-10-27 14:44:52 +0000804 return false;
805
Rafael Espindola737cd212010-10-05 18:01:23 +0000806 if (!Asm.isSymbolLinkerVisible(Symbol) && !Symbol.isUndefined())
807 return false;
808
Rafael Espindolabd701182010-10-19 19:31:37 +0000809 if (Symbol.isTemporary())
Rafael Espindola737cd212010-10-05 18:01:23 +0000810 return false;
811
812 return true;
813}
814
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000815bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
816 bool isUsedInReloc) {
Rafael Espindola737cd212010-10-05 18:01:23 +0000817 if (Data.isExternal())
818 return false;
819
820 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000821 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000822
823 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
824 if (isSignature && !isUsedInReloc)
825 return true;
826
Rafael Espindola737cd212010-10-05 18:01:23 +0000827 return false;
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000828 }
Rafael Espindola737cd212010-10-05 18:01:23 +0000829
830 return true;
831}
832
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000833void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000834 SectionIndexMapTy &SectionIndexMap,
835 const RelMapTy &RelMap) {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000836 unsigned Index = 1;
837 for (MCAssembler::iterator it = Asm.begin(),
838 ie = Asm.end(); it != ie; ++it) {
839 const MCSectionELF &Section =
840 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola2ff9e832010-11-11 18:13:52 +0000841 if (Section.getType() != ELF::SHT_GROUP)
842 continue;
843 SectionIndexMap[&Section] = Index++;
844 }
845
846 for (MCAssembler::iterator it = Asm.begin(),
847 ie = Asm.end(); it != ie; ++it) {
848 const MCSectionELF &Section =
849 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000850 if (Section.getType() == ELF::SHT_GROUP ||
851 Section.getType() == ELF::SHT_REL ||
852 Section.getType() == ELF::SHT_RELA)
Rafael Espindola2ff9e832010-11-11 18:13:52 +0000853 continue;
Rafael Espindolabab2a802010-11-10 21:51:05 +0000854 SectionIndexMap[&Section] = Index++;
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000855 const MCSectionELF *RelSection = RelMap.lookup(&Section);
856 if (RelSection)
857 SectionIndexMap[RelSection] = Index++;
Rafael Espindolabab2a802010-11-10 21:51:05 +0000858 }
859}
860
Daniel Dunbar115a3dd2010-11-13 07:33:40 +0000861void ELFObjectWriter::ComputeSymbolTable(MCAssembler &Asm,
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000862 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000863 RevGroupMapTy RevGroupMap,
864 unsigned NumRegularSections) {
Rafael Espindola5c77c162010-10-05 15:48:37 +0000865 // FIXME: Is this the correct place to do this?
Rafael Espindola378e0ec2011-06-05 01:20:06 +0000866 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindola5c77c162010-10-05 15:48:37 +0000867 if (NeedsGOT) {
868 llvm::StringRef Name = "_GLOBAL_OFFSET_TABLE_";
869 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
870 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
871 Data.setExternal(true);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000872 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindola5c77c162010-10-05 15:48:37 +0000873 }
874
Matt Fleming3565a062010-08-16 18:57:57 +0000875 // Index 0 is always the empty string.
876 StringMap<uint64_t> StringIndexMap;
877 StringTable += '\x00';
878
Rafael Espindolad5321da2011-04-07 23:21:52 +0000879 // FIXME: We could optimize suffixes in strtab in the same way we
880 // optimize them in shstrtab.
881
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000882 // Add the data for the symbols.
Matt Fleming3565a062010-08-16 18:57:57 +0000883 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
884 ie = Asm.symbol_end(); it != ie; ++it) {
885 const MCSymbol &Symbol = it->getSymbol();
886
Rafael Espindola484291c2010-11-01 14:28:48 +0000887 bool Used = UsedInReloc.count(&Symbol);
888 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000889 bool isSignature = RevGroupMap.count(&Symbol);
890
891 if (!isInSymtab(Asm, *it,
892 Used || WeakrefUsed || isSignature,
Rafael Espindola88182132010-10-27 15:18:17 +0000893 Renames.count(&Symbol)))
Matt Fleming3565a062010-08-16 18:57:57 +0000894 continue;
895
Matt Fleming3565a062010-08-16 18:57:57 +0000896 ELFSymbolData MSD;
897 MSD.SymbolData = it;
Rafael Espindola94ed5fc2010-11-15 16:33:49 +0000898 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Matt Fleming3565a062010-08-16 18:57:57 +0000899
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000900 // Undefined symbols are global, but this is the first place we
901 // are able to set it.
902 bool Local = isLocal(*it, isSignature, Used);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000903 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000904 MCSymbolData &SD = Asm.getSymbolData(RefSymbol);
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000905 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
906 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000907 }
908
Rafael Espindola484291c2010-11-01 14:28:48 +0000909 if (RefSymbol.isUndefined() && !Used && WeakrefUsed)
Jan Sjödin2ddfd952011-02-28 21:45:04 +0000910 MCELF::SetBinding(*it, ELF::STB_WEAK);
Rafael Espindola484291c2010-11-01 14:28:48 +0000911
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000912 if (it->isCommon()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000913 assert(!Local);
Rafael Espindolaf7c10a32010-09-21 00:24:38 +0000914 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindolabf052ac2010-10-27 16:04:30 +0000915 } else if (Symbol.isAbsolute() || RefSymbol.isVariable()) {
Rafael Espindolaa0949b52010-10-14 16:34:44 +0000916 MSD.SectionIndex = ELF::SHN_ABS;
Rafael Espindola88182132010-10-27 15:18:17 +0000917 } else if (RefSymbol.isUndefined()) {
Rafael Espindola1f4f9e32010-11-14 04:17:37 +0000918 if (isSignature && !Used)
919 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
920 else
921 MSD.SectionIndex = ELF::SHN_UNDEF;
Matt Fleming3565a062010-08-16 18:57:57 +0000922 } else {
Rafael Espindolabab2a802010-11-10 21:51:05 +0000923 const MCSectionELF &Section =
924 static_cast<const MCSectionELF&>(RefSymbol.getSection());
925 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Rafael Espindola7be2c332010-10-31 00:16:26 +0000926 if (MSD.SectionIndex >= ELF::SHN_LORESERVE)
927 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000928 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindola5df0b652010-10-15 15:39:06 +0000929 }
930
Rafael Espindola88182132010-10-27 15:18:17 +0000931 // The @@@ in symbol version is replaced with @ in undefined symbols and
932 // @@ in defined ones.
933 StringRef Name = Symbol.getName();
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000934 SmallString<32> Buf;
935
Rafael Espindola88182132010-10-27 15:18:17 +0000936 size_t Pos = Name.find("@@@");
Rafael Espindola88182132010-10-27 15:18:17 +0000937 if (Pos != StringRef::npos) {
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000938 Buf += Name.substr(0, Pos);
939 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
940 Buf += Name.substr(Pos + Skip);
941 Name = Buf;
Rafael Espindola88182132010-10-27 15:18:17 +0000942 }
943
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000944 uint64_t &Entry = StringIndexMap[Name];
Rafael Espindolaa6866962010-10-27 14:44:52 +0000945 if (!Entry) {
946 Entry = StringTable.size();
Benjamin Kramer1261a2f2010-11-12 19:26:04 +0000947 StringTable += Name;
Rafael Espindolaa6866962010-10-27 14:44:52 +0000948 StringTable += '\x00';
Matt Fleming3565a062010-08-16 18:57:57 +0000949 }
Rafael Espindolaa6866962010-10-27 14:44:52 +0000950 MSD.StringIndex = Entry;
951 if (MSD.SectionIndex == ELF::SHN_UNDEF)
952 UndefinedSymbolData.push_back(MSD);
953 else if (Local)
954 LocalSymbolData.push_back(MSD);
955 else
956 ExternalSymbolData.push_back(MSD);
Matt Fleming3565a062010-08-16 18:57:57 +0000957 }
958
959 // Symbols are required to be in lexicographic order.
960 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
961 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
962 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
963
964 // Set the symbol indices. Local symbols must come before all other
965 // symbols with non-local bindings.
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000966 unsigned Index = 1;
Matt Fleming3565a062010-08-16 18:57:57 +0000967 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
968 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindolaab4a7af2010-11-14 03:12:24 +0000969
970 Index += NumRegularSections;
971
Matt Fleming3565a062010-08-16 18:57:57 +0000972 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
973 ExternalSymbolData[i].SymbolData->setIndex(Index++);
974 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
975 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
Nick Lewycky7aabcb12011-10-11 03:54:50 +0000976
977 if (NumRegularSections > ELF::SHN_LORESERVE)
978 NeedsSymtabShndx = true;
Matt Fleming3565a062010-08-16 18:57:57 +0000979}
980
Rafael Espindola7c18fa82011-03-20 18:44:20 +0000981void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
982 MCAsmLayout &Layout,
983 RelMapTy &RelMap) {
984 for (MCAssembler::const_iterator it = Asm.begin(),
985 ie = Asm.end(); it != ie; ++it) {
986 const MCSectionData &SD = *it;
987 if (Relocations[&SD].empty())
988 continue;
989
Matt Fleming3565a062010-08-16 18:57:57 +0000990 MCContext &Ctx = Asm.getContext();
Matt Fleming3565a062010-08-16 18:57:57 +0000991 const MCSectionELF &Section =
992 static_cast<const MCSectionELF&>(SD.getSection());
993
994 const StringRef SectionName = Section.getSectionName();
Rafael Espindolabff66a82010-12-18 03:27:34 +0000995 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming3565a062010-08-16 18:57:57 +0000996 RelaSectionName += SectionName;
Benjamin Kramer299fbe32010-08-17 17:56:13 +0000997
998 unsigned EntrySize;
Rafael Espindolabff66a82010-12-18 03:27:34 +0000999 if (hasRelocationAddend())
1000 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramer299fbe32010-08-17 17:56:13 +00001001 else
Rafael Espindolabff66a82010-12-18 03:27:34 +00001002 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming3565a062010-08-16 18:57:57 +00001003
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001004 const MCSectionELF *RelaSection =
1005 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
1006 ELF::SHT_RELA : ELF::SHT_REL, 0,
1007 SectionKind::getReadOnly(),
1008 EntrySize, "");
1009 RelMap[&Section] = RelaSection;
1010 Asm.getOrCreateSectionData(*RelaSection);
1011 }
1012}
Matt Fleming3565a062010-08-16 18:57:57 +00001013
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001014void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1015 const RelMapTy &RelMap) {
1016 for (MCAssembler::const_iterator it = Asm.begin(),
1017 ie = Asm.end(); it != ie; ++it) {
1018 const MCSectionData &SD = *it;
1019 const MCSectionELF &Section =
1020 static_cast<const MCSectionELF&>(SD.getSection());
1021
1022 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1023 if (!RelaSection)
1024 continue;
Matt Fleming3565a062010-08-16 18:57:57 +00001025 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolabff66a82010-12-18 03:27:34 +00001026 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming3565a062010-08-16 18:57:57 +00001027
1028 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001029 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming3565a062010-08-16 18:57:57 +00001030 }
1031}
1032
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001033void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1034 uint64_t Flags, uint64_t Address,
1035 uint64_t Offset, uint64_t Size,
1036 uint32_t Link, uint32_t Info,
1037 uint64_t Alignment,
1038 uint64_t EntrySize) {
Matt Fleming3565a062010-08-16 18:57:57 +00001039 Write32(Name); // sh_name: index into string table
1040 Write32(Type); // sh_type
1041 WriteWord(Flags); // sh_flags
1042 WriteWord(Address); // sh_addr
1043 WriteWord(Offset); // sh_offset
1044 WriteWord(Size); // sh_size
1045 Write32(Link); // sh_link
1046 Write32(Info); // sh_info
1047 WriteWord(Alignment); // sh_addralign
1048 WriteWord(EntrySize); // sh_entsize
1049}
1050
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001051void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1052 MCDataFragment *F,
1053 const MCSectionData *SD) {
Matt Fleming3565a062010-08-16 18:57:57 +00001054 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka00ca8882012-03-23 23:06:45 +00001055
1056 // Sort the relocation entries. Most targets just sort by r_offset, but some
1057 // (e.g., MIPS) have additional constraints.
1058 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming3565a062010-08-16 18:57:57 +00001059
1060 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1061 ELFRelocationEntry entry = Relocs[e - i - 1];
1062
Rafael Espindola12203cc2010-11-21 00:48:25 +00001063 if (!entry.Index)
1064 ;
1065 else if (entry.Index < 0)
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001066 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1067 else
Rafael Espindola12203cc2010-11-21 00:48:25 +00001068 entry.Index += LocalSymbolData.size();
Rafael Espindolabff66a82010-12-18 03:27:34 +00001069 if (is64Bit()) {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001070 String64(*F, entry.r_offset);
Jack Carter93ee2862012-06-27 22:28:30 +00001071 if (TargetObjectWriter->isN64()) {
1072 String32(*F, entry.Index);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001073
Jack Carter93ee2862012-06-27 22:28:30 +00001074 String8(*F, TargetObjectWriter->getRSsym(entry.Type));
1075 String8(*F, TargetObjectWriter->getRType3(entry.Type));
1076 String8(*F, TargetObjectWriter->getRType2(entry.Type));
1077 String8(*F, TargetObjectWriter->getRType(entry.Type));
1078 }
1079 else {
1080 struct ELF::Elf64_Rela ERE64;
1081 ERE64.setSymbolAndType(entry.Index, entry.Type);
1082 String64(*F, ERE64.r_info);
1083 }
Rafael Espindolabff66a82010-12-18 03:27:34 +00001084 if (hasRelocationAddend())
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001085 String64(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001086 } else {
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001087 String32(*F, entry.r_offset);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001088
Rafael Espindola8f413fa2010-10-05 15:11:03 +00001089 struct ELF::Elf32_Rela ERE32;
1090 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001091 String32(*F, ERE32.r_info);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001092
Rafael Espindolabff66a82010-12-18 03:27:34 +00001093 if (hasRelocationAddend())
Rafael Espindolaaf3d38f2010-11-10 20:02:59 +00001094 String32(*F, entry.r_addend);
Benjamin Kramer5e492e82010-09-09 18:01:29 +00001095 }
Matt Fleming3565a062010-08-16 18:57:57 +00001096 }
1097}
1098
Rafael Espindolad5321da2011-04-07 23:21:52 +00001099static int compareBySuffix(const void *a, const void *b) {
1100 const MCSectionELF *secA = *static_cast<const MCSectionELF* const *>(a);
1101 const MCSectionELF *secB = *static_cast<const MCSectionELF* const *>(b);
1102 const StringRef &NameA = secA->getSectionName();
1103 const StringRef &NameB = secB->getSectionName();
1104 const unsigned sizeA = NameA.size();
1105 const unsigned sizeB = NameB.size();
1106 const unsigned len = std::min(sizeA, sizeB);
1107 for (unsigned int i = 0; i < len; ++i) {
1108 char ca = NameA[sizeA - i - 1];
1109 char cb = NameB[sizeB - i - 1];
1110 if (ca != cb)
1111 return cb - ca;
1112 }
1113
1114 return sizeB - sizeA;
1115}
1116
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001117void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1118 MCAsmLayout &Layout,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001119 SectionIndexMapTy &SectionIndexMap,
1120 const RelMapTy &RelMap) {
Matt Fleming3565a062010-08-16 18:57:57 +00001121 MCContext &Ctx = Asm.getContext();
1122 MCDataFragment *F;
1123
Rafael Espindolabff66a82010-12-18 03:27:34 +00001124 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming3565a062010-08-16 18:57:57 +00001125
Rafael Espindola38738bf2010-09-22 19:04:41 +00001126 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001127 const MCSectionELF *ShstrtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001128 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001129 SectionKind::getReadOnly());
Rafael Espindola71859c62010-09-16 19:46:31 +00001130 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1131 ShstrtabSD.setAlignment(1);
Rafael Espindola71859c62010-09-16 19:46:31 +00001132
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001133 const MCSectionELF *SymtabSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001134 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1135 SectionKind::getReadOnly(),
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001136 EntrySize, "");
Matt Fleming3565a062010-08-16 18:57:57 +00001137 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolabff66a82010-12-18 03:27:34 +00001138 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001139
1140 MCSectionData *SymtabShndxSD = NULL;
1141
1142 if (NeedsSymtabShndx) {
Rafael Espindola4283f4b2010-11-10 19:05:07 +00001143 const MCSectionELF *SymtabShndxSection =
Rafael Espindola7be2c332010-10-31 00:16:26 +00001144 Ctx.getELFSection(".symtab_shndx", ELF::SHT_SYMTAB_SHNDX, 0,
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001145 SectionKind::getReadOnly(), 4, "");
Rafael Espindola7be2c332010-10-31 00:16:26 +00001146 SymtabShndxSD = &Asm.getOrCreateSectionData(*SymtabShndxSection);
1147 SymtabShndxSD->setAlignment(4);
1148 }
Matt Fleming3565a062010-08-16 18:57:57 +00001149
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001150 const MCSectionELF *StrtabSection;
Matt Fleming3565a062010-08-16 18:57:57 +00001151 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001152 SectionKind::getReadOnly());
Matt Fleming3565a062010-08-16 18:57:57 +00001153 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1154 StrtabSD.setAlignment(1);
Matt Fleming3565a062010-08-16 18:57:57 +00001155
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001156 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1157
1158 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1159 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1160 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola71859c62010-09-16 19:46:31 +00001161
1162 // Symbol table
1163 F = new MCDataFragment(&SymtabSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001164 MCDataFragment *ShndxF = NULL;
1165 if (NeedsSymtabShndx) {
1166 ShndxF = new MCDataFragment(SymtabShndxSD);
Rafael Espindola7be2c332010-10-31 00:16:26 +00001167 }
Rafael Espindola4beee3d2010-11-10 22:16:43 +00001168 WriteSymbolTable(F, ShndxF, Asm, Layout, SectionIndexMap);
Rafael Espindola71859c62010-09-16 19:46:31 +00001169
Matt Fleming3565a062010-08-16 18:57:57 +00001170 F = new MCDataFragment(&StrtabSD);
1171 F->getContents().append(StringTable.begin(), StringTable.end());
Matt Fleming3565a062010-08-16 18:57:57 +00001172
Matt Fleming3565a062010-08-16 18:57:57 +00001173 F = new MCDataFragment(&ShstrtabSD);
1174
Rafael Espindolad5321da2011-04-07 23:21:52 +00001175 std::vector<const MCSectionELF*> Sections;
1176 for (MCAssembler::const_iterator it = Asm.begin(),
1177 ie = Asm.end(); it != ie; ++it) {
1178 const MCSectionELF &Section =
1179 static_cast<const MCSectionELF&>(it->getSection());
1180 Sections.push_back(&Section);
1181 }
1182 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1183
Matt Fleming3565a062010-08-16 18:57:57 +00001184 // Section header string table.
1185 //
1186 // The first entry of a string table holds a null character so skip
1187 // section 0.
1188 uint64_t Index = 1;
Eli Bendersky550f0ad2012-12-07 22:06:56 +00001189 F->getContents().push_back('\x00');
Matt Fleming3565a062010-08-16 18:57:57 +00001190
Rafael Espindolad5321da2011-04-07 23:21:52 +00001191 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1192 const MCSectionELF &Section = *Sections[I];
Matt Fleming3565a062010-08-16 18:57:57 +00001193
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001194 StringRef Name = Section.getSectionName();
Rafael Espindolad5321da2011-04-07 23:21:52 +00001195 if (I != 0) {
1196 StringRef PreviousName = Sections[I - 1]->getSectionName();
1197 if (PreviousName.endswith(Name)) {
1198 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1199 continue;
1200 }
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001201 }
Matt Fleming3565a062010-08-16 18:57:57 +00001202 // Remember the index into the string table so we can write it
1203 // into the sh_name field of the section header table.
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001204 SectionStringTableIndex[&Section] = Index;
Matt Fleming3565a062010-08-16 18:57:57 +00001205
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001206 Index += Name.size() + 1;
Eli Bendersky550f0ad2012-12-07 22:06:56 +00001207 F->getContents().append(Name.begin(), Name.end());
1208 F->getContents().push_back('\x00');
Matt Fleming3565a062010-08-16 18:57:57 +00001209 }
Rafael Espindola70703872010-09-30 02:22:20 +00001210}
1211
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001212void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1213 MCAsmLayout &Layout,
1214 GroupMapTy &GroupMap,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001215 RevGroupMapTy &RevGroupMap,
1216 SectionIndexMapTy &SectionIndexMap,
1217 const RelMapTy &RelMap) {
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001218 // Create the .note.GNU-stack section if needed.
1219 MCContext &Ctx = Asm.getContext();
1220 if (Asm.getNoExecStack()) {
1221 const MCSectionELF *GnuStackSection =
1222 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1223 SectionKind::getReadOnly());
1224 Asm.getOrCreateSectionData(*GnuStackSection);
1225 }
1226
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001227 // Build the groups
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001228 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1229 it != ie; ++it) {
1230 const MCSectionELF &Section =
1231 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola1c130262011-01-23 04:43:11 +00001232 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001233 continue;
1234
1235 const MCSymbol *SignatureSymbol = Section.getGroup();
1236 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola1f4f9e32010-11-14 04:17:37 +00001237 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001238 if (!Group) {
Rafael Espindola96aa78c2011-01-23 17:55:27 +00001239 Group = Ctx.CreateELFGroupSection();
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001240 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1241 Data.setAlignment(4);
1242 MCDataFragment *F = new MCDataFragment(&Data);
1243 String32(*F, ELF::GRP_COMDAT);
1244 }
1245 GroupMap[Group] = SignatureSymbol;
1246 }
1247
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001248 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1249
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001250 // Add sections to the groups
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001251 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001252 it != ie; ++it) {
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001253 const MCSectionELF &Section =
1254 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola1c130262011-01-23 04:43:11 +00001255 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001256 continue;
Rafael Espindola1f4f9e32010-11-14 04:17:37 +00001257 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001258 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1259 // FIXME: we could use the previous fragment
1260 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001261 unsigned Index = SectionIndexMap.lookup(&Section);
1262 String32(*F, Index);
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001263 }
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001264}
1265
Daniel Dunbar115a3dd2010-11-13 07:33:40 +00001266void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1267 const SectionIndexMapTy &SectionIndexMap,
1268 uint32_t GroupSymbolIndex,
1269 uint64_t Offset, uint64_t Size,
1270 uint64_t Alignment,
1271 const MCSectionELF &Section) {
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001272 uint64_t sh_link = 0;
1273 uint64_t sh_info = 0;
1274
1275 switch(Section.getType()) {
1276 case ELF::SHT_DYNAMIC:
1277 sh_link = SectionStringTableIndex[&Section];
1278 sh_info = 0;
1279 break;
1280
1281 case ELF::SHT_REL:
1282 case ELF::SHT_RELA: {
1283 const MCSectionELF *SymtabSection;
1284 const MCSectionELF *InfoSection;
1285 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1286 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001287 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001288 sh_link = SectionIndexMap.lookup(SymtabSection);
1289 assert(sh_link && ".symtab not found");
1290
1291 // Remove ".rel" and ".rela" prefixes.
1292 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1293 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1294
1295 InfoSection = Asm.getContext().getELFSection(SectionName,
1296 ELF::SHT_PROGBITS, 0,
Rafael Espindola3f2d13c2010-11-11 03:40:25 +00001297 SectionKind::getReadOnly());
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001298 sh_info = SectionIndexMap.lookup(InfoSection);
1299 break;
1300 }
1301
1302 case ELF::SHT_SYMTAB:
1303 case ELF::SHT_DYNSYM:
1304 sh_link = StringTableIndex;
1305 sh_info = LastLocalSymbolIndex;
1306 break;
1307
1308 case ELF::SHT_SYMTAB_SHNDX:
1309 sh_link = SymbolTableIndex;
1310 break;
1311
1312 case ELF::SHT_PROGBITS:
1313 case ELF::SHT_STRTAB:
1314 case ELF::SHT_NOBITS:
Rafael Espindola98976612010-12-26 21:30:59 +00001315 case ELF::SHT_NOTE:
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001316 case ELF::SHT_NULL:
1317 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim86a97f22011-01-12 00:19:25 +00001318 case ELF::SHT_INIT_ARRAY:
1319 case ELF::SHT_FINI_ARRAY:
1320 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola0cf5e3d2011-01-23 05:43:40 +00001321 case ELF::SHT_X86_64_UNWIND:
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001322 // Nothing to do.
1323 break;
1324
Nick Lewycky4a8d43e2011-10-07 23:28:32 +00001325 case ELF::SHT_GROUP:
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001326 sh_link = SymbolTableIndex;
1327 sh_info = GroupSymbolIndex;
1328 break;
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001329
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001330 default:
1331 assert(0 && "FIXME: sh_type value not supported!");
1332 break;
1333 }
1334
1335 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1336 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1337 Alignment, Section.getEntrySize());
1338}
1339
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001340bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolaf8803fe2010-12-06 03:48:09 +00001341 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001342 !SD.getSection().isVirtualSection();
1343}
1344
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001345uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001346 uint64_t Ret = 0;
1347 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1348 ++i) {
1349 const MCFragment &F = *i;
1350 assert(F.getKind() == MCFragment::FT_Data);
1351 Ret += cast<MCDataFragment>(F).getContents().size();
1352 }
1353 return Ret;
1354}
1355
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001356uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1357 const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001358 if (IsELFMetaDataSection(SD))
1359 return DataSectionSize(SD);
1360 return Layout.getSectionFileSize(&SD);
1361}
1362
Jan Sjödin2ddfd952011-02-28 21:45:04 +00001363uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1364 const MCSectionData &SD) {
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001365 if (IsELFMetaDataSection(SD))
1366 return DataSectionSize(SD);
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001367 return Layout.getSectionAddressSize(&SD);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001368}
1369
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001370void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1371 const MCAsmLayout &Layout,
1372 const MCSectionELF &Section) {
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001373 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1374
Benjamin Kramer263109d2012-01-20 14:42:32 +00001375 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001376 WriteZeros(Padding);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001377
1378 if (IsELFMetaDataSection(SD)) {
1379 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1380 ++i) {
1381 const MCFragment &F = *i;
1382 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky550f0ad2012-12-07 22:06:56 +00001383 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001384 }
1385 } else {
Jim Grosbachf77d5b12011-12-06 00:03:48 +00001386 Asm.writeSectionData(&SD, Layout);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001387 }
1388}
1389
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001390void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1391 const GroupMapTy &GroupMap,
1392 const MCAsmLayout &Layout,
1393 const SectionIndexMapTy &SectionIndexMap,
1394 const SectionOffsetMapTy &SectionOffsetMap) {
1395 const unsigned NumSections = Asm.size() + 1;
Matt Fleming3565a062010-08-16 18:57:57 +00001396
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001397 std::vector<const MCSectionELF*> Sections;
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001398 Sections.resize(NumSections - 1);
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001399
1400 for (SectionIndexMapTy::const_iterator i=
1401 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1402 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001403 Sections[p.second - 1] = p.first;
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001404 }
1405
Matt Fleming3565a062010-08-16 18:57:57 +00001406 // Null section first.
Rafael Espindola7be2c332010-10-31 00:16:26 +00001407 uint64_t FirstSectionSize =
1408 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1409 uint32_t FirstSectionLink =
1410 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1411 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming3565a062010-08-16 18:57:57 +00001412
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001413 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001414 const MCSectionELF &Section = *Sections[i];
1415 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1416 uint32_t GroupSymbolIndex;
1417 if (Section.getType() != ELF::SHT_GROUP)
1418 GroupSymbolIndex = 0;
1419 else
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001420 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1421 GroupMap.lookup(&Section));
Matt Fleming3565a062010-08-16 18:57:57 +00001422
Rafael Espindola85f2ecc2010-12-07 00:27:36 +00001423 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola6db8a9f2010-12-02 03:09:06 +00001424
Rafael Espindola2ff9e832010-11-11 18:13:52 +00001425 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001426 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindolac87a94a2010-11-10 23:36:59 +00001427 SD.getAlignment(), Section);
Matt Fleming3565a062010-08-16 18:57:57 +00001428 }
1429}
1430
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001431void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1432 std::vector<const MCSectionELF*> &Sections) {
1433 for (MCAssembler::iterator it = Asm.begin(),
1434 ie = Asm.end(); it != ie; ++it) {
1435 const MCSectionELF &Section =
1436 static_cast<const MCSectionELF &>(it->getSection());
1437 if (Section.getType() == ELF::SHT_GROUP)
1438 Sections.push_back(&Section);
1439 }
1440
1441 for (MCAssembler::iterator it = Asm.begin(),
1442 ie = Asm.end(); it != ie; ++it) {
1443 const MCSectionELF &Section =
1444 static_cast<const MCSectionELF &>(it->getSection());
1445 if (Section.getType() != ELF::SHT_GROUP &&
1446 Section.getType() != ELF::SHT_REL &&
1447 Section.getType() != ELF::SHT_RELA)
1448 Sections.push_back(&Section);
1449 }
1450
1451 for (MCAssembler::iterator it = Asm.begin(),
1452 ie = Asm.end(); it != ie; ++it) {
1453 const MCSectionELF &Section =
1454 static_cast<const MCSectionELF &>(it->getSection());
1455 if (Section.getType() == ELF::SHT_REL ||
1456 Section.getType() == ELF::SHT_RELA)
1457 Sections.push_back(&Section);
1458 }
1459}
1460
1461void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1462 const MCAsmLayout &Layout) {
1463 GroupMapTy GroupMap;
1464 RevGroupMapTy RevGroupMap;
1465 SectionIndexMapTy SectionIndexMap;
1466
1467 unsigned NumUserSections = Asm.size();
1468
1469 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1470 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1471
1472 const unsigned NumUserAndRelocSections = Asm.size();
1473 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1474 RevGroupMap, SectionIndexMap, RelMap);
1475 const unsigned AllSections = Asm.size();
1476 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1477
1478 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1479
1480 // Compute symbol table information.
1481 ComputeSymbolTable(Asm, SectionIndexMap, RevGroupMap, NumRegularSections);
1482
1483
1484 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1485
1486 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1487 const_cast<MCAsmLayout&>(Layout),
1488 SectionIndexMap,
1489 RelMap);
1490
1491 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1492 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1493 sizeof(ELF::Elf32_Ehdr);
1494 uint64_t FileOff = HeaderSize;
1495
1496 std::vector<const MCSectionELF*> Sections;
1497 ComputeSectionOrder(Asm, Sections);
1498 unsigned NumSections = Sections.size();
1499 SectionOffsetMapTy SectionOffsetMap;
1500 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1501 const MCSectionELF &Section = *Sections[i];
1502 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1503
1504 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1505
1506 // Remember the offset into the file for this section.
1507 SectionOffsetMap[&Section] = FileOff;
1508
1509 // Get the size of the section in the output file (including padding).
1510 FileOff += GetSectionFileSize(Layout, SD);
1511 }
1512
1513 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1514
1515 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1516
1517 uint64_t SectionHeaderEntrySize = is64Bit() ?
1518 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1519 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1520
1521 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1522 const MCSectionELF &Section = *Sections[i];
1523 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1524
1525 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1526
1527 // Remember the offset into the file for this section.
1528 SectionOffsetMap[&Section] = FileOff;
1529
1530 // Get the size of the section in the output file (including padding).
1531 FileOff += GetSectionFileSize(Layout, SD);
1532 }
1533
1534 // Write out the ELF header ...
1535 WriteHeader(SectionHeaderOffset, NumSections + 1);
1536
1537 // ... then the regular sections ...
1538 // + because of .shstrtab
1539 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1540 WriteDataSectionData(Asm, Layout, *Sections[i]);
1541
Benjamin Kramer263109d2012-01-20 14:42:32 +00001542 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001543 WriteZeros(Padding);
1544
1545 // ... then the section header table ...
1546 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1547 SectionOffsetMap);
1548
Nick Lewyckyaaae3f62011-10-07 20:56:23 +00001549 // ... and then the remaining sections ...
Rafael Espindola7c18fa82011-03-20 18:44:20 +00001550 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1551 WriteDataSectionData(Asm, Layout, *Sections[i]);
1552}
1553
Eli Friedman78c1e172011-03-03 07:24:36 +00001554bool
1555ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1556 const MCSymbolData &DataA,
1557 const MCFragment &FB,
1558 bool InSet,
1559 bool IsPCRel) const {
1560 if (DataA.getFlags() & ELF_STB_Weak)
1561 return false;
1562 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1563 Asm, DataA, FB,InSet, IsPCRel);
1564}
1565
Rafael Espindola6024c972010-12-17 17:45:22 +00001566MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1567 raw_ostream &OS,
Rafael Espindolabff66a82010-12-18 03:27:34 +00001568 bool IsLittleEndian) {
Rafael Espindola7bd27802011-12-22 03:24:43 +00001569 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolaedae8e12011-12-21 17:30:17 +00001570}