blob: 4ebfc4de557ec0beeccf0714a0c0d7a6406bc424 [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,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000182 bool IsPCRel) const {
183 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000184 }
185
Rafael Espindola29abd972011-12-22 03:38:00 +0000186 public:
Rafael Espindola0ce09712014-03-25 22:43:53 +0000187 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
188 bool IsLittleEndian)
189 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000190 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000191
192 virtual ~ELFObjectWriter();
193
194 void WriteWord(uint64_t W) {
195 if (is64Bit())
196 Write64(W);
197 else
198 Write32(W);
199 }
200
Rafael Espindola0ce09712014-03-25 22:43:53 +0000201 template <typename T> void write(MCDataFragment &F, T Value) {
202 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000203 }
204
Jack Carter1bd90ff2013-01-30 02:09:52 +0000205 void WriteHeader(const MCAssembler &Asm,
206 uint64_t SectionDataSize,
Rafael Espindola29abd972011-12-22 03:38:00 +0000207 unsigned NumberOfSections);
208
Rafael Espindola10be0832014-03-25 23:44:25 +0000209 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000210 const MCAsmLayout &Layout);
211
Rafael Espindola10be0832014-03-25 23:44:25 +0000212 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000213 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000214 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000215
Craig Topper34a61bc2014-03-08 07:02:02 +0000216 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
217 const MCFragment *Fragment, const MCFixup &Fixup,
218 MCValue Target, uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000219
220 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
221 const MCSymbol *S);
222
223 // Map from a group section to the signature symbol
224 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
225 // Map from a signature symbol to the group section
226 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
227 // Map from a section to the section with the relocations
228 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
229 // Map from a section to its offset
230 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
231
Rafael Espindola022bb762014-03-24 03:43:21 +0000232 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000233 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000234 /// \param Asm - The assembler.
235 /// \param SectionIndexMap - Maps a section to its index.
236 /// \param RevGroupMap - Maps a signature symbol to the group section.
237 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000238 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000239 const SectionIndexMapTy &SectionIndexMap,
240 RevGroupMapTy RevGroupMap,
241 unsigned NumRegularSections);
242
243 void ComputeIndexMap(MCAssembler &Asm,
244 SectionIndexMapTy &SectionIndexMap,
245 const RelMapTy &RelMap);
246
247 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
248 RelMapTy &RelMap);
249
250 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
251 const RelMapTy &RelMap);
252
253 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
254 SectionIndexMapTy &SectionIndexMap,
255 const RelMapTy &RelMap);
256
257 // Create the sections that show up in the symbol table. Currently
258 // those are the .note.GNU-stack section and the group sections.
259 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
260 GroupMapTy &GroupMap,
261 RevGroupMapTy &RevGroupMap,
262 SectionIndexMapTy &SectionIndexMap,
263 const RelMapTy &RelMap);
264
Craig Topper34a61bc2014-03-08 07:02:02 +0000265 void ExecutePostLayoutBinding(MCAssembler &Asm,
266 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000267
268 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
269 const MCAsmLayout &Layout,
270 const SectionIndexMapTy &SectionIndexMap,
271 const SectionOffsetMapTy &SectionOffsetMap);
272
273 void ComputeSectionOrder(MCAssembler &Asm,
274 std::vector<const MCSectionELF*> &Sections);
275
276 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
277 uint64_t Address, uint64_t Offset,
278 uint64_t Size, uint32_t Link, uint32_t Info,
279 uint64_t Alignment, uint64_t EntrySize);
280
281 void WriteRelocationsFragment(const MCAssembler &Asm,
282 MCDataFragment *F,
283 const MCSectionData *SD);
284
Craig Topper34a61bc2014-03-08 07:02:02 +0000285 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000286 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
287 const MCSymbolData &DataA,
288 const MCFragment &FB,
289 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000290 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000291
Craig Topper34a61bc2014-03-08 07:02:02 +0000292 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000293 void WriteSection(MCAssembler &Asm,
294 const SectionIndexMapTy &SectionIndexMap,
295 uint32_t GroupSymbolIndex,
296 uint64_t Offset, uint64_t Size, uint64_t Alignment,
297 const MCSectionELF &Section);
298 };
299}
300
Rafael Espindola0ce09712014-03-25 22:43:53 +0000301FragmentWriter::FragmentWriter(bool IsLittleEndian)
302 : IsLittleEndian(IsLittleEndian) {}
303
304template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
305 if (IsLittleEndian)
306 Val = support::endian::byte_swap<T, support::little>(Val);
307 else
308 Val = support::endian::byte_swap<T, support::big>(Val);
309 const char *Start = (const char *)&Val;
310 F.getContents().append(Start, Start + sizeof(T));
311}
312
Rafael Espindola10be0832014-03-25 23:44:25 +0000313void SymbolTableWriter::createSymtabShndx() {
314 if (ShndxF)
315 return;
316
317 MCContext &Ctx = Asm.getContext();
318 const MCSectionELF *SymtabShndxSection =
319 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
320 SectionKind::getReadOnly(), 4, "");
321 MCSectionData *SymtabShndxSD =
322 &Asm.getOrCreateSectionData(*SymtabShndxSection);
323 SymtabShndxSD->setAlignment(4);
324 ShndxF = new MCDataFragment(SymtabShndxSD);
325 unsigned Index = SectionIndexMap.size() + 1;
326 SectionIndexMap[SymtabShndxSection] = Index;
327
328 for (unsigned I = 0; I < NumWritten; ++I)
329 write(*ShndxF, uint32_t(0));
330}
331
332template <typename T>
333void SymbolTableWriter::write(MCDataFragment &F, T Value) {
334 FWriter.write(F, Value);
335}
336
337SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
338 bool Is64Bit,
339 SectionIndexMapTy &SectionIndexMap,
340 MCDataFragment *SymtabF)
341 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
342 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
343 NumWritten(0) {}
344
345void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
346 uint64_t size, uint8_t other,
347 uint32_t shndx, bool Reserved) {
348 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
349
350 if (LargeIndex)
351 createSymtabShndx();
352
353 if (ShndxF) {
354 if (LargeIndex)
355 write(*ShndxF, shndx);
356 else
357 write(*ShndxF, uint32_t(0));
358 }
359
360 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
361
362 raw_svector_ostream OS(SymtabF->getContents());
363
364 if (Is64Bit) {
365 write(*SymtabF, name); // st_name
366 write(*SymtabF, info); // st_info
367 write(*SymtabF, other); // st_other
368 write(*SymtabF, Index); // st_shndx
369 write(*SymtabF, value); // st_value
370 write(*SymtabF, size); // st_size
371 } else {
372 write(*SymtabF, name); // st_name
373 write(*SymtabF, uint32_t(value)); // st_value
374 write(*SymtabF, uint32_t(size)); // st_size
375 write(*SymtabF, info); // st_info
376 write(*SymtabF, other); // st_other
377 write(*SymtabF, Index); // st_shndx
378 }
379
380 ++NumWritten;
381}
382
Jan Sjödin30a52de2011-02-28 21:45:04 +0000383bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
384 const MCFixupKindInfo &FKI =
385 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
386
387 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
388}
389
390bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
391 switch (Variant) {
392 default:
393 return false;
394 case MCSymbolRefExpr::VK_GOT:
395 case MCSymbolRefExpr::VK_PLT:
396 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000397 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000398 case MCSymbolRefExpr::VK_TPOFF:
399 case MCSymbolRefExpr::VK_TLSGD:
400 case MCSymbolRefExpr::VK_GOTTPOFF:
401 case MCSymbolRefExpr::VK_INDNTPOFF:
402 case MCSymbolRefExpr::VK_NTPOFF:
403 case MCSymbolRefExpr::VK_GOTNTPOFF:
404 case MCSymbolRefExpr::VK_TLSLDM:
405 case MCSymbolRefExpr::VK_DTPOFF:
406 case MCSymbolRefExpr::VK_TLSLD:
407 return true;
408 }
409}
410
Jason W Kim96f4c012010-11-15 16:18:39 +0000411ELFObjectWriter::~ELFObjectWriter()
412{}
413
Matt Fleming6c1ad482010-08-16 18:57:57 +0000414// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000415void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
416 uint64_t SectionDataSize,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000417 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000418 // ELF Header
419 // ----------
420 //
421 // Note
422 // ----
423 // emitWord method behaves differently for ELF32 and ELF64, writing
424 // 4 bytes in the former and 8 in the latter.
425
426 Write8(0x7f); // e_ident[EI_MAG0]
427 Write8('E'); // e_ident[EI_MAG1]
428 Write8('L'); // e_ident[EI_MAG2]
429 Write8('F'); // e_ident[EI_MAG3]
430
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000431 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000432
433 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000434 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000435
436 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000437 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000438 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000439 Write8(0); // e_ident[EI_ABIVERSION]
440
441 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
442
443 Write16(ELF::ET_REL); // e_type
444
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000445 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000446
447 Write32(ELF::EV_CURRENT); // e_version
448 WriteWord(0); // e_entry, no entry point in .o file
449 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000450 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramer896bd7e2010-08-17 17:02:29 +0000451 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000452
Jason W Kim4761fba2011-02-04 21:41:11 +0000453 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000454 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000455
456 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000457 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000458
459 Write16(0); // e_phentsize = prog header entry size
460 Write16(0); // e_phnum = # prog header entries = 0
461
462 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000463 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000464
465 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000466 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000467 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000468 else
469 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000470
471 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000472 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000473 Write16(ELF::SHN_XINDEX);
474 else
475 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000476}
477
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000478uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000479 const MCAsmLayout &Layout) {
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000480 MCSymbolData *Data = &OrigData;
481 if (Data->isCommon() && Data->isExternal())
482 return Data->getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000483
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000484 const MCSymbol *Symbol = &Data->getSymbol();
485 bool IsThumbFunc = OrigData.getFlags() & ELF_Other_ThumbFunc;
Roman Divacky55184dd2010-12-20 21:14:39 +0000486
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000487 uint64_t Res = 0;
488 if (Symbol->isVariable()) {
489 const MCExpr *Expr = Symbol->getVariableValue();
490 MCValue Value;
491 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
492 llvm_unreachable("Invalid expression");
493
494 assert(!Value.getSymB());
495
496 Res = Value.getConstant();
497
498 if (const MCSymbolRefExpr *A = Value.getSymA()) {
499 Symbol = &A->getSymbol();
500 Data = &Layout.getAssembler().getSymbolData(*Symbol);
501 } else {
502 Symbol = 0;
503 Data = 0;
Rafael Espindola7bbd5c22014-03-19 00:13:43 +0000504 }
Roman Divacky55184dd2010-12-20 21:14:39 +0000505 }
506
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000507 if (IsThumbFunc)
508 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000509
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000510 if (!Symbol || !Symbol->isInSection())
511 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000512
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000513 Res += Layout.getSymbolOffset(Data);
514
515 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000516}
517
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000518void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
519 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000520 // The presence of symbol versions causes undefined symbols and
521 // versions declared with @@@ to be renamed.
522
523 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
524 ie = Asm.symbol_end(); it != ie; ++it) {
525 const MCSymbol &Alias = it->getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000526 const MCSymbol &Symbol = Alias.AliasedSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000527 MCSymbolData &SD = Asm.getSymbolData(Symbol);
528
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000529 // Not an alias.
530 if (&Symbol == &Alias)
531 continue;
532
Benjamin Kramer14807272010-10-27 19:53:52 +0000533 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000534 size_t Pos = AliasName.find('@');
535 if (Pos == StringRef::npos)
536 continue;
537
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000538 // Aliases defined with .symvar copy the binding from the symbol they alias.
539 // This is the first place we are able to copy this information.
540 it->setExternal(SD.isExternal());
Jan Sjödin30a52de2011-02-28 21:45:04 +0000541 MCELF::SetBinding(*it, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000542
Benjamin Kramer14807272010-10-27 19:53:52 +0000543 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000544 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
545 continue;
546
Rafael Espindola26496e62010-10-27 17:56:18 +0000547 // FIXME: produce a better error message.
548 if (Symbol.isUndefined() && Rest.startswith("@@") &&
549 !Rest.startswith("@@@"))
550 report_fatal_error("A @@ version cannot be undefined");
551
Benjamin Kramer14807272010-10-27 19:53:52 +0000552 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000553 }
554}
555
Roman Divacky5a1c5492014-01-07 20:17:03 +0000556static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
557 uint8_t Type = newType;
558
559 // Propagation rules:
560 // IFUNC > FUNC > OBJECT > NOTYPE
561 // TLS_OBJECT > OBJECT > NOTYPE
562 //
563 // dont let the new type degrade the old type
564 switch (origType) {
565 default:
566 break;
567 case ELF::STT_GNU_IFUNC:
568 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
569 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
570 Type = ELF::STT_GNU_IFUNC;
571 break;
572 case ELF::STT_FUNC:
573 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
574 Type == ELF::STT_TLS)
575 Type = ELF::STT_FUNC;
576 break;
577 case ELF::STT_OBJECT:
578 if (Type == ELF::STT_NOTYPE)
579 Type = ELF::STT_OBJECT;
580 break;
581 case ELF::STT_TLS:
582 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
583 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
584 Type = ELF::STT_TLS;
585 break;
586 }
587
588 return Type;
589}
590
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000591static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
592 const MCSymbol &Symbol) {
593 if (!Symbol.isVariable())
594 return &Symbol;
595
596 const MCExpr *Expr = Symbol.getVariableValue();
597 MCValue Value;
598 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
599 llvm_unreachable("Invalid Expression");
600 assert(!Value.getSymB());
601 const MCSymbolRefExpr *A = Value.getSymA();
602 if (!A)
603 return nullptr;
604 return getBaseSymbol(Layout, A->getSymbol());
605}
606
Rafael Espindola10be0832014-03-25 23:44:25 +0000607void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000608 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000609 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindola85a84912014-03-26 00:16:43 +0000610 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
611
612 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
613 // SHN_COMMON.
614 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000615
Jack Carter2f8d9d92013-02-19 21:57:35 +0000616 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000617 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000618 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000619 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000620 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000621 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
622 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000623 }
Saleem Abdulrasool39f773f2014-03-20 06:05:33 +0000624 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
625 Type = ELF::STT_FUNC;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000626 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000627
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000628 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000629 // 2 bits
630 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000631 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000632 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000633
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000634 uint64_t Value = SymbolValue(OrigData, Layout);
Saleem Abdulrasool39f773f2014-03-20 06:05:33 +0000635 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
636 Value |= 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000637 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000638
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000639 const MCExpr *ESize = OrigData.getSize();
640 if (!ESize && Base)
641 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000642
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000643 if (ESize) {
644 int64_t Res;
645 if (!ESize->EvaluateAsAbsolute(Res, Layout))
646 report_fatal_error("Size expression must be absolute.");
647 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000648 }
649
650 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000651 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
652 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000653}
654
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000655void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000656 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000657 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000658 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000659 // The string table must be emitted first because we need the index
660 // into the string table for all the symbol names.
661 assert(StringTable.size() && "Missing string table");
662
663 // FIXME: Make sure the start of the symbol table is aligned.
664
Rafael Espindola10be0832014-03-25 23:44:25 +0000665 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
666
Matt Fleming6c1ad482010-08-16 18:57:57 +0000667 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000668 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000669
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000670 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000671 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
672 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000673 }
674
Matt Fleming6c1ad482010-08-16 18:57:57 +0000675 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000676 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
677
Matt Fleming6c1ad482010-08-16 18:57:57 +0000678 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
679 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000680 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000681 }
682
Rafael Espindola44bf2662010-09-16 19:46:31 +0000683 // Write out a symbol table entry for each regular section.
Rafael Espindola18014102010-11-10 22:16:43 +0000684 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
685 ++i) {
Eli Friedman1fe0d532010-08-16 21:17:09 +0000686 const MCSectionELF &Section =
Rafael Espindola18014102010-11-10 22:16:43 +0000687 static_cast<const MCSectionELF&>(i->getSection());
688 if (Section.getType() == ELF::SHT_RELA ||
689 Section.getType() == ELF::SHT_REL ||
690 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewycky133a1682011-10-07 23:29:53 +0000691 Section.getType() == ELF::SHT_SYMTAB ||
692 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedman1fe0d532010-08-16 21:17:09 +0000693 continue;
Rafael Espindola10be0832014-03-25 23:44:25 +0000694 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
695 SectionIndexMap.lookup(&Section), false);
Eli Friedman1fe0d532010-08-16 21:17:09 +0000696 LastLocalSymbolIndex++;
697 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000698
699 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
700 ELFSymbolData &MSD = ExternalSymbolData[i];
701 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000702 assert(((Data.getFlags() & ELF_STB_Global) ||
703 (Data.getFlags() & ELF_STB_Weak)) &&
704 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000705 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000706 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000707 LastLocalSymbolIndex++;
708 }
709
710 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
711 ELFSymbolData &MSD = UndefinedSymbolData[i];
712 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000713 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000714 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000715 LastLocalSymbolIndex++;
716 }
717}
718
Rafael Espindola240028d2010-11-14 23:53:26 +0000719const MCSymbol *ELFObjectWriter::SymbolToReloc(const MCAssembler &Asm,
720 const MCValue &Target,
Jim Grosbachdc1e36e2012-05-11 01:41:30 +0000721 const MCFragment &F,
Jason W Kimc09e7262011-05-11 22:53:06 +0000722 const MCFixup &Fixup,
723 bool IsPCRel) const {
Rafael Espindola240028d2010-11-14 23:53:26 +0000724 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000725 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
726 const MCSymbol *Renamed = Renames.lookup(&Symbol);
727 const MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola240028d2010-11-14 23:53:26 +0000728
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000729 if (ASymbol.isUndefined()) {
730 if (Renamed)
731 return Renamed;
Adhemerval Zanellaf2aceda2012-10-25 12:27:42 +0000732 return undefinedExplicitRelSym(Target, Fixup, IsPCRel);
Rafael Espindola240028d2010-11-14 23:53:26 +0000733 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000734
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000735 if (SD.isExternal()) {
736 if (Renamed)
737 return Renamed;
738 return &Symbol;
739 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000740
Rafael Espindolaf987d5e2010-09-30 20:18:35 +0000741 const MCSectionELF &Section =
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000742 static_cast<const MCSectionELF&>(ASymbol.getSection());
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000743 const SectionKind secKind = Section.getKind();
Rafael Espindolaf987d5e2010-09-30 20:18:35 +0000744
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000745 if (secKind.isBSS())
Jason W Kimc09e7262011-05-11 22:53:06 +0000746 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindolaf987d5e2010-09-30 20:18:35 +0000747
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000748 if (secKind.isThreadLocal()) {
749 if (Renamed)
750 return Renamed;
751 return &Symbol;
752 }
753
Rafael Espindola8f3d2c92010-10-06 16:23:36 +0000754 MCSymbolRefExpr::VariantKind Kind = Target.getSymA()->getKind();
Rafael Espindolad7565c32010-10-05 23:57:26 +0000755 const MCSectionELF &Sec2 =
756 static_cast<const MCSectionELF&>(F.getParent()->getSection());
757
Rafael Espindola8f3d2c92010-10-06 16:23:36 +0000758 if (&Sec2 != &Section &&
Rafael Espindola4464e082010-10-18 16:38:04 +0000759 (Kind == MCSymbolRefExpr::VK_PLT ||
760 Kind == MCSymbolRefExpr::VK_GOTPCREL ||
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000761 Kind == MCSymbolRefExpr::VK_GOTOFF)) {
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000762 if (Renamed)
763 return Renamed;
764 return &Symbol;
765 }
Rafael Espindolad7565c32010-10-05 23:57:26 +0000766
Rafael Espindola0e7e34e2011-01-23 04:43:11 +0000767 if (Section.getFlags() & ELF::SHF_MERGE) {
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000768 if (Target.getConstant() == 0)
Jason W Kimc09e7262011-05-11 22:53:06 +0000769 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000770 if (Renamed)
771 return Renamed;
772 return &Symbol;
Rafael Espindola240028d2010-11-14 23:53:26 +0000773 }
Rafael Espindola4464e082010-10-18 16:38:04 +0000774
Jason W Kimc09e7262011-05-11 22:53:06 +0000775 return ExplicitRelSym(Asm, Target, F, Fixup, IsPCRel);
776
Rafael Espindola75d65b92010-09-25 05:42:19 +0000777}
778
Matt Fleming6c1ad482010-08-16 18:57:57 +0000779
Jason W Kim495c2bb2010-12-06 21:57:34 +0000780void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
781 const MCAsmLayout &Layout,
782 const MCFragment *Fragment,
783 const MCFixup &Fixup,
784 MCValue Target,
785 uint64_t &FixedValue) {
786 int64_t Addend = 0;
787 int Index = 0;
788 int64_t Value = Target.getConstant();
789 const MCSymbol *RelocSymbol = NULL;
790
Rafael Espindoladf633352010-12-17 07:28:17 +0000791 bool IsPCRel = isFixupKindPCRel(Asm, Fixup.getKind());
Jason W Kim495c2bb2010-12-06 21:57:34 +0000792 if (!Target.isAbsolute()) {
793 const MCSymbol &Symbol = Target.getSymA()->getSymbol();
794 const MCSymbol &ASymbol = Symbol.AliasedSymbol();
Jason W Kimc09e7262011-05-11 22:53:06 +0000795 RelocSymbol = SymbolToReloc(Asm, Target, *Fragment, Fixup, IsPCRel);
Jason W Kim495c2bb2010-12-06 21:57:34 +0000796
797 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
798 const MCSymbol &SymbolB = RefB->getSymbol();
799 MCSymbolData &SDB = Asm.getSymbolData(SymbolB);
800 IsPCRel = true;
801
David Majnemera45a1762014-01-06 07:39:46 +0000802 if (!SDB.getFragment())
803 Asm.getContext().FatalError(
804 Fixup.getLoc(),
805 Twine("symbol '") + SymbolB.getName() +
806 "' can not be undefined in a subtraction expression");
807
Jason W Kim495c2bb2010-12-06 21:57:34 +0000808 // Offset of the symbol in the section
809 int64_t a = Layout.getSymbolOffset(&SDB);
810
Bruno Cardoso Lopesc9473e92011-11-04 22:24:36 +0000811 // Offset of the relocation in the section
Jason W Kim495c2bb2010-12-06 21:57:34 +0000812 int64_t b = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
813 Value += b - a;
814 }
815
816 if (!RelocSymbol) {
817 MCSymbolData &SD = Asm.getSymbolData(ASymbol);
818 MCFragment *F = SD.getFragment();
819
Adhemerval Zanellaf2aceda2012-10-25 12:27:42 +0000820 if (F) {
821 Index = F->getParent()->getOrdinal() + 1;
822 // Offset of the symbol in the section
823 Value += Layout.getSymbolOffset(&SD);
824 } else {
825 Index = 0;
826 }
Jason W Kim495c2bb2010-12-06 21:57:34 +0000827 } else {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000828 if (Target.getSymA()->getKind() == MCSymbolRefExpr::VK_WEAKREF)
Jason W Kim495c2bb2010-12-06 21:57:34 +0000829 WeakrefUsedInReloc.insert(RelocSymbol);
830 else
831 UsedInReloc.insert(RelocSymbol);
832 Index = -1;
833 }
834 Addend = Value;
Michael Liaod6f31682012-10-16 19:49:51 +0000835 if (hasRelocationAddend())
Jason W Kim495c2bb2010-12-06 21:57:34 +0000836 Value = 0;
837 }
838
839 FixedValue = Value;
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000840 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000841 MCSymbolRefExpr::VariantKind Modifier = Target.isAbsolute() ?
842 MCSymbolRefExpr::VK_None : Target.getSymA()->getKind();
843 if (RelocNeedsGOT(Modifier))
844 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000845
Jason W Kim495c2bb2010-12-06 21:57:34 +0000846 uint64_t RelocOffset = Layout.getFragmentOffset(Fragment) +
847 Fixup.getOffset();
Roman Divackydfbecd12011-08-04 19:08:19 +0000848
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000849 if (!hasRelocationAddend())
850 Addend = 0;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000851
852 if (is64Bit())
853 assert(isInt<64>(Addend));
854 else
855 assert(isInt<32>(Addend));
856
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +0000857 ELFRelocationEntry ERE(RelocOffset, Index, Type, RelocSymbol, Addend, Fixup);
Jason W Kim495c2bb2010-12-06 21:57:34 +0000858 Relocations[Fragment->getParent()].push_back(ERE);
859}
860
861
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000862uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000863ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
864 const MCSymbol *S) {
Benjamin Kramer37b384c2010-08-25 20:09:43 +0000865 MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000866 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000867}
868
Jan Sjödin30a52de2011-02-28 21:45:04 +0000869bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
870 const MCSymbolData &Data,
871 bool Used, bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000872 const MCSymbol &Symbol = Data.getSymbol();
873 if (Symbol.isVariable()) {
874 const MCExpr *Expr = Symbol.getVariableValue();
875 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
876 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
877 return false;
878 }
879 }
Rafael Espindola16145972010-11-01 14:28:48 +0000880
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000881 if (Used)
882 return true;
883
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000884 if (Renamed)
885 return false;
886
Rafael Espindola45834a02010-10-29 23:09:31 +0000887 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
888 return true;
889
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000890 const MCSymbol &A = Symbol.AliasedSymbol();
Rafael Espindola9e18e962011-02-23 20:22:07 +0000891 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
892 return false;
893
Jan Sjödin30a52de2011-02-28 21:45:04 +0000894 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000895 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000896 return false;
897
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000898 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000899 return false;
900
901 return true;
902}
903
Jan Sjödin30a52de2011-02-28 21:45:04 +0000904bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
905 bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000906 if (Data.isExternal())
907 return false;
908
909 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000910 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000911
912 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
913 if (isSignature && !isUsedInReloc)
914 return true;
915
Rafael Espindolab1d07892010-10-05 18:01:23 +0000916 return false;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000917 }
Rafael Espindolab1d07892010-10-05 18:01:23 +0000918
919 return true;
920}
921
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000922void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000923 SectionIndexMapTy &SectionIndexMap,
924 const RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000925 unsigned Index = 1;
926 for (MCAssembler::iterator it = Asm.begin(),
927 ie = Asm.end(); it != ie; ++it) {
928 const MCSectionELF &Section =
929 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000930 if (Section.getType() != ELF::SHT_GROUP)
931 continue;
932 SectionIndexMap[&Section] = Index++;
933 }
934
935 for (MCAssembler::iterator it = Asm.begin(),
936 ie = Asm.end(); it != ie; ++it) {
937 const MCSectionELF &Section =
938 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000939 if (Section.getType() == ELF::SHT_GROUP ||
940 Section.getType() == ELF::SHT_REL ||
941 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000942 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000943 SectionIndexMap[&Section] = Index++;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000944 const MCSectionELF *RelSection = RelMap.lookup(&Section);
945 if (RelSection)
946 SectionIndexMap[RelSection] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +0000947 }
948}
949
Rafael Espindola022bb762014-03-24 03:43:21 +0000950void
951ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
952 const SectionIndexMapTy &SectionIndexMap,
953 RevGroupMapTy RevGroupMap,
954 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000955 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000956 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000957 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000958 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000959 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
960 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
961 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000962 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000963 }
964
Matt Fleming6c1ad482010-08-16 18:57:57 +0000965 // Index 0 is always the empty string.
966 StringMap<uint64_t> StringIndexMap;
967 StringTable += '\x00';
968
Rafael Espindolab80875e2011-04-07 23:21:52 +0000969 // FIXME: We could optimize suffixes in strtab in the same way we
970 // optimize them in shstrtab.
971
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000972 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
973 ie = Asm.file_names_end();
974 it != ie;
975 ++it) {
976 StringRef Name = *it;
977 uint64_t &Entry = StringIndexMap[Name];
978 if (!Entry) {
979 Entry = StringTable.size();
980 StringTable += Name;
981 StringTable += '\x00';
982 }
983 FileSymbolData.push_back(Entry);
984 }
985
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000986 // Add the data for the symbols.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000987 for (MCAssembler::symbol_iterator it = Asm.symbol_begin(),
988 ie = Asm.symbol_end(); it != ie; ++it) {
989 const MCSymbol &Symbol = it->getSymbol();
990
Rafael Espindola16145972010-11-01 14:28:48 +0000991 bool Used = UsedInReloc.count(&Symbol);
992 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000993 bool isSignature = RevGroupMap.count(&Symbol);
994
995 if (!isInSymtab(Asm, *it,
996 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000997 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +0000998 continue;
999
Matt Fleming6c1ad482010-08-16 18:57:57 +00001000 ELFSymbolData MSD;
1001 MSD.SymbolData = it;
Rafael Espindola022bb762014-03-24 03:43:21 +00001002 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001003
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001004 // Undefined symbols are global, but this is the first place we
1005 // are able to set it.
1006 bool Local = isLocal(*it, isSignature, Used);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001007 if (!Local && MCELF::GetBinding(*it) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001008 assert(BaseSymbol);
1009 MCSymbolData &SD = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001010 MCELF::SetBinding(*it, ELF::STB_GLOBAL);
1011 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001012 }
1013
Rafael Espindola022bb762014-03-24 03:43:21 +00001014 if (!BaseSymbol) {
1015 MSD.SectionIndex = ELF::SHN_ABS;
1016 } else if (it->isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001017 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001018 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001019 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001020 if (isSignature && !Used)
1021 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1022 else
1023 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001024 if (!Used && WeakrefUsed)
1025 MCELF::SetBinding(*it, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001026 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001027 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001028 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001029 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001030 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001031 }
1032
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001033 // The @@@ in symbol version is replaced with @ in undefined symbols and
1034 // @@ in defined ones.
1035 StringRef Name = Symbol.getName();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001036 SmallString<32> Buf;
1037
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001038 size_t Pos = Name.find("@@@");
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001039 if (Pos != StringRef::npos) {
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001040 Buf += Name.substr(0, Pos);
1041 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1042 Buf += Name.substr(Pos + Skip);
1043 Name = Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001044 }
1045
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001046 uint64_t &Entry = StringIndexMap[Name];
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001047 if (!Entry) {
1048 Entry = StringTable.size();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001049 StringTable += Name;
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001050 StringTable += '\x00';
Matt Fleming6c1ad482010-08-16 18:57:57 +00001051 }
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001052 MSD.StringIndex = Entry;
1053 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1054 UndefinedSymbolData.push_back(MSD);
1055 else if (Local)
1056 LocalSymbolData.push_back(MSD);
1057 else
1058 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001059 }
1060
1061 // Symbols are required to be in lexicographic order.
1062 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1063 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1064 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1065
1066 // Set the symbol indices. Local symbols must come before all other
1067 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001068 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001069 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1070 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001071
1072 Index += NumRegularSections;
1073
Matt Fleming6c1ad482010-08-16 18:57:57 +00001074 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1075 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1076 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1077 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1078}
1079
Rafael Espindola1557fd62011-03-20 18:44:20 +00001080void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1081 MCAsmLayout &Layout,
1082 RelMapTy &RelMap) {
1083 for (MCAssembler::const_iterator it = Asm.begin(),
1084 ie = Asm.end(); it != ie; ++it) {
1085 const MCSectionData &SD = *it;
1086 if (Relocations[&SD].empty())
1087 continue;
1088
Matt Fleming6c1ad482010-08-16 18:57:57 +00001089 MCContext &Ctx = Asm.getContext();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001090 const MCSectionELF &Section =
1091 static_cast<const MCSectionELF&>(SD.getSection());
1092
1093 const StringRef SectionName = Section.getSectionName();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001094 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming6c1ad482010-08-16 18:57:57 +00001095 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001096
1097 unsigned EntrySize;
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001098 if (hasRelocationAddend())
1099 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramerfd054152010-08-17 17:56:13 +00001100 else
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001101 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001102
Tim Northovera630fb02013-07-10 20:58:17 +00001103 unsigned Flags = 0;
1104 StringRef Group = "";
1105 if (Section.getFlags() & ELF::SHF_GROUP) {
David Blaikie1e412ea2013-10-22 20:34:30 +00001106 Flags = ELF::SHF_GROUP;
1107 Group = Section.getGroup()->getName();
Tim Northovera630fb02013-07-10 20:58:17 +00001108 }
1109
Rafael Espindola1557fd62011-03-20 18:44:20 +00001110 const MCSectionELF *RelaSection =
1111 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
Tim Northovera630fb02013-07-10 20:58:17 +00001112 ELF::SHT_RELA : ELF::SHT_REL, Flags,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001113 SectionKind::getReadOnly(),
Tim Northovera630fb02013-07-10 20:58:17 +00001114 EntrySize, Group);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001115 RelMap[&Section] = RelaSection;
1116 Asm.getOrCreateSectionData(*RelaSection);
1117 }
1118}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001119
Rafael Espindola1557fd62011-03-20 18:44:20 +00001120void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1121 const RelMapTy &RelMap) {
1122 for (MCAssembler::const_iterator it = Asm.begin(),
1123 ie = Asm.end(); it != ie; ++it) {
1124 const MCSectionData &SD = *it;
1125 const MCSectionELF &Section =
1126 static_cast<const MCSectionELF&>(SD.getSection());
1127
1128 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1129 if (!RelaSection)
1130 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001131 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001132 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001133
1134 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001135 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001136 }
1137}
1138
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001139void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1140 uint64_t Flags, uint64_t Address,
1141 uint64_t Offset, uint64_t Size,
1142 uint32_t Link, uint32_t Info,
1143 uint64_t Alignment,
1144 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001145 Write32(Name); // sh_name: index into string table
1146 Write32(Type); // sh_type
1147 WriteWord(Flags); // sh_flags
1148 WriteWord(Address); // sh_addr
1149 WriteWord(Offset); // sh_offset
1150 WriteWord(Size); // sh_size
1151 Write32(Link); // sh_link
1152 Write32(Info); // sh_info
1153 WriteWord(Alignment); // sh_addralign
1154 WriteWord(EntrySize); // sh_entsize
1155}
1156
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001157void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1158 MCDataFragment *F,
1159 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001160 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001161
1162 // Sort the relocation entries. Most targets just sort by r_offset, but some
1163 // (e.g., MIPS) have additional constraints.
1164 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001165
1166 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
1167 ELFRelocationEntry entry = Relocs[e - i - 1];
1168
Rafael Espindola26cb15a2010-11-21 00:48:25 +00001169 if (!entry.Index)
1170 ;
Rafael Espindola0ce09712014-03-25 22:43:53 +00001171 // FIXME: this is most likely a bug if index overflows.
Rafael Espindola26cb15a2010-11-21 00:48:25 +00001172 else if (entry.Index < 0)
Rafael Espindolabce26a12010-10-05 15:11:03 +00001173 entry.Index = getSymbolIndexInSymbolTable(Asm, entry.Symbol);
1174 else
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001175 entry.Index += FileSymbolData.size() + LocalSymbolData.size();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001176 if (is64Bit()) {
Rafael Espindola0ce09712014-03-25 22:43:53 +00001177 write(*F, entry.r_offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001178 if (TargetObjectWriter->isN64()) {
Rafael Espindola0ce09712014-03-25 22:43:53 +00001179 write(*F, uint32_t(entry.Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001180
Rafael Espindola0ce09712014-03-25 22:43:53 +00001181 write(*F, TargetObjectWriter->getRSsym(entry.Type));
1182 write(*F, TargetObjectWriter->getRType3(entry.Type));
1183 write(*F, TargetObjectWriter->getRType2(entry.Type));
1184 write(*F, TargetObjectWriter->getRType(entry.Type));
Jack Carter8ad0c272012-06-27 22:28:30 +00001185 }
1186 else {
1187 struct ELF::Elf64_Rela ERE64;
1188 ERE64.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001189 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001190 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001191 if (hasRelocationAddend())
Rafael Espindola0ce09712014-03-25 22:43:53 +00001192 write(*F, entry.r_addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001193 } else {
Rafael Espindola0ce09712014-03-25 22:43:53 +00001194 write(*F, uint32_t(entry.r_offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001195
Rafael Espindolabce26a12010-10-05 15:11:03 +00001196 struct ELF::Elf32_Rela ERE32;
1197 ERE32.setSymbolAndType(entry.Index, entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001198 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001199
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001200 if (hasRelocationAddend())
Rafael Espindola0ce09712014-03-25 22:43:53 +00001201 write(*F, uint32_t(entry.r_addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001202 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001203 }
1204}
1205
Benjamin Kramer8817cca2013-09-22 14:09:50 +00001206static int compareBySuffix(const MCSectionELF *const *a,
1207 const MCSectionELF *const *b) {
1208 const StringRef &NameA = (*a)->getSectionName();
1209 const StringRef &NameB = (*b)->getSectionName();
Rafael Espindolab80875e2011-04-07 23:21:52 +00001210 const unsigned sizeA = NameA.size();
1211 const unsigned sizeB = NameB.size();
1212 const unsigned len = std::min(sizeA, sizeB);
1213 for (unsigned int i = 0; i < len; ++i) {
1214 char ca = NameA[sizeA - i - 1];
1215 char cb = NameB[sizeB - i - 1];
1216 if (ca != cb)
1217 return cb - ca;
1218 }
1219
1220 return sizeB - sizeA;
1221}
1222
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001223void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1224 MCAsmLayout &Layout,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001225 SectionIndexMapTy &SectionIndexMap,
1226 const RelMapTy &RelMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001227 MCContext &Ctx = Asm.getContext();
1228 MCDataFragment *F;
1229
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001230 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001231
Rafael Espindola0e527b72010-09-22 19:04:41 +00001232 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001233 const MCSectionELF *ShstrtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001234 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001235 SectionKind::getReadOnly());
Rafael Espindola44bf2662010-09-16 19:46:31 +00001236 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1237 ShstrtabSD.setAlignment(1);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001238
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001239 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001240 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1241 SectionKind::getReadOnly(),
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001242 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001243 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001244 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001245
Rafael Espindola1557fd62011-03-20 18:44:20 +00001246 const MCSectionELF *StrtabSection;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001247 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001248 SectionKind::getReadOnly());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001249 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1250 StrtabSD.setAlignment(1);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001251
Rafael Espindola1557fd62011-03-20 18:44:20 +00001252 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1253
1254 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1255 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1256 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001257
1258 // Symbol table
1259 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001260 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001261
Matt Fleming6c1ad482010-08-16 18:57:57 +00001262 F = new MCDataFragment(&StrtabSD);
1263 F->getContents().append(StringTable.begin(), StringTable.end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001264
Matt Fleming6c1ad482010-08-16 18:57:57 +00001265 F = new MCDataFragment(&ShstrtabSD);
1266
Rafael Espindolab80875e2011-04-07 23:21:52 +00001267 std::vector<const MCSectionELF*> Sections;
1268 for (MCAssembler::const_iterator it = Asm.begin(),
1269 ie = Asm.end(); it != ie; ++it) {
1270 const MCSectionELF &Section =
1271 static_cast<const MCSectionELF&>(it->getSection());
1272 Sections.push_back(&Section);
1273 }
1274 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1275
Matt Fleming6c1ad482010-08-16 18:57:57 +00001276 // Section header string table.
1277 //
1278 // The first entry of a string table holds a null character so skip
1279 // section 0.
1280 uint64_t Index = 1;
Eli Bendersky84b2a792012-12-07 22:06:56 +00001281 F->getContents().push_back('\x00');
Matt Fleming6c1ad482010-08-16 18:57:57 +00001282
Rafael Espindolab80875e2011-04-07 23:21:52 +00001283 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1284 const MCSectionELF &Section = *Sections[I];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001285
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001286 StringRef Name = Section.getSectionName();
Rafael Espindolab80875e2011-04-07 23:21:52 +00001287 if (I != 0) {
1288 StringRef PreviousName = Sections[I - 1]->getSectionName();
1289 if (PreviousName.endswith(Name)) {
1290 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1291 continue;
1292 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001293 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001294 // Remember the index into the string table so we can write it
1295 // into the sh_name field of the section header table.
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001296 SectionStringTableIndex[&Section] = Index;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001297
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001298 Index += Name.size() + 1;
Eli Bendersky84b2a792012-12-07 22:06:56 +00001299 F->getContents().append(Name.begin(), Name.end());
1300 F->getContents().push_back('\x00');
Matt Fleming6c1ad482010-08-16 18:57:57 +00001301 }
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001302}
1303
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001304void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1305 MCAsmLayout &Layout,
1306 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001307 RevGroupMapTy &RevGroupMap,
1308 SectionIndexMapTy &SectionIndexMap,
1309 const RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001310 // Create the .note.GNU-stack section if needed.
1311 MCContext &Ctx = Asm.getContext();
1312 if (Asm.getNoExecStack()) {
1313 const MCSectionELF *GnuStackSection =
1314 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1315 SectionKind::getReadOnly());
1316 Asm.getOrCreateSectionData(*GnuStackSection);
1317 }
1318
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001319 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001320 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1321 it != ie; ++it) {
1322 const MCSectionELF &Section =
1323 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001324 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001325 continue;
1326
1327 const MCSymbol *SignatureSymbol = Section.getGroup();
1328 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001329 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001330 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001331 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001332 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1333 Data.setAlignment(4);
1334 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001335 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001336 }
1337 GroupMap[Group] = SignatureSymbol;
1338 }
1339
Rafael Espindola1557fd62011-03-20 18:44:20 +00001340 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1341
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001342 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001343 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001344 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001345 const MCSectionELF &Section =
1346 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001347 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001348 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001349 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001350 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1351 // FIXME: we could use the previous fragment
1352 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001353 uint32_t Index = SectionIndexMap.lookup(&Section);
1354 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001355 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001356}
1357
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001358void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1359 const SectionIndexMapTy &SectionIndexMap,
1360 uint32_t GroupSymbolIndex,
1361 uint64_t Offset, uint64_t Size,
1362 uint64_t Alignment,
1363 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001364 uint64_t sh_link = 0;
1365 uint64_t sh_info = 0;
1366
1367 switch(Section.getType()) {
1368 case ELF::SHT_DYNAMIC:
1369 sh_link = SectionStringTableIndex[&Section];
1370 sh_info = 0;
1371 break;
1372
1373 case ELF::SHT_REL:
1374 case ELF::SHT_RELA: {
1375 const MCSectionELF *SymtabSection;
1376 const MCSectionELF *InfoSection;
1377 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1378 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001379 SectionKind::getReadOnly());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001380 sh_link = SectionIndexMap.lookup(SymtabSection);
1381 assert(sh_link && ".symtab not found");
1382
1383 // Remove ".rel" and ".rela" prefixes.
1384 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1385 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
David Blaikie15b25df2013-10-22 23:41:52 +00001386 StringRef GroupName =
1387 Section.getGroup() ? Section.getGroup()->getName() : "";
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001388
David Blaikie15b25df2013-10-22 23:41:52 +00001389 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1390 0, SectionKind::getReadOnly(),
1391 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001392 sh_info = SectionIndexMap.lookup(InfoSection);
1393 break;
1394 }
1395
1396 case ELF::SHT_SYMTAB:
1397 case ELF::SHT_DYNSYM:
1398 sh_link = StringTableIndex;
1399 sh_info = LastLocalSymbolIndex;
1400 break;
1401
1402 case ELF::SHT_SYMTAB_SHNDX:
1403 sh_link = SymbolTableIndex;
1404 break;
1405
1406 case ELF::SHT_PROGBITS:
1407 case ELF::SHT_STRTAB:
1408 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001409 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001410 case ELF::SHT_NULL:
1411 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001412 case ELF::SHT_INIT_ARRAY:
1413 case ELF::SHT_FINI_ARRAY:
1414 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001415 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001416 case ELF::SHT_MIPS_REGINFO:
1417 case ELF::SHT_MIPS_OPTIONS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001418 // Nothing to do.
1419 break;
1420
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001421 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001422 sh_link = SymbolTableIndex;
1423 sh_info = GroupSymbolIndex;
1424 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001425
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001426 default:
1427 assert(0 && "FIXME: sh_type value not supported!");
1428 break;
1429 }
1430
Logan Chien4b724422013-02-05 14:18:59 +00001431 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1432 Section.getType() == ELF::SHT_ARM_EXIDX) {
1433 StringRef SecName(Section.getSectionName());
1434 if (SecName == ".ARM.exidx") {
1435 sh_link = SectionIndexMap.lookup(
1436 Asm.getContext().getELFSection(".text",
1437 ELF::SHT_PROGBITS,
1438 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1439 SectionKind::getText()));
1440 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001441 StringRef GroupName =
1442 Section.getGroup() ? Section.getGroup()->getName() : "";
1443 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1444 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1445 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1446 GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001447 }
1448 }
1449
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001450 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1451 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1452 Alignment, Section.getEntrySize());
1453}
1454
Jan Sjödin30a52de2011-02-28 21:45:04 +00001455bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001456 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001457 !SD.getSection().isVirtualSection();
1458}
1459
Jan Sjödin30a52de2011-02-28 21:45:04 +00001460uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001461 uint64_t Ret = 0;
1462 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1463 ++i) {
1464 const MCFragment &F = *i;
1465 assert(F.getKind() == MCFragment::FT_Data);
1466 Ret += cast<MCDataFragment>(F).getContents().size();
1467 }
1468 return Ret;
1469}
1470
Jan Sjödin30a52de2011-02-28 21:45:04 +00001471uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1472 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001473 if (IsELFMetaDataSection(SD))
1474 return DataSectionSize(SD);
1475 return Layout.getSectionFileSize(&SD);
1476}
1477
Jan Sjödin30a52de2011-02-28 21:45:04 +00001478uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1479 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001480 if (IsELFMetaDataSection(SD))
1481 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001482 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001483}
1484
Rafael Espindola1557fd62011-03-20 18:44:20 +00001485void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1486 const MCAsmLayout &Layout,
1487 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001488 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1489
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001490 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001491 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001492
1493 if (IsELFMetaDataSection(SD)) {
1494 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1495 ++i) {
1496 const MCFragment &F = *i;
1497 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001498 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001499 }
1500 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001501 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001502 }
1503}
1504
Rafael Espindola1557fd62011-03-20 18:44:20 +00001505void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1506 const GroupMapTy &GroupMap,
1507 const MCAsmLayout &Layout,
1508 const SectionIndexMapTy &SectionIndexMap,
1509 const SectionOffsetMapTy &SectionOffsetMap) {
1510 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001511
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001512 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001513 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001514
1515 for (SectionIndexMapTy::const_iterator i=
1516 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1517 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001518 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001519 }
1520
Matt Fleming6c1ad482010-08-16 18:57:57 +00001521 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001522 uint64_t FirstSectionSize =
1523 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1524 uint32_t FirstSectionLink =
1525 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1526 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001527
Rafael Espindola1557fd62011-03-20 18:44:20 +00001528 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001529 const MCSectionELF &Section = *Sections[i];
1530 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1531 uint32_t GroupSymbolIndex;
1532 if (Section.getType() != ELF::SHT_GROUP)
1533 GroupSymbolIndex = 0;
1534 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001535 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1536 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001537
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001538 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001539
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001540 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001541 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001542 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001543 }
1544}
1545
Rafael Espindola1557fd62011-03-20 18:44:20 +00001546void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1547 std::vector<const MCSectionELF*> &Sections) {
1548 for (MCAssembler::iterator it = Asm.begin(),
1549 ie = Asm.end(); it != ie; ++it) {
1550 const MCSectionELF &Section =
1551 static_cast<const MCSectionELF &>(it->getSection());
1552 if (Section.getType() == ELF::SHT_GROUP)
1553 Sections.push_back(&Section);
1554 }
1555
1556 for (MCAssembler::iterator it = Asm.begin(),
1557 ie = Asm.end(); it != ie; ++it) {
1558 const MCSectionELF &Section =
1559 static_cast<const MCSectionELF &>(it->getSection());
1560 if (Section.getType() != ELF::SHT_GROUP &&
1561 Section.getType() != ELF::SHT_REL &&
1562 Section.getType() != ELF::SHT_RELA)
1563 Sections.push_back(&Section);
1564 }
1565
1566 for (MCAssembler::iterator it = Asm.begin(),
1567 ie = Asm.end(); it != ie; ++it) {
1568 const MCSectionELF &Section =
1569 static_cast<const MCSectionELF &>(it->getSection());
1570 if (Section.getType() == ELF::SHT_REL ||
1571 Section.getType() == ELF::SHT_RELA)
1572 Sections.push_back(&Section);
1573 }
1574}
1575
1576void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1577 const MCAsmLayout &Layout) {
1578 GroupMapTy GroupMap;
1579 RevGroupMapTy RevGroupMap;
1580 SectionIndexMapTy SectionIndexMap;
1581
1582 unsigned NumUserSections = Asm.size();
1583
1584 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1585 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1586
1587 const unsigned NumUserAndRelocSections = Asm.size();
1588 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1589 RevGroupMap, SectionIndexMap, RelMap);
1590 const unsigned AllSections = Asm.size();
1591 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1592
1593 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1594
1595 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001596 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1597 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001598
1599 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1600
1601 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1602 const_cast<MCAsmLayout&>(Layout),
1603 SectionIndexMap,
1604 RelMap);
1605
1606 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1607 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1608 sizeof(ELF::Elf32_Ehdr);
1609 uint64_t FileOff = HeaderSize;
1610
1611 std::vector<const MCSectionELF*> Sections;
1612 ComputeSectionOrder(Asm, Sections);
1613 unsigned NumSections = Sections.size();
1614 SectionOffsetMapTy SectionOffsetMap;
1615 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1616 const MCSectionELF &Section = *Sections[i];
1617 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1618
1619 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1620
1621 // Remember the offset into the file for this section.
1622 SectionOffsetMap[&Section] = FileOff;
1623
1624 // Get the size of the section in the output file (including padding).
1625 FileOff += GetSectionFileSize(Layout, SD);
1626 }
1627
1628 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1629
1630 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1631
1632 uint64_t SectionHeaderEntrySize = is64Bit() ?
1633 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1634 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1635
1636 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1637 const MCSectionELF &Section = *Sections[i];
1638 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1639
1640 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1641
1642 // Remember the offset into the file for this section.
1643 SectionOffsetMap[&Section] = FileOff;
1644
1645 // Get the size of the section in the output file (including padding).
1646 FileOff += GetSectionFileSize(Layout, SD);
1647 }
1648
1649 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001650 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001651
1652 // ... then the regular sections ...
1653 // + because of .shstrtab
1654 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1655 WriteDataSectionData(Asm, Layout, *Sections[i]);
1656
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001657 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001658 WriteZeros(Padding);
1659
1660 // ... then the section header table ...
1661 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1662 SectionOffsetMap);
1663
Nick Lewycky4eb11432011-10-07 20:56:23 +00001664 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001665 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1666 WriteDataSectionData(Asm, Layout, *Sections[i]);
1667}
1668
Eli Friedmand92d17b2011-03-03 07:24:36 +00001669bool
1670ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1671 const MCSymbolData &DataA,
1672 const MCFragment &FB,
1673 bool InSet,
1674 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001675 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001676 return false;
1677 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1678 Asm, DataA, FB,InSet, IsPCRel);
1679}
1680
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001681MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1682 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001683 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001684 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001685}