blob: 3f939bbbc014d5990b3155f2caf6092c6ebeeead [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"
David Blaikie8019bf82014-04-10 21:53:53 +000020#include "llvm/MC/MCAsmInfo.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000021#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000022#include "llvm/MC/MCAssembler.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000023#include "llvm/MC/MCContext.h"
Tim Northover5cc3dc82012-12-07 16:50:23 +000024#include "llvm/MC/MCELF.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000025#include "llvm/MC/MCELFSymbolFlags.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000026#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000027#include "llvm/MC/MCFixupKindInfo.h"
28#include "llvm/MC/MCObjectWriter.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000029#include "llvm/MC/MCSectionELF.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000030#include "llvm/MC/MCValue.h"
David Blaikie8019bf82014-04-10 21:53:53 +000031#include "llvm/Support/Compression.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000032#include "llvm/Support/Debug.h"
Rafael Espindola0ce09712014-03-25 22:43:53 +000033#include "llvm/Support/Endian.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000034#include "llvm/Support/ELF.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000035#include "llvm/Support/ErrorHandling.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000036#include <vector>
37using namespace llvm;
38
Jason W Kimc09e7262011-05-11 22:53:06 +000039#undef DEBUG_TYPE
40#define DEBUG_TYPE "reloc-info"
41
Rafael Espindola29abd972011-12-22 03:38:00 +000042namespace {
Rafael Espindola0ce09712014-03-25 22:43:53 +000043class FragmentWriter {
44 bool IsLittleEndian;
45
46public:
47 FragmentWriter(bool IsLittleEndian);
48 template <typename T> void write(MCDataFragment &F, T Val);
49};
50
Rafael Espindola10be0832014-03-25 23:44:25 +000051typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
52
53class SymbolTableWriter {
54 MCAssembler &Asm;
55 FragmentWriter &FWriter;
56 bool Is64Bit;
57 SectionIndexMapTy &SectionIndexMap;
58
59 // The symbol .symtab fragment we are writting to.
60 MCDataFragment *SymtabF;
61
62 // .symtab_shndx fragment we are writting to.
63 MCDataFragment *ShndxF;
64
65 // The numbel of symbols written so far.
66 unsigned NumWritten;
67
68 void createSymtabShndx();
69
70 template <typename T> void write(MCDataFragment &F, T Value);
71
72public:
73 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
74 SectionIndexMapTy &SectionIndexMap,
75 MCDataFragment *SymtabF);
76
77 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
78 uint8_t other, uint32_t shndx, bool Reserved);
79};
80
Rafael Espindola5904e122014-03-29 06:26:49 +000081struct ELFRelocationEntry {
82 uint64_t Offset; // Where is the relocation.
83 bool UseSymbol; // Relocate with a symbol, not the section.
84 union {
85 const MCSymbol *Symbol; // The symbol to relocate with.
86 const MCSectionData *Section; // The section to relocate with.
87 };
88 unsigned Type; // The type of the relocation.
89 uint64_t Addend; // The addend to use.
90
91 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
92 uint64_t Addend)
93 : Offset(Offset), UseSymbol(true), Symbol(Symbol), Type(Type),
94 Addend(Addend) {}
95
96 ELFRelocationEntry(uint64_t Offset, const MCSectionData *Section,
97 unsigned Type, uint64_t Addend)
98 : Offset(Offset), UseSymbol(false), Section(Section), Type(Type),
99 Addend(Addend) {}
100};
101
Rafael Espindola29abd972011-12-22 03:38:00 +0000102class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola0ce09712014-03-25 22:43:53 +0000103 FragmentWriter FWriter;
104
Rafael Espindola29abd972011-12-22 03:38:00 +0000105 protected:
106
107 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
108 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
109 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
110 static bool isInSymtab(const MCAssembler &Asm, const MCSymbolData &Data,
111 bool Used, bool Renamed);
112 static bool isLocal(const MCSymbolData &Data, bool isSignature,
113 bool isUsedInReloc);
114 static bool IsELFMetaDataSection(const MCSectionData &SD);
115 static uint64_t DataSectionSize(const MCSectionData &SD);
116 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
117 const MCSectionData &SD);
118 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
119 const MCSectionData &SD);
120
121 void WriteDataSectionData(MCAssembler &Asm,
122 const MCAsmLayout &Layout,
123 const MCSectionELF &Section);
124
125 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
126 return Kind == X86::reloc_riprel_4byte ||
127 Kind == X86::reloc_riprel_4byte_movq_load;
128 }*/
129
130 /// ELFSymbolData - Helper struct for containing some precomputed
131 /// information on symbols.
132 struct ELFSymbolData {
133 MCSymbolData *SymbolData;
134 uint64_t StringIndex;
135 uint32_t SectionIndex;
136
137 // Support lexicographic sorting.
138 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindola29abd972011-12-22 03:38:00 +0000139 return SymbolData->getSymbol().getName() <
140 RHS.SymbolData->getSymbol().getName();
141 }
142 };
143
Rafael Espindola29abd972011-12-22 03:38:00 +0000144 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000145 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000146
147 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
148 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
149 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
150
Rafael Espindola5904e122014-03-29 06:26:49 +0000151 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
152 Relocations;
Rafael Espindola29abd972011-12-22 03:38:00 +0000153 DenseMap<const MCSection*, uint64_t> SectionStringTableIndex;
154
155 /// @}
156 /// @name Symbol Table Data
157 /// @{
158
159 SmallString<256> StringTable;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000160 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000161 std::vector<ELFSymbolData> LocalSymbolData;
162 std::vector<ELFSymbolData> ExternalSymbolData;
163 std::vector<ELFSymbolData> UndefinedSymbolData;
164
165 /// @}
166
167 bool NeedsGOT;
168
Rafael Espindola29abd972011-12-22 03:38:00 +0000169 // This holds the symbol table index of the last local symbol.
170 unsigned LastLocalSymbolIndex;
171 // This holds the .strtab section index.
172 unsigned StringTableIndex;
173 // This holds the .symtab section index.
174 unsigned SymbolTableIndex;
175
176 unsigned ShstrtabIndex;
177
178
Rafael Espindola29abd972011-12-22 03:38:00 +0000179 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000180 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
181 bool hasRelocationAddend() const {
182 return TargetObjectWriter->hasRelocationAddend();
183 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000184 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000185 bool IsPCRel) const {
186 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000187 }
188
Rafael Espindola29abd972011-12-22 03:38:00 +0000189 public:
Rafael Espindola0ce09712014-03-25 22:43:53 +0000190 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
191 bool IsLittleEndian)
192 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000193 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000194
195 virtual ~ELFObjectWriter();
196
197 void WriteWord(uint64_t W) {
198 if (is64Bit())
199 Write64(W);
200 else
201 Write32(W);
202 }
203
Rafael Espindola0ce09712014-03-25 22:43:53 +0000204 template <typename T> void write(MCDataFragment &F, T Value) {
205 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000206 }
207
Jack Carter1bd90ff2013-01-30 02:09:52 +0000208 void WriteHeader(const MCAssembler &Asm,
209 uint64_t SectionDataSize,
Rafael Espindola29abd972011-12-22 03:38:00 +0000210 unsigned NumberOfSections);
211
Rafael Espindola10be0832014-03-25 23:44:25 +0000212 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000213 const MCAsmLayout &Layout);
214
Rafael Espindola10be0832014-03-25 23:44:25 +0000215 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000216 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000217 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000218
Rafael Espindola5904e122014-03-29 06:26:49 +0000219 bool shouldRelocateWithSymbol(const MCSymbolRefExpr *RefA,
220 const MCSymbolData *SD, uint64_t C,
221 unsigned Type) const;
222
Craig Topper34a61bc2014-03-08 07:02:02 +0000223 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
224 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000225 MCValue Target, bool &IsPCRel,
226 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000227
228 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
229 const MCSymbol *S);
230
231 // Map from a group section to the signature symbol
232 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
233 // Map from a signature symbol to the group section
234 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
235 // Map from a section to the section with the relocations
236 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
237 // Map from a section to its offset
238 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
239
Rafael Espindola022bb762014-03-24 03:43:21 +0000240 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000241 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000242 /// \param Asm - The assembler.
243 /// \param SectionIndexMap - Maps a section to its index.
244 /// \param RevGroupMap - Maps a signature symbol to the group section.
245 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000246 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000247 const SectionIndexMapTy &SectionIndexMap,
248 RevGroupMapTy RevGroupMap,
249 unsigned NumRegularSections);
250
251 void ComputeIndexMap(MCAssembler &Asm,
252 SectionIndexMapTy &SectionIndexMap,
253 const RelMapTy &RelMap);
254
255 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
256 RelMapTy &RelMap);
257
David Blaikie8019bf82014-04-10 21:53:53 +0000258 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
259
Rafael Espindola29abd972011-12-22 03:38:00 +0000260 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
261 const RelMapTy &RelMap);
262
263 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
264 SectionIndexMapTy &SectionIndexMap,
265 const RelMapTy &RelMap);
266
267 // Create the sections that show up in the symbol table. Currently
268 // those are the .note.GNU-stack section and the group sections.
269 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
270 GroupMapTy &GroupMap,
271 RevGroupMapTy &RevGroupMap,
272 SectionIndexMapTy &SectionIndexMap,
273 const RelMapTy &RelMap);
274
Craig Topper34a61bc2014-03-08 07:02:02 +0000275 void ExecutePostLayoutBinding(MCAssembler &Asm,
276 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000277
278 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
279 const MCAsmLayout &Layout,
280 const SectionIndexMapTy &SectionIndexMap,
281 const SectionOffsetMapTy &SectionOffsetMap);
282
283 void ComputeSectionOrder(MCAssembler &Asm,
284 std::vector<const MCSectionELF*> &Sections);
285
286 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
287 uint64_t Address, uint64_t Offset,
288 uint64_t Size, uint32_t Link, uint32_t Info,
289 uint64_t Alignment, uint64_t EntrySize);
290
291 void WriteRelocationsFragment(const MCAssembler &Asm,
292 MCDataFragment *F,
293 const MCSectionData *SD);
294
Craig Topper34a61bc2014-03-08 07:02:02 +0000295 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000296 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
297 const MCSymbolData &DataA,
298 const MCFragment &FB,
299 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000300 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000301
Craig Topper34a61bc2014-03-08 07:02:02 +0000302 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000303 void WriteSection(MCAssembler &Asm,
304 const SectionIndexMapTy &SectionIndexMap,
305 uint32_t GroupSymbolIndex,
306 uint64_t Offset, uint64_t Size, uint64_t Alignment,
307 const MCSectionELF &Section);
308 };
309}
310
Rafael Espindola0ce09712014-03-25 22:43:53 +0000311FragmentWriter::FragmentWriter(bool IsLittleEndian)
312 : IsLittleEndian(IsLittleEndian) {}
313
314template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
315 if (IsLittleEndian)
316 Val = support::endian::byte_swap<T, support::little>(Val);
317 else
318 Val = support::endian::byte_swap<T, support::big>(Val);
319 const char *Start = (const char *)&Val;
320 F.getContents().append(Start, Start + sizeof(T));
321}
322
Rafael Espindola10be0832014-03-25 23:44:25 +0000323void SymbolTableWriter::createSymtabShndx() {
324 if (ShndxF)
325 return;
326
327 MCContext &Ctx = Asm.getContext();
328 const MCSectionELF *SymtabShndxSection =
329 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
330 SectionKind::getReadOnly(), 4, "");
331 MCSectionData *SymtabShndxSD =
332 &Asm.getOrCreateSectionData(*SymtabShndxSection);
333 SymtabShndxSD->setAlignment(4);
334 ShndxF = new MCDataFragment(SymtabShndxSD);
335 unsigned Index = SectionIndexMap.size() + 1;
336 SectionIndexMap[SymtabShndxSection] = Index;
337
338 for (unsigned I = 0; I < NumWritten; ++I)
339 write(*ShndxF, uint32_t(0));
340}
341
342template <typename T>
343void SymbolTableWriter::write(MCDataFragment &F, T Value) {
344 FWriter.write(F, Value);
345}
346
347SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
348 bool Is64Bit,
349 SectionIndexMapTy &SectionIndexMap,
350 MCDataFragment *SymtabF)
351 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
352 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
353 NumWritten(0) {}
354
355void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
356 uint64_t size, uint8_t other,
357 uint32_t shndx, bool Reserved) {
358 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
359
360 if (LargeIndex)
361 createSymtabShndx();
362
363 if (ShndxF) {
364 if (LargeIndex)
365 write(*ShndxF, shndx);
366 else
367 write(*ShndxF, uint32_t(0));
368 }
369
370 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
371
372 raw_svector_ostream OS(SymtabF->getContents());
373
374 if (Is64Bit) {
375 write(*SymtabF, name); // st_name
376 write(*SymtabF, info); // st_info
377 write(*SymtabF, other); // st_other
378 write(*SymtabF, Index); // st_shndx
379 write(*SymtabF, value); // st_value
380 write(*SymtabF, size); // st_size
381 } else {
382 write(*SymtabF, name); // st_name
383 write(*SymtabF, uint32_t(value)); // st_value
384 write(*SymtabF, uint32_t(size)); // st_size
385 write(*SymtabF, info); // st_info
386 write(*SymtabF, other); // st_other
387 write(*SymtabF, Index); // st_shndx
388 }
389
390 ++NumWritten;
391}
392
Jan Sjödin30a52de2011-02-28 21:45:04 +0000393bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
394 const MCFixupKindInfo &FKI =
395 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
396
397 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
398}
399
400bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
401 switch (Variant) {
402 default:
403 return false;
404 case MCSymbolRefExpr::VK_GOT:
405 case MCSymbolRefExpr::VK_PLT:
406 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000407 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000408 case MCSymbolRefExpr::VK_TPOFF:
409 case MCSymbolRefExpr::VK_TLSGD:
410 case MCSymbolRefExpr::VK_GOTTPOFF:
411 case MCSymbolRefExpr::VK_INDNTPOFF:
412 case MCSymbolRefExpr::VK_NTPOFF:
413 case MCSymbolRefExpr::VK_GOTNTPOFF:
414 case MCSymbolRefExpr::VK_TLSLDM:
415 case MCSymbolRefExpr::VK_DTPOFF:
416 case MCSymbolRefExpr::VK_TLSLD:
417 return true;
418 }
419}
420
Jason W Kim96f4c012010-11-15 16:18:39 +0000421ELFObjectWriter::~ELFObjectWriter()
422{}
423
Matt Fleming6c1ad482010-08-16 18:57:57 +0000424// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000425void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
426 uint64_t SectionDataSize,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000427 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000428 // ELF Header
429 // ----------
430 //
431 // Note
432 // ----
433 // emitWord method behaves differently for ELF32 and ELF64, writing
434 // 4 bytes in the former and 8 in the latter.
435
436 Write8(0x7f); // e_ident[EI_MAG0]
437 Write8('E'); // e_ident[EI_MAG1]
438 Write8('L'); // e_ident[EI_MAG2]
439 Write8('F'); // e_ident[EI_MAG3]
440
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000441 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000442
443 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000444 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000445
446 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000447 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000448 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000449 Write8(0); // e_ident[EI_ABIVERSION]
450
451 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
452
453 Write16(ELF::ET_REL); // e_type
454
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000455 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000456
457 Write32(ELF::EV_CURRENT); // e_version
458 WriteWord(0); // e_entry, no entry point in .o file
459 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000460 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramer896bd7e2010-08-17 17:02:29 +0000461 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000462
Jason W Kim4761fba2011-02-04 21:41:11 +0000463 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000464 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000465
466 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000467 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000468
469 Write16(0); // e_phentsize = prog header entry size
470 Write16(0); // e_phnum = # prog header entries = 0
471
472 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000473 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000474
475 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000476 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000477 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000478 else
479 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000480
481 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000482 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000483 Write16(ELF::SHN_XINDEX);
484 else
485 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000486}
487
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000488uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000489 const MCAsmLayout &Layout) {
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000490 MCSymbolData *Data = &OrigData;
491 if (Data->isCommon() && Data->isExternal())
492 return Data->getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000493
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000494 const MCSymbol *Symbol = &Data->getSymbol();
495 bool IsThumbFunc = OrigData.getFlags() & ELF_Other_ThumbFunc;
Roman Divacky55184dd2010-12-20 21:14:39 +0000496
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000497 uint64_t Res = 0;
498 if (Symbol->isVariable()) {
499 const MCExpr *Expr = Symbol->getVariableValue();
500 MCValue Value;
501 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
502 llvm_unreachable("Invalid expression");
503
504 assert(!Value.getSymB());
505
506 Res = Value.getConstant();
507
508 if (const MCSymbolRefExpr *A = Value.getSymA()) {
509 Symbol = &A->getSymbol();
510 Data = &Layout.getAssembler().getSymbolData(*Symbol);
511 } else {
Craig Topperbb694de2014-04-13 04:57:38 +0000512 Symbol = nullptr;
513 Data = nullptr;
Rafael Espindola7bbd5c22014-03-19 00:13:43 +0000514 }
Roman Divacky55184dd2010-12-20 21:14:39 +0000515 }
516
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000517 if (IsThumbFunc)
518 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000519
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000520 if (!Symbol || !Symbol->isInSection())
521 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000522
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000523 Res += Layout.getSymbolOffset(Data);
524
525 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000526}
527
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000528void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
529 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000530 // The presence of symbol versions causes undefined symbols and
531 // versions declared with @@@ to be renamed.
532
David Blaikie583a31c2014-04-18 18:24:25 +0000533 for (MCSymbolData &OriginalData : Asm.symbols()) {
534 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000535 const MCSymbol &Symbol = Alias.AliasedSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000536 MCSymbolData &SD = Asm.getSymbolData(Symbol);
537
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000538 // Not an alias.
539 if (&Symbol == &Alias)
540 continue;
541
Benjamin Kramer14807272010-10-27 19:53:52 +0000542 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000543 size_t Pos = AliasName.find('@');
544 if (Pos == StringRef::npos)
545 continue;
546
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000547 // Aliases defined with .symvar copy the binding from the symbol they alias.
548 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000549 OriginalData.setExternal(SD.isExternal());
550 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000551
Benjamin Kramer14807272010-10-27 19:53:52 +0000552 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000553 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
554 continue;
555
Rafael Espindola26496e62010-10-27 17:56:18 +0000556 // FIXME: produce a better error message.
557 if (Symbol.isUndefined() && Rest.startswith("@@") &&
558 !Rest.startswith("@@@"))
559 report_fatal_error("A @@ version cannot be undefined");
560
Benjamin Kramer14807272010-10-27 19:53:52 +0000561 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000562 }
563}
564
Roman Divacky5a1c5492014-01-07 20:17:03 +0000565static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
566 uint8_t Type = newType;
567
568 // Propagation rules:
569 // IFUNC > FUNC > OBJECT > NOTYPE
570 // TLS_OBJECT > OBJECT > NOTYPE
571 //
572 // dont let the new type degrade the old type
573 switch (origType) {
574 default:
575 break;
576 case ELF::STT_GNU_IFUNC:
577 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
578 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
579 Type = ELF::STT_GNU_IFUNC;
580 break;
581 case ELF::STT_FUNC:
582 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
583 Type == ELF::STT_TLS)
584 Type = ELF::STT_FUNC;
585 break;
586 case ELF::STT_OBJECT:
587 if (Type == ELF::STT_NOTYPE)
588 Type = ELF::STT_OBJECT;
589 break;
590 case ELF::STT_TLS:
591 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
592 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
593 Type = ELF::STT_TLS;
594 break;
595 }
596
597 return Type;
598}
599
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000600static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
601 const MCSymbol &Symbol) {
602 if (!Symbol.isVariable())
603 return &Symbol;
604
605 const MCExpr *Expr = Symbol.getVariableValue();
606 MCValue Value;
607 if (!Expr->EvaluateAsRelocatable(Value, &Layout))
608 llvm_unreachable("Invalid Expression");
609 assert(!Value.getSymB());
610 const MCSymbolRefExpr *A = Value.getSymA();
611 if (!A)
612 return nullptr;
613 return getBaseSymbol(Layout, A->getSymbol());
614}
615
Rafael Espindola10be0832014-03-25 23:44:25 +0000616void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000617 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000618 MCSymbolData &OrigData = *MSD.SymbolData;
Rafael Espindola85a84912014-03-26 00:16:43 +0000619 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
620
621 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
622 // SHN_COMMON.
623 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000624
Jack Carter2f8d9d92013-02-19 21:57:35 +0000625 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000626 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000627 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000628 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000629 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000630 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
631 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000632 }
Saleem Abdulrasool39f773f2014-03-20 06:05:33 +0000633 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
634 Type = ELF::STT_FUNC;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000635 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000636
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000637 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000638 // 2 bits
639 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000640 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000641 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000642
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000643 uint64_t Value = SymbolValue(OrigData, Layout);
Saleem Abdulrasool39f773f2014-03-20 06:05:33 +0000644 if (OrigData.getFlags() & ELF_Other_ThumbFunc)
645 Value |= 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000646 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000647
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000648 const MCExpr *ESize = OrigData.getSize();
649 if (!ESize && Base)
650 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000651
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000652 if (ESize) {
653 int64_t Res;
654 if (!ESize->EvaluateAsAbsolute(Res, Layout))
655 report_fatal_error("Size expression must be absolute.");
656 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000657 }
658
659 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000660 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
661 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000662}
663
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000664void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000665 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000666 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000667 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000668 // The string table must be emitted first because we need the index
669 // into the string table for all the symbol names.
670 assert(StringTable.size() && "Missing string table");
671
672 // FIXME: Make sure the start of the symbol table is aligned.
673
Rafael Espindola10be0832014-03-25 23:44:25 +0000674 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
675
Matt Fleming6c1ad482010-08-16 18:57:57 +0000676 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000677 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000678
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000679 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000680 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
681 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000682 }
683
Matt Fleming6c1ad482010-08-16 18:57:57 +0000684 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000685 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
686
Matt Fleming6c1ad482010-08-16 18:57:57 +0000687 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
688 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000689 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000690 }
691
Rafael Espindola44bf2662010-09-16 19:46:31 +0000692 // Write out a symbol table entry for each regular section.
Rafael Espindola18014102010-11-10 22:16:43 +0000693 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
694 ++i) {
Eli Friedman1fe0d532010-08-16 21:17:09 +0000695 const MCSectionELF &Section =
Rafael Espindola18014102010-11-10 22:16:43 +0000696 static_cast<const MCSectionELF&>(i->getSection());
697 if (Section.getType() == ELF::SHT_RELA ||
698 Section.getType() == ELF::SHT_REL ||
699 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewycky133a1682011-10-07 23:29:53 +0000700 Section.getType() == ELF::SHT_SYMTAB ||
701 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedman1fe0d532010-08-16 21:17:09 +0000702 continue;
Rafael Espindola10be0832014-03-25 23:44:25 +0000703 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
704 SectionIndexMap.lookup(&Section), false);
Eli Friedman1fe0d532010-08-16 21:17:09 +0000705 LastLocalSymbolIndex++;
706 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000707
708 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
709 ELFSymbolData &MSD = ExternalSymbolData[i];
710 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000711 assert(((Data.getFlags() & ELF_STB_Global) ||
712 (Data.getFlags() & ELF_STB_Weak)) &&
713 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000714 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000715 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000716 LastLocalSymbolIndex++;
717 }
718
719 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
720 ELFSymbolData &MSD = UndefinedSymbolData[i];
721 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000722 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000723 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000724 LastLocalSymbolIndex++;
725 }
726}
727
Rafael Espindola5904e122014-03-29 06:26:49 +0000728// It is always valid to create a relocation with a symbol. It is preferable
729// to use a relocation with a section if that is possible. Using the section
730// allows us to omit some local symbols from the symbol table.
731bool ELFObjectWriter::shouldRelocateWithSymbol(const MCSymbolRefExpr *RefA,
732 const MCSymbolData *SD,
733 uint64_t C,
734 unsigned Type) const {
735 // A PCRel relocation to an absolute value has no symbol (or section). We
736 // represent that with a relocation to a null section.
737 if (!RefA)
738 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000739
Rafael Espindola5904e122014-03-29 06:26:49 +0000740 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
741 switch (Kind) {
742 default:
743 break;
744 // The .odp creation emits a relocation against the symbol ".TOC." which
745 // create a R_PPC64_TOC relocation. However the relocation symbol name
746 // in final object creation should be NULL, since the symbol does not
747 // really exist, it is just the reference to TOC base for the current
748 // object file. Since the symbol is undefined, returning false results
749 // in a relocation with a null section which is the desired result.
750 case MCSymbolRefExpr::VK_PPC_TOCBASE:
751 return false;
752
753 // These VariantKind cause the relocation to refer to something other than
754 // the symbol itself, like a linker generated table. Since the address of
755 // symbol is not relevant, we cannot replace the symbol with the
756 // section and patch the difference in the addend.
757 case MCSymbolRefExpr::VK_GOT:
758 case MCSymbolRefExpr::VK_PLT:
759 case MCSymbolRefExpr::VK_GOTPCREL:
760 case MCSymbolRefExpr::VK_Mips_GOT:
761 case MCSymbolRefExpr::VK_PPC_GOT_LO:
762 case MCSymbolRefExpr::VK_PPC_GOT_HI:
763 case MCSymbolRefExpr::VK_PPC_GOT_HA:
764 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000765 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000766
Rafael Espindola5904e122014-03-29 06:26:49 +0000767 // An undefined symbol is not in any section, so the relocation has to point
768 // to the symbol itself.
769 const MCSymbol &Sym = SD->getSymbol();
770 if (Sym.isUndefined())
771 return true;
772
773 unsigned Binding = MCELF::GetBinding(*SD);
774 switch(Binding) {
775 default:
776 llvm_unreachable("Invalid Binding");
777 case ELF::STB_LOCAL:
778 break;
779 case ELF::STB_WEAK:
780 // If the symbol is weak, it might be overridden by a symbol in another
781 // file. The relocation has to point to the symbol so that the linker
782 // can update it.
783 return true;
784 case ELF::STB_GLOBAL:
785 // Global ELF symbols can be preempted by the dynamic linker. The relocation
786 // has to point to the symbol for a reason analogous to the STB_WEAK case.
787 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000788 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000789
Rafael Espindola5904e122014-03-29 06:26:49 +0000790 // If a relocation points to a mergeable section, we have to be careful.
791 // If the offset is zero, a relocation with the section will encode the
792 // same information. With a non-zero offset, the situation is different.
793 // For example, a relocation can point 42 bytes past the end of a string.
794 // If we change such a relocation to use the section, the linker would think
795 // that it pointed to another string and subtracting 42 at runtime will
796 // produce the wrong value.
797 auto &Sec = cast<MCSectionELF>(Sym.getSection());
798 unsigned Flags = Sec.getFlags();
799 if (Flags & ELF::SHF_MERGE) {
800 if (C != 0)
801 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000802
803 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
804 // only handle section relocations to mergeable sections if using RELA.
805 if (!hasRelocationAddend())
806 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000807 }
808
Rafael Espindola5904e122014-03-29 06:26:49 +0000809 // Most TLS relocations use a got, so they need the symbol. Even those that
810 // are just an offset (@tpoff), require a symbol in some linkers (gold,
811 // but not bfd ld).
812 if (Flags & ELF::SHF_TLS)
813 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000814
Rafael Espindola9ef84412014-04-11 19:18:01 +0000815 // If the symbol is a thumb function the final relocation must set the lowest
816 // bit. With a symbol that is done by just having the symbol have that bit
817 // set, so we would lose the bit if we relocated with the section.
818 // FIXME: We could use the section but add the bit to the relocation value.
819 if (SD->getFlags() & ELF_Other_ThumbFunc)
820 return true;
821
Rafael Espindola5904e122014-03-29 06:26:49 +0000822 if (TargetObjectWriter->needsRelocateWithSymbol(Type))
823 return true;
824 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000825}
826
Jason W Kim495c2bb2010-12-06 21:57:34 +0000827void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
828 const MCAsmLayout &Layout,
829 const MCFragment *Fragment,
830 const MCFixup &Fixup,
831 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000832 bool &IsPCRel,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000833 uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000834 const MCSectionData *FixupSection = Fragment->getParent();
835 uint64_t C = Target.getConstant();
836 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000837
Rafael Espindola5904e122014-03-29 06:26:49 +0000838 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
839 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
840 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000841
Rafael Espindola5904e122014-03-29 06:26:49 +0000842 // Let A, B and C being the components of Target and R be the location of
843 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
844 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000845
Rafael Espindola5904e122014-03-29 06:26:49 +0000846 // In general, ELF has no relocations for -B. It can only represent (A + C)
847 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
848 // replace B to implement it: (A - R - K + C)
849 if (IsPCRel)
850 Asm.getContext().FatalError(
851 Fixup.getLoc(),
852 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000853
Rafael Espindola5904e122014-03-29 06:26:49 +0000854 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000855
Rafael Espindola5904e122014-03-29 06:26:49 +0000856 if (SymB.isUndefined())
857 Asm.getContext().FatalError(
858 Fixup.getLoc(),
859 Twine("symbol '") + SymB.getName() +
860 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000861
Rafael Espindola5904e122014-03-29 06:26:49 +0000862 assert(!SymB.isAbsolute() && "Should have been folded");
863 const MCSection &SecB = SymB.getSection();
864 if (&SecB != &FixupSection->getSection())
865 Asm.getContext().FatalError(
866 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000867
Rafael Espindola5904e122014-03-29 06:26:49 +0000868 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
869 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
870 uint64_t K = SymBOffset - FixupOffset;
871 IsPCRel = true;
872 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000873 }
874
Rafael Espindola5904e122014-03-29 06:26:49 +0000875 // We either rejected the fixup or folded B into C at this point.
876 const MCSymbolRefExpr *RefA = Target.getSymA();
877 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
878 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
879
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000880 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola5904e122014-03-29 06:26:49 +0000881 bool RelocateWithSymbol = shouldRelocateWithSymbol(RefA, SymAD, C, Type);
882 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
883 C += Layout.getSymbolOffset(SymAD);
884
885 uint64_t Addend = 0;
886 if (hasRelocationAddend()) {
887 Addend = C;
888 C = 0;
889 }
890
891 FixedValue = C;
892
893 // FIXME: What is this!?!?
894 MCSymbolRefExpr::VariantKind Modifier =
895 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000896 if (RelocNeedsGOT(Modifier))
897 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000898
Rafael Espindola5904e122014-03-29 06:26:49 +0000899 if (!RelocateWithSymbol) {
900 const MCSection *SecA =
901 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
902 const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
903 ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
904 Relocations[FixupSection].push_back(Rec);
905 return;
906 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000907
Rafael Espindola5904e122014-03-29 06:26:49 +0000908 if (SymA) {
909 if (const MCSymbol *R = Renames.lookup(SymA))
910 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000911
Rafael Espindola5904e122014-03-29 06:26:49 +0000912 if (RefA->getKind() == MCSymbolRefExpr::VK_WEAKREF)
913 WeakrefUsedInReloc.insert(SymA);
914 else
915 UsedInReloc.insert(SymA);
916 }
917 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
918 Relocations[FixupSection].push_back(Rec);
919 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000920}
921
922
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000923uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000924ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
925 const MCSymbol *S) {
Benjamin Kramer37b384c2010-08-25 20:09:43 +0000926 MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000927 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000928}
929
Jan Sjödin30a52de2011-02-28 21:45:04 +0000930bool ELFObjectWriter::isInSymtab(const MCAssembler &Asm,
931 const MCSymbolData &Data,
932 bool Used, bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000933 const MCSymbol &Symbol = Data.getSymbol();
934 if (Symbol.isVariable()) {
935 const MCExpr *Expr = Symbol.getVariableValue();
936 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
937 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
938 return false;
939 }
940 }
Rafael Espindola16145972010-11-01 14:28:48 +0000941
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000942 if (Used)
943 return true;
944
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000945 if (Renamed)
946 return false;
947
Rafael Espindola45834a02010-10-29 23:09:31 +0000948 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
949 return true;
950
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000951 const MCSymbol &A = Symbol.AliasedSymbol();
Rafael Espindola9e18e962011-02-23 20:22:07 +0000952 if (Symbol.isVariable() && !A.isVariable() && A.isUndefined())
953 return false;
954
Jan Sjödin30a52de2011-02-28 21:45:04 +0000955 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000956 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000957 return false;
958
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000959 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000960 return false;
961
962 return true;
963}
964
Jan Sjödin30a52de2011-02-28 21:45:04 +0000965bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isSignature,
966 bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000967 if (Data.isExternal())
968 return false;
969
970 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000971 const MCSymbol &RefSymbol = Symbol.AliasedSymbol();
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000972
973 if (RefSymbol.isUndefined() && !RefSymbol.isVariable()) {
974 if (isSignature && !isUsedInReloc)
975 return true;
976
Rafael Espindolab1d07892010-10-05 18:01:23 +0000977 return false;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000978 }
Rafael Espindolab1d07892010-10-05 18:01:23 +0000979
980 return true;
981}
982
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000983void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000984 SectionIndexMapTy &SectionIndexMap,
985 const RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000986 unsigned Index = 1;
987 for (MCAssembler::iterator it = Asm.begin(),
988 ie = Asm.end(); it != ie; ++it) {
989 const MCSectionELF &Section =
990 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000991 if (Section.getType() != ELF::SHT_GROUP)
992 continue;
993 SectionIndexMap[&Section] = Index++;
994 }
995
996 for (MCAssembler::iterator it = Asm.begin(),
997 ie = Asm.end(); it != ie; ++it) {
998 const MCSectionELF &Section =
999 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001000 if (Section.getType() == ELF::SHT_GROUP ||
1001 Section.getType() == ELF::SHT_REL ||
1002 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001003 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +00001004 SectionIndexMap[&Section] = Index++;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001005 const MCSectionELF *RelSection = RelMap.lookup(&Section);
1006 if (RelSection)
1007 SectionIndexMap[RelSection] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +00001008 }
1009}
1010
Rafael Espindola022bb762014-03-24 03:43:21 +00001011void
1012ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
1013 const SectionIndexMapTy &SectionIndexMap,
1014 RevGroupMapTy RevGroupMap,
1015 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001016 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +00001017 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001018 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00001019 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001020 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1021 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1022 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001023 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001024 }
1025
Matt Fleming6c1ad482010-08-16 18:57:57 +00001026 // Index 0 is always the empty string.
1027 StringMap<uint64_t> StringIndexMap;
1028 StringTable += '\x00';
1029
Rafael Espindolab80875e2011-04-07 23:21:52 +00001030 // FIXME: We could optimize suffixes in strtab in the same way we
1031 // optimize them in shstrtab.
1032
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001033 for (MCAssembler::const_file_name_iterator it = Asm.file_names_begin(),
1034 ie = Asm.file_names_end();
1035 it != ie;
1036 ++it) {
1037 StringRef Name = *it;
1038 uint64_t &Entry = StringIndexMap[Name];
1039 if (!Entry) {
1040 Entry = StringTable.size();
1041 StringTable += Name;
1042 StringTable += '\x00';
1043 }
1044 FileSymbolData.push_back(Entry);
1045 }
1046
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001047 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +00001048 for (MCSymbolData &SD : Asm.symbols()) {
1049 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001050
Rafael Espindola16145972010-11-01 14:28:48 +00001051 bool Used = UsedInReloc.count(&Symbol);
1052 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001053 bool isSignature = RevGroupMap.count(&Symbol);
1054
David Blaikie583a31c2014-04-18 18:24:25 +00001055 if (!isInSymtab(Asm, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001056 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001057 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001058 continue;
1059
Matt Fleming6c1ad482010-08-16 18:57:57 +00001060 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001061 MSD.SymbolData = &SD;
Rafael Espindola022bb762014-03-24 03:43:21 +00001062 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001063
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001064 // Undefined symbols are global, but this is the first place we
1065 // are able to set it.
David Blaikie583a31c2014-04-18 18:24:25 +00001066 bool Local = isLocal(SD, isSignature, Used);
1067 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001068 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001069 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001070 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001071 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001072 }
1073
Rafael Espindola022bb762014-03-24 03:43:21 +00001074 if (!BaseSymbol) {
1075 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001076 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001077 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001078 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001079 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001080 if (isSignature && !Used)
1081 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1082 else
1083 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001084 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001085 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001086 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001087 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001088 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001089 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001090 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001091 }
1092
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001093 // The @@@ in symbol version is replaced with @ in undefined symbols and
1094 // @@ in defined ones.
1095 StringRef Name = Symbol.getName();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001096 SmallString<32> Buf;
1097
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001098 size_t Pos = Name.find("@@@");
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001099 if (Pos != StringRef::npos) {
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001100 Buf += Name.substr(0, Pos);
1101 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1102 Buf += Name.substr(Pos + Skip);
1103 Name = Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001104 }
1105
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001106 uint64_t &Entry = StringIndexMap[Name];
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001107 if (!Entry) {
1108 Entry = StringTable.size();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001109 StringTable += Name;
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001110 StringTable += '\x00';
Matt Fleming6c1ad482010-08-16 18:57:57 +00001111 }
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001112 MSD.StringIndex = Entry;
1113 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1114 UndefinedSymbolData.push_back(MSD);
1115 else if (Local)
1116 LocalSymbolData.push_back(MSD);
1117 else
1118 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001119 }
1120
1121 // Symbols are required to be in lexicographic order.
1122 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1123 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1124 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1125
1126 // Set the symbol indices. Local symbols must come before all other
1127 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001128 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001129 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1130 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001131
1132 Index += NumRegularSections;
1133
Matt Fleming6c1ad482010-08-16 18:57:57 +00001134 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1135 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1136 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1137 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1138}
1139
Rafael Espindola1557fd62011-03-20 18:44:20 +00001140void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1141 MCAsmLayout &Layout,
1142 RelMapTy &RelMap) {
1143 for (MCAssembler::const_iterator it = Asm.begin(),
1144 ie = Asm.end(); it != ie; ++it) {
1145 const MCSectionData &SD = *it;
1146 if (Relocations[&SD].empty())
1147 continue;
1148
Matt Fleming6c1ad482010-08-16 18:57:57 +00001149 MCContext &Ctx = Asm.getContext();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001150 const MCSectionELF &Section =
1151 static_cast<const MCSectionELF&>(SD.getSection());
1152
1153 const StringRef SectionName = Section.getSectionName();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001154 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming6c1ad482010-08-16 18:57:57 +00001155 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001156
1157 unsigned EntrySize;
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001158 if (hasRelocationAddend())
1159 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramerfd054152010-08-17 17:56:13 +00001160 else
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001161 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001162
Tim Northovera630fb02013-07-10 20:58:17 +00001163 unsigned Flags = 0;
1164 StringRef Group = "";
1165 if (Section.getFlags() & ELF::SHF_GROUP) {
David Blaikie1e412ea2013-10-22 20:34:30 +00001166 Flags = ELF::SHF_GROUP;
1167 Group = Section.getGroup()->getName();
Tim Northovera630fb02013-07-10 20:58:17 +00001168 }
1169
Rafael Espindola1557fd62011-03-20 18:44:20 +00001170 const MCSectionELF *RelaSection =
1171 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
Tim Northovera630fb02013-07-10 20:58:17 +00001172 ELF::SHT_RELA : ELF::SHT_REL, Flags,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001173 SectionKind::getReadOnly(),
Tim Northovera630fb02013-07-10 20:58:17 +00001174 EntrySize, Group);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001175 RelMap[&Section] = RelaSection;
1176 Asm.getOrCreateSectionData(*RelaSection);
1177 }
1178}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001179
David Blaikiee06e8012014-04-11 22:11:50 +00001180static SmallVector<char, 128>
1181getUncompressedData(MCAsmLayout &Layout,
1182 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001183 SmallVector<char, 128> UncompressedData;
1184 for (const MCFragment &F : Fragments) {
1185 const SmallVectorImpl<char> *Contents;
1186 switch (F.getKind()) {
1187 case MCFragment::FT_Data:
1188 Contents = &cast<MCDataFragment>(F).getContents();
1189 break;
1190 case MCFragment::FT_Dwarf:
1191 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1192 break;
1193 case MCFragment::FT_DwarfFrame:
1194 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1195 break;
1196 default:
1197 llvm_unreachable(
1198 "Not expecting any other fragment types in a debug_* section");
1199 }
1200 UncompressedData.append(Contents->begin(), Contents->end());
1201 }
1202 return UncompressedData;
1203}
1204
1205// Include the debug info compression header:
1206// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1207// useful for consumers to preallocate a buffer to decompress into.
David Blaikiee06e8012014-04-11 22:11:50 +00001208static void
1209prependCompressionHeader(uint64_t Size,
1210 SmallVectorImpl<char> &CompressedContents) {
David Blaikie8019bf82014-04-10 21:53:53 +00001211 static const StringRef Magic = "ZLIB";
1212 if (sys::IsLittleEndianHost)
1213 Size = sys::SwapByteOrder(Size);
1214 CompressedContents.insert(CompressedContents.begin(),
1215 Magic.size() + sizeof(Size), 0);
1216 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1217 std::copy(reinterpret_cast<char *>(&Size),
1218 reinterpret_cast<char *>(&Size + 1),
1219 CompressedContents.begin() + Magic.size());
1220}
1221
1222// Return a single fragment containing the compressed contents of the whole
1223// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001224static std::unique_ptr<MCDataFragment>
1225getCompressedFragment(MCAsmLayout &Layout,
1226 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001227 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1228
1229 // Gather the uncompressed data from all the fragments, recording the
1230 // alignment fragment, if seen, and any fixups.
1231 SmallVector<char, 128> UncompressedData =
1232 getUncompressedData(Layout, Fragments);
1233
1234 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1235
1236 zlib::Status Success = zlib::compress(
1237 StringRef(UncompressedData.data(), UncompressedData.size()),
1238 CompressedContents);
1239 if (Success != zlib::StatusOK)
1240 return nullptr;
1241
1242 prependCompressionHeader(UncompressedData.size(), CompressedContents);
1243
1244 return CompressedFragment;
1245}
1246
1247static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
1248 const MCSectionELF &Section,
1249 MCSectionData &SD) {
1250 StringRef SectionName = Section.getSectionName();
1251 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1252
1253 std::unique_ptr<MCDataFragment> CompressedFragment =
1254 getCompressedFragment(Layout, Fragments);
1255
1256 // Leave the section as-is if the fragments could not be compressed.
1257 if (!CompressedFragment)
1258 return;
1259
1260 // Invalidate the layout for the whole section since it will have new and
1261 // different fragments now.
1262 Layout.invalidateFragmentsFrom(&Fragments.front());
1263 Fragments.clear();
1264
1265 // Complete the initialization of the new fragment
1266 CompressedFragment->setParent(&SD);
1267 CompressedFragment->setLayoutOrder(0);
1268 Fragments.push_back(CompressedFragment.release());
1269
1270 // Rename from .debug_* to .zdebug_*
1271 Asm.getContext().renameELFSection(&Section,
1272 (".z" + SectionName.drop_front(1)).str());
1273}
1274
1275void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1276 MCAsmLayout &Layout) {
1277 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1278 return;
1279
1280 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001281 const MCSectionELF &Section =
1282 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001283 StringRef SectionName = Section.getSectionName();
1284
1285 // Compressing debug_frame requires handling alignment fragments which is
1286 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1287 // for writing to arbitrary buffers) for little benefit.
1288 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1289 continue;
1290
1291 CompressDebugSection(Asm, Layout, Section, SD);
1292 }
1293}
1294
Rafael Espindola1557fd62011-03-20 18:44:20 +00001295void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1296 const RelMapTy &RelMap) {
1297 for (MCAssembler::const_iterator it = Asm.begin(),
1298 ie = Asm.end(); it != ie; ++it) {
1299 const MCSectionData &SD = *it;
1300 const MCSectionELF &Section =
1301 static_cast<const MCSectionELF&>(SD.getSection());
1302
1303 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1304 if (!RelaSection)
1305 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001306 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001307 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001308
1309 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001310 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001311 }
1312}
1313
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001314void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1315 uint64_t Flags, uint64_t Address,
1316 uint64_t Offset, uint64_t Size,
1317 uint32_t Link, uint32_t Info,
1318 uint64_t Alignment,
1319 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001320 Write32(Name); // sh_name: index into string table
1321 Write32(Type); // sh_type
1322 WriteWord(Flags); // sh_flags
1323 WriteWord(Address); // sh_addr
1324 WriteWord(Offset); // sh_offset
1325 WriteWord(Size); // sh_size
1326 Write32(Link); // sh_link
1327 Write32(Info); // sh_info
1328 WriteWord(Alignment); // sh_addralign
1329 WriteWord(EntrySize); // sh_entsize
1330}
1331
Rafael Espindola5904e122014-03-29 06:26:49 +00001332// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1333// just to match gnu as for easier comparison. The use type is an arbitrary way
1334// of making the sort deterministic.
1335static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1336 const ELFRelocationEntry &A = *AP;
1337 const ELFRelocationEntry &B = *BP;
1338 if (A.Offset != B.Offset)
1339 return B.Offset - A.Offset;
1340 if (B.Type != A.Type)
1341 return A.Type - B.Type;
1342 llvm_unreachable("ELFRelocs might be unstable!");
1343}
1344
1345static void sortRelocs(const MCAssembler &Asm,
1346 std::vector<ELFRelocationEntry> &Relocs) {
1347 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1348}
1349
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001350void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1351 MCDataFragment *F,
1352 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001353 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001354
Rafael Espindola5904e122014-03-29 06:26:49 +00001355 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001356
1357 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001358 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001359
Rafael Espindola5904e122014-03-29 06:26:49 +00001360 unsigned Index;
1361 if (Entry.UseSymbol) {
1362 Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1363 } else {
1364 const MCSectionData *Sec = Entry.Section;
1365 if (Sec)
1366 Index = Sec->getOrdinal() + FileSymbolData.size() +
1367 LocalSymbolData.size() + 1;
1368 else
1369 Index = 0;
1370 }
1371
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001372 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001373 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001374 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001375 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001376
Rafael Espindola5904e122014-03-29 06:26:49 +00001377 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1378 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1379 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1380 write(*F, TargetObjectWriter->getRType(Entry.Type));
1381 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001382 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001383 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001384 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001385 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001386 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001387 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001388 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001389 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001390
Rafael Espindolabce26a12010-10-05 15:11:03 +00001391 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001392 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001393 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001394
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001395 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001396 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001397 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001398 }
1399}
1400
Benjamin Kramer8817cca2013-09-22 14:09:50 +00001401static int compareBySuffix(const MCSectionELF *const *a,
1402 const MCSectionELF *const *b) {
1403 const StringRef &NameA = (*a)->getSectionName();
1404 const StringRef &NameB = (*b)->getSectionName();
Rafael Espindolab80875e2011-04-07 23:21:52 +00001405 const unsigned sizeA = NameA.size();
1406 const unsigned sizeB = NameB.size();
1407 const unsigned len = std::min(sizeA, sizeB);
1408 for (unsigned int i = 0; i < len; ++i) {
1409 char ca = NameA[sizeA - i - 1];
1410 char cb = NameB[sizeB - i - 1];
1411 if (ca != cb)
1412 return cb - ca;
1413 }
1414
1415 return sizeB - sizeA;
1416}
1417
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001418void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1419 MCAsmLayout &Layout,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001420 SectionIndexMapTy &SectionIndexMap,
1421 const RelMapTy &RelMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001422 MCContext &Ctx = Asm.getContext();
1423 MCDataFragment *F;
1424
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001425 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001426
Rafael Espindola0e527b72010-09-22 19:04:41 +00001427 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001428 const MCSectionELF *ShstrtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001429 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001430 SectionKind::getReadOnly());
Rafael Espindola44bf2662010-09-16 19:46:31 +00001431 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1432 ShstrtabSD.setAlignment(1);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001433
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001434 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001435 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1436 SectionKind::getReadOnly(),
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001437 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001438 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001439 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001440
Rafael Espindola1557fd62011-03-20 18:44:20 +00001441 const MCSectionELF *StrtabSection;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001442 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001443 SectionKind::getReadOnly());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001444 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1445 StrtabSD.setAlignment(1);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001446
Rafael Espindola1557fd62011-03-20 18:44:20 +00001447 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1448
1449 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1450 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1451 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001452
1453 // Symbol table
1454 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001455 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001456
Matt Fleming6c1ad482010-08-16 18:57:57 +00001457 F = new MCDataFragment(&StrtabSD);
1458 F->getContents().append(StringTable.begin(), StringTable.end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001459
Matt Fleming6c1ad482010-08-16 18:57:57 +00001460 F = new MCDataFragment(&ShstrtabSD);
1461
Rafael Espindolab80875e2011-04-07 23:21:52 +00001462 std::vector<const MCSectionELF*> Sections;
1463 for (MCAssembler::const_iterator it = Asm.begin(),
1464 ie = Asm.end(); it != ie; ++it) {
1465 const MCSectionELF &Section =
1466 static_cast<const MCSectionELF&>(it->getSection());
1467 Sections.push_back(&Section);
1468 }
1469 array_pod_sort(Sections.begin(), Sections.end(), compareBySuffix);
1470
Matt Fleming6c1ad482010-08-16 18:57:57 +00001471 // Section header string table.
1472 //
1473 // The first entry of a string table holds a null character so skip
1474 // section 0.
1475 uint64_t Index = 1;
Eli Bendersky84b2a792012-12-07 22:06:56 +00001476 F->getContents().push_back('\x00');
Matt Fleming6c1ad482010-08-16 18:57:57 +00001477
Rafael Espindolab80875e2011-04-07 23:21:52 +00001478 for (unsigned int I = 0, E = Sections.size(); I != E; ++I) {
1479 const MCSectionELF &Section = *Sections[I];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001480
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001481 StringRef Name = Section.getSectionName();
Rafael Espindolab80875e2011-04-07 23:21:52 +00001482 if (I != 0) {
1483 StringRef PreviousName = Sections[I - 1]->getSectionName();
1484 if (PreviousName.endswith(Name)) {
1485 SectionStringTableIndex[&Section] = Index - Name.size() - 1;
1486 continue;
1487 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001488 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001489 // Remember the index into the string table so we can write it
1490 // into the sh_name field of the section header table.
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001491 SectionStringTableIndex[&Section] = Index;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001492
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001493 Index += Name.size() + 1;
Eli Bendersky84b2a792012-12-07 22:06:56 +00001494 F->getContents().append(Name.begin(), Name.end());
1495 F->getContents().push_back('\x00');
Matt Fleming6c1ad482010-08-16 18:57:57 +00001496 }
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001497}
1498
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001499void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1500 MCAsmLayout &Layout,
1501 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001502 RevGroupMapTy &RevGroupMap,
1503 SectionIndexMapTy &SectionIndexMap,
1504 const RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001505 // Create the .note.GNU-stack section if needed.
1506 MCContext &Ctx = Asm.getContext();
1507 if (Asm.getNoExecStack()) {
1508 const MCSectionELF *GnuStackSection =
1509 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1510 SectionKind::getReadOnly());
1511 Asm.getOrCreateSectionData(*GnuStackSection);
1512 }
1513
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001514 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001515 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1516 it != ie; ++it) {
1517 const MCSectionELF &Section =
1518 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001519 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001520 continue;
1521
1522 const MCSymbol *SignatureSymbol = Section.getGroup();
1523 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001524 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001525 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001526 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001527 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1528 Data.setAlignment(4);
1529 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001530 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001531 }
1532 GroupMap[Group] = SignatureSymbol;
1533 }
1534
Rafael Espindola1557fd62011-03-20 18:44:20 +00001535 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1536
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001537 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001538 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001539 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001540 const MCSectionELF &Section =
1541 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001542 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001543 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001544 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001545 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1546 // FIXME: we could use the previous fragment
1547 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001548 uint32_t Index = SectionIndexMap.lookup(&Section);
1549 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001550 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001551}
1552
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001553void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1554 const SectionIndexMapTy &SectionIndexMap,
1555 uint32_t GroupSymbolIndex,
1556 uint64_t Offset, uint64_t Size,
1557 uint64_t Alignment,
1558 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001559 uint64_t sh_link = 0;
1560 uint64_t sh_info = 0;
1561
1562 switch(Section.getType()) {
1563 case ELF::SHT_DYNAMIC:
1564 sh_link = SectionStringTableIndex[&Section];
1565 sh_info = 0;
1566 break;
1567
1568 case ELF::SHT_REL:
1569 case ELF::SHT_RELA: {
1570 const MCSectionELF *SymtabSection;
1571 const MCSectionELF *InfoSection;
1572 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1573 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001574 SectionKind::getReadOnly());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001575 sh_link = SectionIndexMap.lookup(SymtabSection);
1576 assert(sh_link && ".symtab not found");
1577
1578 // Remove ".rel" and ".rela" prefixes.
1579 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1580 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
David Blaikie15b25df2013-10-22 23:41:52 +00001581 StringRef GroupName =
1582 Section.getGroup() ? Section.getGroup()->getName() : "";
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001583
David Blaikie15b25df2013-10-22 23:41:52 +00001584 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1585 0, SectionKind::getReadOnly(),
1586 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001587 sh_info = SectionIndexMap.lookup(InfoSection);
1588 break;
1589 }
1590
1591 case ELF::SHT_SYMTAB:
1592 case ELF::SHT_DYNSYM:
1593 sh_link = StringTableIndex;
1594 sh_info = LastLocalSymbolIndex;
1595 break;
1596
1597 case ELF::SHT_SYMTAB_SHNDX:
1598 sh_link = SymbolTableIndex;
1599 break;
1600
1601 case ELF::SHT_PROGBITS:
1602 case ELF::SHT_STRTAB:
1603 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001604 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001605 case ELF::SHT_NULL:
1606 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001607 case ELF::SHT_INIT_ARRAY:
1608 case ELF::SHT_FINI_ARRAY:
1609 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001610 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001611 case ELF::SHT_MIPS_REGINFO:
1612 case ELF::SHT_MIPS_OPTIONS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001613 // Nothing to do.
1614 break;
1615
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001616 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001617 sh_link = SymbolTableIndex;
1618 sh_info = GroupSymbolIndex;
1619 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001620
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001621 default:
1622 assert(0 && "FIXME: sh_type value not supported!");
1623 break;
1624 }
1625
Logan Chien4b724422013-02-05 14:18:59 +00001626 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1627 Section.getType() == ELF::SHT_ARM_EXIDX) {
1628 StringRef SecName(Section.getSectionName());
1629 if (SecName == ".ARM.exidx") {
1630 sh_link = SectionIndexMap.lookup(
1631 Asm.getContext().getELFSection(".text",
1632 ELF::SHT_PROGBITS,
1633 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1634 SectionKind::getText()));
1635 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001636 StringRef GroupName =
1637 Section.getGroup() ? Section.getGroup()->getName() : "";
1638 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1639 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1640 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1641 GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001642 }
1643 }
1644
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001645 WriteSecHdrEntry(SectionStringTableIndex[&Section], Section.getType(),
1646 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1647 Alignment, Section.getEntrySize());
1648}
1649
Jan Sjödin30a52de2011-02-28 21:45:04 +00001650bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001651 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001652 !SD.getSection().isVirtualSection();
1653}
1654
Jan Sjödin30a52de2011-02-28 21:45:04 +00001655uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001656 uint64_t Ret = 0;
1657 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1658 ++i) {
1659 const MCFragment &F = *i;
1660 assert(F.getKind() == MCFragment::FT_Data);
1661 Ret += cast<MCDataFragment>(F).getContents().size();
1662 }
1663 return Ret;
1664}
1665
Jan Sjödin30a52de2011-02-28 21:45:04 +00001666uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1667 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001668 if (IsELFMetaDataSection(SD))
1669 return DataSectionSize(SD);
1670 return Layout.getSectionFileSize(&SD);
1671}
1672
Jan Sjödin30a52de2011-02-28 21:45:04 +00001673uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1674 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001675 if (IsELFMetaDataSection(SD))
1676 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001677 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001678}
1679
Rafael Espindola1557fd62011-03-20 18:44:20 +00001680void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1681 const MCAsmLayout &Layout,
1682 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001683 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1684
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001685 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001686 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001687
1688 if (IsELFMetaDataSection(SD)) {
1689 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1690 ++i) {
1691 const MCFragment &F = *i;
1692 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001693 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001694 }
1695 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001696 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001697 }
1698}
1699
Rafael Espindola1557fd62011-03-20 18:44:20 +00001700void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1701 const GroupMapTy &GroupMap,
1702 const MCAsmLayout &Layout,
1703 const SectionIndexMapTy &SectionIndexMap,
1704 const SectionOffsetMapTy &SectionOffsetMap) {
1705 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001706
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001707 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001708 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001709
1710 for (SectionIndexMapTy::const_iterator i=
1711 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1712 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001713 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001714 }
1715
Matt Fleming6c1ad482010-08-16 18:57:57 +00001716 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001717 uint64_t FirstSectionSize =
1718 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1719 uint32_t FirstSectionLink =
1720 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1721 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001722
Rafael Espindola1557fd62011-03-20 18:44:20 +00001723 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001724 const MCSectionELF &Section = *Sections[i];
1725 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1726 uint32_t GroupSymbolIndex;
1727 if (Section.getType() != ELF::SHT_GROUP)
1728 GroupSymbolIndex = 0;
1729 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001730 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1731 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001732
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001733 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001734
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001735 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001736 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001737 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001738 }
1739}
1740
Rafael Espindola1557fd62011-03-20 18:44:20 +00001741void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1742 std::vector<const MCSectionELF*> &Sections) {
1743 for (MCAssembler::iterator it = Asm.begin(),
1744 ie = Asm.end(); it != ie; ++it) {
1745 const MCSectionELF &Section =
1746 static_cast<const MCSectionELF &>(it->getSection());
1747 if (Section.getType() == ELF::SHT_GROUP)
1748 Sections.push_back(&Section);
1749 }
1750
1751 for (MCAssembler::iterator it = Asm.begin(),
1752 ie = Asm.end(); it != ie; ++it) {
1753 const MCSectionELF &Section =
1754 static_cast<const MCSectionELF &>(it->getSection());
1755 if (Section.getType() != ELF::SHT_GROUP &&
1756 Section.getType() != ELF::SHT_REL &&
1757 Section.getType() != ELF::SHT_RELA)
1758 Sections.push_back(&Section);
1759 }
1760
1761 for (MCAssembler::iterator it = Asm.begin(),
1762 ie = Asm.end(); it != ie; ++it) {
1763 const MCSectionELF &Section =
1764 static_cast<const MCSectionELF &>(it->getSection());
1765 if (Section.getType() == ELF::SHT_REL ||
1766 Section.getType() == ELF::SHT_RELA)
1767 Sections.push_back(&Section);
1768 }
1769}
1770
1771void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1772 const MCAsmLayout &Layout) {
1773 GroupMapTy GroupMap;
1774 RevGroupMapTy RevGroupMap;
1775 SectionIndexMapTy SectionIndexMap;
1776
1777 unsigned NumUserSections = Asm.size();
1778
David Blaikiee06e8012014-04-11 22:11:50 +00001779 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001780
Rafael Espindola1557fd62011-03-20 18:44:20 +00001781 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1782 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1783
1784 const unsigned NumUserAndRelocSections = Asm.size();
1785 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1786 RevGroupMap, SectionIndexMap, RelMap);
1787 const unsigned AllSections = Asm.size();
1788 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1789
1790 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1791
1792 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001793 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1794 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001795
1796 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1797
1798 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1799 const_cast<MCAsmLayout&>(Layout),
1800 SectionIndexMap,
1801 RelMap);
1802
1803 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1804 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1805 sizeof(ELF::Elf32_Ehdr);
1806 uint64_t FileOff = HeaderSize;
1807
1808 std::vector<const MCSectionELF*> Sections;
1809 ComputeSectionOrder(Asm, Sections);
1810 unsigned NumSections = Sections.size();
1811 SectionOffsetMapTy SectionOffsetMap;
1812 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1813 const MCSectionELF &Section = *Sections[i];
1814 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1815
1816 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1817
1818 // Remember the offset into the file for this section.
1819 SectionOffsetMap[&Section] = FileOff;
1820
1821 // Get the size of the section in the output file (including padding).
1822 FileOff += GetSectionFileSize(Layout, SD);
1823 }
1824
1825 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1826
1827 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1828
1829 uint64_t SectionHeaderEntrySize = is64Bit() ?
1830 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1831 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1832
1833 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1834 const MCSectionELF &Section = *Sections[i];
1835 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1836
1837 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1838
1839 // Remember the offset into the file for this section.
1840 SectionOffsetMap[&Section] = FileOff;
1841
1842 // Get the size of the section in the output file (including padding).
1843 FileOff += GetSectionFileSize(Layout, SD);
1844 }
1845
1846 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001847 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001848
1849 // ... then the regular sections ...
1850 // + because of .shstrtab
1851 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1852 WriteDataSectionData(Asm, Layout, *Sections[i]);
1853
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001854 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001855 WriteZeros(Padding);
1856
1857 // ... then the section header table ...
1858 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1859 SectionOffsetMap);
1860
Nick Lewycky4eb11432011-10-07 20:56:23 +00001861 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001862 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1863 WriteDataSectionData(Asm, Layout, *Sections[i]);
1864}
1865
Eli Friedmand92d17b2011-03-03 07:24:36 +00001866bool
1867ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1868 const MCSymbolData &DataA,
1869 const MCFragment &FB,
1870 bool InSet,
1871 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001872 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001873 return false;
1874 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1875 Asm, DataA, FB,InSet, IsPCRel);
1876}
1877
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001878MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1879 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001880 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001881 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001882}