blob: b3ae4a545f17e98e89689f2bc157e71140d6e616 [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
Rafael Espindola6cd21802015-04-07 22:35:40 +0000115 /// Helper struct for containing some precomputed information on symbols.
Rafael Espindola29abd972011-12-22 03:38:00 +0000116 struct ELFSymbolData {
117 MCSymbolData *SymbolData;
118 uint64_t StringIndex;
119 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000120 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000121
122 // Support lexicographic sorting.
123 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolab6613022014-10-17 01:48:58 +0000124 unsigned LHSType = MCELF::GetType(*SymbolData);
125 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
126 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
127 return false;
128 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
129 return true;
130 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
131 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000132 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000133 }
134 };
135
Rafael Espindola29abd972011-12-22 03:38:00 +0000136 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000137 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000138
139 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
140 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
141 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
142
Rafael Espindola5904e122014-03-29 06:26:49 +0000143 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
144 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000145 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000146
147 /// @}
148 /// @name Symbol Table Data
149 /// @{
150
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000151 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000152 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000153 std::vector<ELFSymbolData> LocalSymbolData;
154 std::vector<ELFSymbolData> ExternalSymbolData;
155 std::vector<ELFSymbolData> UndefinedSymbolData;
156
157 /// @}
158
159 bool NeedsGOT;
160
Rafael Espindola29abd972011-12-22 03:38:00 +0000161 // This holds the symbol table index of the last local symbol.
162 unsigned LastLocalSymbolIndex;
163 // This holds the .strtab section index.
164 unsigned StringTableIndex;
165 // This holds the .symtab section index.
166 unsigned SymbolTableIndex;
167
168 unsigned ShstrtabIndex;
169
170
Rafael Espindola29abd972011-12-22 03:38:00 +0000171 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000172 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
173 bool hasRelocationAddend() const {
174 return TargetObjectWriter->hasRelocationAddend();
175 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000176 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000177 bool IsPCRel) const {
178 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000179 }
180
Rafael Espindola29abd972011-12-22 03:38:00 +0000181 public:
David Blaikie9f380a32015-03-16 18:06:57 +0000182 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &OS,
Rafael Espindola0ce09712014-03-25 22:43:53 +0000183 bool IsLittleEndian)
David Blaikie9f380a32015-03-16 18:06:57 +0000184 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000185 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000186
Yaron Keren7773a722015-03-23 18:35:01 +0000187 void reset() override {
188 UsedInReloc.clear();
189 WeakrefUsedInReloc.clear();
190 Renames.clear();
191 Relocations.clear();
192 ShStrTabBuilder.clear();
193 StrTabBuilder.clear();
194 FileSymbolData.clear();
195 LocalSymbolData.clear();
196 ExternalSymbolData.clear();
197 UndefinedSymbolData.clear();
198 MCObjectWriter::reset();
199 }
200
Rafael Espindola29abd972011-12-22 03:38:00 +0000201 virtual ~ELFObjectWriter();
202
203 void WriteWord(uint64_t W) {
204 if (is64Bit())
205 Write64(W);
206 else
207 Write32(W);
208 }
209
Rafael Espindola0ce09712014-03-25 22:43:53 +0000210 template <typename T> void write(MCDataFragment &F, T Value) {
211 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000212 }
213
Jack Carter1bd90ff2013-01-30 02:09:52 +0000214 void WriteHeader(const MCAssembler &Asm,
Rafael Espindola01f4c6c2015-04-07 21:51:41 +0000215 uint64_t SectionHeaderOffset,
Rafael Espindola29abd972011-12-22 03:38:00 +0000216 unsigned NumberOfSections);
217
Rafael Espindola10be0832014-03-25 23:44:25 +0000218 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000219 const MCAsmLayout &Layout);
220
Rafael Espindola10be0832014-03-25 23:44:25 +0000221 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000222 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000223 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000224
Rafael Espindolab60c8292014-04-29 12:46:50 +0000225 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
226 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000227 const MCSymbolData *SD, uint64_t C,
228 unsigned Type) const;
229
Rafael Espindola26585542015-01-19 21:11:14 +0000230 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000231 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000232 MCValue Target, bool &IsPCRel,
233 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000234
235 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
236 const MCSymbol *S);
237
238 // Map from a group section to the signature symbol
239 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
240 // Map from a signature symbol to the group section
241 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
Rafael Espindola29abd972011-12-22 03:38:00 +0000242 // Map from a section to its offset
243 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
244
Rafael Espindola022bb762014-03-24 03:43:21 +0000245 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000246 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000247 /// \param Asm - The assembler.
248 /// \param SectionIndexMap - Maps a section to its index.
249 /// \param RevGroupMap - Maps a signature symbol to the group section.
Rafael Espindola022bb762014-03-24 03:43:21 +0000250 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000251 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000252 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000253
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000254 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000255
Rafael Espindolaead85492015-02-17 20:31:13 +0000256 MCSectionData *createRelocationSection(MCAssembler &Asm,
257 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000258
David Blaikie8019bf82014-04-10 21:53:53 +0000259 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
260
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000261 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
Rafael Espindola29abd972011-12-22 03:38:00 +0000262
263 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolaef6baea2015-02-11 23:11:18 +0000264 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000265
266 // Create the sections that show up in the symbol table. Currently
267 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaead85492015-02-17 20:31:13 +0000268 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000269 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
270 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000271
Craig Topper34a61bc2014-03-08 07:02:02 +0000272 void ExecutePostLayoutBinding(MCAssembler &Asm,
273 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000274
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000275 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000276 const MCAsmLayout &Layout,
277 const SectionIndexMapTy &SectionIndexMap,
278 const SectionOffsetMapTy &SectionOffsetMap);
279
280 void ComputeSectionOrder(MCAssembler &Asm,
281 std::vector<const MCSectionELF*> &Sections);
282
283 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
284 uint64_t Address, uint64_t Offset,
285 uint64_t Size, uint32_t Link, uint32_t Info,
286 uint64_t Alignment, uint64_t EntrySize);
287
288 void WriteRelocationsFragment(const MCAssembler &Asm,
289 MCDataFragment *F,
290 const MCSectionData *SD);
291
Craig Topper34a61bc2014-03-08 07:02:02 +0000292 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000293 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
294 const MCSymbolData &DataA,
Rafael Espindola94a88d72015-04-06 15:27:57 +0000295 const MCSymbolData *DataB,
Rafael Espindola29abd972011-12-22 03:38:00 +0000296 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
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000300 bool isWeak(const MCSymbolData &SD) const override;
301
Craig Topper34a61bc2014-03-08 07:02:02 +0000302 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000303 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000304 const SectionIndexMapTy &SectionIndexMap,
305 uint32_t GroupSymbolIndex,
306 uint64_t Offset, uint64_t Size, uint64_t Alignment,
307 const MCSectionELF &Section);
308 };
309}
310
Rafael Espindola0ce09712014-03-25 22:43:53 +0000311FragmentWriter::FragmentWriter(bool IsLittleEndian)
312 : IsLittleEndian(IsLittleEndian) {}
313
314template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
315 if (IsLittleEndian)
316 Val = support::endian::byte_swap<T, support::little>(Val);
317 else
318 Val = support::endian::byte_swap<T, support::big>(Val);
319 const char *Start = (const char *)&Val;
320 F.getContents().append(Start, Start + sizeof(T));
321}
322
Rafael Espindola10be0832014-03-25 23:44:25 +0000323void SymbolTableWriter::createSymtabShndx() {
324 if (ShndxF)
325 return;
326
327 MCContext &Ctx = Asm.getContext();
328 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000329 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000330 MCSectionData *SymtabShndxSD =
331 &Asm.getOrCreateSectionData(*SymtabShndxSection);
332 SymtabShndxSD->setAlignment(4);
333 ShndxF = new MCDataFragment(SymtabShndxSD);
334 unsigned Index = SectionIndexMap.size() + 1;
335 SectionIndexMap[SymtabShndxSection] = Index;
336
337 for (unsigned I = 0; I < NumWritten; ++I)
338 write(*ShndxF, uint32_t(0));
339}
340
341template <typename T>
342void SymbolTableWriter::write(MCDataFragment &F, T Value) {
343 FWriter.write(F, Value);
344}
345
346SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
347 bool Is64Bit,
348 SectionIndexMapTy &SectionIndexMap,
349 MCDataFragment *SymtabF)
350 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
351 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
352 NumWritten(0) {}
353
354void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
355 uint64_t size, uint8_t other,
356 uint32_t shndx, bool Reserved) {
357 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
358
359 if (LargeIndex)
360 createSymtabShndx();
361
362 if (ShndxF) {
363 if (LargeIndex)
364 write(*ShndxF, shndx);
365 else
366 write(*ShndxF, uint32_t(0));
367 }
368
369 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
370
371 raw_svector_ostream OS(SymtabF->getContents());
372
373 if (Is64Bit) {
374 write(*SymtabF, name); // st_name
375 write(*SymtabF, info); // st_info
376 write(*SymtabF, other); // st_other
377 write(*SymtabF, Index); // st_shndx
378 write(*SymtabF, value); // st_value
379 write(*SymtabF, size); // st_size
380 } else {
381 write(*SymtabF, name); // st_name
382 write(*SymtabF, uint32_t(value)); // st_value
383 write(*SymtabF, uint32_t(size)); // st_size
384 write(*SymtabF, info); // st_info
385 write(*SymtabF, other); // st_other
386 write(*SymtabF, Index); // st_shndx
387 }
388
389 ++NumWritten;
390}
391
Jan Sjödin30a52de2011-02-28 21:45:04 +0000392bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
393 const MCFixupKindInfo &FKI =
394 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
395
396 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
397}
398
399bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
400 switch (Variant) {
401 default:
402 return false;
403 case MCSymbolRefExpr::VK_GOT:
404 case MCSymbolRefExpr::VK_PLT:
405 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000406 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000407 case MCSymbolRefExpr::VK_TPOFF:
408 case MCSymbolRefExpr::VK_TLSGD:
409 case MCSymbolRefExpr::VK_GOTTPOFF:
410 case MCSymbolRefExpr::VK_INDNTPOFF:
411 case MCSymbolRefExpr::VK_NTPOFF:
412 case MCSymbolRefExpr::VK_GOTNTPOFF:
413 case MCSymbolRefExpr::VK_TLSLDM:
414 case MCSymbolRefExpr::VK_DTPOFF:
415 case MCSymbolRefExpr::VK_TLSLD:
416 return true;
417 }
418}
419
Jason W Kim96f4c012010-11-15 16:18:39 +0000420ELFObjectWriter::~ELFObjectWriter()
421{}
422
Matt Fleming6c1ad482010-08-16 18:57:57 +0000423// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000424void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
Rafael Espindola01f4c6c2015-04-07 21:51:41 +0000425 uint64_t SectionHeaderOffset,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000426 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000427 // ELF Header
428 // ----------
429 //
430 // Note
431 // ----
432 // emitWord method behaves differently for ELF32 and ELF64, writing
433 // 4 bytes in the former and 8 in the latter.
434
435 Write8(0x7f); // e_ident[EI_MAG0]
436 Write8('E'); // e_ident[EI_MAG1]
437 Write8('L'); // e_ident[EI_MAG2]
438 Write8('F'); // e_ident[EI_MAG3]
439
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000440 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000441
442 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000443 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000444
445 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000446 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000447 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000448 Write8(0); // e_ident[EI_ABIVERSION]
449
450 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
451
452 Write16(ELF::ET_REL); // e_type
453
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000454 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000455
456 Write32(ELF::EV_CURRENT); // e_version
457 WriteWord(0); // e_entry, no entry point in .o file
458 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola01f4c6c2015-04-07 21:51:41 +0000459 WriteWord(SectionHeaderOffset); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000460
Jason W Kim4761fba2011-02-04 21:41:11 +0000461 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000462 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000463
464 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000465 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000466
467 Write16(0); // e_phentsize = prog header entry size
468 Write16(0); // e_phnum = # prog header entries = 0
469
470 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000471 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000472
473 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000474 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000475 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000476 else
477 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000478
479 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000480 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000481 Write16(ELF::SHN_XINDEX);
482 else
483 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000484}
485
Rafael Espindolafee224f2014-04-30 21:51:13 +0000486uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000487 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000488 if (Data.isCommon() && Data.isExternal())
489 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000490
Rafael Espindolafee224f2014-04-30 21:51:13 +0000491 uint64_t Res;
492 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000493 return 0;
494
Rafael Espindolafee224f2014-04-30 21:51:13 +0000495 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000496 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000497
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000498 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000499}
500
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000501void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
502 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000503 // The presence of symbol versions causes undefined symbols and
504 // versions declared with @@@ to be renamed.
505
David Blaikie583a31c2014-04-18 18:24:25 +0000506 for (MCSymbolData &OriginalData : Asm.symbols()) {
507 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000508
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000509 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000510 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000511 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000512 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
513 if (!Ref)
514 continue;
515 const MCSymbol &Symbol = Ref->getSymbol();
516 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000517
Benjamin Kramer14807272010-10-27 19:53:52 +0000518 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000519 size_t Pos = AliasName.find('@');
520 if (Pos == StringRef::npos)
521 continue;
522
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000523 // Aliases defined with .symvar copy the binding from the symbol they alias.
524 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000525 OriginalData.setExternal(SD.isExternal());
526 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000527
Benjamin Kramer14807272010-10-27 19:53:52 +0000528 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000529 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
530 continue;
531
Rafael Espindola26496e62010-10-27 17:56:18 +0000532 // FIXME: produce a better error message.
533 if (Symbol.isUndefined() && Rest.startswith("@@") &&
534 !Rest.startswith("@@@"))
535 report_fatal_error("A @@ version cannot be undefined");
536
Benjamin Kramer14807272010-10-27 19:53:52 +0000537 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000538 }
539}
540
Roman Divacky5a1c5492014-01-07 20:17:03 +0000541static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
542 uint8_t Type = newType;
543
544 // Propagation rules:
545 // IFUNC > FUNC > OBJECT > NOTYPE
546 // TLS_OBJECT > OBJECT > NOTYPE
547 //
548 // dont let the new type degrade the old type
549 switch (origType) {
550 default:
551 break;
552 case ELF::STT_GNU_IFUNC:
553 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
554 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
555 Type = ELF::STT_GNU_IFUNC;
556 break;
557 case ELF::STT_FUNC:
558 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
559 Type == ELF::STT_TLS)
560 Type = ELF::STT_FUNC;
561 break;
562 case ELF::STT_OBJECT:
563 if (Type == ELF::STT_NOTYPE)
564 Type = ELF::STT_OBJECT;
565 break;
566 case ELF::STT_TLS:
567 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
568 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
569 Type = ELF::STT_TLS;
570 break;
571 }
572
573 return Type;
574}
575
Rafael Espindola10be0832014-03-25 23:44:25 +0000576void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000577 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000578 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000579 assert((!OrigData.getFragment() ||
580 (&OrigData.getFragment()->getParent()->getSection() ==
581 &OrigData.getSymbol().getSection())) &&
582 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000583 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000584
585 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
586 // SHN_COMMON.
587 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000588
Jack Carter2f8d9d92013-02-19 21:57:35 +0000589 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000590 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000591 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000592 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000593 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000594 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
595 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000596 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000597 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000598
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000599 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000600 // 2 bits
601 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000602 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000603 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000604
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000605 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000606 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000607
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000608 const MCExpr *ESize = OrigData.getSize();
609 if (!ESize && Base)
610 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000611
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000612 if (ESize) {
613 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000614 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000615 report_fatal_error("Size expression must be absolute.");
616 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000617 }
618
619 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000620 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
621 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000622}
623
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000624void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000625 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000626 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000627 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000628 // The string table must be emitted first because we need the index
629 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000630
631 // FIXME: Make sure the start of the symbol table is aligned.
632
Rafael Espindola10be0832014-03-25 23:44:25 +0000633 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
634
Matt Fleming6c1ad482010-08-16 18:57:57 +0000635 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000636 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000637
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000638 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000639 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
640 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000641 }
642
Matt Fleming6c1ad482010-08-16 18:57:57 +0000643 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000644 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
645
Matt Fleming6c1ad482010-08-16 18:57:57 +0000646 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
647 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000648 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000649 }
650
Matt Fleming6c1ad482010-08-16 18:57:57 +0000651 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
652 ELFSymbolData &MSD = ExternalSymbolData[i];
653 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000654 assert(((Data.getFlags() & ELF_STB_Global) ||
655 (Data.getFlags() & ELF_STB_Weak)) &&
656 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000657 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000658 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000659 LastLocalSymbolIndex++;
660 }
661
662 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
663 ELFSymbolData &MSD = UndefinedSymbolData[i];
664 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000665 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000666 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000667 LastLocalSymbolIndex++;
668 }
669}
670
Rafael Espindola5904e122014-03-29 06:26:49 +0000671// It is always valid to create a relocation with a symbol. It is preferable
672// to use a relocation with a section if that is possible. Using the section
673// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000674bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
675 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000676 const MCSymbolData *SD,
677 uint64_t C,
678 unsigned Type) const {
679 // A PCRel relocation to an absolute value has no symbol (or section). We
680 // represent that with a relocation to a null section.
681 if (!RefA)
682 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000683
Rafael Espindola5904e122014-03-29 06:26:49 +0000684 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
685 switch (Kind) {
686 default:
687 break;
688 // The .odp creation emits a relocation against the symbol ".TOC." which
689 // create a R_PPC64_TOC relocation. However the relocation symbol name
690 // in final object creation should be NULL, since the symbol does not
691 // really exist, it is just the reference to TOC base for the current
692 // object file. Since the symbol is undefined, returning false results
693 // in a relocation with a null section which is the desired result.
694 case MCSymbolRefExpr::VK_PPC_TOCBASE:
695 return false;
696
697 // These VariantKind cause the relocation to refer to something other than
698 // the symbol itself, like a linker generated table. Since the address of
699 // symbol is not relevant, we cannot replace the symbol with the
700 // section and patch the difference in the addend.
701 case MCSymbolRefExpr::VK_GOT:
702 case MCSymbolRefExpr::VK_PLT:
703 case MCSymbolRefExpr::VK_GOTPCREL:
704 case MCSymbolRefExpr::VK_Mips_GOT:
705 case MCSymbolRefExpr::VK_PPC_GOT_LO:
706 case MCSymbolRefExpr::VK_PPC_GOT_HI:
707 case MCSymbolRefExpr::VK_PPC_GOT_HA:
708 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000709 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000710
Rafael Espindola5904e122014-03-29 06:26:49 +0000711 // An undefined symbol is not in any section, so the relocation has to point
712 // to the symbol itself.
713 const MCSymbol &Sym = SD->getSymbol();
714 if (Sym.isUndefined())
715 return true;
716
717 unsigned Binding = MCELF::GetBinding(*SD);
718 switch(Binding) {
719 default:
720 llvm_unreachable("Invalid Binding");
721 case ELF::STB_LOCAL:
722 break;
723 case ELF::STB_WEAK:
724 // If the symbol is weak, it might be overridden by a symbol in another
725 // file. The relocation has to point to the symbol so that the linker
726 // can update it.
727 return true;
728 case ELF::STB_GLOBAL:
729 // Global ELF symbols can be preempted by the dynamic linker. The relocation
730 // has to point to the symbol for a reason analogous to the STB_WEAK case.
731 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000732 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000733
Rafael Espindola5904e122014-03-29 06:26:49 +0000734 // If a relocation points to a mergeable section, we have to be careful.
735 // If the offset is zero, a relocation with the section will encode the
736 // same information. With a non-zero offset, the situation is different.
737 // For example, a relocation can point 42 bytes past the end of a string.
738 // If we change such a relocation to use the section, the linker would think
739 // that it pointed to another string and subtracting 42 at runtime will
740 // produce the wrong value.
741 auto &Sec = cast<MCSectionELF>(Sym.getSection());
742 unsigned Flags = Sec.getFlags();
743 if (Flags & ELF::SHF_MERGE) {
744 if (C != 0)
745 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000746
747 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
748 // only handle section relocations to mergeable sections if using RELA.
749 if (!hasRelocationAddend())
750 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000751 }
752
Rafael Espindola5904e122014-03-29 06:26:49 +0000753 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000754 // are just an offset (@tpoff), require a symbol in gold versions before
755 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
756 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000757 if (Flags & ELF::SHF_TLS)
758 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000759
Rafael Espindola9ef84412014-04-11 19:18:01 +0000760 // If the symbol is a thumb function the final relocation must set the lowest
761 // bit. With a symbol that is done by just having the symbol have that bit
762 // set, so we would lose the bit if we relocated with the section.
763 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000764 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000765 return true;
766
Ulrich Weigand46797c62014-07-20 23:15:06 +0000767 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000768 return true;
769 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000770}
771
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000772static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
773 const MCSymbol &Sym = Ref.getSymbol();
774
775 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
776 return &Sym;
777
778 if (!Sym.isVariable())
779 return nullptr;
780
781 const MCExpr *Expr = Sym.getVariableValue();
782 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
783 if (!Inner)
784 return nullptr;
785
786 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
787 return &Inner->getSymbol();
788 return nullptr;
789}
790
Rafael Espindolac9e70682015-03-24 23:48:44 +0000791static bool isWeak(const MCSymbolData &D) {
792 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
793}
794
Rafael Espindola26585542015-01-19 21:11:14 +0000795void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000796 const MCAsmLayout &Layout,
797 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000798 const MCFixup &Fixup, MCValue Target,
799 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000800 const MCSectionData *FixupSection = Fragment->getParent();
801 uint64_t C = Target.getConstant();
802 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000803
Rafael Espindola5904e122014-03-29 06:26:49 +0000804 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
805 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
806 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000807
Rafael Espindola5904e122014-03-29 06:26:49 +0000808 // Let A, B and C being the components of Target and R be the location of
809 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
810 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000811
Rafael Espindola5904e122014-03-29 06:26:49 +0000812 // In general, ELF has no relocations for -B. It can only represent (A + C)
813 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
814 // replace B to implement it: (A - R - K + C)
815 if (IsPCRel)
816 Asm.getContext().FatalError(
817 Fixup.getLoc(),
818 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000819
Rafael Espindola5904e122014-03-29 06:26:49 +0000820 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000821
Rafael Espindola5904e122014-03-29 06:26:49 +0000822 if (SymB.isUndefined())
823 Asm.getContext().FatalError(
824 Fixup.getLoc(),
825 Twine("symbol '") + SymB.getName() +
826 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000827
Rafael Espindola5904e122014-03-29 06:26:49 +0000828 assert(!SymB.isAbsolute() && "Should have been folded");
829 const MCSection &SecB = SymB.getSection();
830 if (&SecB != &FixupSection->getSection())
831 Asm.getContext().FatalError(
832 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000833
Rafael Espindola5904e122014-03-29 06:26:49 +0000834 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000835 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000836 Asm.getContext().FatalError(
837 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
838
Rafael Espindola5904e122014-03-29 06:26:49 +0000839 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
840 uint64_t K = SymBOffset - FixupOffset;
841 IsPCRel = true;
842 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000843 }
844
Rafael Espindola5904e122014-03-29 06:26:49 +0000845 // We either rejected the fixup or folded B into C at this point.
846 const MCSymbolRefExpr *RefA = Target.getSymA();
847 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
848 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
849
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000850 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000851 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000852 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
853 C += Layout.getSymbolOffset(SymAD);
854
855 uint64_t Addend = 0;
856 if (hasRelocationAddend()) {
857 Addend = C;
858 C = 0;
859 }
860
861 FixedValue = C;
862
863 // FIXME: What is this!?!?
864 MCSymbolRefExpr::VariantKind Modifier =
865 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000866 if (RelocNeedsGOT(Modifier))
867 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000868
Rafael Espindola5904e122014-03-29 06:26:49 +0000869 if (!RelocateWithSymbol) {
870 const MCSection *SecA =
871 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000872 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
873 MCSymbol *SectionSymbol =
874 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
875 : nullptr;
876 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000877 Relocations[FixupSection].push_back(Rec);
878 return;
879 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000880
Rafael Espindola5904e122014-03-29 06:26:49 +0000881 if (SymA) {
882 if (const MCSymbol *R = Renames.lookup(SymA))
883 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000884
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000885 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
886 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000887 else
888 UsedInReloc.insert(SymA);
889 }
890 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
891 Relocations[FixupSection].push_back(Rec);
892 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000893}
894
895
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000896uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000897ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
898 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000899 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000900 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000901}
902
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000903bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
904 const MCSymbolData &Data, bool Used,
905 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000906 const MCSymbol &Symbol = Data.getSymbol();
907 if (Symbol.isVariable()) {
908 const MCExpr *Expr = Symbol.getVariableValue();
909 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
910 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
911 return false;
912 }
913 }
Rafael Espindola16145972010-11-01 14:28:48 +0000914
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000915 if (Used)
916 return true;
917
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000918 if (Renamed)
919 return false;
920
Rafael Espindola45834a02010-10-29 23:09:31 +0000921 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
922 return true;
923
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000924 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000925 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000926 if (Base && Base->isUndefined())
927 return false;
928 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000929
Jan Sjödin30a52de2011-02-28 21:45:04 +0000930 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000931 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000932 return false;
933
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000934 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000935 return false;
936
937 return true;
938}
939
Rafael Espindola39f50422014-04-28 14:24:44 +0000940bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000941 if (Data.isExternal())
942 return false;
943
944 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000945 if (Symbol.isDefined())
946 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000947
Rafael Espindola39f50422014-04-28 14:24:44 +0000948 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000949 return false;
950
951 return true;
952}
953
Rafael Espindolaead85492015-02-17 20:31:13 +0000954void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000955 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000956 unsigned Index = 1;
957 for (MCAssembler::iterator it = Asm.begin(),
958 ie = Asm.end(); it != ie; ++it) {
959 const MCSectionELF &Section =
960 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000961 if (Section.getType() != ELF::SHT_GROUP)
962 continue;
963 SectionIndexMap[&Section] = Index++;
964 }
965
966 for (MCAssembler::iterator it = Asm.begin(),
967 ie = Asm.end(); it != ie; ++it) {
Rafael Espindolaead85492015-02-17 20:31:13 +0000968 const MCSectionData &SD = *it;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000969 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000970 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000971 if (Section.getType() == ELF::SHT_GROUP ||
972 Section.getType() == ELF::SHT_REL ||
973 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000974 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000975 SectionIndexMap[&Section] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000976 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
977 const MCSectionELF *RelSection =
978 static_cast<const MCSectionELF *>(&RelSD->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000979 SectionIndexMap[RelSection] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000980 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000981 }
982}
983
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000984void ELFObjectWriter::computeSymbolTable(
985 MCAssembler &Asm, const MCAsmLayout &Layout,
986 const SectionIndexMapTy &SectionIndexMap,
987 const RevGroupMapTy &RevGroupMap) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000988 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000989 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000990 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000991 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000992 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
993 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
994 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000995 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000996 }
997
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000998 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000999 for (MCSymbolData &SD : Asm.symbols()) {
1000 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001001
Rafael Espindola16145972010-11-01 14:28:48 +00001002 bool Used = UsedInReloc.count(&Symbol);
1003 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001004 bool isSignature = RevGroupMap.count(&Symbol);
1005
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001006 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001007 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001008 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001009 continue;
1010
Matt Fleming6c1ad482010-08-16 18:57:57 +00001011 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001012 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001013 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001014
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001015 // Undefined symbols are global, but this is the first place we
1016 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001017 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001018 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001019 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001020 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001021 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001022 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001023 }
1024
Rafael Espindola022bb762014-03-24 03:43:21 +00001025 if (!BaseSymbol) {
1026 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001027 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001028 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001029 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001030 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001031 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001032 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001033 else
1034 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001035 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001036 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001037 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001038 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001039 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001040 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001041 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001042 }
1043
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001044 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1045 // in defined ones.
1046 //
1047 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001048 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001049 // trivial.
1050 //
1051 // We thus have to be careful to not perform the symbol version replacement
1052 // blindly:
1053 //
1054 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1055 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1056 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1057 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1058 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1059 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1060 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1061 // "__imp_?" or "__imp_@?".
1062 //
1063 // It would have been interesting to perform the MS mangling prefix check
1064 // only when the target triple is of the form *-pc-windows-elf. But, it
1065 // seems that this information is not easily accessible from the
1066 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001067 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001068 if (!Name.startswith("?") && !Name.startswith("@?") &&
1069 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1070 // This symbol isn't following the MSVC C++ name mangling convention. We
1071 // can thus safely interpret the @@@ in symbol names as specifying symbol
1072 // versioning.
1073 SmallString<32> Buf;
1074 size_t Pos = Name.find("@@@");
1075 if (Pos != StringRef::npos) {
1076 Buf += Name.substr(0, Pos);
1077 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1078 Buf += Name.substr(Pos + Skip);
1079 Name = Buf;
1080 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001081 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001082
1083 // Sections have their own string table
1084 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1085 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001086
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001087 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1088 UndefinedSymbolData.push_back(MSD);
1089 else if (Local)
1090 LocalSymbolData.push_back(MSD);
1091 else
1092 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001093 }
1094
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001095 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1096 StrTabBuilder.add(*i);
1097
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001098 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001099
1100 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1101 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1102
Rafael Espindolab6613022014-10-17 01:48:58 +00001103 for (ELFSymbolData &MSD : LocalSymbolData)
1104 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1105 ? 0
1106 : StrTabBuilder.getOffset(MSD.Name);
1107 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001108 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1109 for (ELFSymbolData& MSD : UndefinedSymbolData)
1110 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1111
Matt Fleming6c1ad482010-08-16 18:57:57 +00001112 // Symbols are required to be in lexicographic order.
1113 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1114 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1115 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1116
1117 // Set the symbol indices. Local symbols must come before all other
1118 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001119 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001120 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1121 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001122
Matt Fleming6c1ad482010-08-16 18:57:57 +00001123 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1124 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1125 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1126 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1127}
1128
Rafael Espindolaead85492015-02-17 20:31:13 +00001129MCSectionData *
1130ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1131 const MCSectionData &SD) {
1132 if (Relocations[&SD].empty())
1133 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001134
Rafael Espindolaead85492015-02-17 20:31:13 +00001135 MCContext &Ctx = Asm.getContext();
1136 const MCSectionELF &Section =
1137 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001138
Rafael Espindolaead85492015-02-17 20:31:13 +00001139 const StringRef SectionName = Section.getSectionName();
1140 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1141 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001142
Rafael Espindolaead85492015-02-17 20:31:13 +00001143 unsigned EntrySize;
1144 if (hasRelocationAddend())
1145 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1146 else
1147 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001148
Rafael Espindolaead85492015-02-17 20:31:13 +00001149 unsigned Flags = 0;
Rafael Espindolac9d06922015-03-30 13:39:16 +00001150 if (Section.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001151 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001152
Rafael Espindolac9d06922015-03-30 13:39:16 +00001153 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001154 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001155 Flags, EntrySize, Section.getGroup(), &Section);
Rafael Espindolaead85492015-02-17 20:31:13 +00001156 return &Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001157}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001158
David Blaikiee06e8012014-04-11 22:11:50 +00001159static SmallVector<char, 128>
1160getUncompressedData(MCAsmLayout &Layout,
1161 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001162 SmallVector<char, 128> UncompressedData;
1163 for (const MCFragment &F : Fragments) {
1164 const SmallVectorImpl<char> *Contents;
1165 switch (F.getKind()) {
1166 case MCFragment::FT_Data:
1167 Contents = &cast<MCDataFragment>(F).getContents();
1168 break;
1169 case MCFragment::FT_Dwarf:
1170 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1171 break;
1172 case MCFragment::FT_DwarfFrame:
1173 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1174 break;
1175 default:
1176 llvm_unreachable(
1177 "Not expecting any other fragment types in a debug_* section");
1178 }
1179 UncompressedData.append(Contents->begin(), Contents->end());
1180 }
1181 return UncompressedData;
1182}
1183
1184// Include the debug info compression header:
1185// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1186// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001187static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001188prependCompressionHeader(uint64_t Size,
1189 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001190 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001191 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1192 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001193 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001194 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001195 CompressedContents.insert(CompressedContents.begin(),
1196 Magic.size() + sizeof(Size), 0);
1197 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1198 std::copy(reinterpret_cast<char *>(&Size),
1199 reinterpret_cast<char *>(&Size + 1),
1200 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001201 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001202}
1203
1204// Return a single fragment containing the compressed contents of the whole
1205// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001206static std::unique_ptr<MCDataFragment>
1207getCompressedFragment(MCAsmLayout &Layout,
1208 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001209 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1210
1211 // Gather the uncompressed data from all the fragments, recording the
1212 // alignment fragment, if seen, and any fixups.
1213 SmallVector<char, 128> UncompressedData =
1214 getUncompressedData(Layout, Fragments);
1215
1216 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1217
1218 zlib::Status Success = zlib::compress(
1219 StringRef(UncompressedData.data(), UncompressedData.size()),
1220 CompressedContents);
1221 if (Success != zlib::StatusOK)
1222 return nullptr;
1223
David Blaikie76d3a3c2014-04-18 21:52:26 +00001224 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1225 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001226
1227 return CompressedFragment;
1228}
1229
David Blaikie39fa6a22014-04-25 00:48:01 +00001230typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1231DefiningSymbolMap;
1232
1233static void UpdateSymbols(const MCAsmLayout &Layout,
1234 const std::vector<MCSymbolData *> &Symbols,
1235 MCFragment &NewFragment) {
1236 for (MCSymbolData *Sym : Symbols) {
1237 Sym->setOffset(Sym->getOffset() +
1238 Layout.getFragmentOffset(Sym->getFragment()));
1239 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001240 }
1241}
1242
David Blaikie8019bf82014-04-10 21:53:53 +00001243static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001244 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001245 const MCSectionELF &Section,
1246 MCSectionData &SD) {
1247 StringRef SectionName = Section.getSectionName();
1248 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1249
1250 std::unique_ptr<MCDataFragment> CompressedFragment =
1251 getCompressedFragment(Layout, Fragments);
1252
1253 // Leave the section as-is if the fragments could not be compressed.
1254 if (!CompressedFragment)
1255 return;
1256
David Blaikiec029ab42014-04-18 21:24:12 +00001257 // Update the fragment+offsets of any symbols referring to fragments in this
1258 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001259 auto I = DefiningSymbols.find(&SD);
1260 if (I != DefiningSymbols.end())
1261 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001262
David Blaikie8019bf82014-04-10 21:53:53 +00001263 // Invalidate the layout for the whole section since it will have new and
1264 // different fragments now.
1265 Layout.invalidateFragmentsFrom(&Fragments.front());
1266 Fragments.clear();
1267
1268 // Complete the initialization of the new fragment
1269 CompressedFragment->setParent(&SD);
1270 CompressedFragment->setLayoutOrder(0);
1271 Fragments.push_back(CompressedFragment.release());
1272
1273 // Rename from .debug_* to .zdebug_*
1274 Asm.getContext().renameELFSection(&Section,
1275 (".z" + SectionName.drop_front(1)).str());
1276}
1277
1278void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1279 MCAsmLayout &Layout) {
1280 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1281 return;
1282
David Blaikie39fa6a22014-04-25 00:48:01 +00001283 DefiningSymbolMap DefiningSymbols;
1284
1285 for (MCSymbolData &SD : Asm.symbols())
1286 if (MCFragment *F = SD.getFragment())
1287 DefiningSymbols[F->getParent()].push_back(&SD);
1288
David Blaikie8019bf82014-04-10 21:53:53 +00001289 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001290 const MCSectionELF &Section =
1291 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001292 StringRef SectionName = Section.getSectionName();
1293
1294 // Compressing debug_frame requires handling alignment fragments which is
1295 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1296 // for writing to arbitrary buffers) for little benefit.
1297 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1298 continue;
1299
David Blaikie39fa6a22014-04-25 00:48:01 +00001300 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001301 }
1302}
1303
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001304void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001305 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1306 MCSectionData &RelSD = *it;
1307 const MCSectionELF &RelSection =
1308 static_cast<const MCSectionELF &>(RelSD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001309
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001310 unsigned Type = RelSection.getType();
1311 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001312 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001313
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001314 const MCSectionELF *Section = RelSection.getAssociatedSection();
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001315 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1316 RelSD.setAlignment(is64Bit() ? 8 : 4);
1317
1318 MCDataFragment *F = new MCDataFragment(&RelSD);
1319 WriteRelocationsFragment(Asm, F, &SD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001320 }
1321}
1322
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001323void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1324 uint64_t Flags, uint64_t Address,
1325 uint64_t Offset, uint64_t Size,
1326 uint32_t Link, uint32_t Info,
1327 uint64_t Alignment,
1328 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001329 Write32(Name); // sh_name: index into string table
1330 Write32(Type); // sh_type
1331 WriteWord(Flags); // sh_flags
1332 WriteWord(Address); // sh_addr
1333 WriteWord(Offset); // sh_offset
1334 WriteWord(Size); // sh_size
1335 Write32(Link); // sh_link
1336 Write32(Info); // sh_info
1337 WriteWord(Alignment); // sh_addralign
1338 WriteWord(EntrySize); // sh_entsize
1339}
1340
Rafael Espindola5904e122014-03-29 06:26:49 +00001341// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1342// just to match gnu as for easier comparison. The use type is an arbitrary way
1343// of making the sort deterministic.
1344static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1345 const ELFRelocationEntry &A = *AP;
1346 const ELFRelocationEntry &B = *BP;
1347 if (A.Offset != B.Offset)
1348 return B.Offset - A.Offset;
1349 if (B.Type != A.Type)
1350 return A.Type - B.Type;
Daniel Sanders60f1db02015-03-13 12:45:09 +00001351 //llvm_unreachable("ELFRelocs might be unstable!");
1352 return 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001353}
1354
1355static void sortRelocs(const MCAssembler &Asm,
1356 std::vector<ELFRelocationEntry> &Relocs) {
1357 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1358}
1359
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001360void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1361 MCDataFragment *F,
1362 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001363 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001364
Rafael Espindola5904e122014-03-29 06:26:49 +00001365 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001366
1367 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001368 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001369 unsigned Index =
1370 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001371
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001372 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001373 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001374 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001375 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001376
Rafael Espindola5904e122014-03-29 06:26:49 +00001377 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1378 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1379 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1380 write(*F, TargetObjectWriter->getRType(Entry.Type));
1381 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001382 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001383 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001384 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001385 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001386 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001387 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001388 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001389 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001390
Rafael Espindolabce26a12010-10-05 15:11:03 +00001391 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001392 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001393 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001394
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001395 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001396 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001397 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001398 }
1399}
1400
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001401void ELFObjectWriter::CreateMetadataSections(
1402 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001403 MCContext &Ctx = Asm.getContext();
1404 MCDataFragment *F;
1405
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001406 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001407
Rafael Espindola0e527b72010-09-22 19:04:41 +00001408 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001409 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001410 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001411 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1412 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001413 ShstrtabIndex = SectionIndexMap.size() + 1;
1414 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001415
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001416 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001417 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001418 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001419 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001420 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001421 SymbolTableIndex = SectionIndexMap.size() + 1;
1422 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001423
Rafael Espindola1557fd62011-03-20 18:44:20 +00001424 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001425 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001426 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1427 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001428 StringTableIndex = SectionIndexMap.size() + 1;
1429 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001430
1431 // Symbol table
1432 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001433 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001434
Matt Fleming6c1ad482010-08-16 18:57:57 +00001435 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001436 F->getContents().append(StrTabBuilder.data().begin(),
1437 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001438
Matt Fleming6c1ad482010-08-16 18:57:57 +00001439 F = new MCDataFragment(&ShstrtabSD);
1440
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001441 // Section header string table.
1442 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001443 const MCSectionELF &Section =
1444 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001445 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001446 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001447 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001448 F->getContents().append(ShStrTabBuilder.data().begin(),
1449 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001450}
1451
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001452void ELFObjectWriter::createIndexedSections(
1453 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1454 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001455 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001456
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001457 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001458 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1459 it != ie; ++it) {
1460 const MCSectionELF &Section =
1461 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001462 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001463 continue;
1464
1465 const MCSymbol *SignatureSymbol = Section.getGroup();
1466 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001467 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001468 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001469 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001470 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1471 Data.setAlignment(4);
1472 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001473 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001474 }
1475 GroupMap[Group] = SignatureSymbol;
1476 }
1477
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001478 computeIndexMap(Asm, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001479
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001480 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001481 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001482 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001483 const MCSectionELF &Section =
1484 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001485 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001486 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001487 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001488 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1489 // FIXME: we could use the previous fragment
1490 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001491 uint32_t Index = SectionIndexMap.lookup(&Section);
1492 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001493 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001494}
1495
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001496void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001497 const SectionIndexMapTy &SectionIndexMap,
1498 uint32_t GroupSymbolIndex,
1499 uint64_t Offset, uint64_t Size,
1500 uint64_t Alignment,
1501 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001502 uint64_t sh_link = 0;
1503 uint64_t sh_info = 0;
1504
1505 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001506 default:
1507 // Nothing to do.
1508 break;
1509
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001510 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001511 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001512 break;
1513
1514 case ELF::SHT_REL:
1515 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001516 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001517 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001518 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001519 sh_info = SectionIndexMap.lookup(InfoSection);
1520 break;
1521 }
1522
1523 case ELF::SHT_SYMTAB:
1524 case ELF::SHT_DYNSYM:
1525 sh_link = StringTableIndex;
1526 sh_info = LastLocalSymbolIndex;
1527 break;
1528
1529 case ELF::SHT_SYMTAB_SHNDX:
1530 sh_link = SymbolTableIndex;
1531 break;
1532
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001533 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001534 sh_link = SymbolTableIndex;
1535 sh_info = GroupSymbolIndex;
1536 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001537 }
1538
Logan Chien4b724422013-02-05 14:18:59 +00001539 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001540 Section.getType() == ELF::SHT_ARM_EXIDX)
1541 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001542
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001543 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1544 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001545 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1546 Alignment, Section.getEntrySize());
1547}
1548
Jan Sjödin30a52de2011-02-28 21:45:04 +00001549bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001550 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001551 !SD.getSection().isVirtualSection();
1552}
1553
Jan Sjödin30a52de2011-02-28 21:45:04 +00001554uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001555 uint64_t Ret = 0;
1556 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1557 ++i) {
1558 const MCFragment &F = *i;
1559 assert(F.getKind() == MCFragment::FT_Data);
1560 Ret += cast<MCDataFragment>(F).getContents().size();
1561 }
1562 return Ret;
1563}
1564
Jan Sjödin30a52de2011-02-28 21:45:04 +00001565uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1566 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001567 if (IsELFMetaDataSection(SD))
1568 return DataSectionSize(SD);
1569 return Layout.getSectionFileSize(&SD);
1570}
1571
Jan Sjödin30a52de2011-02-28 21:45:04 +00001572uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1573 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001574 if (IsELFMetaDataSection(SD))
1575 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001576 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001577}
1578
Rafael Espindola1557fd62011-03-20 18:44:20 +00001579void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1580 const MCAsmLayout &Layout,
1581 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001582 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1583
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001584 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001585 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001586
1587 if (IsELFMetaDataSection(SD)) {
1588 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1589 ++i) {
1590 const MCFragment &F = *i;
1591 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001592 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001593 }
1594 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001595 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001596 }
1597}
1598
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001599void ELFObjectWriter::writeSectionHeader(
1600 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001601 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001602 const SectionOffsetMapTy &SectionOffsetMap) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001603 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001604
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001605 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001606 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001607
1608 for (SectionIndexMapTy::const_iterator i=
1609 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1610 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001611 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001612 }
1613
Matt Fleming6c1ad482010-08-16 18:57:57 +00001614 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001615 uint64_t FirstSectionSize =
1616 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1617 uint32_t FirstSectionLink =
1618 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1619 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001620
Rafael Espindola1557fd62011-03-20 18:44:20 +00001621 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001622 const MCSectionELF &Section = *Sections[i];
1623 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1624 uint32_t GroupSymbolIndex;
1625 if (Section.getType() != ELF::SHT_GROUP)
1626 GroupSymbolIndex = 0;
1627 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001628 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1629 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001630
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001631 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001632
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001633 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1634 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1635 Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001636 }
1637}
1638
Rafael Espindola1557fd62011-03-20 18:44:20 +00001639void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1640 std::vector<const MCSectionELF*> &Sections) {
1641 for (MCAssembler::iterator it = Asm.begin(),
1642 ie = Asm.end(); it != ie; ++it) {
1643 const MCSectionELF &Section =
1644 static_cast<const MCSectionELF &>(it->getSection());
1645 if (Section.getType() == ELF::SHT_GROUP)
1646 Sections.push_back(&Section);
1647 }
1648
1649 for (MCAssembler::iterator it = Asm.begin(),
1650 ie = Asm.end(); it != ie; ++it) {
1651 const MCSectionELF &Section =
1652 static_cast<const MCSectionELF &>(it->getSection());
1653 if (Section.getType() != ELF::SHT_GROUP &&
1654 Section.getType() != ELF::SHT_REL &&
1655 Section.getType() != ELF::SHT_RELA)
1656 Sections.push_back(&Section);
1657 }
1658
1659 for (MCAssembler::iterator it = Asm.begin(),
1660 ie = Asm.end(); it != ie; ++it) {
1661 const MCSectionELF &Section =
1662 static_cast<const MCSectionELF &>(it->getSection());
1663 if (Section.getType() == ELF::SHT_REL ||
1664 Section.getType() == ELF::SHT_RELA)
1665 Sections.push_back(&Section);
1666 }
1667}
1668
1669void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1670 const MCAsmLayout &Layout) {
1671 GroupMapTy GroupMap;
1672 RevGroupMapTy RevGroupMap;
1673 SectionIndexMapTy SectionIndexMap;
1674
David Blaikiee06e8012014-04-11 22:11:50 +00001675 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001676 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1677 RevGroupMap, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001678
Rafael Espindola39e20aa2015-04-07 19:17:47 +00001679 unsigned NumRegularSections = Asm.size();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001680
1681 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001682 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001683
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001684 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola1557fd62011-03-20 18:44:20 +00001685
1686 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1687 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001688 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001689
1690 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1691 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1692 sizeof(ELF::Elf32_Ehdr);
1693 uint64_t FileOff = HeaderSize;
1694
1695 std::vector<const MCSectionELF*> Sections;
1696 ComputeSectionOrder(Asm, Sections);
1697 unsigned NumSections = Sections.size();
1698 SectionOffsetMapTy SectionOffsetMap;
1699 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1700 const MCSectionELF &Section = *Sections[i];
1701 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1702
1703 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1704
1705 // Remember the offset into the file for this section.
1706 SectionOffsetMap[&Section] = FileOff;
1707
1708 // Get the size of the section in the output file (including padding).
1709 FileOff += GetSectionFileSize(Layout, SD);
1710 }
1711
1712 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1713
Rafael Espindola01f4c6c2015-04-07 21:51:41 +00001714 const unsigned SectionHeaderOffset = FileOff;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001715
1716 uint64_t SectionHeaderEntrySize = is64Bit() ?
1717 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1718 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1719
1720 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1721 const MCSectionELF &Section = *Sections[i];
1722 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1723
1724 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1725
1726 // Remember the offset into the file for this section.
1727 SectionOffsetMap[&Section] = FileOff;
1728
1729 // Get the size of the section in the output file (including padding).
1730 FileOff += GetSectionFileSize(Layout, SD);
1731 }
1732
1733 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001734 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001735
1736 // ... then the regular sections ...
1737 // + because of .shstrtab
1738 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1739 WriteDataSectionData(Asm, Layout, *Sections[i]);
1740
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001741 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001742 WriteZeros(Padding);
1743
1744 // ... then the section header table ...
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001745 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001746
Nick Lewycky4eb11432011-10-07 20:56:23 +00001747 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001748 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1749 WriteDataSectionData(Asm, Layout, *Sections[i]);
1750}
1751
Rafael Espindola94a88d72015-04-06 15:27:57 +00001752bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1753 const MCAssembler &Asm, const MCSymbolData &DataA,
1754 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1755 bool IsPCRel) const {
1756 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
Eli Friedmand92d17b2011-03-03 07:24:36 +00001757 return false;
1758 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola94a88d72015-04-06 15:27:57 +00001759 Asm, DataA, DataB, FB, InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001760}
1761
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001762bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1763 return ::isWeak(SD);
1764}
1765
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001766MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1767 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001768 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001769 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001770}