blob: 3fa857e69ac66b1ffab2526f645ac7ecf4ee30d9 [file] [log] [blame]
Nick Lewycky4288f9e2013-03-09 09:32:16 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
Matt Fleming6c1ad482010-08-16 18:57:57 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements ELF object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/MC/MCELFObjectWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallString.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000018#include "llvm/ADT/StringMap.h"
Evan Cheng5928e692011-07-25 23:24:55 +000019#include "llvm/MC/MCAsmBackend.h"
David Blaikie8019bf82014-04-10 21:53:53 +000020#include "llvm/MC/MCAsmInfo.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000021#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000022#include "llvm/MC/MCAssembler.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000023#include "llvm/MC/MCContext.h"
Tim Northover5cc3dc82012-12-07 16:50:23 +000024#include "llvm/MC/MCELF.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000025#include "llvm/MC/MCELFSymbolFlags.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000026#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000027#include "llvm/MC/MCFixupKindInfo.h"
28#include "llvm/MC/MCObjectWriter.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000029#include "llvm/MC/MCSectionELF.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000030#include "llvm/MC/MCValue.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000031#include "llvm/MC/StringTableBuilder.h"
David Blaikie8019bf82014-04-10 21:53:53 +000032#include "llvm/Support/Compression.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000033#include "llvm/Support/Debug.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000034#include "llvm/Support/ELF.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/Endian.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/ErrorHandling.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000037#include <vector>
38using namespace llvm;
39
Jason W Kimc09e7262011-05-11 22:53:06 +000040#undef DEBUG_TYPE
41#define DEBUG_TYPE "reloc-info"
42
Rafael Espindola29abd972011-12-22 03:38:00 +000043namespace {
Rafael Espindola0ce09712014-03-25 22:43:53 +000044class FragmentWriter {
45 bool IsLittleEndian;
46
47public:
48 FragmentWriter(bool IsLittleEndian);
49 template <typename T> void write(MCDataFragment &F, T Val);
50};
51
Rafael Espindola10be0832014-03-25 23:44:25 +000052typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
53
54class SymbolTableWriter {
55 MCAssembler &Asm;
56 FragmentWriter &FWriter;
57 bool Is64Bit;
58 SectionIndexMapTy &SectionIndexMap;
59
60 // The symbol .symtab fragment we are writting to.
61 MCDataFragment *SymtabF;
62
63 // .symtab_shndx fragment we are writting to.
64 MCDataFragment *ShndxF;
65
66 // The numbel of symbols written so far.
67 unsigned NumWritten;
68
69 void createSymtabShndx();
70
71 template <typename T> void write(MCDataFragment &F, T Value);
72
73public:
74 SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
75 SectionIndexMapTy &SectionIndexMap,
76 MCDataFragment *SymtabF);
77
78 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
79 uint8_t other, uint32_t shndx, bool Reserved);
80};
81
Rafael Espindola5904e122014-03-29 06:26:49 +000082struct ELFRelocationEntry {
83 uint64_t Offset; // Where is the relocation.
Rafael Espindolab6613022014-10-17 01:48:58 +000084 const MCSymbol *Symbol; // The symbol to relocate with.
Rafael Espindola5904e122014-03-29 06:26:49 +000085 unsigned Type; // The type of the relocation.
86 uint64_t Addend; // The addend to use.
87
88 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
89 uint64_t Addend)
Rafael Espindolab6613022014-10-17 01:48:58 +000090 : Offset(Offset), Symbol(Symbol), Type(Type), Addend(Addend) {}
Rafael Espindola5904e122014-03-29 06:26:49 +000091};
92
Rafael Espindola29abd972011-12-22 03:38:00 +000093class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola0ce09712014-03-25 22:43:53 +000094 FragmentWriter FWriter;
95
Rafael Espindola29abd972011-12-22 03:38:00 +000096 protected:
97
98 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
99 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
100 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000101 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
Rafael Espindola29abd972011-12-22 03:38:00 +0000102 bool Used, bool Renamed);
Rafael Espindola39f50422014-04-28 14:24:44 +0000103 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
Rafael Espindola29abd972011-12-22 03:38:00 +0000104 static bool IsELFMetaDataSection(const MCSectionData &SD);
105 static uint64_t DataSectionSize(const MCSectionData &SD);
106 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
107 const MCSectionData &SD);
108 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
109 const MCSectionData &SD);
110
111 void WriteDataSectionData(MCAssembler &Asm,
112 const MCAsmLayout &Layout,
113 const MCSectionELF &Section);
114
115 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
116 return Kind == X86::reloc_riprel_4byte ||
117 Kind == X86::reloc_riprel_4byte_movq_load;
118 }*/
119
120 /// ELFSymbolData - Helper struct for containing some precomputed
121 /// information on symbols.
122 struct ELFSymbolData {
123 MCSymbolData *SymbolData;
124 uint64_t StringIndex;
125 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000126 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000127
128 // Support lexicographic sorting.
129 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolab6613022014-10-17 01:48:58 +0000130 unsigned LHSType = MCELF::GetType(*SymbolData);
131 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
132 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
133 return false;
134 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
135 return true;
136 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
137 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000138 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000139 }
140 };
141
Rafael Espindola29abd972011-12-22 03:38:00 +0000142 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000143 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000144
145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
146 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
147 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
148
Rafael Espindola5904e122014-03-29 06:26:49 +0000149 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
150 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000151 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000152
153 /// @}
154 /// @name Symbol Table Data
155 /// @{
156
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000157 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000158 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000159 std::vector<ELFSymbolData> LocalSymbolData;
160 std::vector<ELFSymbolData> ExternalSymbolData;
161 std::vector<ELFSymbolData> UndefinedSymbolData;
162
163 /// @}
164
165 bool NeedsGOT;
166
Rafael Espindola29abd972011-12-22 03:38:00 +0000167 // This holds the symbol table index of the last local symbol.
168 unsigned LastLocalSymbolIndex;
169 // This holds the .strtab section index.
170 unsigned StringTableIndex;
171 // This holds the .symtab section index.
172 unsigned SymbolTableIndex;
173
174 unsigned ShstrtabIndex;
175
176
Rafael Espindola29abd972011-12-22 03:38:00 +0000177 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000178 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
179 bool hasRelocationAddend() const {
180 return TargetObjectWriter->hasRelocationAddend();
181 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000182 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000183 bool IsPCRel) const {
184 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000185 }
186
Rafael Espindola29abd972011-12-22 03:38:00 +0000187 public:
David Blaikie9f380a32015-03-16 18:06:57 +0000188 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &OS,
Rafael Espindola0ce09712014-03-25 22:43:53 +0000189 bool IsLittleEndian)
David Blaikie9f380a32015-03-16 18:06:57 +0000190 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000191 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000192
Yaron Keren7773a722015-03-23 18:35:01 +0000193 void reset() override {
194 UsedInReloc.clear();
195 WeakrefUsedInReloc.clear();
196 Renames.clear();
197 Relocations.clear();
198 ShStrTabBuilder.clear();
199 StrTabBuilder.clear();
200 FileSymbolData.clear();
201 LocalSymbolData.clear();
202 ExternalSymbolData.clear();
203 UndefinedSymbolData.clear();
204 MCObjectWriter::reset();
205 }
206
Rafael Espindola29abd972011-12-22 03:38:00 +0000207 virtual ~ELFObjectWriter();
208
209 void WriteWord(uint64_t W) {
210 if (is64Bit())
211 Write64(W);
212 else
213 Write32(W);
214 }
215
Rafael Espindola0ce09712014-03-25 22:43:53 +0000216 template <typename T> void write(MCDataFragment &F, T Value) {
217 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000218 }
219
Jack Carter1bd90ff2013-01-30 02:09:52 +0000220 void WriteHeader(const MCAssembler &Asm,
221 uint64_t SectionDataSize,
Rafael Espindola29abd972011-12-22 03:38:00 +0000222 unsigned NumberOfSections);
223
Rafael Espindola10be0832014-03-25 23:44:25 +0000224 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000225 const MCAsmLayout &Layout);
226
Rafael Espindola10be0832014-03-25 23:44:25 +0000227 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000228 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000229 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000230
Rafael Espindolab60c8292014-04-29 12:46:50 +0000231 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
232 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000233 const MCSymbolData *SD, uint64_t C,
234 unsigned Type) const;
235
Rafael Espindola26585542015-01-19 21:11:14 +0000236 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000237 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000238 MCValue Target, bool &IsPCRel,
239 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000240
241 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
242 const MCSymbol *S);
243
244 // Map from a group section to the signature symbol
245 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
246 // Map from a signature symbol to the group section
247 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
Rafael Espindola29abd972011-12-22 03:38:00 +0000248 // Map from a section to its offset
249 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
250
Rafael Espindola022bb762014-03-24 03:43:21 +0000251 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000252 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000253 /// \param Asm - The assembler.
254 /// \param SectionIndexMap - Maps a section to its index.
255 /// \param RevGroupMap - Maps a signature symbol to the group section.
256 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000257 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000258 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000259 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000260
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000261 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000262
Rafael Espindolaead85492015-02-17 20:31:13 +0000263 MCSectionData *createRelocationSection(MCAssembler &Asm,
264 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000265
David Blaikie8019bf82014-04-10 21:53:53 +0000266 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
267
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000268 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
Rafael Espindola29abd972011-12-22 03:38:00 +0000269
270 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolaef6baea2015-02-11 23:11:18 +0000271 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000272
273 // Create the sections that show up in the symbol table. Currently
274 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaead85492015-02-17 20:31:13 +0000275 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000276 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
277 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000278
Craig Topper34a61bc2014-03-08 07:02:02 +0000279 void ExecutePostLayoutBinding(MCAssembler &Asm,
280 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000281
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000282 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000283 const MCAsmLayout &Layout,
284 const SectionIndexMapTy &SectionIndexMap,
285 const SectionOffsetMapTy &SectionOffsetMap);
286
287 void ComputeSectionOrder(MCAssembler &Asm,
288 std::vector<const MCSectionELF*> &Sections);
289
290 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
291 uint64_t Address, uint64_t Offset,
292 uint64_t Size, uint32_t Link, uint32_t Info,
293 uint64_t Alignment, uint64_t EntrySize);
294
295 void WriteRelocationsFragment(const MCAssembler &Asm,
296 MCDataFragment *F,
297 const MCSectionData *SD);
298
Craig Topper34a61bc2014-03-08 07:02:02 +0000299 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000300 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
301 const MCSymbolData &DataA,
Rafael Espindola94a88d72015-04-06 15:27:57 +0000302 const MCSymbolData *DataB,
Rafael Espindola29abd972011-12-22 03:38:00 +0000303 const MCFragment &FB,
304 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000305 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000306
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000307 bool isWeak(const MCSymbolData &SD) const override;
308
Craig Topper34a61bc2014-03-08 07:02:02 +0000309 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000310 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000311 const SectionIndexMapTy &SectionIndexMap,
312 uint32_t GroupSymbolIndex,
313 uint64_t Offset, uint64_t Size, uint64_t Alignment,
314 const MCSectionELF &Section);
315 };
316}
317
Rafael Espindola0ce09712014-03-25 22:43:53 +0000318FragmentWriter::FragmentWriter(bool IsLittleEndian)
319 : IsLittleEndian(IsLittleEndian) {}
320
321template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
322 if (IsLittleEndian)
323 Val = support::endian::byte_swap<T, support::little>(Val);
324 else
325 Val = support::endian::byte_swap<T, support::big>(Val);
326 const char *Start = (const char *)&Val;
327 F.getContents().append(Start, Start + sizeof(T));
328}
329
Rafael Espindola10be0832014-03-25 23:44:25 +0000330void SymbolTableWriter::createSymtabShndx() {
331 if (ShndxF)
332 return;
333
334 MCContext &Ctx = Asm.getContext();
335 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000336 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000337 MCSectionData *SymtabShndxSD =
338 &Asm.getOrCreateSectionData(*SymtabShndxSection);
339 SymtabShndxSD->setAlignment(4);
340 ShndxF = new MCDataFragment(SymtabShndxSD);
341 unsigned Index = SectionIndexMap.size() + 1;
342 SectionIndexMap[SymtabShndxSection] = Index;
343
344 for (unsigned I = 0; I < NumWritten; ++I)
345 write(*ShndxF, uint32_t(0));
346}
347
348template <typename T>
349void SymbolTableWriter::write(MCDataFragment &F, T Value) {
350 FWriter.write(F, Value);
351}
352
353SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
354 bool Is64Bit,
355 SectionIndexMapTy &SectionIndexMap,
356 MCDataFragment *SymtabF)
357 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
358 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
359 NumWritten(0) {}
360
361void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
362 uint64_t size, uint8_t other,
363 uint32_t shndx, bool Reserved) {
364 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
365
366 if (LargeIndex)
367 createSymtabShndx();
368
369 if (ShndxF) {
370 if (LargeIndex)
371 write(*ShndxF, shndx);
372 else
373 write(*ShndxF, uint32_t(0));
374 }
375
376 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
377
378 raw_svector_ostream OS(SymtabF->getContents());
379
380 if (Is64Bit) {
381 write(*SymtabF, name); // st_name
382 write(*SymtabF, info); // st_info
383 write(*SymtabF, other); // st_other
384 write(*SymtabF, Index); // st_shndx
385 write(*SymtabF, value); // st_value
386 write(*SymtabF, size); // st_size
387 } else {
388 write(*SymtabF, name); // st_name
389 write(*SymtabF, uint32_t(value)); // st_value
390 write(*SymtabF, uint32_t(size)); // st_size
391 write(*SymtabF, info); // st_info
392 write(*SymtabF, other); // st_other
393 write(*SymtabF, Index); // st_shndx
394 }
395
396 ++NumWritten;
397}
398
Jan Sjödin30a52de2011-02-28 21:45:04 +0000399bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
400 const MCFixupKindInfo &FKI =
401 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
402
403 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
404}
405
406bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
407 switch (Variant) {
408 default:
409 return false;
410 case MCSymbolRefExpr::VK_GOT:
411 case MCSymbolRefExpr::VK_PLT:
412 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000413 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000414 case MCSymbolRefExpr::VK_TPOFF:
415 case MCSymbolRefExpr::VK_TLSGD:
416 case MCSymbolRefExpr::VK_GOTTPOFF:
417 case MCSymbolRefExpr::VK_INDNTPOFF:
418 case MCSymbolRefExpr::VK_NTPOFF:
419 case MCSymbolRefExpr::VK_GOTNTPOFF:
420 case MCSymbolRefExpr::VK_TLSLDM:
421 case MCSymbolRefExpr::VK_DTPOFF:
422 case MCSymbolRefExpr::VK_TLSLD:
423 return true;
424 }
425}
426
Jason W Kim96f4c012010-11-15 16:18:39 +0000427ELFObjectWriter::~ELFObjectWriter()
428{}
429
Matt Fleming6c1ad482010-08-16 18:57:57 +0000430// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000431void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
432 uint64_t SectionDataSize,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000433 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000434 // ELF Header
435 // ----------
436 //
437 // Note
438 // ----
439 // emitWord method behaves differently for ELF32 and ELF64, writing
440 // 4 bytes in the former and 8 in the latter.
441
442 Write8(0x7f); // e_ident[EI_MAG0]
443 Write8('E'); // e_ident[EI_MAG1]
444 Write8('L'); // e_ident[EI_MAG2]
445 Write8('F'); // e_ident[EI_MAG3]
446
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000447 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000448
449 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000450 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000451
452 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000453 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000454 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000455 Write8(0); // e_ident[EI_ABIVERSION]
456
457 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
458
459 Write16(ELF::ET_REL); // e_type
460
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000461 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000462
463 Write32(ELF::EV_CURRENT); // e_version
464 WriteWord(0); // e_entry, no entry point in .o file
465 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000466 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramer896bd7e2010-08-17 17:02:29 +0000467 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000468
Jason W Kim4761fba2011-02-04 21:41:11 +0000469 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000470 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000471
472 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000473 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000474
475 Write16(0); // e_phentsize = prog header entry size
476 Write16(0); // e_phnum = # prog header entries = 0
477
478 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000479 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000480
481 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000482 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000483 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000484 else
485 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000486
487 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000488 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000489 Write16(ELF::SHN_XINDEX);
490 else
491 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000492}
493
Rafael Espindolafee224f2014-04-30 21:51:13 +0000494uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000495 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000496 if (Data.isCommon() && Data.isExternal())
497 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000498
Rafael Espindolafee224f2014-04-30 21:51:13 +0000499 uint64_t Res;
500 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000501 return 0;
502
Rafael Espindolafee224f2014-04-30 21:51:13 +0000503 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000504 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000505
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000506 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000507}
508
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000509void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
510 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000511 // The presence of symbol versions causes undefined symbols and
512 // versions declared with @@@ to be renamed.
513
David Blaikie583a31c2014-04-18 18:24:25 +0000514 for (MCSymbolData &OriginalData : Asm.symbols()) {
515 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000516
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000517 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000518 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000519 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000520 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
521 if (!Ref)
522 continue;
523 const MCSymbol &Symbol = Ref->getSymbol();
524 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000525
Benjamin Kramer14807272010-10-27 19:53:52 +0000526 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000527 size_t Pos = AliasName.find('@');
528 if (Pos == StringRef::npos)
529 continue;
530
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000531 // Aliases defined with .symvar copy the binding from the symbol they alias.
532 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000533 OriginalData.setExternal(SD.isExternal());
534 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000535
Benjamin Kramer14807272010-10-27 19:53:52 +0000536 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000537 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
538 continue;
539
Rafael Espindola26496e62010-10-27 17:56:18 +0000540 // FIXME: produce a better error message.
541 if (Symbol.isUndefined() && Rest.startswith("@@") &&
542 !Rest.startswith("@@@"))
543 report_fatal_error("A @@ version cannot be undefined");
544
Benjamin Kramer14807272010-10-27 19:53:52 +0000545 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000546 }
547}
548
Roman Divacky5a1c5492014-01-07 20:17:03 +0000549static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
550 uint8_t Type = newType;
551
552 // Propagation rules:
553 // IFUNC > FUNC > OBJECT > NOTYPE
554 // TLS_OBJECT > OBJECT > NOTYPE
555 //
556 // dont let the new type degrade the old type
557 switch (origType) {
558 default:
559 break;
560 case ELF::STT_GNU_IFUNC:
561 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
562 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
563 Type = ELF::STT_GNU_IFUNC;
564 break;
565 case ELF::STT_FUNC:
566 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
567 Type == ELF::STT_TLS)
568 Type = ELF::STT_FUNC;
569 break;
570 case ELF::STT_OBJECT:
571 if (Type == ELF::STT_NOTYPE)
572 Type = ELF::STT_OBJECT;
573 break;
574 case ELF::STT_TLS:
575 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
576 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
577 Type = ELF::STT_TLS;
578 break;
579 }
580
581 return Type;
582}
583
Rafael Espindola10be0832014-03-25 23:44:25 +0000584void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000585 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000586 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000587 assert((!OrigData.getFragment() ||
588 (&OrigData.getFragment()->getParent()->getSection() ==
589 &OrigData.getSymbol().getSection())) &&
590 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000591 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000592
593 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
594 // SHN_COMMON.
595 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000596
Jack Carter2f8d9d92013-02-19 21:57:35 +0000597 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000598 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000599 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000600 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000601 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000602 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
603 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000604 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000605 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000606
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000607 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000608 // 2 bits
609 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000610 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000611 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000612
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000613 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000614 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000615
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000616 const MCExpr *ESize = OrigData.getSize();
617 if (!ESize && Base)
618 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000619
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000620 if (ESize) {
621 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000622 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000623 report_fatal_error("Size expression must be absolute.");
624 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000625 }
626
627 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000628 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
629 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000630}
631
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000632void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000633 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000634 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000635 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000636 // The string table must be emitted first because we need the index
637 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000638
639 // FIXME: Make sure the start of the symbol table is aligned.
640
Rafael Espindola10be0832014-03-25 23:44:25 +0000641 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
642
Matt Fleming6c1ad482010-08-16 18:57:57 +0000643 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000644 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000645
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000646 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000647 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
648 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000649 }
650
Matt Fleming6c1ad482010-08-16 18:57:57 +0000651 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000652 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
653
Matt Fleming6c1ad482010-08-16 18:57:57 +0000654 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
655 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000656 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000657 }
658
Matt Fleming6c1ad482010-08-16 18:57:57 +0000659 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
660 ELFSymbolData &MSD = ExternalSymbolData[i];
661 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000662 assert(((Data.getFlags() & ELF_STB_Global) ||
663 (Data.getFlags() & ELF_STB_Weak)) &&
664 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000665 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000666 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000667 LastLocalSymbolIndex++;
668 }
669
670 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
671 ELFSymbolData &MSD = UndefinedSymbolData[i];
672 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000673 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000674 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000675 LastLocalSymbolIndex++;
676 }
677}
678
Rafael Espindola5904e122014-03-29 06:26:49 +0000679// It is always valid to create a relocation with a symbol. It is preferable
680// to use a relocation with a section if that is possible. Using the section
681// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000682bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
683 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000684 const MCSymbolData *SD,
685 uint64_t C,
686 unsigned Type) const {
687 // A PCRel relocation to an absolute value has no symbol (or section). We
688 // represent that with a relocation to a null section.
689 if (!RefA)
690 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000691
Rafael Espindola5904e122014-03-29 06:26:49 +0000692 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
693 switch (Kind) {
694 default:
695 break;
696 // The .odp creation emits a relocation against the symbol ".TOC." which
697 // create a R_PPC64_TOC relocation. However the relocation symbol name
698 // in final object creation should be NULL, since the symbol does not
699 // really exist, it is just the reference to TOC base for the current
700 // object file. Since the symbol is undefined, returning false results
701 // in a relocation with a null section which is the desired result.
702 case MCSymbolRefExpr::VK_PPC_TOCBASE:
703 return false;
704
705 // These VariantKind cause the relocation to refer to something other than
706 // the symbol itself, like a linker generated table. Since the address of
707 // symbol is not relevant, we cannot replace the symbol with the
708 // section and patch the difference in the addend.
709 case MCSymbolRefExpr::VK_GOT:
710 case MCSymbolRefExpr::VK_PLT:
711 case MCSymbolRefExpr::VK_GOTPCREL:
712 case MCSymbolRefExpr::VK_Mips_GOT:
713 case MCSymbolRefExpr::VK_PPC_GOT_LO:
714 case MCSymbolRefExpr::VK_PPC_GOT_HI:
715 case MCSymbolRefExpr::VK_PPC_GOT_HA:
716 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000717 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000718
Rafael Espindola5904e122014-03-29 06:26:49 +0000719 // An undefined symbol is not in any section, so the relocation has to point
720 // to the symbol itself.
721 const MCSymbol &Sym = SD->getSymbol();
722 if (Sym.isUndefined())
723 return true;
724
725 unsigned Binding = MCELF::GetBinding(*SD);
726 switch(Binding) {
727 default:
728 llvm_unreachable("Invalid Binding");
729 case ELF::STB_LOCAL:
730 break;
731 case ELF::STB_WEAK:
732 // If the symbol is weak, it might be overridden by a symbol in another
733 // file. The relocation has to point to the symbol so that the linker
734 // can update it.
735 return true;
736 case ELF::STB_GLOBAL:
737 // Global ELF symbols can be preempted by the dynamic linker. The relocation
738 // has to point to the symbol for a reason analogous to the STB_WEAK case.
739 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000740 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000741
Rafael Espindola5904e122014-03-29 06:26:49 +0000742 // If a relocation points to a mergeable section, we have to be careful.
743 // If the offset is zero, a relocation with the section will encode the
744 // same information. With a non-zero offset, the situation is different.
745 // For example, a relocation can point 42 bytes past the end of a string.
746 // If we change such a relocation to use the section, the linker would think
747 // that it pointed to another string and subtracting 42 at runtime will
748 // produce the wrong value.
749 auto &Sec = cast<MCSectionELF>(Sym.getSection());
750 unsigned Flags = Sec.getFlags();
751 if (Flags & ELF::SHF_MERGE) {
752 if (C != 0)
753 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000754
755 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
756 // only handle section relocations to mergeable sections if using RELA.
757 if (!hasRelocationAddend())
758 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000759 }
760
Rafael Espindola5904e122014-03-29 06:26:49 +0000761 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000762 // are just an offset (@tpoff), require a symbol in gold versions before
763 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
764 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000765 if (Flags & ELF::SHF_TLS)
766 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000767
Rafael Espindola9ef84412014-04-11 19:18:01 +0000768 // If the symbol is a thumb function the final relocation must set the lowest
769 // bit. With a symbol that is done by just having the symbol have that bit
770 // set, so we would lose the bit if we relocated with the section.
771 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000772 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000773 return true;
774
Ulrich Weigand46797c62014-07-20 23:15:06 +0000775 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000776 return true;
777 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000778}
779
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000780static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
781 const MCSymbol &Sym = Ref.getSymbol();
782
783 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
784 return &Sym;
785
786 if (!Sym.isVariable())
787 return nullptr;
788
789 const MCExpr *Expr = Sym.getVariableValue();
790 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
791 if (!Inner)
792 return nullptr;
793
794 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
795 return &Inner->getSymbol();
796 return nullptr;
797}
798
Rafael Espindolac9e70682015-03-24 23:48:44 +0000799static bool isWeak(const MCSymbolData &D) {
800 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
801}
802
Rafael Espindola26585542015-01-19 21:11:14 +0000803void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000804 const MCAsmLayout &Layout,
805 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000806 const MCFixup &Fixup, MCValue Target,
807 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000808 const MCSectionData *FixupSection = Fragment->getParent();
809 uint64_t C = Target.getConstant();
810 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000811
Rafael Espindola5904e122014-03-29 06:26:49 +0000812 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
813 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
814 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000815
Rafael Espindola5904e122014-03-29 06:26:49 +0000816 // Let A, B and C being the components of Target and R be the location of
817 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
818 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000819
Rafael Espindola5904e122014-03-29 06:26:49 +0000820 // In general, ELF has no relocations for -B. It can only represent (A + C)
821 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
822 // replace B to implement it: (A - R - K + C)
823 if (IsPCRel)
824 Asm.getContext().FatalError(
825 Fixup.getLoc(),
826 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000827
Rafael Espindola5904e122014-03-29 06:26:49 +0000828 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000829
Rafael Espindola5904e122014-03-29 06:26:49 +0000830 if (SymB.isUndefined())
831 Asm.getContext().FatalError(
832 Fixup.getLoc(),
833 Twine("symbol '") + SymB.getName() +
834 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000835
Rafael Espindola5904e122014-03-29 06:26:49 +0000836 assert(!SymB.isAbsolute() && "Should have been folded");
837 const MCSection &SecB = SymB.getSection();
838 if (&SecB != &FixupSection->getSection())
839 Asm.getContext().FatalError(
840 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000841
Rafael Espindola5904e122014-03-29 06:26:49 +0000842 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000843 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000844 Asm.getContext().FatalError(
845 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
846
Rafael Espindola5904e122014-03-29 06:26:49 +0000847 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
848 uint64_t K = SymBOffset - FixupOffset;
849 IsPCRel = true;
850 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000851 }
852
Rafael Espindola5904e122014-03-29 06:26:49 +0000853 // We either rejected the fixup or folded B into C at this point.
854 const MCSymbolRefExpr *RefA = Target.getSymA();
855 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
856 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
857
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000858 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000859 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000860 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
861 C += Layout.getSymbolOffset(SymAD);
862
863 uint64_t Addend = 0;
864 if (hasRelocationAddend()) {
865 Addend = C;
866 C = 0;
867 }
868
869 FixedValue = C;
870
871 // FIXME: What is this!?!?
872 MCSymbolRefExpr::VariantKind Modifier =
873 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000874 if (RelocNeedsGOT(Modifier))
875 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000876
Rafael Espindola5904e122014-03-29 06:26:49 +0000877 if (!RelocateWithSymbol) {
878 const MCSection *SecA =
879 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000880 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
881 MCSymbol *SectionSymbol =
882 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
883 : nullptr;
884 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000885 Relocations[FixupSection].push_back(Rec);
886 return;
887 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000888
Rafael Espindola5904e122014-03-29 06:26:49 +0000889 if (SymA) {
890 if (const MCSymbol *R = Renames.lookup(SymA))
891 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000892
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000893 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
894 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000895 else
896 UsedInReloc.insert(SymA);
897 }
898 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
899 Relocations[FixupSection].push_back(Rec);
900 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000901}
902
903
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000904uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000905ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
906 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000907 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000908 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000909}
910
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000911bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
912 const MCSymbolData &Data, bool Used,
913 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000914 const MCSymbol &Symbol = Data.getSymbol();
915 if (Symbol.isVariable()) {
916 const MCExpr *Expr = Symbol.getVariableValue();
917 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
918 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
919 return false;
920 }
921 }
Rafael Espindola16145972010-11-01 14:28:48 +0000922
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000923 if (Used)
924 return true;
925
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000926 if (Renamed)
927 return false;
928
Rafael Espindola45834a02010-10-29 23:09:31 +0000929 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
930 return true;
931
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000932 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000933 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000934 if (Base && Base->isUndefined())
935 return false;
936 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000937
Jan Sjödin30a52de2011-02-28 21:45:04 +0000938 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000939 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000940 return false;
941
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000942 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000943 return false;
944
945 return true;
946}
947
Rafael Espindola39f50422014-04-28 14:24:44 +0000948bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000949 if (Data.isExternal())
950 return false;
951
952 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000953 if (Symbol.isDefined())
954 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000955
Rafael Espindola39f50422014-04-28 14:24:44 +0000956 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000957 return false;
958
959 return true;
960}
961
Rafael Espindolaead85492015-02-17 20:31:13 +0000962void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000963 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000964 unsigned Index = 1;
965 for (MCAssembler::iterator it = Asm.begin(),
966 ie = Asm.end(); it != ie; ++it) {
967 const MCSectionELF &Section =
968 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000969 if (Section.getType() != ELF::SHT_GROUP)
970 continue;
971 SectionIndexMap[&Section] = Index++;
972 }
973
974 for (MCAssembler::iterator it = Asm.begin(),
975 ie = Asm.end(); it != ie; ++it) {
Rafael Espindolaead85492015-02-17 20:31:13 +0000976 const MCSectionData &SD = *it;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000977 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000978 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000979 if (Section.getType() == ELF::SHT_GROUP ||
980 Section.getType() == ELF::SHT_REL ||
981 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000982 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000983 SectionIndexMap[&Section] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000984 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
985 const MCSectionELF *RelSection =
986 static_cast<const MCSectionELF *>(&RelSD->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000987 SectionIndexMap[RelSection] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000988 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000989 }
990}
991
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000992void ELFObjectWriter::computeSymbolTable(
993 MCAssembler &Asm, const MCAsmLayout &Layout,
994 const SectionIndexMapTy &SectionIndexMap,
995 const RevGroupMapTy &RevGroupMap) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000996 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000997 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000998 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000999 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001000 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1001 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1002 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001003 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001004 }
1005
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001006 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +00001007 for (MCSymbolData &SD : Asm.symbols()) {
1008 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001009
Rafael Espindola16145972010-11-01 14:28:48 +00001010 bool Used = UsedInReloc.count(&Symbol);
1011 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001012 bool isSignature = RevGroupMap.count(&Symbol);
1013
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001014 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001015 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001016 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001017 continue;
1018
Matt Fleming6c1ad482010-08-16 18:57:57 +00001019 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001020 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001021 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001022
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001023 // Undefined symbols are global, but this is the first place we
1024 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001025 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001026 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001027 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001028 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001029 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001030 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001031 }
1032
Rafael Espindola022bb762014-03-24 03:43:21 +00001033 if (!BaseSymbol) {
1034 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001035 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001036 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001037 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001038 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001039 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001040 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001041 else
1042 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001043 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001044 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001045 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001046 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001047 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001048 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001049 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001050 }
1051
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001052 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1053 // in defined ones.
1054 //
1055 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001056 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001057 // trivial.
1058 //
1059 // We thus have to be careful to not perform the symbol version replacement
1060 // blindly:
1061 //
1062 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1063 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1064 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1065 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1066 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1067 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1068 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1069 // "__imp_?" or "__imp_@?".
1070 //
1071 // It would have been interesting to perform the MS mangling prefix check
1072 // only when the target triple is of the form *-pc-windows-elf. But, it
1073 // seems that this information is not easily accessible from the
1074 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001075 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001076 if (!Name.startswith("?") && !Name.startswith("@?") &&
1077 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1078 // This symbol isn't following the MSVC C++ name mangling convention. We
1079 // can thus safely interpret the @@@ in symbol names as specifying symbol
1080 // versioning.
1081 SmallString<32> Buf;
1082 size_t Pos = Name.find("@@@");
1083 if (Pos != StringRef::npos) {
1084 Buf += Name.substr(0, Pos);
1085 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1086 Buf += Name.substr(Pos + Skip);
1087 Name = Buf;
1088 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001089 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001090
1091 // Sections have their own string table
1092 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1093 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001094
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001095 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1096 UndefinedSymbolData.push_back(MSD);
1097 else if (Local)
1098 LocalSymbolData.push_back(MSD);
1099 else
1100 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001101 }
1102
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001103 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1104 StrTabBuilder.add(*i);
1105
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001106 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001107
1108 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1109 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1110
Rafael Espindolab6613022014-10-17 01:48:58 +00001111 for (ELFSymbolData &MSD : LocalSymbolData)
1112 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1113 ? 0
1114 : StrTabBuilder.getOffset(MSD.Name);
1115 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001116 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1117 for (ELFSymbolData& MSD : UndefinedSymbolData)
1118 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1119
Matt Fleming6c1ad482010-08-16 18:57:57 +00001120 // Symbols are required to be in lexicographic order.
1121 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1122 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1123 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1124
1125 // Set the symbol indices. Local symbols must come before all other
1126 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001127 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001128 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1129 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001130
Matt Fleming6c1ad482010-08-16 18:57:57 +00001131 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1132 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1133 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1134 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1135}
1136
Rafael Espindolaead85492015-02-17 20:31:13 +00001137MCSectionData *
1138ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1139 const MCSectionData &SD) {
1140 if (Relocations[&SD].empty())
1141 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001142
Rafael Espindolaead85492015-02-17 20:31:13 +00001143 MCContext &Ctx = Asm.getContext();
1144 const MCSectionELF &Section =
1145 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001146
Rafael Espindolaead85492015-02-17 20:31:13 +00001147 const StringRef SectionName = Section.getSectionName();
1148 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1149 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001150
Rafael Espindolaead85492015-02-17 20:31:13 +00001151 unsigned EntrySize;
1152 if (hasRelocationAddend())
1153 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1154 else
1155 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001156
Rafael Espindolaead85492015-02-17 20:31:13 +00001157 unsigned Flags = 0;
Rafael Espindolac9d06922015-03-30 13:39:16 +00001158 if (Section.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001159 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001160
Rafael Espindolac9d06922015-03-30 13:39:16 +00001161 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001162 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001163 Flags, EntrySize, Section.getGroup(), &Section);
Rafael Espindolaead85492015-02-17 20:31:13 +00001164 return &Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001165}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001166
David Blaikiee06e8012014-04-11 22:11:50 +00001167static SmallVector<char, 128>
1168getUncompressedData(MCAsmLayout &Layout,
1169 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001170 SmallVector<char, 128> UncompressedData;
1171 for (const MCFragment &F : Fragments) {
1172 const SmallVectorImpl<char> *Contents;
1173 switch (F.getKind()) {
1174 case MCFragment::FT_Data:
1175 Contents = &cast<MCDataFragment>(F).getContents();
1176 break;
1177 case MCFragment::FT_Dwarf:
1178 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1179 break;
1180 case MCFragment::FT_DwarfFrame:
1181 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1182 break;
1183 default:
1184 llvm_unreachable(
1185 "Not expecting any other fragment types in a debug_* section");
1186 }
1187 UncompressedData.append(Contents->begin(), Contents->end());
1188 }
1189 return UncompressedData;
1190}
1191
1192// Include the debug info compression header:
1193// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1194// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001195static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001196prependCompressionHeader(uint64_t Size,
1197 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001198 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001199 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1200 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001201 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001202 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001203 CompressedContents.insert(CompressedContents.begin(),
1204 Magic.size() + sizeof(Size), 0);
1205 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1206 std::copy(reinterpret_cast<char *>(&Size),
1207 reinterpret_cast<char *>(&Size + 1),
1208 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001209 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001210}
1211
1212// Return a single fragment containing the compressed contents of the whole
1213// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001214static std::unique_ptr<MCDataFragment>
1215getCompressedFragment(MCAsmLayout &Layout,
1216 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001217 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1218
1219 // Gather the uncompressed data from all the fragments, recording the
1220 // alignment fragment, if seen, and any fixups.
1221 SmallVector<char, 128> UncompressedData =
1222 getUncompressedData(Layout, Fragments);
1223
1224 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1225
1226 zlib::Status Success = zlib::compress(
1227 StringRef(UncompressedData.data(), UncompressedData.size()),
1228 CompressedContents);
1229 if (Success != zlib::StatusOK)
1230 return nullptr;
1231
David Blaikie76d3a3c2014-04-18 21:52:26 +00001232 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1233 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001234
1235 return CompressedFragment;
1236}
1237
David Blaikie39fa6a22014-04-25 00:48:01 +00001238typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1239DefiningSymbolMap;
1240
1241static void UpdateSymbols(const MCAsmLayout &Layout,
1242 const std::vector<MCSymbolData *> &Symbols,
1243 MCFragment &NewFragment) {
1244 for (MCSymbolData *Sym : Symbols) {
1245 Sym->setOffset(Sym->getOffset() +
1246 Layout.getFragmentOffset(Sym->getFragment()));
1247 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001248 }
1249}
1250
David Blaikie8019bf82014-04-10 21:53:53 +00001251static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001252 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001253 const MCSectionELF &Section,
1254 MCSectionData &SD) {
1255 StringRef SectionName = Section.getSectionName();
1256 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1257
1258 std::unique_ptr<MCDataFragment> CompressedFragment =
1259 getCompressedFragment(Layout, Fragments);
1260
1261 // Leave the section as-is if the fragments could not be compressed.
1262 if (!CompressedFragment)
1263 return;
1264
David Blaikiec029ab42014-04-18 21:24:12 +00001265 // Update the fragment+offsets of any symbols referring to fragments in this
1266 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001267 auto I = DefiningSymbols.find(&SD);
1268 if (I != DefiningSymbols.end())
1269 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001270
David Blaikie8019bf82014-04-10 21:53:53 +00001271 // Invalidate the layout for the whole section since it will have new and
1272 // different fragments now.
1273 Layout.invalidateFragmentsFrom(&Fragments.front());
1274 Fragments.clear();
1275
1276 // Complete the initialization of the new fragment
1277 CompressedFragment->setParent(&SD);
1278 CompressedFragment->setLayoutOrder(0);
1279 Fragments.push_back(CompressedFragment.release());
1280
1281 // Rename from .debug_* to .zdebug_*
1282 Asm.getContext().renameELFSection(&Section,
1283 (".z" + SectionName.drop_front(1)).str());
1284}
1285
1286void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1287 MCAsmLayout &Layout) {
1288 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1289 return;
1290
David Blaikie39fa6a22014-04-25 00:48:01 +00001291 DefiningSymbolMap DefiningSymbols;
1292
1293 for (MCSymbolData &SD : Asm.symbols())
1294 if (MCFragment *F = SD.getFragment())
1295 DefiningSymbols[F->getParent()].push_back(&SD);
1296
David Blaikie8019bf82014-04-10 21:53:53 +00001297 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001298 const MCSectionELF &Section =
1299 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001300 StringRef SectionName = Section.getSectionName();
1301
1302 // Compressing debug_frame requires handling alignment fragments which is
1303 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1304 // for writing to arbitrary buffers) for little benefit.
1305 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1306 continue;
1307
David Blaikie39fa6a22014-04-25 00:48:01 +00001308 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001309 }
1310}
1311
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001312void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001313 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1314 MCSectionData &RelSD = *it;
1315 const MCSectionELF &RelSection =
1316 static_cast<const MCSectionELF &>(RelSD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001317
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001318 unsigned Type = RelSection.getType();
1319 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001320 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001321
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001322 const MCSectionELF *Section = RelSection.getAssociatedSection();
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001323 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1324 RelSD.setAlignment(is64Bit() ? 8 : 4);
1325
1326 MCDataFragment *F = new MCDataFragment(&RelSD);
1327 WriteRelocationsFragment(Asm, F, &SD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001328 }
1329}
1330
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001331void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1332 uint64_t Flags, uint64_t Address,
1333 uint64_t Offset, uint64_t Size,
1334 uint32_t Link, uint32_t Info,
1335 uint64_t Alignment,
1336 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001337 Write32(Name); // sh_name: index into string table
1338 Write32(Type); // sh_type
1339 WriteWord(Flags); // sh_flags
1340 WriteWord(Address); // sh_addr
1341 WriteWord(Offset); // sh_offset
1342 WriteWord(Size); // sh_size
1343 Write32(Link); // sh_link
1344 Write32(Info); // sh_info
1345 WriteWord(Alignment); // sh_addralign
1346 WriteWord(EntrySize); // sh_entsize
1347}
1348
Rafael Espindola5904e122014-03-29 06:26:49 +00001349// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1350// just to match gnu as for easier comparison. The use type is an arbitrary way
1351// of making the sort deterministic.
1352static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1353 const ELFRelocationEntry &A = *AP;
1354 const ELFRelocationEntry &B = *BP;
1355 if (A.Offset != B.Offset)
1356 return B.Offset - A.Offset;
1357 if (B.Type != A.Type)
1358 return A.Type - B.Type;
Daniel Sanders60f1db02015-03-13 12:45:09 +00001359 //llvm_unreachable("ELFRelocs might be unstable!");
1360 return 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001361}
1362
1363static void sortRelocs(const MCAssembler &Asm,
1364 std::vector<ELFRelocationEntry> &Relocs) {
1365 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1366}
1367
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001368void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1369 MCDataFragment *F,
1370 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001371 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001372
Rafael Espindola5904e122014-03-29 06:26:49 +00001373 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001374
1375 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001376 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001377 unsigned Index =
1378 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001379
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001380 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001381 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001382 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001383 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001384
Rafael Espindola5904e122014-03-29 06:26:49 +00001385 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1386 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1387 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1388 write(*F, TargetObjectWriter->getRType(Entry.Type));
1389 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001390 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001391 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001392 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001393 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001394 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001395 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001396 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001397 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001398
Rafael Espindolabce26a12010-10-05 15:11:03 +00001399 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001400 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001401 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001402
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001403 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001404 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001405 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001406 }
1407}
1408
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001409void ELFObjectWriter::CreateMetadataSections(
1410 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001411 MCContext &Ctx = Asm.getContext();
1412 MCDataFragment *F;
1413
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001414 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001415
Rafael Espindola0e527b72010-09-22 19:04:41 +00001416 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001417 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001418 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001419 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1420 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001421 ShstrtabIndex = SectionIndexMap.size() + 1;
1422 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001423
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001424 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001425 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001426 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001427 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001428 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001429 SymbolTableIndex = SectionIndexMap.size() + 1;
1430 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001431
Rafael Espindola1557fd62011-03-20 18:44:20 +00001432 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001433 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001434 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1435 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001436 StringTableIndex = SectionIndexMap.size() + 1;
1437 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001438
1439 // Symbol table
1440 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001441 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001442
Matt Fleming6c1ad482010-08-16 18:57:57 +00001443 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001444 F->getContents().append(StrTabBuilder.data().begin(),
1445 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001446
Matt Fleming6c1ad482010-08-16 18:57:57 +00001447 F = new MCDataFragment(&ShstrtabSD);
1448
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001449 // Section header string table.
1450 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001451 const MCSectionELF &Section =
1452 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001453 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001454 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001455 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001456 F->getContents().append(ShStrTabBuilder.data().begin(),
1457 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001458}
1459
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001460void ELFObjectWriter::createIndexedSections(
1461 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1462 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001463 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001464
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001465 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001466 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1467 it != ie; ++it) {
1468 const MCSectionELF &Section =
1469 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001470 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001471 continue;
1472
1473 const MCSymbol *SignatureSymbol = Section.getGroup();
1474 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001475 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001476 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001477 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001478 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1479 Data.setAlignment(4);
1480 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001481 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001482 }
1483 GroupMap[Group] = SignatureSymbol;
1484 }
1485
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001486 computeIndexMap(Asm, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001487
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001488 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001489 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001490 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001491 const MCSectionELF &Section =
1492 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001493 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001494 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001495 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001496 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1497 // FIXME: we could use the previous fragment
1498 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001499 uint32_t Index = SectionIndexMap.lookup(&Section);
1500 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001501 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001502}
1503
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001504void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001505 const SectionIndexMapTy &SectionIndexMap,
1506 uint32_t GroupSymbolIndex,
1507 uint64_t Offset, uint64_t Size,
1508 uint64_t Alignment,
1509 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001510 uint64_t sh_link = 0;
1511 uint64_t sh_info = 0;
1512
1513 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001514 default:
1515 // Nothing to do.
1516 break;
1517
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001518 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001519 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001520 break;
1521
1522 case ELF::SHT_REL:
1523 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001524 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001525 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001526 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001527 sh_info = SectionIndexMap.lookup(InfoSection);
1528 break;
1529 }
1530
1531 case ELF::SHT_SYMTAB:
1532 case ELF::SHT_DYNSYM:
1533 sh_link = StringTableIndex;
1534 sh_info = LastLocalSymbolIndex;
1535 break;
1536
1537 case ELF::SHT_SYMTAB_SHNDX:
1538 sh_link = SymbolTableIndex;
1539 break;
1540
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001541 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001542 sh_link = SymbolTableIndex;
1543 sh_info = GroupSymbolIndex;
1544 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001545 }
1546
Logan Chien4b724422013-02-05 14:18:59 +00001547 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001548 Section.getType() == ELF::SHT_ARM_EXIDX)
1549 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001550
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001551 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1552 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001553 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1554 Alignment, Section.getEntrySize());
1555}
1556
Jan Sjödin30a52de2011-02-28 21:45:04 +00001557bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001558 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001559 !SD.getSection().isVirtualSection();
1560}
1561
Jan Sjödin30a52de2011-02-28 21:45:04 +00001562uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001563 uint64_t Ret = 0;
1564 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1565 ++i) {
1566 const MCFragment &F = *i;
1567 assert(F.getKind() == MCFragment::FT_Data);
1568 Ret += cast<MCDataFragment>(F).getContents().size();
1569 }
1570 return Ret;
1571}
1572
Jan Sjödin30a52de2011-02-28 21:45:04 +00001573uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1574 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001575 if (IsELFMetaDataSection(SD))
1576 return DataSectionSize(SD);
1577 return Layout.getSectionFileSize(&SD);
1578}
1579
Jan Sjödin30a52de2011-02-28 21:45:04 +00001580uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1581 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001582 if (IsELFMetaDataSection(SD))
1583 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001584 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001585}
1586
Rafael Espindola1557fd62011-03-20 18:44:20 +00001587void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1588 const MCAsmLayout &Layout,
1589 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001590 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1591
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001592 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001593 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001594
1595 if (IsELFMetaDataSection(SD)) {
1596 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1597 ++i) {
1598 const MCFragment &F = *i;
1599 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001600 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001601 }
1602 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001603 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001604 }
1605}
1606
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001607void ELFObjectWriter::writeSectionHeader(
1608 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001609 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001610 const SectionOffsetMapTy &SectionOffsetMap) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001611 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001612
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001613 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001614 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001615
1616 for (SectionIndexMapTy::const_iterator i=
1617 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1618 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001619 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001620 }
1621
Matt Fleming6c1ad482010-08-16 18:57:57 +00001622 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001623 uint64_t FirstSectionSize =
1624 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1625 uint32_t FirstSectionLink =
1626 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1627 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001628
Rafael Espindola1557fd62011-03-20 18:44:20 +00001629 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001630 const MCSectionELF &Section = *Sections[i];
1631 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1632 uint32_t GroupSymbolIndex;
1633 if (Section.getType() != ELF::SHT_GROUP)
1634 GroupSymbolIndex = 0;
1635 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001636 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1637 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001638
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001639 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001640
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001641 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1642 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1643 Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001644 }
1645}
1646
Rafael Espindola1557fd62011-03-20 18:44:20 +00001647void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1648 std::vector<const MCSectionELF*> &Sections) {
1649 for (MCAssembler::iterator it = Asm.begin(),
1650 ie = Asm.end(); it != ie; ++it) {
1651 const MCSectionELF &Section =
1652 static_cast<const MCSectionELF &>(it->getSection());
1653 if (Section.getType() == ELF::SHT_GROUP)
1654 Sections.push_back(&Section);
1655 }
1656
1657 for (MCAssembler::iterator it = Asm.begin(),
1658 ie = Asm.end(); it != ie; ++it) {
1659 const MCSectionELF &Section =
1660 static_cast<const MCSectionELF &>(it->getSection());
1661 if (Section.getType() != ELF::SHT_GROUP &&
1662 Section.getType() != ELF::SHT_REL &&
1663 Section.getType() != ELF::SHT_RELA)
1664 Sections.push_back(&Section);
1665 }
1666
1667 for (MCAssembler::iterator it = Asm.begin(),
1668 ie = Asm.end(); it != ie; ++it) {
1669 const MCSectionELF &Section =
1670 static_cast<const MCSectionELF &>(it->getSection());
1671 if (Section.getType() == ELF::SHT_REL ||
1672 Section.getType() == ELF::SHT_RELA)
1673 Sections.push_back(&Section);
1674 }
1675}
1676
1677void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1678 const MCAsmLayout &Layout) {
1679 GroupMapTy GroupMap;
1680 RevGroupMapTy RevGroupMap;
1681 SectionIndexMapTy SectionIndexMap;
1682
1683 unsigned NumUserSections = Asm.size();
1684
David Blaikiee06e8012014-04-11 22:11:50 +00001685 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001686
Rafael Espindola1557fd62011-03-20 18:44:20 +00001687 const unsigned NumUserAndRelocSections = Asm.size();
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001688 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1689 RevGroupMap, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001690 const unsigned AllSections = Asm.size();
1691 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1692
1693 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1694
1695 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001696 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001697
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001698 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola1557fd62011-03-20 18:44:20 +00001699
1700 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1701 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001702 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001703
1704 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1705 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1706 sizeof(ELF::Elf32_Ehdr);
1707 uint64_t FileOff = HeaderSize;
1708
1709 std::vector<const MCSectionELF*> Sections;
1710 ComputeSectionOrder(Asm, Sections);
1711 unsigned NumSections = Sections.size();
1712 SectionOffsetMapTy SectionOffsetMap;
1713 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1714 const MCSectionELF &Section = *Sections[i];
1715 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1716
1717 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1718
1719 // Remember the offset into the file for this section.
1720 SectionOffsetMap[&Section] = FileOff;
1721
1722 // Get the size of the section in the output file (including padding).
1723 FileOff += GetSectionFileSize(Layout, SD);
1724 }
1725
1726 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1727
1728 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1729
1730 uint64_t SectionHeaderEntrySize = is64Bit() ?
1731 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1732 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1733
1734 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1735 const MCSectionELF &Section = *Sections[i];
1736 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1737
1738 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1739
1740 // Remember the offset into the file for this section.
1741 SectionOffsetMap[&Section] = FileOff;
1742
1743 // Get the size of the section in the output file (including padding).
1744 FileOff += GetSectionFileSize(Layout, SD);
1745 }
1746
1747 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001748 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001749
1750 // ... then the regular sections ...
1751 // + because of .shstrtab
1752 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1753 WriteDataSectionData(Asm, Layout, *Sections[i]);
1754
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001755 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001756 WriteZeros(Padding);
1757
1758 // ... then the section header table ...
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001759 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001760
Nick Lewycky4eb11432011-10-07 20:56:23 +00001761 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001762 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1763 WriteDataSectionData(Asm, Layout, *Sections[i]);
1764}
1765
Rafael Espindola94a88d72015-04-06 15:27:57 +00001766bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1767 const MCAssembler &Asm, const MCSymbolData &DataA,
1768 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1769 bool IsPCRel) const {
1770 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
Eli Friedmand92d17b2011-03-03 07:24:36 +00001771 return false;
1772 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola94a88d72015-04-06 15:27:57 +00001773 Asm, DataA, DataB, FB, InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001774}
1775
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001776bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1777 return ::isWeak(SD);
1778}
1779
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001780MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1781 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001782 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001783 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001784}