blob: 277716c89b46e3e23c914a87331303e0b3497b90 [file] [log] [blame]
Nick Lewycky4288f9e2013-03-09 09:32:16 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
Matt Fleming6c1ad482010-08-16 18:57:57 +00002//
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 Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/MC/MCELFObjectWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallString.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000018#include "llvm/ADT/StringMap.h"
Evan Cheng5928e692011-07-25 23:24:55 +000019#include "llvm/MC/MCAsmBackend.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000020#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000021#include "llvm/MC/MCAssembler.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000022#include "llvm/MC/MCContext.h"
Tim Northover5cc3dc82012-12-07 16:50:23 +000023#include "llvm/MC/MCELF.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000024#include "llvm/MC/MCELFSymbolFlags.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000025#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000026#include "llvm/MC/MCFixupKindInfo.h"
27#include "llvm/MC/MCObjectWriter.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000028#include "llvm/MC/MCSectionELF.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000029#include "llvm/MC/MCValue.h"
30#include "llvm/Support/Debug.h"
Rafael Espindola0ce09712014-03-25 22:43:53 +000031#include "llvm/Support/Endian.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000032#include "llvm/Support/ELF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/ErrorHandling.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000034#include <vector>
35using namespace llvm;
36
Jason W Kimc09e7262011-05-11 22:53:06 +000037#undef DEBUG_TYPE
38#define DEBUG_TYPE "reloc-info"
39
Rafael Espindola29abd972011-12-22 03:38:00 +000040namespace {
Rafael Espindola0ce09712014-03-25 22:43:53 +000041class FragmentWriter {
42 bool IsLittleEndian;
43
44public:
45 FragmentWriter(bool IsLittleEndian);
46 template <typename T> void write(MCDataFragment &F, T Val);
47};
48
Rafael Espindola10be0832014-03-25 23:44:25 +000049typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
50
51class SymbolTableWriter {
52 MCAssembler &Asm;
53 FragmentWriter &FWriter;
54 bool Is64Bit;
55 SectionIndexMapTy &SectionIndexMap;
56
57 // The symbol .symtab fragment we are writting to.
58 MCDataFragment *SymtabF;
59
60 // .symtab_shndx fragment we are writting to.
61 MCDataFragment *ShndxF;
62
63 // The numbel of symbols written so far.
64 unsigned NumWritten;
65
66 void createSymtabShndx();
67
68 template <typename T> void write(MCDataFragment &F, T Value);
69
70public:
71 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
72 SectionIndexMapTy &SectionIndexMap,
73 MCDataFragment *SymtabF);
74
75 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
76 uint8_t other, uint32_t shndx, bool Reserved);
77};
78
Rafael Espindola29abd972011-12-22 03:38:00 +000079class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola0ce09712014-03-25 22:43:53 +000080 FragmentWriter FWriter;
81
Rafael Espindola29abd972011-12-22 03:38:00 +000082 protected:
83
84 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
85 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
86 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
87 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
88 bool Used, bool Renamed);
89 static bool isLocal(const MCSymbolData &Data, bool isSignature,
90 bool isUsedInReloc);
91 static bool IsELFMetaDataSection(const MCSectionData &SD);
92 static uint64_t DataSectionSize(const MCSectionData &SD);
93 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
94 const MCSectionData &SD);
95 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
96 const MCSectionData &SD);
97
98 void WriteDataSectionData(MCAssembler &Asm,
99 const MCAsmLayout &Layout,
100 const MCSectionELF &Section);
101
102 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
103 return Kind == X86::reloc_riprel_4byte ||
104 Kind == X86::reloc_riprel_4byte_movq_load;
105 }*/
106
107 /// ELFSymbolData - Helper struct for containing some precomputed
108 /// information on symbols.
109 struct ELFSymbolData {
110 MCSymbolData *SymbolData;
111 uint64_t StringIndex;
112 uint32_t SectionIndex;
113
114 // Support lexicographic sorting.
115 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindola29abd972011-12-22 03:38:00 +0000116 return SymbolData->getSymbol().getName() <
117 RHS.SymbolData->getSymbol().getName();
118 }
119 };
120
Rafael Espindola29abd972011-12-22 03:38:00 +0000121 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000122 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000123
124 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
125 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
126 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
127
128 llvm::DenseMap<const MCSectionData*,
129 std::vector<ELFRelocationEntry> > Relocations;
130 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
131
132 /// @}
133 /// @name Symbol Table Data
134 /// @{
135
136 SmallString<256> StringTable;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000137 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000138 std::vector<ELFSymbolData> LocalSymbolData;
139 std::vector<ELFSymbolData> ExternalSymbolData;
140 std::vector<ELFSymbolData> UndefinedSymbolData;
141
142 /// @}
143
144 bool NeedsGOT;
145
Rafael Espindola29abd972011-12-22 03:38:00 +0000146 // This holds the symbol table index of the last local symbol.
147 unsigned LastLocalSymbolIndex;
148 // This holds the .strtab section index.
149 unsigned StringTableIndex;
150 // This holds the .symtab section index.
151 unsigned SymbolTableIndex;
152
153 unsigned ShstrtabIndex;
154
155
156 const MCSymbol *SymbolToReloc(const MCAssembler &Asm,
157 const MCValue &Target,
158 const MCFragment &F,
159 const MCFixup &Fixup,
160 bool IsPCRel) const;
161
162 // TargetObjectWriter wrappers.
163 const MCSymbol *ExplicitRelSym(const MCAssembler &Asm,
164 const MCValue &Target,
165 const MCFragment &F,
166 const MCFixup &Fixup,
167 bool IsPCRel) const {
168 return TargetObjectWriter->ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
169 }
Adhemerval Zanellaf2aceda2012-10-25 12:27:42 +0000170 const MCSymbol *undefinedExplicitRelSym(const MCValue &Target,
171 const MCFixup &Fixup,
172 bool IsPCRel) const {
Jack Carterf6622ba2013-02-12 21:29:39 +0000173 return TargetObjectWriter->undefinedExplicitRelSym(Target, Fixup,
174 IsPCRel);
Adhemerval Zanellaf2aceda2012-10-25 12:27:42 +0000175 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000176
177 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
178 bool hasRelocationAddend() const {
179 return TargetObjectWriter->hasRelocationAddend();
180 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000181 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
182 bool IsPCRel, bool IsRelocWithSymbol,
183 int64_t Addend) const {
184 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel,
185 IsRelocWithSymbol, Addend);
186 }
187
Rafael Espindola29abd972011-12-22 03:38:00 +0000188 public:
Rafael Espindola0ce09712014-03-25 22:43:53 +0000189 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
190 bool IsLittleEndian)
191 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000192 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000193
194 virtual ~ELFObjectWriter();
195
196 void WriteWord(uint64_t W) {
197 if (is64Bit())
198 Write64(W);
199 else
200 Write32(W);
201 }
202
Rafael Espindola0ce09712014-03-25 22:43:53 +0000203 template <typename T> void write(MCDataFragment &F, T Value) {
204 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000205 }
206
Jack Carter1bd90ff2013-01-30 02:09:52 +0000207 void WriteHeader(const MCAssembler &Asm,
208 uint64_t SectionDataSize,
Rafael Espindola29abd972011-12-22 03:38:00 +0000209 unsigned NumberOfSections);
210
Rafael Espindola10be0832014-03-25 23:44:25 +0000211 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000212 const MCAsmLayout &Layout);
213
Rafael Espindola10be0832014-03-25 23:44:25 +0000214 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000215 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000216 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000217
Craig Topper34a61bc2014-03-08 07:02:02 +0000218 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
219 const MCFragment *Fragment, const MCFixup &Fixup,
220 MCValue Target, uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000221
222 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
223 const MCSymbol *S);
224
225 // Map from a group section to the signature symbol
226 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
227 // Map from a signature symbol to the group section
228 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
229 // Map from a section to the section with the relocations
230 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
231 // Map from a section to its offset
232 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
233
Rafael Espindola022bb762014-03-24 03:43:21 +0000234 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000235 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000236 /// \param Asm - The assembler.
237 /// \param SectionIndexMap - Maps a section to its index.
238 /// \param RevGroupMap - Maps a signature symbol to the group section.
239 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000240 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000241 const SectionIndexMapTy &SectionIndexMap,
242 RevGroupMapTy RevGroupMap,
243 unsigned NumRegularSections);
244
245 void ComputeIndexMap(MCAssembler &Asm,
246 SectionIndexMapTy &SectionIndexMap,
247 const RelMapTy &RelMap);
248
249 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
250 RelMapTy &RelMap);
251
252 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
253 const RelMapTy &RelMap);
254
255 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
256 SectionIndexMapTy &SectionIndexMap,
257 const RelMapTy &RelMap);
258
259 // Create the sections that show up in the symbol table. Currently
260 // those are the .note.GNU-stack section and the group sections.
261 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
262 GroupMapTy &GroupMap,
263 RevGroupMapTy &RevGroupMap,
264 SectionIndexMapTy &SectionIndexMap,
265 const RelMapTy &RelMap);
266
Craig Topper34a61bc2014-03-08 07:02:02 +0000267 void ExecutePostLayoutBinding(MCAssembler &Asm,
268 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000269
270 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
271 const MCAsmLayout &Layout,
272 const SectionIndexMapTy &SectionIndexMap,
273 const SectionOffsetMapTy &SectionOffsetMap);
274
275 void ComputeSectionOrder(MCAssembler &Asm,
276 std::vector<const MCSectionELF*> &Sections);
277
278 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
279 uint64_t Address, uint64_t Offset,
280 uint64_t Size, uint32_t Link, uint32_t Info,
281 uint64_t Alignment, uint64_t EntrySize);
282
283 void WriteRelocationsFragment(const MCAssembler &Asm,
284 MCDataFragment *F,
285 const MCSectionData *SD);
286
Craig Topper34a61bc2014-03-08 07:02:02 +0000287 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000288 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
289 const MCSymbolData &DataA,
290 const MCFragment &FB,
291 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000292 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000293
Craig Topper34a61bc2014-03-08 07:02:02 +0000294 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000295 void WriteSection(MCAssembler &Asm,
296 const SectionIndexMapTy &SectionIndexMap,
297 uint32_t GroupSymbolIndex,
298 uint64_t Offset, uint64_t Size, uint64_t Alignment,
299 const MCSectionELF &Section);
300 };
301}
302
Rafael Espindola0ce09712014-03-25 22:43:53 +0000303FragmentWriter::FragmentWriter(bool IsLittleEndian)
304 : IsLittleEndian(IsLittleEndian) {}
305
306template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
307 if (IsLittleEndian)
308 Val = support::endian::byte_swap<T, support::little>(Val);
309 else
310 Val = support::endian::byte_swap<T, support::big>(Val);
311 const char *Start = (const char *)&Val;
312 F.getContents().append(Start, Start + sizeof(T));
313}
314
Rafael Espindola10be0832014-03-25 23:44:25 +0000315void SymbolTableWriter::createSymtabShndx() {
316 if (ShndxF)
317 return;
318
319 MCContext &Ctx = Asm.getContext();
320 const MCSectionELF *SymtabShndxSection =
321 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
322 SectionKind::getReadOnly(), 4, "");
323 MCSectionData *SymtabShndxSD =
324 &Asm.getOrCreateSectionData(*SymtabShndxSection);
325 SymtabShndxSD->setAlignment(4);
326 ShndxF = new MCDataFragment(SymtabShndxSD);
327 unsigned Index = SectionIndexMap.size() + 1;
328 SectionIndexMap[SymtabShndxSection] = Index;
329
330 for (unsigned I = 0; I < NumWritten; ++I)
331 write(*ShndxF, uint32_t(0));
332}
333
334template <typename T>
335void SymbolTableWriter::write(MCDataFragment &F, T Value) {
336 FWriter.write(F, Value);
337}
338
339SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
340 bool Is64Bit,
341 SectionIndexMapTy &SectionIndexMap,
342 MCDataFragment *SymtabF)
343 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
344 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
345 NumWritten(0) {}
346
347void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
348 uint64_t size, uint8_t other,
349 uint32_t shndx, bool Reserved) {
350 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
351
352 if (LargeIndex)
353 createSymtabShndx();
354
355 if (ShndxF) {
356 if (LargeIndex)
357 write(*ShndxF, shndx);
358 else
359 write(*ShndxF, uint32_t(0));
360 }
361
362 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
363
364 raw_svector_ostream OS(SymtabF->getContents());
365
366 if (Is64Bit) {
367 write(*SymtabF, name); // st_name
368 write(*SymtabF, info); // st_info
369 write(*SymtabF, other); // st_other
370 write(*SymtabF, Index); // st_shndx
371 write(*SymtabF, value); // st_value
372 write(*SymtabF, size); // st_size
373 } else {
374 write(*SymtabF, name); // st_name
375 write(*SymtabF, uint32_t(value)); // st_value
376 write(*SymtabF, uint32_t(size)); // st_size
377 write(*SymtabF, info); // st_info
378 write(*SymtabF, other); // st_other
379 write(*SymtabF, Index); // st_shndx
380 }
381
382 ++NumWritten;
383}
384
Jan Sjödin30a52de2011-02-28 21:45:04 +0000385bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
386 const MCFixupKindInfo &FKI =
387 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
388
389 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
390}
391
392bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
393 switch (Variant) {
394 default:
395 return false;
396 case MCSymbolRefExpr::VK_GOT:
397 case MCSymbolRefExpr::VK_PLT:
398 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000399 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000400 case MCSymbolRefExpr::VK_TPOFF:
401 case MCSymbolRefExpr::VK_TLSGD:
402 case MCSymbolRefExpr::VK_GOTTPOFF:
403 case MCSymbolRefExpr::VK_INDNTPOFF:
404 case MCSymbolRefExpr::VK_NTPOFF:
405 case MCSymbolRefExpr::VK_GOTNTPOFF:
406 case MCSymbolRefExpr::VK_TLSLDM:
407 case MCSymbolRefExpr::VK_DTPOFF:
408 case MCSymbolRefExpr::VK_TLSLD:
409 return true;
410 }
411}
412
Jason W Kim96f4c012010-11-15 16:18:39 +0000413ELFObjectWriter::~ELFObjectWriter()
414{}
415
Matt Fleming6c1ad482010-08-16 18:57:57 +0000416// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000417void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
418 uint64_t SectionDataSize,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000419 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000420 // ELF Header
421 // ----------
422 //
423 // Note
424 // ----
425 // emitWord method behaves differently for ELF32 and ELF64, writing
426 // 4 bytes in the former and 8 in the latter.
427
428 Write8(0x7f); // e_ident[EI_MAG0]
429 Write8('E'); // e_ident[EI_MAG1]
430 Write8('L'); // e_ident[EI_MAG2]
431 Write8('F'); // e_ident[EI_MAG3]
432
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000433 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000434
435 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000436 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000437
438 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000439 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000440 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000441 Write8(0); // e_ident[EI_ABIVERSION]
442
443 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
444
445 Write16(ELF::ET_REL); // e_type
446
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000447 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000448
449 Write32(ELF::EV_CURRENT); // e_version
450 WriteWord(0); // e_entry, no entry point in .o file
451 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000452 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramer896bd7e2010-08-17 17:02:29 +0000453 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000454
Jason W Kim4761fba2011-02-04 21:41:11 +0000455 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000456 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000457
458 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000459 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000460
461 Write16(0); // e_phentsize = prog header entry size
462 Write16(0); // e_phnum = # prog header entries = 0
463
464 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000465 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000466
467 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000468 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000469 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000470 else
471 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000472
473 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000474 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000475 Write16(ELF::SHN_XINDEX);
476 else
477 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000478}
479
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000480uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000481 const MCAsmLayout &Layout) {
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000482 MCSymbolData *Data = &OrigData;
483 if (Data->isCommon() && Data->isExternal())
484 return Data->getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000485
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000486 const MCSymbol *Symbol = &Data->getSymbol();
487 bool IsThumbFunc = OrigData.getFlags() & ELF_Other_ThumbFunc;
Roman Divacky55184dd2010-12-20 21:14:39 +0000488
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000489 uint64_t Res = 0;
490 if (Symbol->isVariable()) {
491 const MCExpr *Expr = Symbol->getVariableValue();
492 MCValue Value;
493 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
494 llvm_unreachable("Invalid expression");
495
496 assert(!Value.getSymB());
497
498 Res = Value.getConstant();
499
500 if (const MCSymbolRefExpr *A = Value.getSymA()) {
501 Symbol = &A->getSymbol();
502 Data = &Layout.getAssembler().getSymbolData(*Symbol);
503 } else {
504 Symbol = 0;
505 Data = 0;
Rafael Espindola7bbd5c22014-03-19 00:13:43 +0000506 }
Roman Divacky55184dd2010-12-20 21:14:39 +0000507 }
508
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000509 if (IsThumbFunc)
510 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000511
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000512 if (!Symbol || !Symbol->isInSection())
513 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000514
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000515 Res += Layout.getSymbolOffset(Data);
516
517 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000518}
519
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000520void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
521 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000522 // The presence of symbol versions causes undefined symbols and
523 // versions declared with @@@ to be renamed.
524
525 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
526 ie = Asm.symbol_end(); it != ie; ++it) {
527 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000528 const MCSymbol &Symbol = Alias.AliasedSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000529 MCSymbolData &SD = Asm.getSymbolData(Symbol);
530
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000531 // Not an alias.
532 if (&Symbol == &Alias)
533 continue;
534
Benjamin Kramer14807272010-10-27 19:53:52 +0000535 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000536 size_t Pos = AliasName.find('@');
537 if (Pos == StringRef::npos)
538 continue;
539
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000540 // Aliases defined with .symvar copy the binding from the symbol they alias.
541 // This is the first place we are able to copy this information.
542 it->setExternal(SD.isExternal());
Jan Sjödin30a52de2011-02-28 21:45:04 +0000543 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000544
Benjamin Kramer14807272010-10-27 19:53:52 +0000545 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000546 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
547 continue;
548
Rafael Espindola26496e62010-10-27 17:56:18 +0000549 // FIXME: produce a better error message.
550 if (Symbol.isUndefined() && Rest.startswith("@@") &&
551 !Rest.startswith("@@@"))
552 report_fatal_error("A @@ version cannot be undefined");
553
Benjamin Kramer14807272010-10-27 19:53:52 +0000554 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000555 }
556}
557
Roman Divacky5a1c5492014-01-07 20:17:03 +0000558static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
559 uint8_t Type = newType;
560
561 // Propagation rules:
562 // IFUNC > FUNC > OBJECT > NOTYPE
563 // TLS_OBJECT > OBJECT > NOTYPE
564 //
565 // dont let the new type degrade the old type
566 switch (origType) {
567 default:
568 break;
569 case ELF::STT_GNU_IFUNC:
570 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
571 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
572 Type = ELF::STT_GNU_IFUNC;
573 break;
574 case ELF::STT_FUNC:
575 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
576 Type == ELF::STT_TLS)
577 Type = ELF::STT_FUNC;
578 break;
579 case ELF::STT_OBJECT:
580 if (Type == ELF::STT_NOTYPE)
581 Type = ELF::STT_OBJECT;
582 break;
583 case ELF::STT_TLS:
584 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
585 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
586 Type = ELF::STT_TLS;
587 break;
588 }
589
590 return Type;
591}
592
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000593static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
594 const MCSymbol &Symbol) {
595 if (!Symbol.isVariable())
596 return &Symbol;
597
598 const MCExpr *Expr = Symbol.getVariableValue();
599 MCValue Value;
600 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
601 llvm_unreachable("Invalid Expression");
602 assert(!Value.getSymB());
603 const MCSymbolRefExpr *A = Value.getSymA();
604 if (!A)
605 return nullptr;
606 return getBaseSymbol(Layout, A->getSymbol());
607}
608
Rafael Espindola10be0832014-03-25 23:44:25 +0000609void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000610 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000611 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindola85a84912014-03-26 00:16:43 +0000612 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
613
614 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
615 // SHN_COMMON.
616 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000617
Jack Carter2f8d9d92013-02-19 21:57:35 +0000618 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000619 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000620 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000621 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000622 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000623 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
624 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000625 }
Saleem Abdulrasool39f773f2014-03-20 06:05:33 +0000626 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
627 Type = ELF::STT_FUNC;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000628 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000629
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000630 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000631 // 2 bits
632 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000633 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000634 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000635
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000636 uint64_t Value = SymbolValue(OrigData, Layout);
Saleem Abdulrasool39f773f2014-03-20 06:05:33 +0000637 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
638 Value |= 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000639 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000640
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000641 const MCExpr *ESize = OrigData.getSize();
642 if (!ESize && Base)
643 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000644
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000645 if (ESize) {
646 int64_t Res;
647 if (!ESize->EvaluateAsAbsolute(Res, Layout))
648 report_fatal_error("Size expression must be absolute.");
649 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000650 }
651
652 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000653 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
654 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000655}
656
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000657void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000658 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000659 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000660 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000661 // The string table must be emitted first because we need the index
662 // into the string table for all the symbol names.
663 assert(StringTable.size() && "Missing string table");
664
665 // FIXME: Make sure the start of the symbol table is aligned.
666
Rafael Espindola10be0832014-03-25 23:44:25 +0000667 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
668
Matt Fleming6c1ad482010-08-16 18:57:57 +0000669 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000670 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000671
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000672 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000673 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
674 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000675 }
676
Matt Fleming6c1ad482010-08-16 18:57:57 +0000677 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000678 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
679
Matt Fleming6c1ad482010-08-16 18:57:57 +0000680 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
681 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000682 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000683 }
684
Rafael Espindola44bf2662010-09-16 19:46:31 +0000685 // Write out a symbol table entry for each regular section.
Rafael Espindola18014102010-11-10 22:16:43 +0000686 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
687 ++i) {
Eli Friedman1fe0d532010-08-16 21:17:09 +0000688 const MCSectionELF &Section =
Rafael Espindola18014102010-11-10 22:16:43 +0000689 static_cast<const MCSectionELF&>(i->getSection());
690 if (Section.getType() == ELF::SHT_RELA ||
691 Section.getType() == ELF::SHT_REL ||
692 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewycky133a1682011-10-07 23:29:53 +0000693 Section.getType() == ELF::SHT_SYMTAB ||
694 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedman1fe0d532010-08-16 21:17:09 +0000695 continue;
Rafael Espindola10be0832014-03-25 23:44:25 +0000696 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
697 SectionIndexMap.lookup(&Section), false);
Eli Friedman1fe0d532010-08-16 21:17:09 +0000698 LastLocalSymbolIndex++;
699 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000700
701 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
702 ELFSymbolData &MSD = ExternalSymbolData[i];
703 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000704 assert(((Data.getFlags() & ELF_STB_Global) ||
705 (Data.getFlags() & ELF_STB_Weak)) &&
706 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000707 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000708 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000709 LastLocalSymbolIndex++;
710 }
711
712 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
713 ELFSymbolData &MSD = UndefinedSymbolData[i];
714 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000715 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000716 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000717 LastLocalSymbolIndex++;
718 }
719}
720
Rafael Espindola240028d2010-11-14 23:53:26 +0000721const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
722 const MCValue &Target,
Jim Grosbachdc1e36e2012-05-11 01:41:30 +0000723 const MCFragment &F,
Jason W Kimc09e7262011-05-11 22:53:06 +0000724 const MCFixup &Fixup,
725 bool IsPCRel) const {
Rafael Espindola240028d2010-11-14 23:53:26 +0000726 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000727 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
728 const MCSymbol *Renamed = Renames.lookup(&Symbol);
729 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola240028d2010-11-14 23:53:26 +0000730
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000731 if (ASymbol.isUndefined()) {
732 if (Renamed)
733 return Renamed;
Adhemerval Zanellaf2aceda2012-10-25 12:27:42 +0000734 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
Rafael Espindola240028d2010-11-14 23:53:26 +0000735 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000736
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000737 if (SD.isExternal()) {
738 if (Renamed)
739 return Renamed;
740 return &Symbol;
741 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000742
Rafael Espindolaf987d5e2010-09-30 20:18:35 +0000743 const MCSectionELF &Section =
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000744 static_cast<const MCSectionELF&>(ASymbol.getSection());
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000745 const SectionKind secKind = Section.getKind();
Rafael Espindolaf987d5e2010-09-30 20:18:35 +0000746
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000747 if (secKind.isBSS())
Jason W Kimc09e7262011-05-11 22:53:06 +0000748 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindolaf987d5e2010-09-30 20:18:35 +0000749
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000750 if (secKind.isThreadLocal()) {
751 if (Renamed)
752 return Renamed;
753 return &Symbol;
754 }
755
Rafael Espindola8f3d2c92010-10-06 16:23:36 +0000756 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindolad7565c32010-10-05 23:57:26 +0000757 const MCSectionELF &Sec2 =
758 static_cast<const MCSectionELF&>(F.getParent()->getSection());
759
Rafael Espindola8f3d2c92010-10-06 16:23:36 +0000760 if (&Sec2 != &Section &&
Rafael Espindola4464e082010-10-18 16:38:04 +0000761 (Kind == MCSymbolRefExpr::VK_PLT ||
762 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000763 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000764 if (Renamed)
765 return Renamed;
766 return &Symbol;
767 }
Rafael Espindolad7565c32010-10-05 23:57:26 +0000768
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000769 if (Section.getFlags() & ELF::SHF_MERGE) {
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000770 if (Target.getConstant() == 0)
Jason W Kimc09e7262011-05-11 22:53:06 +0000771 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000772 if (Renamed)
773 return Renamed;
774 return &Symbol;
Rafael Espindola240028d2010-11-14 23:53:26 +0000775 }
Rafael Espindola4464e082010-10-18 16:38:04 +0000776
Jason W Kimc09e7262011-05-11 22:53:06 +0000777 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
778
Rafael Espindola75d65b92010-09-25 05:42:19 +0000779}
780
Matt Fleming6c1ad482010-08-16 18:57:57 +0000781
Jason W Kim495c2bb2010-12-06 21:57:34 +0000782void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
783 const MCAsmLayout &Layout,
784 const MCFragment *Fragment,
785 const MCFixup &Fixup,
786 MCValue Target,
787 uint64_t &FixedValue) {
788 int64_t Addend = 0;
789 int Index = 0;
790 int64_t Value = Target.getConstant();
791 const MCSymbol *RelocSymbol = NULL;
792
Rafael Espindoladf633352010-12-17 07:28:17 +0000793 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Jason W Kim495c2bb2010-12-06 21:57:34 +0000794 if (!Target.isAbsolute()) {
795 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
796 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
Jason W Kimc09e7262011-05-11 22:53:06 +0000797 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
Jason W Kim495c2bb2010-12-06 21:57:34 +0000798
799 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
800 const MCSymbol &SymbolB = RefB->getSymbol();
801 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
802 IsPCRel = true;
803
David Majnemera45a1762014-01-06 07:39:46 +0000804 if (!SDB.getFragment())
805 Asm.getContext().FatalError(
806 Fixup.getLoc(),
807 Twine("symbol '") + SymbolB.getName() +
808 "' can not be undefined in a subtraction expression");
809
Jason W Kim495c2bb2010-12-06 21:57:34 +0000810 // Offset of the symbol in the section
811 int64_t a = Layout.getSymbolOffset(&SDB);
812
Bruno Cardoso Lopesc9473e92011-11-04 22:24:36 +0000813 // Offset of the relocation in the section
Jason W Kim495c2bb2010-12-06 21:57:34 +0000814 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
815 Value += b - a;
816 }
817
818 if (!RelocSymbol) {
819 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
820 MCFragment *F = SD.getFragment();
821
Adhemerval Zanellaf2aceda2012-10-25 12:27:42 +0000822 if (F) {
823 Index = F->getParent()->getOrdinal() + 1;
824 // Offset of the symbol in the section
825 Value += Layout.getSymbolOffset(&SD);
826 } else {
827 Index = 0;
828 }
Jason W Kim495c2bb2010-12-06 21:57:34 +0000829 } else {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000830 if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_WEAKREF)
Jason W Kim495c2bb2010-12-06 21:57:34 +0000831 WeakrefUsedInReloc.insert(RelocSymbol);
832 else
833 UsedInReloc.insert(RelocSymbol);
834 Index = -1;
835 }
836 Addend = Value;
Michael Liaod6f31682012-10-16 19:49:51 +0000837 if (hasRelocationAddend())
Jason W Kim495c2bb2010-12-06 21:57:34 +0000838 Value = 0;
839 }
840
841 FixedValue = Value;
842 unsigned Type = GetRelocType(Target, Fixup, IsPCRel,
843 (RelocSymbol != 0), Addend);
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000844 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
845 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
846 if (RelocNeedsGOT(Modifier))
847 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000848
Jason W Kim495c2bb2010-12-06 21:57:34 +0000849 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
850 Fixup.getOffset();
Roman Divackydfbecd12011-08-04 19:08:19 +0000851
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000852 if (!hasRelocationAddend())
853 Addend = 0;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000854
855 if (is64Bit())
856 assert(isInt<64>(Addend));
857 else
858 assert(isInt<32>(Addend));
859
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +0000860 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
Jason W Kim495c2bb2010-12-06 21:57:34 +0000861 Relocations[Fragment->getParent()].push_back(ERE);
862}
863
864
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000865uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000866ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
867 const MCSymbol *S) {
Benjamin Kramer37b384c2010-08-25 20:09:43 +0000868 MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000869 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000870}
871
Jan Sjödin30a52de2011-02-28 21:45:04 +0000872bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
873 const MCSymbolData &Data,
874 bool Used, bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000875 const MCSymbol &Symbol = Data.getSymbol();
876 if (Symbol.isVariable()) {
877 const MCExpr *Expr = Symbol.getVariableValue();
878 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
879 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
880 return false;
881 }
882 }
Rafael Espindola16145972010-11-01 14:28:48 +0000883
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000884 if (Used)
885 return true;
886
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000887 if (Renamed)
888 return false;
889
Rafael Espindola45834a02010-10-29 23:09:31 +0000890 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
891 return true;
892
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000893 const MCSymbol &A = Symbol.AliasedSymbol();
Rafael Espindola9e18e962011-02-23 20:22:07 +0000894 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
895 return false;
896
Jan Sjödin30a52de2011-02-28 21:45:04 +0000897 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000898 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000899 return false;
900
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000901 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000902 return false;
903
904 return true;
905}
906
Jan Sjödin30a52de2011-02-28 21:45:04 +0000907bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
908 bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000909 if (Data.isExternal())
910 return false;
911
912 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000913 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000914
915 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
916 if (isSignature && !isUsedInReloc)
917 return true;
918
Rafael Espindolab1d07892010-10-05 18:01:23 +0000919 return false;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000920 }
Rafael Espindolab1d07892010-10-05 18:01:23 +0000921
922 return true;
923}
924
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000925void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000926 SectionIndexMapTy &SectionIndexMap,
927 const RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000928 unsigned Index = 1;
929 for (MCAssembler::iterator it = Asm.begin(),
930 ie = Asm.end(); it != ie; ++it) {
931 const MCSectionELF &Section =
932 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000933 if (Section.getType() != ELF::SHT_GROUP)
934 continue;
935 SectionIndexMap[&Section] = Index++;
936 }
937
938 for (MCAssembler::iterator it = Asm.begin(),
939 ie = Asm.end(); it != ie; ++it) {
940 const MCSectionELF &Section =
941 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000942 if (Section.getType() == ELF::SHT_GROUP ||
943 Section.getType() == ELF::SHT_REL ||
944 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000945 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000946 SectionIndexMap[&Section] = Index++;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000947 const MCSectionELF *RelSection = RelMap.lookup(&Section);
948 if (RelSection)
949 SectionIndexMap[RelSection] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +0000950 }
951}
952
Rafael Espindola022bb762014-03-24 03:43:21 +0000953void
954ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
955 const SectionIndexMapTy &SectionIndexMap,
956 RevGroupMapTy RevGroupMap,
957 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000958 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000959 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000960 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000961 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000962 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
963 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
964 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000965 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000966 }
967
Matt Fleming6c1ad482010-08-16 18:57:57 +0000968 // Index 0 is always the empty string.
969 StringMap<uint64_t> StringIndexMap;
970 StringTable += '\x00';
971
Rafael Espindolab80875e2011-04-07 23:21:52 +0000972 // FIXME: We could optimize suffixes in strtab in the same way we
973 // optimize them in shstrtab.
974
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000975 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
976 ie = Asm.file_names_end();
977 it != ie;
978 ++it) {
979 StringRef Name = *it;
980 uint64_t &Entry = StringIndexMap[Name];
981 if (!Entry) {
982 Entry = StringTable.size();
983 StringTable += Name;
984 StringTable += '\x00';
985 }
986 FileSymbolData.push_back(Entry);
987 }
988
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000989 // Add the data for the symbols.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000990 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
991 ie = Asm.symbol_end(); it != ie; ++it) {
992 const MCSymbol &Symbol = it->getSymbol();
993
Rafael Espindola16145972010-11-01 14:28:48 +0000994 bool Used = UsedInReloc.count(&Symbol);
995 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000996 bool isSignature = RevGroupMap.count(&Symbol);
997
998 if (!isInSymtab(Asm, *it,
999 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001000 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001001 continue;
1002
Matt Fleming6c1ad482010-08-16 18:57:57 +00001003 ELFSymbolData MSD;
1004 MSD.SymbolData = it;
Rafael Espindola022bb762014-03-24 03:43:21 +00001005 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001006
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001007 // Undefined symbols are global, but this is the first place we
1008 // are able to set it.
1009 bool Local = isLocal(*it, isSignature, Used);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001010 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001011 assert(BaseSymbol);
1012 MCSymbolData &SD = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001013 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
1014 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001015 }
1016
Rafael Espindola022bb762014-03-24 03:43:21 +00001017 if (!BaseSymbol) {
1018 MSD.SectionIndex = ELF::SHN_ABS;
1019 } else if (it->isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001020 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001021 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001022 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001023 if (isSignature && !Used)
1024 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1025 else
1026 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001027 if (!Used && WeakrefUsed)
1028 MCELF::SetBinding(*it, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001029 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001030 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001031 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001032 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001033 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001034 }
1035
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001036 // The @@@ in symbol version is replaced with @ in undefined symbols and
1037 // @@ in defined ones.
1038 StringRef Name = Symbol.getName();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001039 SmallString<32> Buf;
1040
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001041 size_t Pos = Name.find("@@@");
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001042 if (Pos != StringRef::npos) {
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001043 Buf += Name.substr(0, Pos);
1044 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1045 Buf += Name.substr(Pos + Skip);
1046 Name = Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001047 }
1048
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001049 uint64_t &Entry = StringIndexMap[Name];
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001050 if (!Entry) {
1051 Entry = StringTable.size();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001052 StringTable += Name;
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001053 StringTable += '\x00';
Matt Fleming6c1ad482010-08-16 18:57:57 +00001054 }
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001055 MSD.StringIndex = Entry;
1056 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1057 UndefinedSymbolData.push_back(MSD);
1058 else if (Local)
1059 LocalSymbolData.push_back(MSD);
1060 else
1061 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001062 }
1063
1064 // Symbols are required to be in lexicographic order.
1065 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1066 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1067 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1068
1069 // Set the symbol indices. Local symbols must come before all other
1070 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001071 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001072 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1073 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001074
1075 Index += NumRegularSections;
1076
Matt Fleming6c1ad482010-08-16 18:57:57 +00001077 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1078 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1079 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1080 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1081}
1082
Rafael Espindola1557fd62011-03-20 18:44:20 +00001083void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1084 MCAsmLayout &Layout,
1085 RelMapTy &RelMap) {
1086 for (MCAssembler::const_iterator it = Asm.begin(),
1087 ie = Asm.end(); it != ie; ++it) {
1088 const MCSectionData &SD = *it;
1089 if (Relocations[&SD].empty())
1090 continue;
1091
Matt Fleming6c1ad482010-08-16 18:57:57 +00001092 MCContext &Ctx = Asm.getContext();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001093 const MCSectionELF &Section =
1094 static_cast<const MCSectionELF&>(SD.getSection());
1095
1096 const StringRef SectionName = Section.getSectionName();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001097 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming6c1ad482010-08-16 18:57:57 +00001098 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001099
1100 unsigned EntrySize;
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001101 if (hasRelocationAddend())
1102 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramerfd054152010-08-17 17:56:13 +00001103 else
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001104 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001105
Tim Northovera630fb02013-07-10 20:58:17 +00001106 unsigned Flags = 0;
1107 StringRef Group = "";
1108 if (Section.getFlags() & ELF::SHF_GROUP) {
David Blaikie1e412ea2013-10-22 20:34:30 +00001109 Flags = ELF::SHF_GROUP;
1110 Group = Section.getGroup()->getName();
Tim Northovera630fb02013-07-10 20:58:17 +00001111 }
1112
Rafael Espindola1557fd62011-03-20 18:44:20 +00001113 const MCSectionELF *RelaSection =
1114 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
Tim Northovera630fb02013-07-10 20:58:17 +00001115 ELF::SHT_RELA : ELF::SHT_REL, Flags,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001116 SectionKind::getReadOnly(),
Tim Northovera630fb02013-07-10 20:58:17 +00001117 EntrySize, Group);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001118 RelMap[&Section] = RelaSection;
1119 Asm.getOrCreateSectionData(*RelaSection);
1120 }
1121}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001122
Rafael Espindola1557fd62011-03-20 18:44:20 +00001123void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1124 const RelMapTy &RelMap) {
1125 for (MCAssembler::const_iterator it = Asm.begin(),
1126 ie = Asm.end(); it != ie; ++it) {
1127 const MCSectionData &SD = *it;
1128 const MCSectionELF &Section =
1129 static_cast<const MCSectionELF&>(SD.getSection());
1130
1131 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1132 if (!RelaSection)
1133 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001134 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001135 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001136
1137 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001138 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001139 }
1140}
1141
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001142void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1143 uint64_t Flags, uint64_t Address,
1144 uint64_t Offset, uint64_t Size,
1145 uint32_t Link, uint32_t Info,
1146 uint64_t Alignment,
1147 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001148 Write32(Name); // sh_name: index into string table
1149 Write32(Type); // sh_type
1150 WriteWord(Flags); // sh_flags
1151 WriteWord(Address); // sh_addr
1152 WriteWord(Offset); // sh_offset
1153 WriteWord(Size); // sh_size
1154 Write32(Link); // sh_link
1155 Write32(Info); // sh_info
1156 WriteWord(Alignment); // sh_addralign
1157 WriteWord(EntrySize); // sh_entsize
1158}
1159
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001160void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1161 MCDataFragment *F,
1162 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001163 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001164
1165 // Sort the relocation entries. Most targets just sort by r_offset, but some
1166 // (e.g., MIPS) have additional constraints.
1167 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001168
1169 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1170 ELFRelocationEntry entry = Relocs[e - i - 1];
1171
Rafael Espindola26cb15a2010-11-21 00:48:25 +00001172 if (!entry.Index)
1173 ;
Rafael Espindola0ce09712014-03-25 22:43:53 +00001174 // FIXME: this is most likely a bug if index overflows.
Rafael Espindola26cb15a2010-11-21 00:48:25 +00001175 else if (entry.Index < 0)
Rafael Espindolabce26a12010-10-05 15:11:03 +00001176 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1177 else
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001178 entry.Index += FileSymbolData.size() + LocalSymbolData.size();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001179 if (is64Bit()) {
Rafael Espindola0ce09712014-03-25 22:43:53 +00001180 write(*F, entry.r_offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001181 if (TargetObjectWriter->isN64()) {
Rafael Espindola0ce09712014-03-25 22:43:53 +00001182 write(*F, uint32_t(entry.Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001183
Rafael Espindola0ce09712014-03-25 22:43:53 +00001184 write(*F, TargetObjectWriter->getRSsym(entry.Type));
1185 write(*F, TargetObjectWriter->getRType3(entry.Type));
1186 write(*F, TargetObjectWriter->getRType2(entry.Type));
1187 write(*F, TargetObjectWriter->getRType(entry.Type));
Jack Carter8ad0c272012-06-27 22:28:30 +00001188 }
1189 else {
1190 struct ELF::Elf64_Rela ERE64;
1191 ERE64.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001192 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001193 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001194 if (hasRelocationAddend())
Rafael Espindola0ce09712014-03-25 22:43:53 +00001195 write(*F, entry.r_addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001196 } else {
Rafael Espindola0ce09712014-03-25 22:43:53 +00001197 write(*F, uint32_t(entry.r_offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001198
Rafael Espindolabce26a12010-10-05 15:11:03 +00001199 struct ELF::Elf32_Rela ERE32;
1200 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001201 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001202
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001203 if (hasRelocationAddend())
Rafael Espindola0ce09712014-03-25 22:43:53 +00001204 write(*F, uint32_t(entry.r_addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001205 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001206 }
1207}
1208
Benjamin Kramer8817cca2013-09-22 14:09:50 +00001209static int compareBySuffix(const MCSectionELF *const *a,
1210 const MCSectionELF *const *b) {
1211 const StringRef &NameA = (*a)->getSectionName();
1212 const StringRef &NameB = (*b)->getSectionName();
Rafael Espindolab80875e2011-04-07 23:21:52 +00001213 const unsigned sizeA = NameA.size();
1214 const unsigned sizeB = NameB.size();
1215 const unsigned len = std::min(sizeA, sizeB);
1216 for (unsigned int i = 0; i < len; ++i) {
1217 char ca = NameA[sizeA - i - 1];
1218 char cb = NameB[sizeB - i - 1];
1219 if (ca != cb)
1220 return cb - ca;
1221 }
1222
1223 return sizeB - sizeA;
1224}
1225
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001226void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1227 MCAsmLayout &Layout,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001228 SectionIndexMapTy &SectionIndexMap,
1229 const RelMapTy &RelMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001230 MCContext &Ctx = Asm.getContext();
1231 MCDataFragment *F;
1232
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001233 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001234
Rafael Espindola0e527b72010-09-22 19:04:41 +00001235 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001236 const MCSectionELF *ShstrtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001237 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001238 SectionKind::getReadOnly());
Rafael Espindola44bf2662010-09-16 19:46:31 +00001239 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1240 ShstrtabSD.setAlignment(1);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001241
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001242 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001243 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1244 SectionKind::getReadOnly(),
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001245 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001246 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001247 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001248
Rafael Espindola1557fd62011-03-20 18:44:20 +00001249 const MCSectionELF *StrtabSection;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001250 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001251 SectionKind::getReadOnly());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001252 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1253 StrtabSD.setAlignment(1);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001254
Rafael Espindola1557fd62011-03-20 18:44:20 +00001255 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1256
1257 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1258 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1259 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001260
1261 // Symbol table
1262 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001263 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001264
Matt Fleming6c1ad482010-08-16 18:57:57 +00001265 F = new MCDataFragment(&StrtabSD);
1266 F->getContents().append(StringTable.begin(), StringTable.end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001267
Matt Fleming6c1ad482010-08-16 18:57:57 +00001268 F = new MCDataFragment(&ShstrtabSD);
1269
Rafael Espindolab80875e2011-04-07 23:21:52 +00001270 std::vector<const MCSectionELF*> Sections;
1271 for (MCAssembler::const_iterator it = Asm.begin(),
1272 ie = Asm.end(); it != ie; ++it) {
1273 const MCSectionELF &Section =
1274 static_cast<const MCSectionELF&>(it->getSection());
1275 Sections.push_back(&Section);
1276 }
1277 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1278
Matt Fleming6c1ad482010-08-16 18:57:57 +00001279 // Section header string table.
1280 //
1281 // The first entry of a string table holds a null character so skip
1282 // section 0.
1283 uint64_t Index = 1;
Eli Bendersky84b2a792012-12-07 22:06:56 +00001284 F->getContents().push_back('\x00');
Matt Fleming6c1ad482010-08-16 18:57:57 +00001285
Rafael Espindolab80875e2011-04-07 23:21:52 +00001286 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1287 const MCSectionELF &Section = *Sections[I];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001288
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001289 StringRef Name = Section.getSectionName();
Rafael Espindolab80875e2011-04-07 23:21:52 +00001290 if (I != 0) {
1291 StringRef PreviousName = Sections[I - 1]->getSectionName();
1292 if (PreviousName.endswith(Name)) {
1293 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1294 continue;
1295 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001296 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001297 // Remember the index into the string table so we can write it
1298 // into the sh_name field of the section header table.
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001299 SectionStringTableIndex[&Section] = Index;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001300
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001301 Index += Name.size() + 1;
Eli Bendersky84b2a792012-12-07 22:06:56 +00001302 F->getContents().append(Name.begin(), Name.end());
1303 F->getContents().push_back('\x00');
Matt Fleming6c1ad482010-08-16 18:57:57 +00001304 }
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001305}
1306
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001307void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1308 MCAsmLayout &Layout,
1309 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001310 RevGroupMapTy &RevGroupMap,
1311 SectionIndexMapTy &SectionIndexMap,
1312 const RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001313 // Create the .note.GNU-stack section if needed.
1314 MCContext &Ctx = Asm.getContext();
1315 if (Asm.getNoExecStack()) {
1316 const MCSectionELF *GnuStackSection =
1317 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1318 SectionKind::getReadOnly());
1319 Asm.getOrCreateSectionData(*GnuStackSection);
1320 }
1321
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001322 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001323 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1324 it != ie; ++it) {
1325 const MCSectionELF &Section =
1326 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001327 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001328 continue;
1329
1330 const MCSymbol *SignatureSymbol = Section.getGroup();
1331 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001332 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001333 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001334 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001335 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1336 Data.setAlignment(4);
1337 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001338 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001339 }
1340 GroupMap[Group] = SignatureSymbol;
1341 }
1342
Rafael Espindola1557fd62011-03-20 18:44:20 +00001343 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1344
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001345 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001346 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001347 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001348 const MCSectionELF &Section =
1349 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001350 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001351 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001352 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001353 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1354 // FIXME: we could use the previous fragment
1355 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001356 uint32_t Index = SectionIndexMap.lookup(&Section);
1357 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001358 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001359}
1360
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001361void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1362 const SectionIndexMapTy &SectionIndexMap,
1363 uint32_t GroupSymbolIndex,
1364 uint64_t Offset, uint64_t Size,
1365 uint64_t Alignment,
1366 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001367 uint64_t sh_link = 0;
1368 uint64_t sh_info = 0;
1369
1370 switch(Section.getType()) {
1371 case ELF::SHT_DYNAMIC:
1372 sh_link = SectionStringTableIndex[&Section];
1373 sh_info = 0;
1374 break;
1375
1376 case ELF::SHT_REL:
1377 case ELF::SHT_RELA: {
1378 const MCSectionELF *SymtabSection;
1379 const MCSectionELF *InfoSection;
1380 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1381 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001382 SectionKind::getReadOnly());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001383 sh_link = SectionIndexMap.lookup(SymtabSection);
1384 assert(sh_link && ".symtab not found");
1385
1386 // Remove ".rel" and ".rela" prefixes.
1387 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1388 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
David Blaikie15b25df2013-10-22 23:41:52 +00001389 StringRef GroupName =
1390 Section.getGroup() ? Section.getGroup()->getName() : "";
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001391
David Blaikie15b25df2013-10-22 23:41:52 +00001392 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1393 0, SectionKind::getReadOnly(),
1394 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001395 sh_info = SectionIndexMap.lookup(InfoSection);
1396 break;
1397 }
1398
1399 case ELF::SHT_SYMTAB:
1400 case ELF::SHT_DYNSYM:
1401 sh_link = StringTableIndex;
1402 sh_info = LastLocalSymbolIndex;
1403 break;
1404
1405 case ELF::SHT_SYMTAB_SHNDX:
1406 sh_link = SymbolTableIndex;
1407 break;
1408
1409 case ELF::SHT_PROGBITS:
1410 case ELF::SHT_STRTAB:
1411 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001412 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001413 case ELF::SHT_NULL:
1414 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001415 case ELF::SHT_INIT_ARRAY:
1416 case ELF::SHT_FINI_ARRAY:
1417 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001418 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001419 case ELF::SHT_MIPS_REGINFO:
1420 case ELF::SHT_MIPS_OPTIONS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001421 // Nothing to do.
1422 break;
1423
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001424 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001425 sh_link = SymbolTableIndex;
1426 sh_info = GroupSymbolIndex;
1427 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001428
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001429 default:
1430 assert(0 && "FIXME: sh_type value not supported!");
1431 break;
1432 }
1433
Logan Chien4b724422013-02-05 14:18:59 +00001434 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1435 Section.getType() == ELF::SHT_ARM_EXIDX) {
1436 StringRef SecName(Section.getSectionName());
1437 if (SecName == ".ARM.exidx") {
1438 sh_link = SectionIndexMap.lookup(
1439 Asm.getContext().getELFSection(".text",
1440 ELF::SHT_PROGBITS,
1441 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1442 SectionKind::getText()));
1443 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001444 StringRef GroupName =
1445 Section.getGroup() ? Section.getGroup()->getName() : "";
1446 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1447 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1448 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1449 GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001450 }
1451 }
1452
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001453 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1454 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1455 Alignment, Section.getEntrySize());
1456}
1457
Jan Sjödin30a52de2011-02-28 21:45:04 +00001458bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001459 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001460 !SD.getSection().isVirtualSection();
1461}
1462
Jan Sjödin30a52de2011-02-28 21:45:04 +00001463uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001464 uint64_t Ret = 0;
1465 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1466 ++i) {
1467 const MCFragment &F = *i;
1468 assert(F.getKind() == MCFragment::FT_Data);
1469 Ret += cast<MCDataFragment>(F).getContents().size();
1470 }
1471 return Ret;
1472}
1473
Jan Sjödin30a52de2011-02-28 21:45:04 +00001474uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1475 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001476 if (IsELFMetaDataSection(SD))
1477 return DataSectionSize(SD);
1478 return Layout.getSectionFileSize(&SD);
1479}
1480
Jan Sjödin30a52de2011-02-28 21:45:04 +00001481uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1482 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001483 if (IsELFMetaDataSection(SD))
1484 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001485 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001486}
1487
Rafael Espindola1557fd62011-03-20 18:44:20 +00001488void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1489 const MCAsmLayout &Layout,
1490 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001491 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1492
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001493 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001494 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001495
1496 if (IsELFMetaDataSection(SD)) {
1497 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1498 ++i) {
1499 const MCFragment &F = *i;
1500 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001501 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001502 }
1503 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001504 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001505 }
1506}
1507
Rafael Espindola1557fd62011-03-20 18:44:20 +00001508void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1509 const GroupMapTy &GroupMap,
1510 const MCAsmLayout &Layout,
1511 const SectionIndexMapTy &SectionIndexMap,
1512 const SectionOffsetMapTy &SectionOffsetMap) {
1513 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001514
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001515 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001516 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001517
1518 for (SectionIndexMapTy::const_iterator i=
1519 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1520 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001521 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001522 }
1523
Matt Fleming6c1ad482010-08-16 18:57:57 +00001524 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001525 uint64_t FirstSectionSize =
1526 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1527 uint32_t FirstSectionLink =
1528 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1529 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001530
Rafael Espindola1557fd62011-03-20 18:44:20 +00001531 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001532 const MCSectionELF &Section = *Sections[i];
1533 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1534 uint32_t GroupSymbolIndex;
1535 if (Section.getType() != ELF::SHT_GROUP)
1536 GroupSymbolIndex = 0;
1537 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001538 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1539 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001540
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001541 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001542
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001543 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001544 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001545 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001546 }
1547}
1548
Rafael Espindola1557fd62011-03-20 18:44:20 +00001549void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1550 std::vector<const MCSectionELF*> &Sections) {
1551 for (MCAssembler::iterator it = Asm.begin(),
1552 ie = Asm.end(); it != ie; ++it) {
1553 const MCSectionELF &Section =
1554 static_cast<const MCSectionELF &>(it->getSection());
1555 if (Section.getType() == ELF::SHT_GROUP)
1556 Sections.push_back(&Section);
1557 }
1558
1559 for (MCAssembler::iterator it = Asm.begin(),
1560 ie = Asm.end(); it != ie; ++it) {
1561 const MCSectionELF &Section =
1562 static_cast<const MCSectionELF &>(it->getSection());
1563 if (Section.getType() != ELF::SHT_GROUP &&
1564 Section.getType() != ELF::SHT_REL &&
1565 Section.getType() != ELF::SHT_RELA)
1566 Sections.push_back(&Section);
1567 }
1568
1569 for (MCAssembler::iterator it = Asm.begin(),
1570 ie = Asm.end(); it != ie; ++it) {
1571 const MCSectionELF &Section =
1572 static_cast<const MCSectionELF &>(it->getSection());
1573 if (Section.getType() == ELF::SHT_REL ||
1574 Section.getType() == ELF::SHT_RELA)
1575 Sections.push_back(&Section);
1576 }
1577}
1578
1579void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1580 const MCAsmLayout &Layout) {
1581 GroupMapTy GroupMap;
1582 RevGroupMapTy RevGroupMap;
1583 SectionIndexMapTy SectionIndexMap;
1584
1585 unsigned NumUserSections = Asm.size();
1586
1587 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1588 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1589
1590 const unsigned NumUserAndRelocSections = Asm.size();
1591 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1592 RevGroupMap, SectionIndexMap, RelMap);
1593 const unsigned AllSections = Asm.size();
1594 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1595
1596 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1597
1598 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001599 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1600 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001601
1602 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1603
1604 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1605 const_cast<MCAsmLayout&>(Layout),
1606 SectionIndexMap,
1607 RelMap);
1608
1609 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1610 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1611 sizeof(ELF::Elf32_Ehdr);
1612 uint64_t FileOff = HeaderSize;
1613
1614 std::vector<const MCSectionELF*> Sections;
1615 ComputeSectionOrder(Asm, Sections);
1616 unsigned NumSections = Sections.size();
1617 SectionOffsetMapTy SectionOffsetMap;
1618 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1619 const MCSectionELF &Section = *Sections[i];
1620 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1621
1622 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1623
1624 // Remember the offset into the file for this section.
1625 SectionOffsetMap[&Section] = FileOff;
1626
1627 // Get the size of the section in the output file (including padding).
1628 FileOff += GetSectionFileSize(Layout, SD);
1629 }
1630
1631 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1632
1633 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1634
1635 uint64_t SectionHeaderEntrySize = is64Bit() ?
1636 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1637 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1638
1639 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1640 const MCSectionELF &Section = *Sections[i];
1641 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1642
1643 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1644
1645 // Remember the offset into the file for this section.
1646 SectionOffsetMap[&Section] = FileOff;
1647
1648 // Get the size of the section in the output file (including padding).
1649 FileOff += GetSectionFileSize(Layout, SD);
1650 }
1651
1652 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001653 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001654
1655 // ... then the regular sections ...
1656 // + because of .shstrtab
1657 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1658 WriteDataSectionData(Asm, Layout, *Sections[i]);
1659
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001660 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001661 WriteZeros(Padding);
1662
1663 // ... then the section header table ...
1664 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1665 SectionOffsetMap);
1666
Nick Lewycky4eb11432011-10-07 20:56:23 +00001667 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001668 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1669 WriteDataSectionData(Asm, Layout, *Sections[i]);
1670}
1671
Eli Friedmand92d17b2011-03-03 07:24:36 +00001672bool
1673ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1674 const MCSymbolData &DataA,
1675 const MCFragment &FB,
1676 bool InSet,
1677 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001678 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001679 return false;
1680 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1681 Asm, DataA, FB,InSet, IsPCRel);
1682}
1683
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001684MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1685 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001686 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001687 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001688}