blob: 27b607f520efd0e5c6ff715ee9305ea726db2593 [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"
Rafael Espindola97de4742014-07-03 02:01:39 +000031#include "llvm/MC/StringTableBuilder.h"
David Blaikie8019bf82014-04-10 21:53:53 +000032#include "llvm/Support/Compression.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000033#include "llvm/Support/Debug.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000034#include "llvm/Support/ELF.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/Endian.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/ErrorHandling.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000037#include <vector>
38using namespace llvm;
39
Jason W Kimc09e7262011-05-11 22:53:06 +000040#undef DEBUG_TYPE
41#define DEBUG_TYPE "reloc-info"
42
Rafael Espindola29abd972011-12-22 03:38:00 +000043namespace {
Rafael Espindola0ce09712014-03-25 22:43:53 +000044class FragmentWriter {
45 bool IsLittleEndian;
46
47public:
48 FragmentWriter(bool IsLittleEndian);
49 template <typename T> void write(MCDataFragment &F, T Val);
50};
51
Rafael Espindola10be0832014-03-25 23:44:25 +000052typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
53
54class SymbolTableWriter {
55 MCAssembler &Asm;
56 FragmentWriter &FWriter;
57 bool Is64Bit;
58 SectionIndexMapTy &SectionIndexMap;
59
60 // The symbol .symtab fragment we are writting to.
61 MCDataFragment *SymtabF;
62
63 // .symtab_shndx fragment we are writting to.
64 MCDataFragment *ShndxF;
65
66 // The numbel of symbols written so far.
67 unsigned NumWritten;
68
69 void createSymtabShndx();
70
71 template <typename T> void write(MCDataFragment &F, T Value);
72
73public:
74 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
75 SectionIndexMapTy &SectionIndexMap,
76 MCDataFragment *SymtabF);
77
78 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
79 uint8_t other, uint32_t shndx, bool Reserved);
80};
81
Rafael Espindola5904e122014-03-29 06:26:49 +000082struct ELFRelocationEntry {
83 uint64_t Offset; // Where is the relocation.
Rafael Espindolab6613022014-10-17 01:48:58 +000084 const MCSymbol *Symbol; // The symbol to relocate with.
Rafael Espindola5904e122014-03-29 06:26:49 +000085 unsigned Type; // The type of the relocation.
86 uint64_t Addend; // The addend to use.
87
88 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
89 uint64_t Addend)
Rafael Espindolab6613022014-10-17 01:48:58 +000090 : Offset(Offset), Symbol(Symbol), Type(Type), Addend(Addend) {}
Rafael Espindola5904e122014-03-29 06:26:49 +000091};
92
Rafael Espindola29abd972011-12-22 03:38:00 +000093class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola0ce09712014-03-25 22:43:53 +000094 FragmentWriter FWriter;
95
Rafael Espindola29abd972011-12-22 03:38:00 +000096 protected:
97
98 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
99 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
100 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000101 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
Rafael Espindola29abd972011-12-22 03:38:00 +0000102 bool Used, bool Renamed);
Rafael Espindola39f50422014-04-28 14:24:44 +0000103 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
Rafael Espindola29abd972011-12-22 03:38:00 +0000104 static bool IsELFMetaDataSection(const MCSectionData &SD);
105 static uint64_t DataSectionSize(const MCSectionData &SD);
106 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
107 const MCSectionData &SD);
108 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
109 const MCSectionData &SD);
110
111 void WriteDataSectionData(MCAssembler &Asm,
112 const MCAsmLayout &Layout,
113 const MCSectionELF &Section);
114
115 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
116 return Kind == X86::reloc_riprel_4byte ||
117 Kind == X86::reloc_riprel_4byte_movq_load;
118 }*/
119
120 /// ELFSymbolData - Helper struct for containing some precomputed
121 /// information on symbols.
122 struct ELFSymbolData {
123 MCSymbolData *SymbolData;
124 uint64_t StringIndex;
125 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000126 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000127
128 // Support lexicographic sorting.
129 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolab6613022014-10-17 01:48:58 +0000130 unsigned LHSType = MCELF::GetType(*SymbolData);
131 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
132 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
133 return false;
134 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
135 return true;
136 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
137 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000138 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000139 }
140 };
141
Rafael Espindola29abd972011-12-22 03:38:00 +0000142 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000143 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000144
145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
146 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
147 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
148
Rafael Espindola5904e122014-03-29 06:26:49 +0000149 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
150 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000151 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000152
153 /// @}
154 /// @name Symbol Table Data
155 /// @{
156
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000157 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000158 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000159 std::vector<ELFSymbolData> LocalSymbolData;
160 std::vector<ELFSymbolData> ExternalSymbolData;
161 std::vector<ELFSymbolData> UndefinedSymbolData;
162
163 /// @}
164
165 bool NeedsGOT;
166
Rafael Espindola29abd972011-12-22 03:38:00 +0000167 // This holds the symbol table index of the last local symbol.
168 unsigned LastLocalSymbolIndex;
169 // This holds the .strtab section index.
170 unsigned StringTableIndex;
171 // This holds the .symtab section index.
172 unsigned SymbolTableIndex;
173
174 unsigned ShstrtabIndex;
175
176
Rafael Espindola29abd972011-12-22 03:38:00 +0000177 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000178 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
179 bool hasRelocationAddend() const {
180 return TargetObjectWriter->hasRelocationAddend();
181 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000182 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000183 bool IsPCRel) const {
184 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000185 }
186
Rafael Espindola29abd972011-12-22 03:38:00 +0000187 public:
Rafael Espindola0ce09712014-03-25 22:43:53 +0000188 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
189 bool IsLittleEndian)
190 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000191 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000192
193 virtual ~ELFObjectWriter();
194
195 void WriteWord(uint64_t W) {
196 if (is64Bit())
197 Write64(W);
198 else
199 Write32(W);
200 }
201
Rafael Espindola0ce09712014-03-25 22:43:53 +0000202 template <typename T> void write(MCDataFragment &F, T Value) {
203 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000204 }
205
Jack Carter1bd90ff2013-01-30 02:09:52 +0000206 void WriteHeader(const MCAssembler &Asm,
207 uint64_t SectionDataSize,
Rafael Espindola29abd972011-12-22 03:38:00 +0000208 unsigned NumberOfSections);
209
Rafael Espindola10be0832014-03-25 23:44:25 +0000210 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000211 const MCAsmLayout &Layout);
212
Rafael Espindola10be0832014-03-25 23:44:25 +0000213 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000214 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000215 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000216
Rafael Espindolab60c8292014-04-29 12:46:50 +0000217 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
218 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000219 const MCSymbolData *SD, uint64_t C,
220 unsigned Type) const;
221
Rafael Espindola26585542015-01-19 21:11:14 +0000222 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000223 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000224 MCValue Target, bool &IsPCRel,
225 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000226
227 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
228 const MCSymbol *S);
229
230 // Map from a group section to the signature symbol
231 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
232 // Map from a signature symbol to the group section
233 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
234 // Map from a section to the section with the relocations
235 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
236 // Map from a section to its offset
237 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
238
Rafael Espindola022bb762014-03-24 03:43:21 +0000239 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000240 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000241 /// \param Asm - The assembler.
242 /// \param SectionIndexMap - Maps a section to its index.
243 /// \param RevGroupMap - Maps a signature symbol to the group section.
244 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000245 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000246 const SectionIndexMapTy &SectionIndexMap,
Benjamin Kramer04f9da82014-09-19 12:26:38 +0000247 const RevGroupMapTy &RevGroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000248 unsigned NumRegularSections);
249
Rafael Espindolaead85492015-02-17 20:31:13 +0000250 void computeIndexMap(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000251 SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaead85492015-02-17 20:31:13 +0000252 RelMapTy &RelMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000253
Rafael Espindolaead85492015-02-17 20:31:13 +0000254 MCSectionData *createRelocationSection(MCAssembler &Asm,
255 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000256
David Blaikie8019bf82014-04-10 21:53:53 +0000257 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
258
Rafael Espindola29abd972011-12-22 03:38:00 +0000259 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
260 const RelMapTy &RelMap);
261
262 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolaef6baea2015-02-11 23:11:18 +0000263 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000264
265 // Create the sections that show up in the symbol table. Currently
266 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaead85492015-02-17 20:31:13 +0000267 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000268 GroupMapTy &GroupMap,
269 RevGroupMapTy &RevGroupMap,
270 SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaead85492015-02-17 20:31:13 +0000271 RelMapTy &RelMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000272
Craig Topper34a61bc2014-03-08 07:02:02 +0000273 void ExecutePostLayoutBinding(MCAssembler &Asm,
274 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000275
Chandler Carruthd99f4272015-02-13 07:52:39 +0000276 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000277 const MCAsmLayout &Layout,
278 const SectionIndexMapTy &SectionIndexMap,
279 const SectionOffsetMapTy &SectionOffsetMap);
280
281 void ComputeSectionOrder(MCAssembler &Asm,
282 std::vector<const MCSectionELF*> &Sections);
283
284 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
285 uint64_t Address, uint64_t Offset,
286 uint64_t Size, uint32_t Link, uint32_t Info,
287 uint64_t Alignment, uint64_t EntrySize);
288
289 void WriteRelocationsFragment(const MCAssembler &Asm,
290 MCDataFragment *F,
291 const MCSectionData *SD);
292
Craig Topper34a61bc2014-03-08 07:02:02 +0000293 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000294 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
295 const MCSymbolData &DataA,
296 const MCFragment &FB,
297 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000298 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000299
Craig Topper34a61bc2014-03-08 07:02:02 +0000300 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Chandler Carruthd99f4272015-02-13 07:52:39 +0000301 void WriteSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000302 const SectionIndexMapTy &SectionIndexMap,
303 uint32_t GroupSymbolIndex,
304 uint64_t Offset, uint64_t Size, uint64_t Alignment,
305 const MCSectionELF &Section);
306 };
307}
308
Rafael Espindola0ce09712014-03-25 22:43:53 +0000309FragmentWriter::FragmentWriter(bool IsLittleEndian)
310 : IsLittleEndian(IsLittleEndian) {}
311
312template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
313 if (IsLittleEndian)
314 Val = support::endian::byte_swap<T, support::little>(Val);
315 else
316 Val = support::endian::byte_swap<T, support::big>(Val);
317 const char *Start = (const char *)&Val;
318 F.getContents().append(Start, Start + sizeof(T));
319}
320
Rafael Espindola10be0832014-03-25 23:44:25 +0000321void SymbolTableWriter::createSymtabShndx() {
322 if (ShndxF)
323 return;
324
325 MCContext &Ctx = Asm.getContext();
326 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000327 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000328 MCSectionData *SymtabShndxSD =
329 &Asm.getOrCreateSectionData(*SymtabShndxSection);
330 SymtabShndxSD->setAlignment(4);
331 ShndxF = new MCDataFragment(SymtabShndxSD);
332 unsigned Index = SectionIndexMap.size() + 1;
333 SectionIndexMap[SymtabShndxSection] = Index;
334
335 for (unsigned I = 0; I < NumWritten; ++I)
336 write(*ShndxF, uint32_t(0));
337}
338
339template <typename T>
340void SymbolTableWriter::write(MCDataFragment &F, T Value) {
341 FWriter.write(F, Value);
342}
343
344SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
345 bool Is64Bit,
346 SectionIndexMapTy &SectionIndexMap,
347 MCDataFragment *SymtabF)
348 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
349 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
350 NumWritten(0) {}
351
352void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
353 uint64_t size, uint8_t other,
354 uint32_t shndx, bool Reserved) {
355 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
356
357 if (LargeIndex)
358 createSymtabShndx();
359
360 if (ShndxF) {
361 if (LargeIndex)
362 write(*ShndxF, shndx);
363 else
364 write(*ShndxF, uint32_t(0));
365 }
366
367 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
368
369 raw_svector_ostream OS(SymtabF->getContents());
370
371 if (Is64Bit) {
372 write(*SymtabF, name); // st_name
373 write(*SymtabF, info); // st_info
374 write(*SymtabF, other); // st_other
375 write(*SymtabF, Index); // st_shndx
376 write(*SymtabF, value); // st_value
377 write(*SymtabF, size); // st_size
378 } else {
379 write(*SymtabF, name); // st_name
380 write(*SymtabF, uint32_t(value)); // st_value
381 write(*SymtabF, uint32_t(size)); // st_size
382 write(*SymtabF, info); // st_info
383 write(*SymtabF, other); // st_other
384 write(*SymtabF, Index); // st_shndx
385 }
386
387 ++NumWritten;
388}
389
Jan Sjödin30a52de2011-02-28 21:45:04 +0000390bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
391 const MCFixupKindInfo &FKI =
392 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
393
394 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
395}
396
397bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
398 switch (Variant) {
399 default:
400 return false;
401 case MCSymbolRefExpr::VK_GOT:
402 case MCSymbolRefExpr::VK_PLT:
403 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000404 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000405 case MCSymbolRefExpr::VK_TPOFF:
406 case MCSymbolRefExpr::VK_TLSGD:
407 case MCSymbolRefExpr::VK_GOTTPOFF:
408 case MCSymbolRefExpr::VK_INDNTPOFF:
409 case MCSymbolRefExpr::VK_NTPOFF:
410 case MCSymbolRefExpr::VK_GOTNTPOFF:
411 case MCSymbolRefExpr::VK_TLSLDM:
412 case MCSymbolRefExpr::VK_DTPOFF:
413 case MCSymbolRefExpr::VK_TLSLD:
414 return true;
415 }
416}
417
Jason W Kim96f4c012010-11-15 16:18:39 +0000418ELFObjectWriter::~ELFObjectWriter()
419{}
420
Matt Fleming6c1ad482010-08-16 18:57:57 +0000421// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000422void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
423 uint64_t SectionDataSize,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000424 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000425 // ELF Header
426 // ----------
427 //
428 // Note
429 // ----
430 // emitWord method behaves differently for ELF32 and ELF64, writing
431 // 4 bytes in the former and 8 in the latter.
432
433 Write8(0x7f); // e_ident[EI_MAG0]
434 Write8('E'); // e_ident[EI_MAG1]
435 Write8('L'); // e_ident[EI_MAG2]
436 Write8('F'); // e_ident[EI_MAG3]
437
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000438 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000439
440 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000441 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000442
443 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000444 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000445 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000446 Write8(0); // e_ident[EI_ABIVERSION]
447
448 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
449
450 Write16(ELF::ET_REL); // e_type
451
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000452 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000453
454 Write32(ELF::EV_CURRENT); // e_version
455 WriteWord(0); // e_entry, no entry point in .o file
456 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000457 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramer896bd7e2010-08-17 17:02:29 +0000458 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000459
Jason W Kim4761fba2011-02-04 21:41:11 +0000460 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000461 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000462
463 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000464 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000465
466 Write16(0); // e_phentsize = prog header entry size
467 Write16(0); // e_phnum = # prog header entries = 0
468
469 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000470 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000471
472 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000473 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000474 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000475 else
476 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000477
478 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000479 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000480 Write16(ELF::SHN_XINDEX);
481 else
482 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000483}
484
Rafael Espindolafee224f2014-04-30 21:51:13 +0000485uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000486 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000487 if (Data.isCommon() && Data.isExternal())
488 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000489
Rafael Espindolafee224f2014-04-30 21:51:13 +0000490 uint64_t Res;
491 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000492 return 0;
493
Rafael Espindolafee224f2014-04-30 21:51:13 +0000494 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000495 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000496
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000497 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000498}
499
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000500void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
501 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000502 // The presence of symbol versions causes undefined symbols and
503 // versions declared with @@@ to be renamed.
504
David Blaikie583a31c2014-04-18 18:24:25 +0000505 for (MCSymbolData &OriginalData : Asm.symbols()) {
506 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000507
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000508 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000509 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000510 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000511 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
512 if (!Ref)
513 continue;
514 const MCSymbol &Symbol = Ref->getSymbol();
515 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000516
Benjamin Kramer14807272010-10-27 19:53:52 +0000517 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000518 size_t Pos = AliasName.find('@');
519 if (Pos == StringRef::npos)
520 continue;
521
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000522 // Aliases defined with .symvar copy the binding from the symbol they alias.
523 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000524 OriginalData.setExternal(SD.isExternal());
525 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000526
Benjamin Kramer14807272010-10-27 19:53:52 +0000527 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000528 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
529 continue;
530
Rafael Espindola26496e62010-10-27 17:56:18 +0000531 // FIXME: produce a better error message.
532 if (Symbol.isUndefined() && Rest.startswith("@@") &&
533 !Rest.startswith("@@@"))
534 report_fatal_error("A @@ version cannot be undefined");
535
Benjamin Kramer14807272010-10-27 19:53:52 +0000536 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000537 }
538}
539
Roman Divacky5a1c5492014-01-07 20:17:03 +0000540static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
541 uint8_t Type = newType;
542
543 // Propagation rules:
544 // IFUNC > FUNC > OBJECT > NOTYPE
545 // TLS_OBJECT > OBJECT > NOTYPE
546 //
547 // dont let the new type degrade the old type
548 switch (origType) {
549 default:
550 break;
551 case ELF::STT_GNU_IFUNC:
552 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
553 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
554 Type = ELF::STT_GNU_IFUNC;
555 break;
556 case ELF::STT_FUNC:
557 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
558 Type == ELF::STT_TLS)
559 Type = ELF::STT_FUNC;
560 break;
561 case ELF::STT_OBJECT:
562 if (Type == ELF::STT_NOTYPE)
563 Type = ELF::STT_OBJECT;
564 break;
565 case ELF::STT_TLS:
566 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
567 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
568 Type = ELF::STT_TLS;
569 break;
570 }
571
572 return Type;
573}
574
Rafael Espindola10be0832014-03-25 23:44:25 +0000575void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000576 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000577 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000578 assert((!OrigData.getFragment() ||
579 (&OrigData.getFragment()->getParent()->getSection() ==
580 &OrigData.getSymbol().getSection())) &&
581 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000582 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000583
584 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
585 // SHN_COMMON.
586 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000587
Jack Carter2f8d9d92013-02-19 21:57:35 +0000588 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000589 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000590 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000591 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000592 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000593 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
594 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000595 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000596 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000597
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000598 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000599 // 2 bits
600 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000601 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000602 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000603
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000604 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000605 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000606
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000607 const MCExpr *ESize = OrigData.getSize();
608 if (!ESize && Base)
609 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000610
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000611 if (ESize) {
612 int64_t Res;
613 if (!ESize->EvaluateAsAbsolute(Res, Layout))
614 report_fatal_error("Size expression must be absolute.");
615 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000616 }
617
618 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000619 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
620 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000621}
622
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000623void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000624 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000625 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000626 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000627 // The string table must be emitted first because we need the index
628 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000629
630 // FIXME: Make sure the start of the symbol table is aligned.
631
Rafael Espindola10be0832014-03-25 23:44:25 +0000632 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
633
Matt Fleming6c1ad482010-08-16 18:57:57 +0000634 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000635 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000636
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000637 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000638 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
639 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000640 }
641
Matt Fleming6c1ad482010-08-16 18:57:57 +0000642 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000643 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
644
Matt Fleming6c1ad482010-08-16 18:57:57 +0000645 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
646 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000647 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000648 }
649
Matt Fleming6c1ad482010-08-16 18:57:57 +0000650 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
651 ELFSymbolData &MSD = ExternalSymbolData[i];
652 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000653 assert(((Data.getFlags() & ELF_STB_Global) ||
654 (Data.getFlags() & ELF_STB_Weak)) &&
655 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000656 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000657 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000658 LastLocalSymbolIndex++;
659 }
660
661 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
662 ELFSymbolData &MSD = UndefinedSymbolData[i];
663 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000664 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000665 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000666 LastLocalSymbolIndex++;
667 }
668}
669
Rafael Espindola5904e122014-03-29 06:26:49 +0000670// It is always valid to create a relocation with a symbol. It is preferable
671// to use a relocation with a section if that is possible. Using the section
672// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000673bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
674 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000675 const MCSymbolData *SD,
676 uint64_t C,
677 unsigned Type) const {
678 // A PCRel relocation to an absolute value has no symbol (or section). We
679 // represent that with a relocation to a null section.
680 if (!RefA)
681 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000682
Rafael Espindola5904e122014-03-29 06:26:49 +0000683 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
684 switch (Kind) {
685 default:
686 break;
687 // The .odp creation emits a relocation against the symbol ".TOC." which
688 // create a R_PPC64_TOC relocation. However the relocation symbol name
689 // in final object creation should be NULL, since the symbol does not
690 // really exist, it is just the reference to TOC base for the current
691 // object file. Since the symbol is undefined, returning false results
692 // in a relocation with a null section which is the desired result.
693 case MCSymbolRefExpr::VK_PPC_TOCBASE:
694 return false;
695
696 // These VariantKind cause the relocation to refer to something other than
697 // the symbol itself, like a linker generated table. Since the address of
698 // symbol is not relevant, we cannot replace the symbol with the
699 // section and patch the difference in the addend.
700 case MCSymbolRefExpr::VK_GOT:
701 case MCSymbolRefExpr::VK_PLT:
702 case MCSymbolRefExpr::VK_GOTPCREL:
703 case MCSymbolRefExpr::VK_Mips_GOT:
704 case MCSymbolRefExpr::VK_PPC_GOT_LO:
705 case MCSymbolRefExpr::VK_PPC_GOT_HI:
706 case MCSymbolRefExpr::VK_PPC_GOT_HA:
707 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000708 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000709
Rafael Espindola5904e122014-03-29 06:26:49 +0000710 // An undefined symbol is not in any section, so the relocation has to point
711 // to the symbol itself.
712 const MCSymbol &Sym = SD->getSymbol();
713 if (Sym.isUndefined())
714 return true;
715
716 unsigned Binding = MCELF::GetBinding(*SD);
717 switch(Binding) {
718 default:
719 llvm_unreachable("Invalid Binding");
720 case ELF::STB_LOCAL:
721 break;
722 case ELF::STB_WEAK:
723 // If the symbol is weak, it might be overridden by a symbol in another
724 // file. The relocation has to point to the symbol so that the linker
725 // can update it.
726 return true;
727 case ELF::STB_GLOBAL:
728 // Global ELF symbols can be preempted by the dynamic linker. The relocation
729 // has to point to the symbol for a reason analogous to the STB_WEAK case.
730 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000731 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000732
Rafael Espindola5904e122014-03-29 06:26:49 +0000733 // If a relocation points to a mergeable section, we have to be careful.
734 // If the offset is zero, a relocation with the section will encode the
735 // same information. With a non-zero offset, the situation is different.
736 // For example, a relocation can point 42 bytes past the end of a string.
737 // If we change such a relocation to use the section, the linker would think
738 // that it pointed to another string and subtracting 42 at runtime will
739 // produce the wrong value.
740 auto &Sec = cast<MCSectionELF>(Sym.getSection());
741 unsigned Flags = Sec.getFlags();
742 if (Flags & ELF::SHF_MERGE) {
743 if (C != 0)
744 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000745
746 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
747 // only handle section relocations to mergeable sections if using RELA.
748 if (!hasRelocationAddend())
749 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000750 }
751
Rafael Espindola5904e122014-03-29 06:26:49 +0000752 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000753 // are just an offset (@tpoff), require a symbol in gold versions before
754 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
755 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000756 if (Flags & ELF::SHF_TLS)
757 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000758
Rafael Espindola9ef84412014-04-11 19:18:01 +0000759 // If the symbol is a thumb function the final relocation must set the lowest
760 // bit. With a symbol that is done by just having the symbol have that bit
761 // set, so we would lose the bit if we relocated with the section.
762 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000763 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000764 return true;
765
Ulrich Weigand46797c62014-07-20 23:15:06 +0000766 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000767 return true;
768 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000769}
770
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000771static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
772 const MCSymbol &Sym = Ref.getSymbol();
773
774 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
775 return &Sym;
776
777 if (!Sym.isVariable())
778 return nullptr;
779
780 const MCExpr *Expr = Sym.getVariableValue();
781 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
782 if (!Inner)
783 return nullptr;
784
785 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
786 return &Inner->getSymbol();
787 return nullptr;
788}
789
Rafael Espindola26585542015-01-19 21:11:14 +0000790void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000791 const MCAsmLayout &Layout,
792 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000793 const MCFixup &Fixup, MCValue Target,
794 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000795 const MCSectionData *FixupSection = Fragment->getParent();
796 uint64_t C = Target.getConstant();
797 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000798
Rafael Espindola5904e122014-03-29 06:26:49 +0000799 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
800 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
801 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000802
Rafael Espindola5904e122014-03-29 06:26:49 +0000803 // Let A, B and C being the components of Target and R be the location of
804 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
805 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000806
Rafael Espindola5904e122014-03-29 06:26:49 +0000807 // In general, ELF has no relocations for -B. It can only represent (A + C)
808 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
809 // replace B to implement it: (A - R - K + C)
810 if (IsPCRel)
811 Asm.getContext().FatalError(
812 Fixup.getLoc(),
813 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000814
Rafael Espindola5904e122014-03-29 06:26:49 +0000815 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000816
Rafael Espindola5904e122014-03-29 06:26:49 +0000817 if (SymB.isUndefined())
818 Asm.getContext().FatalError(
819 Fixup.getLoc(),
820 Twine("symbol '") + SymB.getName() +
821 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000822
Rafael Espindola5904e122014-03-29 06:26:49 +0000823 assert(!SymB.isAbsolute() && "Should have been folded");
824 const MCSection &SecB = SymB.getSection();
825 if (&SecB != &FixupSection->getSection())
826 Asm.getContext().FatalError(
827 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000828
Rafael Espindola5904e122014-03-29 06:26:49 +0000829 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
830 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
831 uint64_t K = SymBOffset - FixupOffset;
832 IsPCRel = true;
833 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000834 }
835
Rafael Espindola5904e122014-03-29 06:26:49 +0000836 // We either rejected the fixup or folded B into C at this point.
837 const MCSymbolRefExpr *RefA = Target.getSymA();
838 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
839 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
840
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000841 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000842 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000843 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
844 C += Layout.getSymbolOffset(SymAD);
845
846 uint64_t Addend = 0;
847 if (hasRelocationAddend()) {
848 Addend = C;
849 C = 0;
850 }
851
852 FixedValue = C;
853
854 // FIXME: What is this!?!?
855 MCSymbolRefExpr::VariantKind Modifier =
856 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000857 if (RelocNeedsGOT(Modifier))
858 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000859
Rafael Espindola5904e122014-03-29 06:26:49 +0000860 if (!RelocateWithSymbol) {
861 const MCSection *SecA =
862 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000863 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
864 MCSymbol *SectionSymbol =
865 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
866 : nullptr;
867 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000868 Relocations[FixupSection].push_back(Rec);
869 return;
870 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000871
Rafael Espindola5904e122014-03-29 06:26:49 +0000872 if (SymA) {
873 if (const MCSymbol *R = Renames.lookup(SymA))
874 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000875
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000876 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
877 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000878 else
879 UsedInReloc.insert(SymA);
880 }
881 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
882 Relocations[FixupSection].push_back(Rec);
883 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000884}
885
886
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000887uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000888ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
889 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000890 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000891 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000892}
893
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000894bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
895 const MCSymbolData &Data, bool Used,
896 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000897 const MCSymbol &Symbol = Data.getSymbol();
898 if (Symbol.isVariable()) {
899 const MCExpr *Expr = Symbol.getVariableValue();
900 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
901 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
902 return false;
903 }
904 }
Rafael Espindola16145972010-11-01 14:28:48 +0000905
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000906 if (Used)
907 return true;
908
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000909 if (Renamed)
910 return false;
911
Rafael Espindola45834a02010-10-29 23:09:31 +0000912 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
913 return true;
914
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000915 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000916 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000917 if (Base && Base->isUndefined())
918 return false;
919 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000920
Jan Sjödin30a52de2011-02-28 21:45:04 +0000921 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000922 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000923 return false;
924
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000925 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000926 return false;
927
928 return true;
929}
930
Rafael Espindola39f50422014-04-28 14:24:44 +0000931bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000932 if (Data.isExternal())
933 return false;
934
935 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000936 if (Symbol.isDefined())
937 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000938
Rafael Espindola39f50422014-04-28 14:24:44 +0000939 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000940 return false;
941
942 return true;
943}
944
Rafael Espindolaead85492015-02-17 20:31:13 +0000945void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000946 SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaead85492015-02-17 20:31:13 +0000947 RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000948 unsigned Index = 1;
949 for (MCAssembler::iterator it = Asm.begin(),
950 ie = Asm.end(); it != ie; ++it) {
951 const MCSectionELF &Section =
952 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000953 if (Section.getType() != ELF::SHT_GROUP)
954 continue;
955 SectionIndexMap[&Section] = Index++;
956 }
957
958 for (MCAssembler::iterator it = Asm.begin(),
959 ie = Asm.end(); it != ie; ++it) {
Rafael Espindolaead85492015-02-17 20:31:13 +0000960 const MCSectionData &SD = *it;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000961 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000962 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000963 if (Section.getType() == ELF::SHT_GROUP ||
964 Section.getType() == ELF::SHT_REL ||
965 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000966 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000967 SectionIndexMap[&Section] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000968 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
969 const MCSectionELF *RelSection =
970 static_cast<const MCSectionELF *>(&RelSD->getSection());
971 RelMap[&Section] = RelSection;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000972 SectionIndexMap[RelSection] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000973 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000974 }
975}
976
Rafael Espindola022bb762014-03-24 03:43:21 +0000977void
978ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
979 const SectionIndexMapTy &SectionIndexMap,
Benjamin Kramer04f9da82014-09-19 12:26:38 +0000980 const RevGroupMapTy &RevGroupMap,
Rafael Espindola022bb762014-03-24 03:43:21 +0000981 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000982 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000983 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000984 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000985 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000986 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
987 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
988 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000989 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000990 }
991
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000992 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000993 for (MCSymbolData &SD : Asm.symbols()) {
994 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000995
Rafael Espindola16145972010-11-01 14:28:48 +0000996 bool Used = UsedInReloc.count(&Symbol);
997 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000998 bool isSignature = RevGroupMap.count(&Symbol);
999
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001000 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001001 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001002 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001003 continue;
1004
Matt Fleming6c1ad482010-08-16 18:57:57 +00001005 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001006 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001007 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001008
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001009 // Undefined symbols are global, but this is the first place we
1010 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001011 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001012 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001013 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001014 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001015 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001016 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001017 }
1018
Rafael Espindola022bb762014-03-24 03:43:21 +00001019 if (!BaseSymbol) {
1020 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001021 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001022 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001023 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001024 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001025 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001026 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001027 else
1028 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001029 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001030 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001031 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001032 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001033 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001034 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001035 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001036 }
1037
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001038 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1039 // in defined ones.
1040 //
1041 // FIXME: All name handling should be done before we get to the writer,
1042 // including dealing with GNU-style version suffixes. Fixing this isn’t
1043 // trivial.
1044 //
1045 // We thus have to be careful to not perform the symbol version replacement
1046 // blindly:
1047 //
1048 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1049 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1050 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1051 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1052 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1053 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1054 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1055 // "__imp_?" or "__imp_@?".
1056 //
1057 // It would have been interesting to perform the MS mangling prefix check
1058 // only when the target triple is of the form *-pc-windows-elf. But, it
1059 // seems that this information is not easily accessible from the
1060 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001061 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001062 if (!Name.startswith("?") && !Name.startswith("@?") &&
1063 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1064 // This symbol isn't following the MSVC C++ name mangling convention. We
1065 // can thus safely interpret the @@@ in symbol names as specifying symbol
1066 // versioning.
1067 SmallString<32> Buf;
1068 size_t Pos = Name.find("@@@");
1069 if (Pos != StringRef::npos) {
1070 Buf += Name.substr(0, Pos);
1071 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1072 Buf += Name.substr(Pos + Skip);
1073 Name = Buf;
1074 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001075 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001076
1077 // Sections have their own string table
1078 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1079 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001080
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001081 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1082 UndefinedSymbolData.push_back(MSD);
1083 else if (Local)
1084 LocalSymbolData.push_back(MSD);
1085 else
1086 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001087 }
1088
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001089 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1090 StrTabBuilder.add(*i);
1091
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001092 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001093
1094 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1095 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1096
Rafael Espindolab6613022014-10-17 01:48:58 +00001097 for (ELFSymbolData &MSD : LocalSymbolData)
1098 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1099 ? 0
1100 : StrTabBuilder.getOffset(MSD.Name);
1101 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001102 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1103 for (ELFSymbolData& MSD : UndefinedSymbolData)
1104 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1105
Matt Fleming6c1ad482010-08-16 18:57:57 +00001106 // Symbols are required to be in lexicographic order.
1107 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1108 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1109 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1110
1111 // Set the symbol indices. Local symbols must come before all other
1112 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001113 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001114 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1115 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001116
Matt Fleming6c1ad482010-08-16 18:57:57 +00001117 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1118 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1119 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1120 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1121}
1122
Rafael Espindolaead85492015-02-17 20:31:13 +00001123MCSectionData *
1124ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1125 const MCSectionData &SD) {
1126 if (Relocations[&SD].empty())
1127 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001128
Rafael Espindolaead85492015-02-17 20:31:13 +00001129 MCContext &Ctx = Asm.getContext();
1130 const MCSectionELF &Section =
1131 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001132
Rafael Espindolaead85492015-02-17 20:31:13 +00001133 const StringRef SectionName = Section.getSectionName();
1134 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1135 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001136
Rafael Espindolaead85492015-02-17 20:31:13 +00001137 unsigned EntrySize;
1138 if (hasRelocationAddend())
1139 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1140 else
1141 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001142
Rafael Espindolaead85492015-02-17 20:31:13 +00001143 unsigned Flags = 0;
1144 StringRef Group = "";
1145 if (Section.getFlags() & ELF::SHF_GROUP) {
1146 Flags = ELF::SHF_GROUP;
1147 Group = Section.getGroup()->getName();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001148 }
Rafael Espindolaead85492015-02-17 20:31:13 +00001149
1150 const MCSectionELF *RelaSection = Ctx.getELFSection(
1151 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
1152 Flags, EntrySize, Group);
1153 return &Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001154}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001155
David Blaikiee06e8012014-04-11 22:11:50 +00001156static SmallVector<char, 128>
1157getUncompressedData(MCAsmLayout &Layout,
1158 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001159 SmallVector<char, 128> UncompressedData;
1160 for (const MCFragment &F : Fragments) {
1161 const SmallVectorImpl<char> *Contents;
1162 switch (F.getKind()) {
1163 case MCFragment::FT_Data:
1164 Contents = &cast<MCDataFragment>(F).getContents();
1165 break;
1166 case MCFragment::FT_Dwarf:
1167 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1168 break;
1169 case MCFragment::FT_DwarfFrame:
1170 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1171 break;
1172 default:
1173 llvm_unreachable(
1174 "Not expecting any other fragment types in a debug_* section");
1175 }
1176 UncompressedData.append(Contents->begin(), Contents->end());
1177 }
1178 return UncompressedData;
1179}
1180
1181// Include the debug info compression header:
1182// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1183// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001184static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001185prependCompressionHeader(uint64_t Size,
1186 SmallVectorImpl<char> &CompressedContents) {
David Blaikie8019bf82014-04-10 21:53:53 +00001187 static const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001188 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1189 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001190 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001191 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001192 CompressedContents.insert(CompressedContents.begin(),
1193 Magic.size() + sizeof(Size), 0);
1194 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1195 std::copy(reinterpret_cast<char *>(&Size),
1196 reinterpret_cast<char *>(&Size + 1),
1197 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001198 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001199}
1200
1201// Return a single fragment containing the compressed contents of the whole
1202// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001203static std::unique_ptr<MCDataFragment>
1204getCompressedFragment(MCAsmLayout &Layout,
1205 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001206 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1207
1208 // Gather the uncompressed data from all the fragments, recording the
1209 // alignment fragment, if seen, and any fixups.
1210 SmallVector<char, 128> UncompressedData =
1211 getUncompressedData(Layout, Fragments);
1212
1213 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1214
1215 zlib::Status Success = zlib::compress(
1216 StringRef(UncompressedData.data(), UncompressedData.size()),
1217 CompressedContents);
1218 if (Success != zlib::StatusOK)
1219 return nullptr;
1220
David Blaikie76d3a3c2014-04-18 21:52:26 +00001221 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1222 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001223
1224 return CompressedFragment;
1225}
1226
David Blaikie39fa6a22014-04-25 00:48:01 +00001227typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1228DefiningSymbolMap;
1229
1230static void UpdateSymbols(const MCAsmLayout &Layout,
1231 const std::vector<MCSymbolData *> &Symbols,
1232 MCFragment &NewFragment) {
1233 for (MCSymbolData *Sym : Symbols) {
1234 Sym->setOffset(Sym->getOffset() +
1235 Layout.getFragmentOffset(Sym->getFragment()));
1236 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001237 }
1238}
1239
David Blaikie8019bf82014-04-10 21:53:53 +00001240static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001241 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001242 const MCSectionELF &Section,
1243 MCSectionData &SD) {
1244 StringRef SectionName = Section.getSectionName();
1245 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1246
1247 std::unique_ptr<MCDataFragment> CompressedFragment =
1248 getCompressedFragment(Layout, Fragments);
1249
1250 // Leave the section as-is if the fragments could not be compressed.
1251 if (!CompressedFragment)
1252 return;
1253
David Blaikiec029ab42014-04-18 21:24:12 +00001254 // Update the fragment+offsets of any symbols referring to fragments in this
1255 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001256 auto I = DefiningSymbols.find(&SD);
1257 if (I != DefiningSymbols.end())
1258 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001259
David Blaikie8019bf82014-04-10 21:53:53 +00001260 // 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
David Blaikie39fa6a22014-04-25 00:48:01 +00001280 DefiningSymbolMap DefiningSymbols;
1281
1282 for (MCSymbolData &SD : Asm.symbols())
1283 if (MCFragment *F = SD.getFragment())
1284 DefiningSymbols[F->getParent()].push_back(&SD);
1285
David Blaikie8019bf82014-04-10 21:53:53 +00001286 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001287 const MCSectionELF &Section =
1288 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001289 StringRef SectionName = Section.getSectionName();
1290
1291 // Compressing debug_frame requires handling alignment fragments which is
1292 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1293 // for writing to arbitrary buffers) for little benefit.
1294 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1295 continue;
1296
David Blaikie39fa6a22014-04-25 00:48:01 +00001297 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001298 }
1299}
1300
Rafael Espindola1557fd62011-03-20 18:44:20 +00001301void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1302 const RelMapTy &RelMap) {
Chandler Carruthd99f4272015-02-13 07:52:39 +00001303 for (MCAssembler::const_iterator it = Asm.begin(),
1304 ie = Asm.end(); it != ie; ++it) {
1305 const MCSectionData &SD = *it;
1306 const MCSectionELF &Section =
1307 static_cast<const MCSectionELF&>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001308
Chandler Carruthd99f4272015-02-13 07:52:39 +00001309 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1310 if (!RelaSection)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001311 continue;
Chandler Carruthd99f4272015-02-13 07:52:39 +00001312 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
1313 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001314
Chandler Carruthd99f4272015-02-13 07:52:39 +00001315 MCDataFragment *F = new MCDataFragment(&RelaSD);
1316 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001317 }
1318}
1319
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001320void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1321 uint64_t Flags, uint64_t Address,
1322 uint64_t Offset, uint64_t Size,
1323 uint32_t Link, uint32_t Info,
1324 uint64_t Alignment,
1325 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001326 Write32(Name); // sh_name: index into string table
1327 Write32(Type); // sh_type
1328 WriteWord(Flags); // sh_flags
1329 WriteWord(Address); // sh_addr
1330 WriteWord(Offset); // sh_offset
1331 WriteWord(Size); // sh_size
1332 Write32(Link); // sh_link
1333 Write32(Info); // sh_info
1334 WriteWord(Alignment); // sh_addralign
1335 WriteWord(EntrySize); // sh_entsize
1336}
1337
Rafael Espindola5904e122014-03-29 06:26:49 +00001338// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1339// just to match gnu as for easier comparison. The use type is an arbitrary way
1340// of making the sort deterministic.
1341static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1342 const ELFRelocationEntry &A = *AP;
1343 const ELFRelocationEntry &B = *BP;
1344 if (A.Offset != B.Offset)
1345 return B.Offset - A.Offset;
1346 if (B.Type != A.Type)
1347 return A.Type - B.Type;
1348 llvm_unreachable("ELFRelocs might be unstable!");
1349}
1350
1351static void sortRelocs(const MCAssembler &Asm,
1352 std::vector<ELFRelocationEntry> &Relocs) {
1353 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1354}
1355
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001356void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1357 MCDataFragment *F,
1358 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001359 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001360
Rafael Espindola5904e122014-03-29 06:26:49 +00001361 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001362
1363 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001364 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001365 unsigned Index =
1366 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001367
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001368 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001369 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001370 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001371 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001372
Rafael Espindola5904e122014-03-29 06:26:49 +00001373 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1374 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1375 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1376 write(*F, TargetObjectWriter->getRType(Entry.Type));
1377 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001378 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001379 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001380 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001381 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001382 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001383 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001384 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001385 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001386
Rafael Espindolabce26a12010-10-05 15:11:03 +00001387 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001388 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001389 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001390
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001391 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001392 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001393 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001394 }
1395}
1396
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001397void ELFObjectWriter::CreateMetadataSections(
1398 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001399 MCContext &Ctx = Asm.getContext();
1400 MCDataFragment *F;
1401
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001402 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001403
Rafael Espindola0e527b72010-09-22 19:04:41 +00001404 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001405 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001406 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001407 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1408 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001409 ShstrtabIndex = SectionIndexMap.size() + 1;
1410 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001411
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001412 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001413 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001414 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001415 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001416 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001417 SymbolTableIndex = SectionIndexMap.size() + 1;
1418 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001419
Rafael Espindola1557fd62011-03-20 18:44:20 +00001420 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001421 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001422 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1423 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001424 StringTableIndex = SectionIndexMap.size() + 1;
1425 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001426
1427 // Symbol table
1428 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001429 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001430
Matt Fleming6c1ad482010-08-16 18:57:57 +00001431 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001432 F->getContents().append(StrTabBuilder.data().begin(),
1433 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001434
Matt Fleming6c1ad482010-08-16 18:57:57 +00001435 F = new MCDataFragment(&ShstrtabSD);
1436
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001437 // Section header string table.
1438 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001439 const MCSectionELF &Section =
1440 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001441 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001442 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001443 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001444 F->getContents().append(ShStrTabBuilder.data().begin(),
1445 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001446}
1447
Rafael Espindolaead85492015-02-17 20:31:13 +00001448void ELFObjectWriter::createIndexedSections(MCAssembler &Asm,
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001449 MCAsmLayout &Layout,
1450 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001451 RevGroupMapTy &RevGroupMap,
1452 SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaead85492015-02-17 20:31:13 +00001453 RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001454 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001455
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001456 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001457 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1458 it != ie; ++it) {
1459 const MCSectionELF &Section =
1460 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001461 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001462 continue;
1463
1464 const MCSymbol *SignatureSymbol = Section.getGroup();
1465 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001466 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001467 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001468 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001469 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1470 Data.setAlignment(4);
1471 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001472 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001473 }
1474 GroupMap[Group] = SignatureSymbol;
1475 }
1476
Rafael Espindolaead85492015-02-17 20:31:13 +00001477 computeIndexMap(Asm, SectionIndexMap, RelMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001478
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001479 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001480 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001481 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001482 const MCSectionELF &Section =
1483 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001484 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001485 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001486 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001487 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1488 // FIXME: we could use the previous fragment
1489 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001490 uint32_t Index = SectionIndexMap.lookup(&Section);
1491 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001492 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001493}
1494
Chandler Carruthd99f4272015-02-13 07:52:39 +00001495void ELFObjectWriter::WriteSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001496 const SectionIndexMapTy &SectionIndexMap,
1497 uint32_t GroupSymbolIndex,
1498 uint64_t Offset, uint64_t Size,
1499 uint64_t Alignment,
1500 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001501 uint64_t sh_link = 0;
1502 uint64_t sh_info = 0;
1503
1504 switch(Section.getType()) {
1505 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001506 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001507 sh_info = 0;
1508 break;
1509
1510 case ELF::SHT_REL:
1511 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001512 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001513 assert(sh_link && ".symtab not found");
Chandler Carruthd99f4272015-02-13 07:52:39 +00001514
1515 // Remove ".rel" and ".rela" prefixes.
1516 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1517 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
1518 StringRef GroupName =
1519 Section.getGroup() ? Section.getGroup()->getName() : "";
1520
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001521 const MCSectionELF *InfoSection = Asm.getContext().getELFSection(
1522 SectionName, ELF::SHT_PROGBITS, 0, 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001523 sh_info = SectionIndexMap.lookup(InfoSection);
1524 break;
1525 }
1526
1527 case ELF::SHT_SYMTAB:
1528 case ELF::SHT_DYNSYM:
1529 sh_link = StringTableIndex;
1530 sh_info = LastLocalSymbolIndex;
1531 break;
1532
1533 case ELF::SHT_SYMTAB_SHNDX:
1534 sh_link = SymbolTableIndex;
1535 break;
1536
1537 case ELF::SHT_PROGBITS:
1538 case ELF::SHT_STRTAB:
1539 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001540 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001541 case ELF::SHT_NULL:
1542 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001543 case ELF::SHT_INIT_ARRAY:
1544 case ELF::SHT_FINI_ARRAY:
1545 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001546 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001547 case ELF::SHT_MIPS_REGINFO:
1548 case ELF::SHT_MIPS_OPTIONS:
Vladimir Medicfb8a2a92014-07-08 08:59:22 +00001549 case ELF::SHT_MIPS_ABIFLAGS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001550 // Nothing to do.
1551 break;
1552
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001553 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001554 sh_link = SymbolTableIndex;
1555 sh_info = GroupSymbolIndex;
1556 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001557
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001558 default:
Craig Topper35b2f752014-06-19 06:10:58 +00001559 llvm_unreachable("FIXME: sh_type value not supported!");
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001560 }
1561
Logan Chien4b724422013-02-05 14:18:59 +00001562 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1563 Section.getType() == ELF::SHT_ARM_EXIDX) {
1564 StringRef SecName(Section.getSectionName());
1565 if (SecName == ".ARM.exidx") {
Rafael Espindolaba31e272015-01-29 17:33:21 +00001566 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1567 ".text", ELF::SHT_PROGBITS, ELF::SHF_EXECINSTR | ELF::SHF_ALLOC));
Logan Chien4b724422013-02-05 14:18:59 +00001568 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001569 StringRef GroupName =
1570 Section.getGroup() ? Section.getGroup()->getName() : "";
1571 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1572 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
Rafael Espindolaba31e272015-01-29 17:33:21 +00001573 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, 0, GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001574 }
1575 }
1576
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001577 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1578 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001579 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1580 Alignment, Section.getEntrySize());
1581}
1582
Jan Sjödin30a52de2011-02-28 21:45:04 +00001583bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001584 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001585 !SD.getSection().isVirtualSection();
1586}
1587
Jan Sjödin30a52de2011-02-28 21:45:04 +00001588uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001589 uint64_t Ret = 0;
1590 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1591 ++i) {
1592 const MCFragment &F = *i;
1593 assert(F.getKind() == MCFragment::FT_Data);
1594 Ret += cast<MCDataFragment>(F).getContents().size();
1595 }
1596 return Ret;
1597}
1598
Jan Sjödin30a52de2011-02-28 21:45:04 +00001599uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1600 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001601 if (IsELFMetaDataSection(SD))
1602 return DataSectionSize(SD);
1603 return Layout.getSectionFileSize(&SD);
1604}
1605
Jan Sjödin30a52de2011-02-28 21:45:04 +00001606uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1607 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001608 if (IsELFMetaDataSection(SD))
1609 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001610 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001611}
1612
Rafael Espindola1557fd62011-03-20 18:44:20 +00001613void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1614 const MCAsmLayout &Layout,
1615 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001616 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1617
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001618 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001619 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001620
1621 if (IsELFMetaDataSection(SD)) {
1622 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1623 ++i) {
1624 const MCFragment &F = *i;
1625 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001626 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001627 }
1628 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001629 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001630 }
1631}
1632
Chandler Carruthd99f4272015-02-13 07:52:39 +00001633void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1634 const GroupMapTy &GroupMap,
1635 const MCAsmLayout &Layout,
1636 const SectionIndexMapTy &SectionIndexMap,
1637 const SectionOffsetMapTy &SectionOffsetMap) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001638 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001639
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001640 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001641 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001642
1643 for (SectionIndexMapTy::const_iterator i=
1644 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1645 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001646 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001647 }
1648
Matt Fleming6c1ad482010-08-16 18:57:57 +00001649 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001650 uint64_t FirstSectionSize =
1651 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1652 uint32_t FirstSectionLink =
1653 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1654 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001655
Rafael Espindola1557fd62011-03-20 18:44:20 +00001656 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001657 const MCSectionELF &Section = *Sections[i];
1658 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1659 uint32_t GroupSymbolIndex;
1660 if (Section.getType() != ELF::SHT_GROUP)
1661 GroupSymbolIndex = 0;
1662 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001663 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1664 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001665
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001666 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001667
Chandler Carruthd99f4272015-02-13 07:52:39 +00001668 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001669 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001670 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001671 }
1672}
1673
Rafael Espindola1557fd62011-03-20 18:44:20 +00001674void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1675 std::vector<const MCSectionELF*> &Sections) {
1676 for (MCAssembler::iterator it = Asm.begin(),
1677 ie = Asm.end(); it != ie; ++it) {
1678 const MCSectionELF &Section =
1679 static_cast<const MCSectionELF &>(it->getSection());
1680 if (Section.getType() == ELF::SHT_GROUP)
1681 Sections.push_back(&Section);
1682 }
1683
1684 for (MCAssembler::iterator it = Asm.begin(),
1685 ie = Asm.end(); it != ie; ++it) {
1686 const MCSectionELF &Section =
1687 static_cast<const MCSectionELF &>(it->getSection());
1688 if (Section.getType() != ELF::SHT_GROUP &&
1689 Section.getType() != ELF::SHT_REL &&
1690 Section.getType() != ELF::SHT_RELA)
1691 Sections.push_back(&Section);
1692 }
1693
1694 for (MCAssembler::iterator it = Asm.begin(),
1695 ie = Asm.end(); it != ie; ++it) {
1696 const MCSectionELF &Section =
1697 static_cast<const MCSectionELF &>(it->getSection());
1698 if (Section.getType() == ELF::SHT_REL ||
1699 Section.getType() == ELF::SHT_RELA)
1700 Sections.push_back(&Section);
1701 }
1702}
1703
1704void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1705 const MCAsmLayout &Layout) {
1706 GroupMapTy GroupMap;
1707 RevGroupMapTy RevGroupMap;
1708 SectionIndexMapTy SectionIndexMap;
1709
1710 unsigned NumUserSections = Asm.size();
1711
David Blaikiee06e8012014-04-11 22:11:50 +00001712 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001713
Rafael Espindola1557fd62011-03-20 18:44:20 +00001714 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001715 const unsigned NumUserAndRelocSections = Asm.size();
Rafael Espindolaead85492015-02-17 20:31:13 +00001716 createIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001717 RevGroupMap, SectionIndexMap, RelMap);
1718 const unsigned AllSections = Asm.size();
1719 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1720
1721 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1722
1723 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001724 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1725 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001726
1727 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1728
1729 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1730 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001731 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001732
1733 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1734 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1735 sizeof(ELF::Elf32_Ehdr);
1736 uint64_t FileOff = HeaderSize;
1737
1738 std::vector<const MCSectionELF*> Sections;
1739 ComputeSectionOrder(Asm, Sections);
1740 unsigned NumSections = Sections.size();
1741 SectionOffsetMapTy SectionOffsetMap;
1742 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1743 const MCSectionELF &Section = *Sections[i];
1744 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1745
1746 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1747
1748 // Remember the offset into the file for this section.
1749 SectionOffsetMap[&Section] = FileOff;
1750
1751 // Get the size of the section in the output file (including padding).
1752 FileOff += GetSectionFileSize(Layout, SD);
1753 }
1754
1755 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1756
1757 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1758
1759 uint64_t SectionHeaderEntrySize = is64Bit() ?
1760 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1761 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1762
1763 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1764 const MCSectionELF &Section = *Sections[i];
1765 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1766
1767 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1768
1769 // Remember the offset into the file for this section.
1770 SectionOffsetMap[&Section] = FileOff;
1771
1772 // Get the size of the section in the output file (including padding).
1773 FileOff += GetSectionFileSize(Layout, SD);
1774 }
1775
1776 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001777 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001778
1779 // ... then the regular sections ...
1780 // + because of .shstrtab
1781 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1782 WriteDataSectionData(Asm, Layout, *Sections[i]);
1783
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001784 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001785 WriteZeros(Padding);
1786
1787 // ... then the section header table ...
Chandler Carruthd99f4272015-02-13 07:52:39 +00001788 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001789 SectionOffsetMap);
1790
Nick Lewycky4eb11432011-10-07 20:56:23 +00001791 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001792 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1793 WriteDataSectionData(Asm, Layout, *Sections[i]);
1794}
1795
Eli Friedmand92d17b2011-03-03 07:24:36 +00001796bool
1797ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1798 const MCSymbolData &DataA,
1799 const MCFragment &FB,
1800 bool InSet,
1801 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001802 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001803 return false;
1804 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1805 Asm, DataA, FB,InSet, IsPCRel);
1806}
1807
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001808MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1809 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001810 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001811 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001812}