blob: 13b2d6e3f8aa0acc727a89b6c5dd75d2c7590df3 [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.
250 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000251 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000252 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000253 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000254
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000255 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000256
Rafael Espindolaead85492015-02-17 20:31:13 +0000257 MCSectionData *createRelocationSection(MCAssembler &Asm,
258 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000259
David Blaikie8019bf82014-04-10 21:53:53 +0000260 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
261
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000262 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
Rafael Espindola29abd972011-12-22 03:38:00 +0000263
264 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolaef6baea2015-02-11 23:11:18 +0000265 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000266
267 // Create the sections that show up in the symbol table. Currently
268 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaead85492015-02-17 20:31:13 +0000269 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000270 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
271 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000272
Craig Topper34a61bc2014-03-08 07:02:02 +0000273 void ExecutePostLayoutBinding(MCAssembler &Asm,
274 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000275
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000276 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000277 const MCAsmLayout &Layout,
278 const SectionIndexMapTy &SectionIndexMap,
279 const SectionOffsetMapTy &SectionOffsetMap);
280
281 void ComputeSectionOrder(MCAssembler &Asm,
282 std::vector<const MCSectionELF*> &Sections);
283
284 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
285 uint64_t Address, uint64_t Offset,
286 uint64_t Size, uint32_t Link, uint32_t Info,
287 uint64_t Alignment, uint64_t EntrySize);
288
289 void WriteRelocationsFragment(const MCAssembler &Asm,
290 MCDataFragment *F,
291 const MCSectionData *SD);
292
Craig Topper34a61bc2014-03-08 07:02:02 +0000293 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000294 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
295 const MCSymbolData &DataA,
Rafael Espindola94a88d72015-04-06 15:27:57 +0000296 const MCSymbolData *DataB,
Rafael Espindola29abd972011-12-22 03:38:00 +0000297 const MCFragment &FB,
298 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000299 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000300
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000301 bool isWeak(const MCSymbolData &SD) const override;
302
Craig Topper34a61bc2014-03-08 07:02:02 +0000303 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000304 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000305 const SectionIndexMapTy &SectionIndexMap,
306 uint32_t GroupSymbolIndex,
307 uint64_t Offset, uint64_t Size, uint64_t Alignment,
308 const MCSectionELF &Section);
309 };
310}
311
Rafael Espindola0ce09712014-03-25 22:43:53 +0000312FragmentWriter::FragmentWriter(bool IsLittleEndian)
313 : IsLittleEndian(IsLittleEndian) {}
314
315template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
316 if (IsLittleEndian)
317 Val = support::endian::byte_swap<T, support::little>(Val);
318 else
319 Val = support::endian::byte_swap<T, support::big>(Val);
320 const char *Start = (const char *)&Val;
321 F.getContents().append(Start, Start + sizeof(T));
322}
323
Rafael Espindola10be0832014-03-25 23:44:25 +0000324void SymbolTableWriter::createSymtabShndx() {
325 if (ShndxF)
326 return;
327
328 MCContext &Ctx = Asm.getContext();
329 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000330 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000331 MCSectionData *SymtabShndxSD =
332 &Asm.getOrCreateSectionData(*SymtabShndxSection);
333 SymtabShndxSD->setAlignment(4);
334 ShndxF = new MCDataFragment(SymtabShndxSD);
335 unsigned Index = SectionIndexMap.size() + 1;
336 SectionIndexMap[SymtabShndxSection] = Index;
337
338 for (unsigned I = 0; I < NumWritten; ++I)
339 write(*ShndxF, uint32_t(0));
340}
341
342template <typename T>
343void SymbolTableWriter::write(MCDataFragment &F, T Value) {
344 FWriter.write(F, Value);
345}
346
347SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
348 bool Is64Bit,
349 SectionIndexMapTy &SectionIndexMap,
350 MCDataFragment *SymtabF)
351 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
352 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
353 NumWritten(0) {}
354
355void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
356 uint64_t size, uint8_t other,
357 uint32_t shndx, bool Reserved) {
358 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
359
360 if (LargeIndex)
361 createSymtabShndx();
362
363 if (ShndxF) {
364 if (LargeIndex)
365 write(*ShndxF, shndx);
366 else
367 write(*ShndxF, uint32_t(0));
368 }
369
370 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
371
372 raw_svector_ostream OS(SymtabF->getContents());
373
374 if (Is64Bit) {
375 write(*SymtabF, name); // st_name
376 write(*SymtabF, info); // st_info
377 write(*SymtabF, other); // st_other
378 write(*SymtabF, Index); // st_shndx
379 write(*SymtabF, value); // st_value
380 write(*SymtabF, size); // st_size
381 } else {
382 write(*SymtabF, name); // st_name
383 write(*SymtabF, uint32_t(value)); // st_value
384 write(*SymtabF, uint32_t(size)); // st_size
385 write(*SymtabF, info); // st_info
386 write(*SymtabF, other); // st_other
387 write(*SymtabF, Index); // st_shndx
388 }
389
390 ++NumWritten;
391}
392
Jan Sjödin30a52de2011-02-28 21:45:04 +0000393bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
394 const MCFixupKindInfo &FKI =
395 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
396
397 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
398}
399
400bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
401 switch (Variant) {
402 default:
403 return false;
404 case MCSymbolRefExpr::VK_GOT:
405 case MCSymbolRefExpr::VK_PLT:
406 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000407 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000408 case MCSymbolRefExpr::VK_TPOFF:
409 case MCSymbolRefExpr::VK_TLSGD:
410 case MCSymbolRefExpr::VK_GOTTPOFF:
411 case MCSymbolRefExpr::VK_INDNTPOFF:
412 case MCSymbolRefExpr::VK_NTPOFF:
413 case MCSymbolRefExpr::VK_GOTNTPOFF:
414 case MCSymbolRefExpr::VK_TLSLDM:
415 case MCSymbolRefExpr::VK_DTPOFF:
416 case MCSymbolRefExpr::VK_TLSLD:
417 return true;
418 }
419}
420
Jason W Kim96f4c012010-11-15 16:18:39 +0000421ELFObjectWriter::~ELFObjectWriter()
422{}
423
Matt Fleming6c1ad482010-08-16 18:57:57 +0000424// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000425void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
Rafael Espindola01f4c6c2015-04-07 21:51:41 +0000426 uint64_t SectionHeaderOffset,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000427 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000428 // ELF Header
429 // ----------
430 //
431 // Note
432 // ----
433 // emitWord method behaves differently for ELF32 and ELF64, writing
434 // 4 bytes in the former and 8 in the latter.
435
436 Write8(0x7f); // e_ident[EI_MAG0]
437 Write8('E'); // e_ident[EI_MAG1]
438 Write8('L'); // e_ident[EI_MAG2]
439 Write8('F'); // e_ident[EI_MAG3]
440
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000441 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000442
443 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000444 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000445
446 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000447 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000448 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000449 Write8(0); // e_ident[EI_ABIVERSION]
450
451 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
452
453 Write16(ELF::ET_REL); // e_type
454
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000455 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000456
457 Write32(ELF::EV_CURRENT); // e_version
458 WriteWord(0); // e_entry, no entry point in .o file
459 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola01f4c6c2015-04-07 21:51:41 +0000460 WriteWord(SectionHeaderOffset); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000461
Jason W Kim4761fba2011-02-04 21:41:11 +0000462 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000463 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000464
465 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000466 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000467
468 Write16(0); // e_phentsize = prog header entry size
469 Write16(0); // e_phnum = # prog header entries = 0
470
471 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000472 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000473
474 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000475 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000476 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000477 else
478 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000479
480 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000481 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000482 Write16(ELF::SHN_XINDEX);
483 else
484 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000485}
486
Rafael Espindolafee224f2014-04-30 21:51:13 +0000487uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000488 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000489 if (Data.isCommon() && Data.isExternal())
490 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000491
Rafael Espindolafee224f2014-04-30 21:51:13 +0000492 uint64_t Res;
493 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000494 return 0;
495
Rafael Espindolafee224f2014-04-30 21:51:13 +0000496 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000497 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000498
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000499 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000500}
501
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000502void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
503 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000504 // The presence of symbol versions causes undefined symbols and
505 // versions declared with @@@ to be renamed.
506
David Blaikie583a31c2014-04-18 18:24:25 +0000507 for (MCSymbolData &OriginalData : Asm.symbols()) {
508 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000509
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000510 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000511 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000512 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000513 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
514 if (!Ref)
515 continue;
516 const MCSymbol &Symbol = Ref->getSymbol();
517 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000518
Benjamin Kramer14807272010-10-27 19:53:52 +0000519 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000520 size_t Pos = AliasName.find('@');
521 if (Pos == StringRef::npos)
522 continue;
523
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000524 // Aliases defined with .symvar copy the binding from the symbol they alias.
525 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000526 OriginalData.setExternal(SD.isExternal());
527 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000528
Benjamin Kramer14807272010-10-27 19:53:52 +0000529 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000530 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
531 continue;
532
Rafael Espindola26496e62010-10-27 17:56:18 +0000533 // FIXME: produce a better error message.
534 if (Symbol.isUndefined() && Rest.startswith("@@") &&
535 !Rest.startswith("@@@"))
536 report_fatal_error("A @@ version cannot be undefined");
537
Benjamin Kramer14807272010-10-27 19:53:52 +0000538 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000539 }
540}
541
Roman Divacky5a1c5492014-01-07 20:17:03 +0000542static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
543 uint8_t Type = newType;
544
545 // Propagation rules:
546 // IFUNC > FUNC > OBJECT > NOTYPE
547 // TLS_OBJECT > OBJECT > NOTYPE
548 //
549 // dont let the new type degrade the old type
550 switch (origType) {
551 default:
552 break;
553 case ELF::STT_GNU_IFUNC:
554 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
555 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
556 Type = ELF::STT_GNU_IFUNC;
557 break;
558 case ELF::STT_FUNC:
559 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
560 Type == ELF::STT_TLS)
561 Type = ELF::STT_FUNC;
562 break;
563 case ELF::STT_OBJECT:
564 if (Type == ELF::STT_NOTYPE)
565 Type = ELF::STT_OBJECT;
566 break;
567 case ELF::STT_TLS:
568 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
569 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
570 Type = ELF::STT_TLS;
571 break;
572 }
573
574 return Type;
575}
576
Rafael Espindola10be0832014-03-25 23:44:25 +0000577void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000578 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000579 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000580 assert((!OrigData.getFragment() ||
581 (&OrigData.getFragment()->getParent()->getSection() ==
582 &OrigData.getSymbol().getSection())) &&
583 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000584 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000585
586 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
587 // SHN_COMMON.
588 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000589
Jack Carter2f8d9d92013-02-19 21:57:35 +0000590 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000591 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000592 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000593 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000594 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000595 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
596 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000597 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000598 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000599
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000600 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000601 // 2 bits
602 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000603 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000604 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000605
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000606 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000607 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000608
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000609 const MCExpr *ESize = OrigData.getSize();
610 if (!ESize && Base)
611 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000612
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000613 if (ESize) {
614 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000615 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000616 report_fatal_error("Size expression must be absolute.");
617 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000618 }
619
620 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000621 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
622 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000623}
624
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000625void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000626 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000627 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000628 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000629 // The string table must be emitted first because we need the index
630 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000631
632 // FIXME: Make sure the start of the symbol table is aligned.
633
Rafael Espindola10be0832014-03-25 23:44:25 +0000634 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
635
Matt Fleming6c1ad482010-08-16 18:57:57 +0000636 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000637 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000638
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000639 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000640 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
641 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000642 }
643
Matt Fleming6c1ad482010-08-16 18:57:57 +0000644 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000645 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
646
Matt Fleming6c1ad482010-08-16 18:57:57 +0000647 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
648 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000649 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000650 }
651
Matt Fleming6c1ad482010-08-16 18:57:57 +0000652 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
653 ELFSymbolData &MSD = ExternalSymbolData[i];
654 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000655 assert(((Data.getFlags() & ELF_STB_Global) ||
656 (Data.getFlags() & ELF_STB_Weak)) &&
657 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000658 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000659 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000660 LastLocalSymbolIndex++;
661 }
662
663 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
664 ELFSymbolData &MSD = UndefinedSymbolData[i];
665 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000666 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000667 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000668 LastLocalSymbolIndex++;
669 }
670}
671
Rafael Espindola5904e122014-03-29 06:26:49 +0000672// It is always valid to create a relocation with a symbol. It is preferable
673// to use a relocation with a section if that is possible. Using the section
674// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000675bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
676 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000677 const MCSymbolData *SD,
678 uint64_t C,
679 unsigned Type) const {
680 // A PCRel relocation to an absolute value has no symbol (or section). We
681 // represent that with a relocation to a null section.
682 if (!RefA)
683 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000684
Rafael Espindola5904e122014-03-29 06:26:49 +0000685 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
686 switch (Kind) {
687 default:
688 break;
689 // The .odp creation emits a relocation against the symbol ".TOC." which
690 // create a R_PPC64_TOC relocation. However the relocation symbol name
691 // in final object creation should be NULL, since the symbol does not
692 // really exist, it is just the reference to TOC base for the current
693 // object file. Since the symbol is undefined, returning false results
694 // in a relocation with a null section which is the desired result.
695 case MCSymbolRefExpr::VK_PPC_TOCBASE:
696 return false;
697
698 // These VariantKind cause the relocation to refer to something other than
699 // the symbol itself, like a linker generated table. Since the address of
700 // symbol is not relevant, we cannot replace the symbol with the
701 // section and patch the difference in the addend.
702 case MCSymbolRefExpr::VK_GOT:
703 case MCSymbolRefExpr::VK_PLT:
704 case MCSymbolRefExpr::VK_GOTPCREL:
705 case MCSymbolRefExpr::VK_Mips_GOT:
706 case MCSymbolRefExpr::VK_PPC_GOT_LO:
707 case MCSymbolRefExpr::VK_PPC_GOT_HI:
708 case MCSymbolRefExpr::VK_PPC_GOT_HA:
709 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000710 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000711
Rafael Espindola5904e122014-03-29 06:26:49 +0000712 // An undefined symbol is not in any section, so the relocation has to point
713 // to the symbol itself.
714 const MCSymbol &Sym = SD->getSymbol();
715 if (Sym.isUndefined())
716 return true;
717
718 unsigned Binding = MCELF::GetBinding(*SD);
719 switch(Binding) {
720 default:
721 llvm_unreachable("Invalid Binding");
722 case ELF::STB_LOCAL:
723 break;
724 case ELF::STB_WEAK:
725 // If the symbol is weak, it might be overridden by a symbol in another
726 // file. The relocation has to point to the symbol so that the linker
727 // can update it.
728 return true;
729 case ELF::STB_GLOBAL:
730 // Global ELF symbols can be preempted by the dynamic linker. The relocation
731 // has to point to the symbol for a reason analogous to the STB_WEAK case.
732 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000733 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000734
Rafael Espindola5904e122014-03-29 06:26:49 +0000735 // If a relocation points to a mergeable section, we have to be careful.
736 // If the offset is zero, a relocation with the section will encode the
737 // same information. With a non-zero offset, the situation is different.
738 // For example, a relocation can point 42 bytes past the end of a string.
739 // If we change such a relocation to use the section, the linker would think
740 // that it pointed to another string and subtracting 42 at runtime will
741 // produce the wrong value.
742 auto &Sec = cast<MCSectionELF>(Sym.getSection());
743 unsigned Flags = Sec.getFlags();
744 if (Flags & ELF::SHF_MERGE) {
745 if (C != 0)
746 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000747
748 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
749 // only handle section relocations to mergeable sections if using RELA.
750 if (!hasRelocationAddend())
751 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000752 }
753
Rafael Espindola5904e122014-03-29 06:26:49 +0000754 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000755 // are just an offset (@tpoff), require a symbol in gold versions before
756 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
757 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000758 if (Flags & ELF::SHF_TLS)
759 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000760
Rafael Espindola9ef84412014-04-11 19:18:01 +0000761 // If the symbol is a thumb function the final relocation must set the lowest
762 // bit. With a symbol that is done by just having the symbol have that bit
763 // set, so we would lose the bit if we relocated with the section.
764 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000765 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000766 return true;
767
Ulrich Weigand46797c62014-07-20 23:15:06 +0000768 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000769 return true;
770 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000771}
772
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000773static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
774 const MCSymbol &Sym = Ref.getSymbol();
775
776 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
777 return &Sym;
778
779 if (!Sym.isVariable())
780 return nullptr;
781
782 const MCExpr *Expr = Sym.getVariableValue();
783 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
784 if (!Inner)
785 return nullptr;
786
787 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
788 return &Inner->getSymbol();
789 return nullptr;
790}
791
Rafael Espindolac9e70682015-03-24 23:48:44 +0000792static bool isWeak(const MCSymbolData &D) {
793 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
794}
795
Rafael Espindola26585542015-01-19 21:11:14 +0000796void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000797 const MCAsmLayout &Layout,
798 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000799 const MCFixup &Fixup, MCValue Target,
800 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000801 const MCSectionData *FixupSection = Fragment->getParent();
802 uint64_t C = Target.getConstant();
803 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000804
Rafael Espindola5904e122014-03-29 06:26:49 +0000805 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
806 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
807 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000808
Rafael Espindola5904e122014-03-29 06:26:49 +0000809 // Let A, B and C being the components of Target and R be the location of
810 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
811 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000812
Rafael Espindola5904e122014-03-29 06:26:49 +0000813 // In general, ELF has no relocations for -B. It can only represent (A + C)
814 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
815 // replace B to implement it: (A - R - K + C)
816 if (IsPCRel)
817 Asm.getContext().FatalError(
818 Fixup.getLoc(),
819 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000820
Rafael Espindola5904e122014-03-29 06:26:49 +0000821 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000822
Rafael Espindola5904e122014-03-29 06:26:49 +0000823 if (SymB.isUndefined())
824 Asm.getContext().FatalError(
825 Fixup.getLoc(),
826 Twine("symbol '") + SymB.getName() +
827 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000828
Rafael Espindola5904e122014-03-29 06:26:49 +0000829 assert(!SymB.isAbsolute() && "Should have been folded");
830 const MCSection &SecB = SymB.getSection();
831 if (&SecB != &FixupSection->getSection())
832 Asm.getContext().FatalError(
833 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000834
Rafael Espindola5904e122014-03-29 06:26:49 +0000835 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000836 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000837 Asm.getContext().FatalError(
838 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
839
Rafael Espindola5904e122014-03-29 06:26:49 +0000840 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
841 uint64_t K = SymBOffset - FixupOffset;
842 IsPCRel = true;
843 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000844 }
845
Rafael Espindola5904e122014-03-29 06:26:49 +0000846 // We either rejected the fixup or folded B into C at this point.
847 const MCSymbolRefExpr *RefA = Target.getSymA();
848 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
849 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
850
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000851 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000852 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000853 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
854 C += Layout.getSymbolOffset(SymAD);
855
856 uint64_t Addend = 0;
857 if (hasRelocationAddend()) {
858 Addend = C;
859 C = 0;
860 }
861
862 FixedValue = C;
863
864 // FIXME: What is this!?!?
865 MCSymbolRefExpr::VariantKind Modifier =
866 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000867 if (RelocNeedsGOT(Modifier))
868 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000869
Rafael Espindola5904e122014-03-29 06:26:49 +0000870 if (!RelocateWithSymbol) {
871 const MCSection *SecA =
872 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000873 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
874 MCSymbol *SectionSymbol =
875 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
876 : nullptr;
877 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000878 Relocations[FixupSection].push_back(Rec);
879 return;
880 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000881
Rafael Espindola5904e122014-03-29 06:26:49 +0000882 if (SymA) {
883 if (const MCSymbol *R = Renames.lookup(SymA))
884 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000885
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000886 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
887 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000888 else
889 UsedInReloc.insert(SymA);
890 }
891 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
892 Relocations[FixupSection].push_back(Rec);
893 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000894}
895
896
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000897uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000898ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
899 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000900 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000901 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000902}
903
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000904bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
905 const MCSymbolData &Data, bool Used,
906 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000907 const MCSymbol &Symbol = Data.getSymbol();
908 if (Symbol.isVariable()) {
909 const MCExpr *Expr = Symbol.getVariableValue();
910 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
911 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
912 return false;
913 }
914 }
Rafael Espindola16145972010-11-01 14:28:48 +0000915
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000916 if (Used)
917 return true;
918
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000919 if (Renamed)
920 return false;
921
Rafael Espindola45834a02010-10-29 23:09:31 +0000922 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
923 return true;
924
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000925 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000926 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000927 if (Base && Base->isUndefined())
928 return false;
929 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000930
Jan Sjödin30a52de2011-02-28 21:45:04 +0000931 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000932 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000933 return false;
934
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000935 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000936 return false;
937
938 return true;
939}
940
Rafael Espindola39f50422014-04-28 14:24:44 +0000941bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000942 if (Data.isExternal())
943 return false;
944
945 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000946 if (Symbol.isDefined())
947 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000948
Rafael Espindola39f50422014-04-28 14:24:44 +0000949 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000950 return false;
951
952 return true;
953}
954
Rafael Espindolaead85492015-02-17 20:31:13 +0000955void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000956 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000957 unsigned Index = 1;
958 for (MCAssembler::iterator it = Asm.begin(),
959 ie = Asm.end(); it != ie; ++it) {
960 const MCSectionELF &Section =
961 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000962 if (Section.getType() != ELF::SHT_GROUP)
963 continue;
964 SectionIndexMap[&Section] = Index++;
965 }
966
967 for (MCAssembler::iterator it = Asm.begin(),
968 ie = Asm.end(); it != ie; ++it) {
Rafael Espindolaead85492015-02-17 20:31:13 +0000969 const MCSectionData &SD = *it;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000970 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000971 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000972 if (Section.getType() == ELF::SHT_GROUP ||
973 Section.getType() == ELF::SHT_REL ||
974 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000975 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000976 SectionIndexMap[&Section] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000977 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
978 const MCSectionELF *RelSection =
979 static_cast<const MCSectionELF *>(&RelSD->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000980 SectionIndexMap[RelSection] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000981 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000982 }
983}
984
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000985void ELFObjectWriter::computeSymbolTable(
986 MCAssembler &Asm, const MCAsmLayout &Layout,
987 const SectionIndexMapTy &SectionIndexMap,
988 const RevGroupMapTy &RevGroupMap) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000989 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000990 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000991 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000992 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000993 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
994 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
995 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000996 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000997 }
998
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000999 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +00001000 for (MCSymbolData &SD : Asm.symbols()) {
1001 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001002
Rafael Espindola16145972010-11-01 14:28:48 +00001003 bool Used = UsedInReloc.count(&Symbol);
1004 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001005 bool isSignature = RevGroupMap.count(&Symbol);
1006
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001007 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001008 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001009 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001010 continue;
1011
Matt Fleming6c1ad482010-08-16 18:57:57 +00001012 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001013 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001014 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001015
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001016 // Undefined symbols are global, but this is the first place we
1017 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001018 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001019 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001020 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001021 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001022 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001023 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001024 }
1025
Rafael Espindola022bb762014-03-24 03:43:21 +00001026 if (!BaseSymbol) {
1027 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001028 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001029 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001030 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001031 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001032 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001033 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001034 else
1035 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001036 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001037 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001038 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001039 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001040 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001041 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001042 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001043 }
1044
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001045 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1046 // in defined ones.
1047 //
1048 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001049 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001050 // trivial.
1051 //
1052 // We thus have to be careful to not perform the symbol version replacement
1053 // blindly:
1054 //
1055 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1056 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1057 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1058 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1059 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1060 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1061 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1062 // "__imp_?" or "__imp_@?".
1063 //
1064 // It would have been interesting to perform the MS mangling prefix check
1065 // only when the target triple is of the form *-pc-windows-elf. But, it
1066 // seems that this information is not easily accessible from the
1067 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001068 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001069 if (!Name.startswith("?") && !Name.startswith("@?") &&
1070 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1071 // This symbol isn't following the MSVC C++ name mangling convention. We
1072 // can thus safely interpret the @@@ in symbol names as specifying symbol
1073 // versioning.
1074 SmallString<32> Buf;
1075 size_t Pos = Name.find("@@@");
1076 if (Pos != StringRef::npos) {
1077 Buf += Name.substr(0, Pos);
1078 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1079 Buf += Name.substr(Pos + Skip);
1080 Name = Buf;
1081 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001082 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001083
1084 // Sections have their own string table
1085 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1086 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001087
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001088 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1089 UndefinedSymbolData.push_back(MSD);
1090 else if (Local)
1091 LocalSymbolData.push_back(MSD);
1092 else
1093 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001094 }
1095
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001096 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1097 StrTabBuilder.add(*i);
1098
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001099 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001100
1101 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1102 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1103
Rafael Espindolab6613022014-10-17 01:48:58 +00001104 for (ELFSymbolData &MSD : LocalSymbolData)
1105 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1106 ? 0
1107 : StrTabBuilder.getOffset(MSD.Name);
1108 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001109 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1110 for (ELFSymbolData& MSD : UndefinedSymbolData)
1111 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1112
Matt Fleming6c1ad482010-08-16 18:57:57 +00001113 // Symbols are required to be in lexicographic order.
1114 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1115 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1116 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1117
1118 // Set the symbol indices. Local symbols must come before all other
1119 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001120 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001121 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1122 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001123
Matt Fleming6c1ad482010-08-16 18:57:57 +00001124 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1125 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1126 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1127 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1128}
1129
Rafael Espindolaead85492015-02-17 20:31:13 +00001130MCSectionData *
1131ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1132 const MCSectionData &SD) {
1133 if (Relocations[&SD].empty())
1134 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001135
Rafael Espindolaead85492015-02-17 20:31:13 +00001136 MCContext &Ctx = Asm.getContext();
1137 const MCSectionELF &Section =
1138 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001139
Rafael Espindolaead85492015-02-17 20:31:13 +00001140 const StringRef SectionName = Section.getSectionName();
1141 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1142 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001143
Rafael Espindolaead85492015-02-17 20:31:13 +00001144 unsigned EntrySize;
1145 if (hasRelocationAddend())
1146 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1147 else
1148 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001149
Rafael Espindolaead85492015-02-17 20:31:13 +00001150 unsigned Flags = 0;
Rafael Espindolac9d06922015-03-30 13:39:16 +00001151 if (Section.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001152 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001153
Rafael Espindolac9d06922015-03-30 13:39:16 +00001154 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001155 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001156 Flags, EntrySize, Section.getGroup(), &Section);
Rafael Espindolaead85492015-02-17 20:31:13 +00001157 return &Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001158}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001159
David Blaikiee06e8012014-04-11 22:11:50 +00001160static SmallVector<char, 128>
1161getUncompressedData(MCAsmLayout &Layout,
1162 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001163 SmallVector<char, 128> UncompressedData;
1164 for (const MCFragment &F : Fragments) {
1165 const SmallVectorImpl<char> *Contents;
1166 switch (F.getKind()) {
1167 case MCFragment::FT_Data:
1168 Contents = &cast<MCDataFragment>(F).getContents();
1169 break;
1170 case MCFragment::FT_Dwarf:
1171 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1172 break;
1173 case MCFragment::FT_DwarfFrame:
1174 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1175 break;
1176 default:
1177 llvm_unreachable(
1178 "Not expecting any other fragment types in a debug_* section");
1179 }
1180 UncompressedData.append(Contents->begin(), Contents->end());
1181 }
1182 return UncompressedData;
1183}
1184
1185// Include the debug info compression header:
1186// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1187// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001188static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001189prependCompressionHeader(uint64_t Size,
1190 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001191 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001192 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1193 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001194 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001195 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001196 CompressedContents.insert(CompressedContents.begin(),
1197 Magic.size() + sizeof(Size), 0);
1198 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1199 std::copy(reinterpret_cast<char *>(&Size),
1200 reinterpret_cast<char *>(&Size + 1),
1201 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001202 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001203}
1204
1205// Return a single fragment containing the compressed contents of the whole
1206// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001207static std::unique_ptr<MCDataFragment>
1208getCompressedFragment(MCAsmLayout &Layout,
1209 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001210 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1211
1212 // Gather the uncompressed data from all the fragments, recording the
1213 // alignment fragment, if seen, and any fixups.
1214 SmallVector<char, 128> UncompressedData =
1215 getUncompressedData(Layout, Fragments);
1216
1217 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1218
1219 zlib::Status Success = zlib::compress(
1220 StringRef(UncompressedData.data(), UncompressedData.size()),
1221 CompressedContents);
1222 if (Success != zlib::StatusOK)
1223 return nullptr;
1224
David Blaikie76d3a3c2014-04-18 21:52:26 +00001225 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1226 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001227
1228 return CompressedFragment;
1229}
1230
David Blaikie39fa6a22014-04-25 00:48:01 +00001231typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1232DefiningSymbolMap;
1233
1234static void UpdateSymbols(const MCAsmLayout &Layout,
1235 const std::vector<MCSymbolData *> &Symbols,
1236 MCFragment &NewFragment) {
1237 for (MCSymbolData *Sym : Symbols) {
1238 Sym->setOffset(Sym->getOffset() +
1239 Layout.getFragmentOffset(Sym->getFragment()));
1240 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001241 }
1242}
1243
David Blaikie8019bf82014-04-10 21:53:53 +00001244static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001245 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001246 const MCSectionELF &Section,
1247 MCSectionData &SD) {
1248 StringRef SectionName = Section.getSectionName();
1249 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1250
1251 std::unique_ptr<MCDataFragment> CompressedFragment =
1252 getCompressedFragment(Layout, Fragments);
1253
1254 // Leave the section as-is if the fragments could not be compressed.
1255 if (!CompressedFragment)
1256 return;
1257
David Blaikiec029ab42014-04-18 21:24:12 +00001258 // Update the fragment+offsets of any symbols referring to fragments in this
1259 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001260 auto I = DefiningSymbols.find(&SD);
1261 if (I != DefiningSymbols.end())
1262 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001263
David Blaikie8019bf82014-04-10 21:53:53 +00001264 // Invalidate the layout for the whole section since it will have new and
1265 // different fragments now.
1266 Layout.invalidateFragmentsFrom(&Fragments.front());
1267 Fragments.clear();
1268
1269 // Complete the initialization of the new fragment
1270 CompressedFragment->setParent(&SD);
1271 CompressedFragment->setLayoutOrder(0);
1272 Fragments.push_back(CompressedFragment.release());
1273
1274 // Rename from .debug_* to .zdebug_*
1275 Asm.getContext().renameELFSection(&Section,
1276 (".z" + SectionName.drop_front(1)).str());
1277}
1278
1279void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1280 MCAsmLayout &Layout) {
1281 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1282 return;
1283
David Blaikie39fa6a22014-04-25 00:48:01 +00001284 DefiningSymbolMap DefiningSymbols;
1285
1286 for (MCSymbolData &SD : Asm.symbols())
1287 if (MCFragment *F = SD.getFragment())
1288 DefiningSymbols[F->getParent()].push_back(&SD);
1289
David Blaikie8019bf82014-04-10 21:53:53 +00001290 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001291 const MCSectionELF &Section =
1292 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001293 StringRef SectionName = Section.getSectionName();
1294
1295 // Compressing debug_frame requires handling alignment fragments which is
1296 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1297 // for writing to arbitrary buffers) for little benefit.
1298 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1299 continue;
1300
David Blaikie39fa6a22014-04-25 00:48:01 +00001301 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001302 }
1303}
1304
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001305void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001306 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1307 MCSectionData &RelSD = *it;
1308 const MCSectionELF &RelSection =
1309 static_cast<const MCSectionELF &>(RelSD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001310
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001311 unsigned Type = RelSection.getType();
1312 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001313 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001314
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001315 const MCSectionELF *Section = RelSection.getAssociatedSection();
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001316 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1317 RelSD.setAlignment(is64Bit() ? 8 : 4);
1318
1319 MCDataFragment *F = new MCDataFragment(&RelSD);
1320 WriteRelocationsFragment(Asm, F, &SD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001321 }
1322}
1323
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001324void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1325 uint64_t Flags, uint64_t Address,
1326 uint64_t Offset, uint64_t Size,
1327 uint32_t Link, uint32_t Info,
1328 uint64_t Alignment,
1329 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001330 Write32(Name); // sh_name: index into string table
1331 Write32(Type); // sh_type
1332 WriteWord(Flags); // sh_flags
1333 WriteWord(Address); // sh_addr
1334 WriteWord(Offset); // sh_offset
1335 WriteWord(Size); // sh_size
1336 Write32(Link); // sh_link
1337 Write32(Info); // sh_info
1338 WriteWord(Alignment); // sh_addralign
1339 WriteWord(EntrySize); // sh_entsize
1340}
1341
Rafael Espindola5904e122014-03-29 06:26:49 +00001342// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1343// just to match gnu as for easier comparison. The use type is an arbitrary way
1344// of making the sort deterministic.
1345static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1346 const ELFRelocationEntry &A = *AP;
1347 const ELFRelocationEntry &B = *BP;
1348 if (A.Offset != B.Offset)
1349 return B.Offset - A.Offset;
1350 if (B.Type != A.Type)
1351 return A.Type - B.Type;
Daniel Sanders60f1db02015-03-13 12:45:09 +00001352 //llvm_unreachable("ELFRelocs might be unstable!");
1353 return 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001354}
1355
1356static void sortRelocs(const MCAssembler &Asm,
1357 std::vector<ELFRelocationEntry> &Relocs) {
1358 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1359}
1360
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001361void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1362 MCDataFragment *F,
1363 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001364 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001365
Rafael Espindola5904e122014-03-29 06:26:49 +00001366 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001367
1368 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001369 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001370 unsigned Index =
1371 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001372
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001373 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001374 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001375 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001376 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001377
Rafael Espindola5904e122014-03-29 06:26:49 +00001378 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1379 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1380 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1381 write(*F, TargetObjectWriter->getRType(Entry.Type));
1382 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001383 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001384 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001385 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001386 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001387 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001388 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001389 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001390 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001391
Rafael Espindolabce26a12010-10-05 15:11:03 +00001392 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001393 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001394 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001395
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001396 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001397 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001398 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001399 }
1400}
1401
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001402void ELFObjectWriter::CreateMetadataSections(
1403 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001404 MCContext &Ctx = Asm.getContext();
1405 MCDataFragment *F;
1406
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001407 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001408
Rafael Espindola0e527b72010-09-22 19:04:41 +00001409 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001410 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001411 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001412 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1413 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001414 ShstrtabIndex = SectionIndexMap.size() + 1;
1415 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001416
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001417 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001418 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001419 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001420 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001421 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001422 SymbolTableIndex = SectionIndexMap.size() + 1;
1423 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001424
Rafael Espindola1557fd62011-03-20 18:44:20 +00001425 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001426 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001427 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1428 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001429 StringTableIndex = SectionIndexMap.size() + 1;
1430 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001431
1432 // Symbol table
1433 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001434 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001435
Matt Fleming6c1ad482010-08-16 18:57:57 +00001436 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001437 F->getContents().append(StrTabBuilder.data().begin(),
1438 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001439
Matt Fleming6c1ad482010-08-16 18:57:57 +00001440 F = new MCDataFragment(&ShstrtabSD);
1441
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001442 // Section header string table.
1443 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001444 const MCSectionELF &Section =
1445 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001446 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001447 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001448 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001449 F->getContents().append(ShStrTabBuilder.data().begin(),
1450 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001451}
1452
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001453void ELFObjectWriter::createIndexedSections(
1454 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1455 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001456 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001457
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001458 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001459 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1460 it != ie; ++it) {
1461 const MCSectionELF &Section =
1462 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001463 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001464 continue;
1465
1466 const MCSymbol *SignatureSymbol = Section.getGroup();
1467 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001468 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001469 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001470 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001471 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1472 Data.setAlignment(4);
1473 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001474 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001475 }
1476 GroupMap[Group] = SignatureSymbol;
1477 }
1478
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001479 computeIndexMap(Asm, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001480
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001481 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001482 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001483 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001484 const MCSectionELF &Section =
1485 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001486 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001487 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001488 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001489 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1490 // FIXME: we could use the previous fragment
1491 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001492 uint32_t Index = SectionIndexMap.lookup(&Section);
1493 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001494 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001495}
1496
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001497void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001498 const SectionIndexMapTy &SectionIndexMap,
1499 uint32_t GroupSymbolIndex,
1500 uint64_t Offset, uint64_t Size,
1501 uint64_t Alignment,
1502 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001503 uint64_t sh_link = 0;
1504 uint64_t sh_info = 0;
1505
1506 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001507 default:
1508 // Nothing to do.
1509 break;
1510
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001511 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001512 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001513 break;
1514
1515 case ELF::SHT_REL:
1516 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001517 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001518 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001519 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001520 sh_info = SectionIndexMap.lookup(InfoSection);
1521 break;
1522 }
1523
1524 case ELF::SHT_SYMTAB:
1525 case ELF::SHT_DYNSYM:
1526 sh_link = StringTableIndex;
1527 sh_info = LastLocalSymbolIndex;
1528 break;
1529
1530 case ELF::SHT_SYMTAB_SHNDX:
1531 sh_link = SymbolTableIndex;
1532 break;
1533
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001534 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001535 sh_link = SymbolTableIndex;
1536 sh_info = GroupSymbolIndex;
1537 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001538 }
1539
Logan Chien4b724422013-02-05 14:18:59 +00001540 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001541 Section.getType() == ELF::SHT_ARM_EXIDX)
1542 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001543
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001544 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1545 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001546 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1547 Alignment, Section.getEntrySize());
1548}
1549
Jan Sjödin30a52de2011-02-28 21:45:04 +00001550bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001551 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001552 !SD.getSection().isVirtualSection();
1553}
1554
Jan Sjödin30a52de2011-02-28 21:45:04 +00001555uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001556 uint64_t Ret = 0;
1557 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1558 ++i) {
1559 const MCFragment &F = *i;
1560 assert(F.getKind() == MCFragment::FT_Data);
1561 Ret += cast<MCDataFragment>(F).getContents().size();
1562 }
1563 return Ret;
1564}
1565
Jan Sjödin30a52de2011-02-28 21:45:04 +00001566uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1567 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001568 if (IsELFMetaDataSection(SD))
1569 return DataSectionSize(SD);
1570 return Layout.getSectionFileSize(&SD);
1571}
1572
Jan Sjödin30a52de2011-02-28 21:45:04 +00001573uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1574 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001575 if (IsELFMetaDataSection(SD))
1576 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001577 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001578}
1579
Rafael Espindola1557fd62011-03-20 18:44:20 +00001580void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1581 const MCAsmLayout &Layout,
1582 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001583 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1584
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001585 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001586 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001587
1588 if (IsELFMetaDataSection(SD)) {
1589 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1590 ++i) {
1591 const MCFragment &F = *i;
1592 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001593 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001594 }
1595 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001596 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001597 }
1598}
1599
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001600void ELFObjectWriter::writeSectionHeader(
1601 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001602 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001603 const SectionOffsetMapTy &SectionOffsetMap) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001604 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001605
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001606 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001607 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001608
1609 for (SectionIndexMapTy::const_iterator i=
1610 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1611 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001612 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001613 }
1614
Matt Fleming6c1ad482010-08-16 18:57:57 +00001615 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001616 uint64_t FirstSectionSize =
1617 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1618 uint32_t FirstSectionLink =
1619 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1620 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001621
Rafael Espindola1557fd62011-03-20 18:44:20 +00001622 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001623 const MCSectionELF &Section = *Sections[i];
1624 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1625 uint32_t GroupSymbolIndex;
1626 if (Section.getType() != ELF::SHT_GROUP)
1627 GroupSymbolIndex = 0;
1628 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001629 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1630 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001631
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001632 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001633
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001634 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1635 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1636 Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001637 }
1638}
1639
Rafael Espindola1557fd62011-03-20 18:44:20 +00001640void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1641 std::vector<const MCSectionELF*> &Sections) {
1642 for (MCAssembler::iterator it = Asm.begin(),
1643 ie = Asm.end(); it != ie; ++it) {
1644 const MCSectionELF &Section =
1645 static_cast<const MCSectionELF &>(it->getSection());
1646 if (Section.getType() == ELF::SHT_GROUP)
1647 Sections.push_back(&Section);
1648 }
1649
1650 for (MCAssembler::iterator it = Asm.begin(),
1651 ie = Asm.end(); it != ie; ++it) {
1652 const MCSectionELF &Section =
1653 static_cast<const MCSectionELF &>(it->getSection());
1654 if (Section.getType() != ELF::SHT_GROUP &&
1655 Section.getType() != ELF::SHT_REL &&
1656 Section.getType() != ELF::SHT_RELA)
1657 Sections.push_back(&Section);
1658 }
1659
1660 for (MCAssembler::iterator it = Asm.begin(),
1661 ie = Asm.end(); it != ie; ++it) {
1662 const MCSectionELF &Section =
1663 static_cast<const MCSectionELF &>(it->getSection());
1664 if (Section.getType() == ELF::SHT_REL ||
1665 Section.getType() == ELF::SHT_RELA)
1666 Sections.push_back(&Section);
1667 }
1668}
1669
1670void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1671 const MCAsmLayout &Layout) {
1672 GroupMapTy GroupMap;
1673 RevGroupMapTy RevGroupMap;
1674 SectionIndexMapTy SectionIndexMap;
1675
David Blaikiee06e8012014-04-11 22:11:50 +00001676 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001677 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1678 RevGroupMap, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001679
Rafael Espindola39e20aa2015-04-07 19:17:47 +00001680 unsigned NumRegularSections = Asm.size();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001681
1682 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001683 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001684
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001685 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola1557fd62011-03-20 18:44:20 +00001686
1687 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1688 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001689 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001690
1691 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1692 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1693 sizeof(ELF::Elf32_Ehdr);
1694 uint64_t FileOff = HeaderSize;
1695
1696 std::vector<const MCSectionELF*> Sections;
1697 ComputeSectionOrder(Asm, Sections);
1698 unsigned NumSections = Sections.size();
1699 SectionOffsetMapTy SectionOffsetMap;
1700 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1701 const MCSectionELF &Section = *Sections[i];
1702 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1703
1704 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1705
1706 // Remember the offset into the file for this section.
1707 SectionOffsetMap[&Section] = FileOff;
1708
1709 // Get the size of the section in the output file (including padding).
1710 FileOff += GetSectionFileSize(Layout, SD);
1711 }
1712
1713 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1714
Rafael Espindola01f4c6c2015-04-07 21:51:41 +00001715 const unsigned SectionHeaderOffset = FileOff;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001716
1717 uint64_t SectionHeaderEntrySize = is64Bit() ?
1718 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1719 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1720
1721 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1722 const MCSectionELF &Section = *Sections[i];
1723 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1724
1725 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1726
1727 // Remember the offset into the file for this section.
1728 SectionOffsetMap[&Section] = FileOff;
1729
1730 // Get the size of the section in the output file (including padding).
1731 FileOff += GetSectionFileSize(Layout, SD);
1732 }
1733
1734 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001735 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001736
1737 // ... then the regular sections ...
1738 // + because of .shstrtab
1739 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1740 WriteDataSectionData(Asm, Layout, *Sections[i]);
1741
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001742 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001743 WriteZeros(Padding);
1744
1745 // ... then the section header table ...
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001746 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001747
Nick Lewycky4eb11432011-10-07 20:56:23 +00001748 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001749 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1750 WriteDataSectionData(Asm, Layout, *Sections[i]);
1751}
1752
Rafael Espindola94a88d72015-04-06 15:27:57 +00001753bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1754 const MCAssembler &Asm, const MCSymbolData &DataA,
1755 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1756 bool IsPCRel) const {
1757 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
Eli Friedmand92d17b2011-03-03 07:24:36 +00001758 return false;
1759 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola94a88d72015-04-06 15:27:57 +00001760 Asm, DataA, DataB, FB, InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001761}
1762
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001763bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1764 return ::isWeak(SD);
1765}
1766
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001767MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1768 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001769 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001770 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001771}