blob: 2004b1b8a2de3a602f49acdba33c8c806ffc220a [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,
Benjamin Kramer04f9da82014-09-19 12:26:38 +0000259 const RevGroupMapTy &RevGroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000260 unsigned NumRegularSections);
261
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000262 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000263
Rafael Espindolaead85492015-02-17 20:31:13 +0000264 MCSectionData *createRelocationSection(MCAssembler &Asm,
265 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000266
David Blaikie8019bf82014-04-10 21:53:53 +0000267 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
268
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000269 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
Rafael Espindola29abd972011-12-22 03:38:00 +0000270
271 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolaef6baea2015-02-11 23:11:18 +0000272 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000273
274 // Create the sections that show up in the symbol table. Currently
275 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaead85492015-02-17 20:31:13 +0000276 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000277 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
278 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000279
Craig Topper34a61bc2014-03-08 07:02:02 +0000280 void ExecutePostLayoutBinding(MCAssembler &Asm,
281 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000282
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000283 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000284 const MCAsmLayout &Layout,
285 const SectionIndexMapTy &SectionIndexMap,
286 const SectionOffsetMapTy &SectionOffsetMap);
287
288 void ComputeSectionOrder(MCAssembler &Asm,
289 std::vector<const MCSectionELF*> &Sections);
290
291 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
292 uint64_t Address, uint64_t Offset,
293 uint64_t Size, uint32_t Link, uint32_t Info,
294 uint64_t Alignment, uint64_t EntrySize);
295
296 void WriteRelocationsFragment(const MCAssembler &Asm,
297 MCDataFragment *F,
298 const MCSectionData *SD);
299
Craig Topper34a61bc2014-03-08 07:02:02 +0000300 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000301 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
302 const MCSymbolData &DataA,
303 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;
622 if (!ESize->EvaluateAsAbsolute(Res, Layout))
623 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 Espindola022bb762014-03-24 03:43:21 +0000992void
993ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
994 const SectionIndexMapTy &SectionIndexMap,
Benjamin Kramer04f9da82014-09-19 12:26:38 +0000995 const RevGroupMapTy &RevGroupMap,
Rafael Espindola022bb762014-03-24 03:43:21 +0000996 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000997 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000998 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000999 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00001000 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001001 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1002 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1003 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001004 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001005 }
1006
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001007 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +00001008 for (MCSymbolData &SD : Asm.symbols()) {
1009 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001010
Rafael Espindola16145972010-11-01 14:28:48 +00001011 bool Used = UsedInReloc.count(&Symbol);
1012 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001013 bool isSignature = RevGroupMap.count(&Symbol);
1014
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001015 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001016 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001017 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001018 continue;
1019
Matt Fleming6c1ad482010-08-16 18:57:57 +00001020 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001021 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001022 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001023
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001024 // Undefined symbols are global, but this is the first place we
1025 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001026 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001027 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001028 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001029 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001030 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001031 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001032 }
1033
Rafael Espindola022bb762014-03-24 03:43:21 +00001034 if (!BaseSymbol) {
1035 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001036 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001037 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001038 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001039 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001040 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001041 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001042 else
1043 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001044 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001045 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001046 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001047 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001048 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001049 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001050 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001051 }
1052
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001053 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1054 // in defined ones.
1055 //
1056 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001057 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001058 // trivial.
1059 //
1060 // We thus have to be careful to not perform the symbol version replacement
1061 // blindly:
1062 //
1063 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1064 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1065 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1066 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1067 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1068 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1069 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1070 // "__imp_?" or "__imp_@?".
1071 //
1072 // It would have been interesting to perform the MS mangling prefix check
1073 // only when the target triple is of the form *-pc-windows-elf. But, it
1074 // seems that this information is not easily accessible from the
1075 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001076 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001077 if (!Name.startswith("?") && !Name.startswith("@?") &&
1078 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1079 // This symbol isn't following the MSVC C++ name mangling convention. We
1080 // can thus safely interpret the @@@ in symbol names as specifying symbol
1081 // versioning.
1082 SmallString<32> Buf;
1083 size_t Pos = Name.find("@@@");
1084 if (Pos != StringRef::npos) {
1085 Buf += Name.substr(0, Pos);
1086 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1087 Buf += Name.substr(Pos + Skip);
1088 Name = Buf;
1089 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001090 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001091
1092 // Sections have their own string table
1093 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1094 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001095
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001096 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1097 UndefinedSymbolData.push_back(MSD);
1098 else if (Local)
1099 LocalSymbolData.push_back(MSD);
1100 else
1101 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001102 }
1103
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001104 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1105 StrTabBuilder.add(*i);
1106
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001107 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001108
1109 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1110 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1111
Rafael Espindolab6613022014-10-17 01:48:58 +00001112 for (ELFSymbolData &MSD : LocalSymbolData)
1113 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1114 ? 0
1115 : StrTabBuilder.getOffset(MSD.Name);
1116 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001117 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1118 for (ELFSymbolData& MSD : UndefinedSymbolData)
1119 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1120
Matt Fleming6c1ad482010-08-16 18:57:57 +00001121 // Symbols are required to be in lexicographic order.
1122 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1123 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1124 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1125
1126 // Set the symbol indices. Local symbols must come before all other
1127 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001128 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001129 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1130 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001131
Matt Fleming6c1ad482010-08-16 18:57:57 +00001132 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1133 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1134 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1135 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1136}
1137
Rafael Espindolaead85492015-02-17 20:31:13 +00001138MCSectionData *
1139ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1140 const MCSectionData &SD) {
1141 if (Relocations[&SD].empty())
1142 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001143
Rafael Espindolaead85492015-02-17 20:31:13 +00001144 MCContext &Ctx = Asm.getContext();
1145 const MCSectionELF &Section =
1146 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001147
Rafael Espindolaead85492015-02-17 20:31:13 +00001148 const StringRef SectionName = Section.getSectionName();
1149 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1150 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001151
Rafael Espindolaead85492015-02-17 20:31:13 +00001152 unsigned EntrySize;
1153 if (hasRelocationAddend())
1154 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1155 else
1156 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001157
Rafael Espindolaead85492015-02-17 20:31:13 +00001158 unsigned Flags = 0;
Rafael Espindolac9d06922015-03-30 13:39:16 +00001159 if (Section.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001160 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001161
Rafael Espindolac9d06922015-03-30 13:39:16 +00001162 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001163 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001164 Flags, EntrySize, Section.getGroup(), &Section);
Rafael Espindolaead85492015-02-17 20:31:13 +00001165 return &Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001166}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001167
David Blaikiee06e8012014-04-11 22:11:50 +00001168static SmallVector<char, 128>
1169getUncompressedData(MCAsmLayout &Layout,
1170 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001171 SmallVector<char, 128> UncompressedData;
1172 for (const MCFragment &F : Fragments) {
1173 const SmallVectorImpl<char> *Contents;
1174 switch (F.getKind()) {
1175 case MCFragment::FT_Data:
1176 Contents = &cast<MCDataFragment>(F).getContents();
1177 break;
1178 case MCFragment::FT_Dwarf:
1179 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1180 break;
1181 case MCFragment::FT_DwarfFrame:
1182 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1183 break;
1184 default:
1185 llvm_unreachable(
1186 "Not expecting any other fragment types in a debug_* section");
1187 }
1188 UncompressedData.append(Contents->begin(), Contents->end());
1189 }
1190 return UncompressedData;
1191}
1192
1193// Include the debug info compression header:
1194// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1195// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001196static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001197prependCompressionHeader(uint64_t Size,
1198 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001199 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001200 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1201 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001202 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001203 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001204 CompressedContents.insert(CompressedContents.begin(),
1205 Magic.size() + sizeof(Size), 0);
1206 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1207 std::copy(reinterpret_cast<char *>(&Size),
1208 reinterpret_cast<char *>(&Size + 1),
1209 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001210 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001211}
1212
1213// Return a single fragment containing the compressed contents of the whole
1214// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001215static std::unique_ptr<MCDataFragment>
1216getCompressedFragment(MCAsmLayout &Layout,
1217 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001218 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1219
1220 // Gather the uncompressed data from all the fragments, recording the
1221 // alignment fragment, if seen, and any fixups.
1222 SmallVector<char, 128> UncompressedData =
1223 getUncompressedData(Layout, Fragments);
1224
1225 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1226
1227 zlib::Status Success = zlib::compress(
1228 StringRef(UncompressedData.data(), UncompressedData.size()),
1229 CompressedContents);
1230 if (Success != zlib::StatusOK)
1231 return nullptr;
1232
David Blaikie76d3a3c2014-04-18 21:52:26 +00001233 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1234 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001235
1236 return CompressedFragment;
1237}
1238
David Blaikie39fa6a22014-04-25 00:48:01 +00001239typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1240DefiningSymbolMap;
1241
1242static void UpdateSymbols(const MCAsmLayout &Layout,
1243 const std::vector<MCSymbolData *> &Symbols,
1244 MCFragment &NewFragment) {
1245 for (MCSymbolData *Sym : Symbols) {
1246 Sym->setOffset(Sym->getOffset() +
1247 Layout.getFragmentOffset(Sym->getFragment()));
1248 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001249 }
1250}
1251
David Blaikie8019bf82014-04-10 21:53:53 +00001252static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001253 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001254 const MCSectionELF &Section,
1255 MCSectionData &SD) {
1256 StringRef SectionName = Section.getSectionName();
1257 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1258
1259 std::unique_ptr<MCDataFragment> CompressedFragment =
1260 getCompressedFragment(Layout, Fragments);
1261
1262 // Leave the section as-is if the fragments could not be compressed.
1263 if (!CompressedFragment)
1264 return;
1265
David Blaikiec029ab42014-04-18 21:24:12 +00001266 // Update the fragment+offsets of any symbols referring to fragments in this
1267 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001268 auto I = DefiningSymbols.find(&SD);
1269 if (I != DefiningSymbols.end())
1270 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001271
David Blaikie8019bf82014-04-10 21:53:53 +00001272 // Invalidate the layout for the whole section since it will have new and
1273 // different fragments now.
1274 Layout.invalidateFragmentsFrom(&Fragments.front());
1275 Fragments.clear();
1276
1277 // Complete the initialization of the new fragment
1278 CompressedFragment->setParent(&SD);
1279 CompressedFragment->setLayoutOrder(0);
1280 Fragments.push_back(CompressedFragment.release());
1281
1282 // Rename from .debug_* to .zdebug_*
1283 Asm.getContext().renameELFSection(&Section,
1284 (".z" + SectionName.drop_front(1)).str());
1285}
1286
1287void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1288 MCAsmLayout &Layout) {
1289 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1290 return;
1291
David Blaikie39fa6a22014-04-25 00:48:01 +00001292 DefiningSymbolMap DefiningSymbols;
1293
1294 for (MCSymbolData &SD : Asm.symbols())
1295 if (MCFragment *F = SD.getFragment())
1296 DefiningSymbols[F->getParent()].push_back(&SD);
1297
David Blaikie8019bf82014-04-10 21:53:53 +00001298 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001299 const MCSectionELF &Section =
1300 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001301 StringRef SectionName = Section.getSectionName();
1302
1303 // Compressing debug_frame requires handling alignment fragments which is
1304 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1305 // for writing to arbitrary buffers) for little benefit.
1306 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1307 continue;
1308
David Blaikie39fa6a22014-04-25 00:48:01 +00001309 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001310 }
1311}
1312
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001313void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001314 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1315 MCSectionData &RelSD = *it;
1316 const MCSectionELF &RelSection =
1317 static_cast<const MCSectionELF &>(RelSD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001318
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001319 unsigned Type = RelSection.getType();
1320 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001321 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001322
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001323 const MCSectionELF *Section = RelSection.getAssociatedSection();
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001324 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1325 RelSD.setAlignment(is64Bit() ? 8 : 4);
1326
1327 MCDataFragment *F = new MCDataFragment(&RelSD);
1328 WriteRelocationsFragment(Asm, F, &SD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001329 }
1330}
1331
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001332void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1333 uint64_t Flags, uint64_t Address,
1334 uint64_t Offset, uint64_t Size,
1335 uint32_t Link, uint32_t Info,
1336 uint64_t Alignment,
1337 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001338 Write32(Name); // sh_name: index into string table
1339 Write32(Type); // sh_type
1340 WriteWord(Flags); // sh_flags
1341 WriteWord(Address); // sh_addr
1342 WriteWord(Offset); // sh_offset
1343 WriteWord(Size); // sh_size
1344 Write32(Link); // sh_link
1345 Write32(Info); // sh_info
1346 WriteWord(Alignment); // sh_addralign
1347 WriteWord(EntrySize); // sh_entsize
1348}
1349
Rafael Espindola5904e122014-03-29 06:26:49 +00001350// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1351// just to match gnu as for easier comparison. The use type is an arbitrary way
1352// of making the sort deterministic.
1353static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1354 const ELFRelocationEntry &A = *AP;
1355 const ELFRelocationEntry &B = *BP;
1356 if (A.Offset != B.Offset)
1357 return B.Offset - A.Offset;
1358 if (B.Type != A.Type)
1359 return A.Type - B.Type;
Daniel Sanders60f1db02015-03-13 12:45:09 +00001360 //llvm_unreachable("ELFRelocs might be unstable!");
1361 return 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001362}
1363
1364static void sortRelocs(const MCAssembler &Asm,
1365 std::vector<ELFRelocationEntry> &Relocs) {
1366 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1367}
1368
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001369void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1370 MCDataFragment *F,
1371 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001372 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001373
Rafael Espindola5904e122014-03-29 06:26:49 +00001374 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001375
1376 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001377 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001378 unsigned Index =
1379 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001380
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001381 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001382 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001383 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001384 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001385
Rafael Espindola5904e122014-03-29 06:26:49 +00001386 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1387 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1388 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1389 write(*F, TargetObjectWriter->getRType(Entry.Type));
1390 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001391 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001392 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001393 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001394 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001395 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001396 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001397 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001398 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001399
Rafael Espindolabce26a12010-10-05 15:11:03 +00001400 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001401 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001402 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001403
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001404 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001405 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001406 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001407 }
1408}
1409
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001410void ELFObjectWriter::CreateMetadataSections(
1411 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001412 MCContext &Ctx = Asm.getContext();
1413 MCDataFragment *F;
1414
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001415 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001416
Rafael Espindola0e527b72010-09-22 19:04:41 +00001417 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001418 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001419 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001420 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1421 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001422 ShstrtabIndex = SectionIndexMap.size() + 1;
1423 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001424
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001425 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001426 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001427 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001428 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001429 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001430 SymbolTableIndex = SectionIndexMap.size() + 1;
1431 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001432
Rafael Espindola1557fd62011-03-20 18:44:20 +00001433 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001434 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001435 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1436 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001437 StringTableIndex = SectionIndexMap.size() + 1;
1438 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001439
1440 // Symbol table
1441 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001442 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001443
Matt Fleming6c1ad482010-08-16 18:57:57 +00001444 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001445 F->getContents().append(StrTabBuilder.data().begin(),
1446 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001447
Matt Fleming6c1ad482010-08-16 18:57:57 +00001448 F = new MCDataFragment(&ShstrtabSD);
1449
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001450 // Section header string table.
1451 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001452 const MCSectionELF &Section =
1453 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001454 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001455 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001456 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001457 F->getContents().append(ShStrTabBuilder.data().begin(),
1458 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001459}
1460
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001461void ELFObjectWriter::createIndexedSections(
1462 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1463 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001464 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001465
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001466 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001467 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1468 it != ie; ++it) {
1469 const MCSectionELF &Section =
1470 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001471 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001472 continue;
1473
1474 const MCSymbol *SignatureSymbol = Section.getGroup();
1475 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001476 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001477 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001478 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001479 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1480 Data.setAlignment(4);
1481 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001482 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001483 }
1484 GroupMap[Group] = SignatureSymbol;
1485 }
1486
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001487 computeIndexMap(Asm, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001488
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001489 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001490 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001491 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001492 const MCSectionELF &Section =
1493 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001494 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001495 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001496 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001497 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1498 // FIXME: we could use the previous fragment
1499 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001500 uint32_t Index = SectionIndexMap.lookup(&Section);
1501 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001502 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001503}
1504
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001505void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001506 const SectionIndexMapTy &SectionIndexMap,
1507 uint32_t GroupSymbolIndex,
1508 uint64_t Offset, uint64_t Size,
1509 uint64_t Alignment,
1510 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001511 uint64_t sh_link = 0;
1512 uint64_t sh_info = 0;
1513
1514 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001515 default:
1516 // Nothing to do.
1517 break;
1518
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001519 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001520 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001521 break;
1522
1523 case ELF::SHT_REL:
1524 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001525 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001526 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001527 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001528 sh_info = SectionIndexMap.lookup(InfoSection);
1529 break;
1530 }
1531
1532 case ELF::SHT_SYMTAB:
1533 case ELF::SHT_DYNSYM:
1534 sh_link = StringTableIndex;
1535 sh_info = LastLocalSymbolIndex;
1536 break;
1537
1538 case ELF::SHT_SYMTAB_SHNDX:
1539 sh_link = SymbolTableIndex;
1540 break;
1541
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001542 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001543 sh_link = SymbolTableIndex;
1544 sh_info = GroupSymbolIndex;
1545 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001546 }
1547
Logan Chien4b724422013-02-05 14:18:59 +00001548 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001549 Section.getType() == ELF::SHT_ARM_EXIDX)
1550 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001551
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001552 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1553 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001554 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1555 Alignment, Section.getEntrySize());
1556}
1557
Jan Sjödin30a52de2011-02-28 21:45:04 +00001558bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001559 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001560 !SD.getSection().isVirtualSection();
1561}
1562
Jan Sjödin30a52de2011-02-28 21:45:04 +00001563uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001564 uint64_t Ret = 0;
1565 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1566 ++i) {
1567 const MCFragment &F = *i;
1568 assert(F.getKind() == MCFragment::FT_Data);
1569 Ret += cast<MCDataFragment>(F).getContents().size();
1570 }
1571 return Ret;
1572}
1573
Jan Sjödin30a52de2011-02-28 21:45:04 +00001574uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1575 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001576 if (IsELFMetaDataSection(SD))
1577 return DataSectionSize(SD);
1578 return Layout.getSectionFileSize(&SD);
1579}
1580
Jan Sjödin30a52de2011-02-28 21:45:04 +00001581uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1582 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001583 if (IsELFMetaDataSection(SD))
1584 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001585 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001586}
1587
Rafael Espindola1557fd62011-03-20 18:44:20 +00001588void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1589 const MCAsmLayout &Layout,
1590 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001591 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1592
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001593 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001594 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001595
1596 if (IsELFMetaDataSection(SD)) {
1597 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1598 ++i) {
1599 const MCFragment &F = *i;
1600 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001601 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001602 }
1603 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001604 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001605 }
1606}
1607
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001608void ELFObjectWriter::writeSectionHeader(
1609 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001610 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001611 const SectionOffsetMapTy &SectionOffsetMap) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001612 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001613
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001614 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001615 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001616
1617 for (SectionIndexMapTy::const_iterator i=
1618 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1619 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001620 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001621 }
1622
Matt Fleming6c1ad482010-08-16 18:57:57 +00001623 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001624 uint64_t FirstSectionSize =
1625 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1626 uint32_t FirstSectionLink =
1627 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1628 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001629
Rafael Espindola1557fd62011-03-20 18:44:20 +00001630 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001631 const MCSectionELF &Section = *Sections[i];
1632 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1633 uint32_t GroupSymbolIndex;
1634 if (Section.getType() != ELF::SHT_GROUP)
1635 GroupSymbolIndex = 0;
1636 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001637 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1638 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001639
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001640 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001641
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001642 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1643 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1644 Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001645 }
1646}
1647
Rafael Espindola1557fd62011-03-20 18:44:20 +00001648void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1649 std::vector<const MCSectionELF*> &Sections) {
1650 for (MCAssembler::iterator it = Asm.begin(),
1651 ie = Asm.end(); it != ie; ++it) {
1652 const MCSectionELF &Section =
1653 static_cast<const MCSectionELF &>(it->getSection());
1654 if (Section.getType() == ELF::SHT_GROUP)
1655 Sections.push_back(&Section);
1656 }
1657
1658 for (MCAssembler::iterator it = Asm.begin(),
1659 ie = Asm.end(); it != ie; ++it) {
1660 const MCSectionELF &Section =
1661 static_cast<const MCSectionELF &>(it->getSection());
1662 if (Section.getType() != ELF::SHT_GROUP &&
1663 Section.getType() != ELF::SHT_REL &&
1664 Section.getType() != ELF::SHT_RELA)
1665 Sections.push_back(&Section);
1666 }
1667
1668 for (MCAssembler::iterator it = Asm.begin(),
1669 ie = Asm.end(); it != ie; ++it) {
1670 const MCSectionELF &Section =
1671 static_cast<const MCSectionELF &>(it->getSection());
1672 if (Section.getType() == ELF::SHT_REL ||
1673 Section.getType() == ELF::SHT_RELA)
1674 Sections.push_back(&Section);
1675 }
1676}
1677
1678void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1679 const MCAsmLayout &Layout) {
1680 GroupMapTy GroupMap;
1681 RevGroupMapTy RevGroupMap;
1682 SectionIndexMapTy SectionIndexMap;
1683
1684 unsigned NumUserSections = Asm.size();
1685
David Blaikiee06e8012014-04-11 22:11:50 +00001686 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001687
Rafael Espindola1557fd62011-03-20 18:44:20 +00001688 const unsigned NumUserAndRelocSections = Asm.size();
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001689 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1690 RevGroupMap, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001691 const unsigned AllSections = Asm.size();
1692 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1693
1694 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1695
1696 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001697 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1698 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001699
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001700 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola1557fd62011-03-20 18:44:20 +00001701
1702 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1703 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001704 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001705
1706 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1707 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1708 sizeof(ELF::Elf32_Ehdr);
1709 uint64_t FileOff = HeaderSize;
1710
1711 std::vector<const MCSectionELF*> Sections;
1712 ComputeSectionOrder(Asm, Sections);
1713 unsigned NumSections = Sections.size();
1714 SectionOffsetMapTy SectionOffsetMap;
1715 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1716 const MCSectionELF &Section = *Sections[i];
1717 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1718
1719 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1720
1721 // Remember the offset into the file for this section.
1722 SectionOffsetMap[&Section] = FileOff;
1723
1724 // Get the size of the section in the output file (including padding).
1725 FileOff += GetSectionFileSize(Layout, SD);
1726 }
1727
1728 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1729
1730 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1731
1732 uint64_t SectionHeaderEntrySize = is64Bit() ?
1733 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1734 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1735
1736 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1737 const MCSectionELF &Section = *Sections[i];
1738 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1739
1740 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1741
1742 // Remember the offset into the file for this section.
1743 SectionOffsetMap[&Section] = FileOff;
1744
1745 // Get the size of the section in the output file (including padding).
1746 FileOff += GetSectionFileSize(Layout, SD);
1747 }
1748
1749 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001750 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001751
1752 // ... then the regular sections ...
1753 // + because of .shstrtab
1754 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1755 WriteDataSectionData(Asm, Layout, *Sections[i]);
1756
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001757 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001758 WriteZeros(Padding);
1759
1760 // ... then the section header table ...
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001761 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001762
Nick Lewycky4eb11432011-10-07 20:56:23 +00001763 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001764 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1765 WriteDataSectionData(Asm, Layout, *Sections[i]);
1766}
1767
Eli Friedmand92d17b2011-03-03 07:24:36 +00001768bool
1769ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1770 const MCSymbolData &DataA,
1771 const MCFragment &FB,
1772 bool InSet,
1773 bool IsPCRel) const {
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001774 if (::isWeak(DataA))
Eli Friedmand92d17b2011-03-03 07:24:36 +00001775 return false;
1776 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1777 Asm, DataA, FB,InSet, IsPCRel);
1778}
1779
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001780bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1781 return ::isWeak(SD);
1782}
1783
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001784MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1785 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001786 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001787 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001788}