blob: ccf3a8ed27d944e16208b316010c17054601f9ce [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 Espindola29abd972011-12-22 03:38:00 +000082class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola0ce09712014-03-25 22:43:53 +000083 FragmentWriter FWriter;
84
Rafael Espindola29abd972011-12-22 03:38:00 +000085 protected:
86
87 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
88 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
89 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
Rafael Espindola3b5ee552014-04-28 13:39:57 +000090 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
Rafael Espindola29abd972011-12-22 03:38:00 +000091 bool Used, bool Renamed);
Rafael Espindola39f50422014-04-28 14:24:44 +000092 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
Rafael Espindola29abd972011-12-22 03:38:00 +000093 static bool IsELFMetaDataSection(const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +000094
Rafael Espindola642a2212015-04-14 22:54:16 +000095 void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
96 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +000097
Rafael Espindola6cd21802015-04-07 22:35:40 +000098 /// Helper struct for containing some precomputed information on symbols.
Rafael Espindola29abd972011-12-22 03:38:00 +000099 struct ELFSymbolData {
100 MCSymbolData *SymbolData;
101 uint64_t StringIndex;
102 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000103 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000104
105 // Support lexicographic sorting.
106 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolab6613022014-10-17 01:48:58 +0000107 unsigned LHSType = MCELF::GetType(*SymbolData);
108 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
109 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
110 return false;
111 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
112 return true;
113 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
114 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000115 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000116 }
117 };
118
Rafael Espindola29abd972011-12-22 03:38:00 +0000119 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000120 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000121
122 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
123 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
124 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
125
Rafael Espindola5904e122014-03-29 06:26:49 +0000126 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
127 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000128 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000129
130 /// @}
131 /// @name Symbol Table Data
132 /// @{
133
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000134 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000135 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000136 std::vector<ELFSymbolData> LocalSymbolData;
137 std::vector<ELFSymbolData> ExternalSymbolData;
138 std::vector<ELFSymbolData> UndefinedSymbolData;
139
140 /// @}
141
142 bool NeedsGOT;
143
Rafael Espindola29abd972011-12-22 03:38:00 +0000144 // This holds the symbol table index of the last local symbol.
145 unsigned LastLocalSymbolIndex;
146 // This holds the .strtab section index.
147 unsigned StringTableIndex;
148 // This holds the .symtab section index.
149 unsigned SymbolTableIndex;
150
151 unsigned ShstrtabIndex;
152
153
Rafael Espindola29abd972011-12-22 03:38:00 +0000154 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000155 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
156 bool hasRelocationAddend() const {
157 return TargetObjectWriter->hasRelocationAddend();
158 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000159 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000160 bool IsPCRel) const {
161 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000162 }
163
Rafael Espindola29abd972011-12-22 03:38:00 +0000164 public:
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000165 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
Rafael Espindola0ce09712014-03-25 22:43:53 +0000166 bool IsLittleEndian)
David Blaikie9f380a32015-03-16 18:06:57 +0000167 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000168 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000169
Yaron Keren7773a722015-03-23 18:35:01 +0000170 void reset() override {
171 UsedInReloc.clear();
172 WeakrefUsedInReloc.clear();
173 Renames.clear();
174 Relocations.clear();
175 ShStrTabBuilder.clear();
176 StrTabBuilder.clear();
177 FileSymbolData.clear();
178 LocalSymbolData.clear();
179 ExternalSymbolData.clear();
180 UndefinedSymbolData.clear();
181 MCObjectWriter::reset();
182 }
183
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000184 ~ELFObjectWriter() override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000185
186 void WriteWord(uint64_t W) {
187 if (is64Bit())
188 Write64(W);
189 else
190 Write32(W);
191 }
192
Rafael Espindola0ce09712014-03-25 22:43:53 +0000193 template <typename T> void write(MCDataFragment &F, T Value) {
194 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000195 }
196
Jack Carter1bd90ff2013-01-30 02:09:52 +0000197 void WriteHeader(const MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000198 unsigned NumberOfSections);
199
Rafael Espindola10be0832014-03-25 23:44:25 +0000200 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000201 const MCAsmLayout &Layout);
202
Rafael Espindola10be0832014-03-25 23:44:25 +0000203 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000204 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000205 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000206
Rafael Espindolab60c8292014-04-29 12:46:50 +0000207 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
208 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000209 const MCSymbolData *SD, uint64_t C,
210 unsigned Type) const;
211
Rafael Espindola26585542015-01-19 21:11:14 +0000212 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000213 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000214 MCValue Target, bool &IsPCRel,
215 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000216
217 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
218 const MCSymbol *S);
219
220 // Map from a group section to the signature symbol
221 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
222 // Map from a signature symbol to the group section
223 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
Rafael Espindolaa8201692015-04-28 15:26:21 +0000224 // Start and end offset of each section
225 typedef std::vector<std::pair<uint64_t, uint64_t>> SectionOffsetsTy;
Rafael Espindola29abd972011-12-22 03:38:00 +0000226
Rafael Espindola022bb762014-03-24 03:43:21 +0000227 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000228 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000229 /// \param Asm - The assembler.
230 /// \param SectionIndexMap - Maps a section to its index.
231 /// \param RevGroupMap - Maps a signature symbol to the group section.
Rafael Espindola022bb762014-03-24 03:43:21 +0000232 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000233 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000234 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000235
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000236 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000237
Rafael Espindolaead85492015-02-17 20:31:13 +0000238 MCSectionData *createRelocationSection(MCAssembler &Asm,
239 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000240
David Blaikie8019bf82014-04-10 21:53:53 +0000241 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
242
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000243 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
Rafael Espindola29abd972011-12-22 03:38:00 +0000244
245 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolaef6baea2015-02-11 23:11:18 +0000246 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000247
248 // Create the sections that show up in the symbol table. Currently
249 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaead85492015-02-17 20:31:13 +0000250 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000251 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
252 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000253
Craig Topper34a61bc2014-03-08 07:02:02 +0000254 void ExecutePostLayoutBinding(MCAssembler &Asm,
255 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000256
Rafael Espindolabf0db6c2015-04-15 13:07:47 +0000257 void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
258 MCAssembler &Asm, const GroupMapTy &GroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000259 const MCAsmLayout &Layout,
260 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +0000261 const SectionOffsetsTy &SectionOffsets);
Rafael Espindola29abd972011-12-22 03:38:00 +0000262
Rafael Espindola29abd972011-12-22 03:38:00 +0000263 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
264 uint64_t Address, uint64_t Offset,
265 uint64_t Size, uint32_t Link, uint32_t Info,
266 uint64_t Alignment, uint64_t EntrySize);
267
268 void WriteRelocationsFragment(const MCAssembler &Asm,
269 MCDataFragment *F,
270 const MCSectionData *SD);
271
Craig Topper34a61bc2014-03-08 07:02:02 +0000272 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000273 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
274 const MCSymbolData &DataA,
275 const MCFragment &FB,
276 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000277 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000278
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000279 bool isWeak(const MCSymbolData &SD) const override;
280
Craig Topper34a61bc2014-03-08 07:02:02 +0000281 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000282 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000283 const SectionIndexMapTy &SectionIndexMap,
284 uint32_t GroupSymbolIndex,
285 uint64_t Offset, uint64_t Size, uint64_t Alignment,
286 const MCSectionELF &Section);
287 };
288}
289
Rafael Espindola0ce09712014-03-25 22:43:53 +0000290FragmentWriter::FragmentWriter(bool IsLittleEndian)
291 : IsLittleEndian(IsLittleEndian) {}
292
293template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
294 if (IsLittleEndian)
295 Val = support::endian::byte_swap<T, support::little>(Val);
296 else
297 Val = support::endian::byte_swap<T, support::big>(Val);
298 const char *Start = (const char *)&Val;
299 F.getContents().append(Start, Start + sizeof(T));
300}
301
Rafael Espindola10be0832014-03-25 23:44:25 +0000302void SymbolTableWriter::createSymtabShndx() {
303 if (ShndxF)
304 return;
305
306 MCContext &Ctx = Asm.getContext();
307 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000308 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000309 MCSectionData *SymtabShndxSD =
310 &Asm.getOrCreateSectionData(*SymtabShndxSection);
311 SymtabShndxSD->setAlignment(4);
312 ShndxF = new MCDataFragment(SymtabShndxSD);
313 unsigned Index = SectionIndexMap.size() + 1;
314 SectionIndexMap[SymtabShndxSection] = Index;
315
316 for (unsigned I = 0; I < NumWritten; ++I)
317 write(*ShndxF, uint32_t(0));
318}
319
320template <typename T>
321void SymbolTableWriter::write(MCDataFragment &F, T Value) {
322 FWriter.write(F, Value);
323}
324
325SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
326 bool Is64Bit,
327 SectionIndexMapTy &SectionIndexMap,
328 MCDataFragment *SymtabF)
329 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
330 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
331 NumWritten(0) {}
332
333void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
334 uint64_t size, uint8_t other,
335 uint32_t shndx, bool Reserved) {
336 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
337
338 if (LargeIndex)
339 createSymtabShndx();
340
341 if (ShndxF) {
342 if (LargeIndex)
343 write(*ShndxF, shndx);
344 else
345 write(*ShndxF, uint32_t(0));
346 }
347
348 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
349
Rafael Espindola10be0832014-03-25 23:44:25 +0000350 if (Is64Bit) {
351 write(*SymtabF, name); // st_name
352 write(*SymtabF, info); // st_info
353 write(*SymtabF, other); // st_other
354 write(*SymtabF, Index); // st_shndx
355 write(*SymtabF, value); // st_value
356 write(*SymtabF, size); // st_size
357 } else {
358 write(*SymtabF, name); // st_name
359 write(*SymtabF, uint32_t(value)); // st_value
360 write(*SymtabF, uint32_t(size)); // st_size
361 write(*SymtabF, info); // st_info
362 write(*SymtabF, other); // st_other
363 write(*SymtabF, Index); // st_shndx
364 }
365
366 ++NumWritten;
367}
368
Jan Sjödin30a52de2011-02-28 21:45:04 +0000369bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
370 const MCFixupKindInfo &FKI =
371 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
372
373 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
374}
375
376bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
377 switch (Variant) {
378 default:
379 return false;
380 case MCSymbolRefExpr::VK_GOT:
381 case MCSymbolRefExpr::VK_PLT:
382 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000383 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000384 case MCSymbolRefExpr::VK_TPOFF:
385 case MCSymbolRefExpr::VK_TLSGD:
386 case MCSymbolRefExpr::VK_GOTTPOFF:
387 case MCSymbolRefExpr::VK_INDNTPOFF:
388 case MCSymbolRefExpr::VK_NTPOFF:
389 case MCSymbolRefExpr::VK_GOTNTPOFF:
390 case MCSymbolRefExpr::VK_TLSLDM:
391 case MCSymbolRefExpr::VK_DTPOFF:
392 case MCSymbolRefExpr::VK_TLSLD:
393 return true;
394 }
395}
396
Jason W Kim96f4c012010-11-15 16:18:39 +0000397ELFObjectWriter::~ELFObjectWriter()
398{}
399
Matt Fleming6c1ad482010-08-16 18:57:57 +0000400// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000401void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000402 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000403 // ELF Header
404 // ----------
405 //
406 // Note
407 // ----
408 // emitWord method behaves differently for ELF32 and ELF64, writing
409 // 4 bytes in the former and 8 in the latter.
410
Benjamin Kramer97fbdd52015-04-17 11:12:43 +0000411 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000412
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000413 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000414
415 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000416 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000417
418 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000419 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000420 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000421 Write8(0); // e_ident[EI_ABIVERSION]
422
423 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
424
425 Write16(ELF::ET_REL); // e_type
426
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000427 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000428
429 Write32(ELF::EV_CURRENT); // e_version
430 WriteWord(0); // e_entry, no entry point in .o file
431 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola642a2212015-04-14 22:54:16 +0000432 WriteWord(0); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000433
Jason W Kim4761fba2011-02-04 21:41:11 +0000434 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000435 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000436
437 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000438 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000439
440 Write16(0); // e_phentsize = prog header entry size
441 Write16(0); // e_phnum = # prog header entries = 0
442
443 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000444 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000445
446 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000447 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000448 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000449 else
450 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000451
452 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000453 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000454 Write16(ELF::SHN_XINDEX);
455 else
456 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000457}
458
Rafael Espindolafee224f2014-04-30 21:51:13 +0000459uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000460 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000461 if (Data.isCommon() && Data.isExternal())
462 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000463
Rafael Espindolafee224f2014-04-30 21:51:13 +0000464 uint64_t Res;
465 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000466 return 0;
467
Rafael Espindolafee224f2014-04-30 21:51:13 +0000468 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000469 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000470
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000471 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000472}
473
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000474void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
475 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000476 // The presence of symbol versions causes undefined symbols and
477 // versions declared with @@@ to be renamed.
478
David Blaikie583a31c2014-04-18 18:24:25 +0000479 for (MCSymbolData &OriginalData : Asm.symbols()) {
480 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000481
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000482 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000483 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000484 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000485 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
486 if (!Ref)
487 continue;
488 const MCSymbol &Symbol = Ref->getSymbol();
489 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000490
Benjamin Kramer14807272010-10-27 19:53:52 +0000491 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000492 size_t Pos = AliasName.find('@');
493 if (Pos == StringRef::npos)
494 continue;
495
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000496 // Aliases defined with .symvar copy the binding from the symbol they alias.
497 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000498 OriginalData.setExternal(SD.isExternal());
499 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000500
Benjamin Kramer14807272010-10-27 19:53:52 +0000501 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000502 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
503 continue;
504
Rafael Espindola26496e62010-10-27 17:56:18 +0000505 // FIXME: produce a better error message.
506 if (Symbol.isUndefined() && Rest.startswith("@@") &&
507 !Rest.startswith("@@@"))
508 report_fatal_error("A @@ version cannot be undefined");
509
Benjamin Kramer14807272010-10-27 19:53:52 +0000510 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000511 }
512}
513
Roman Divacky5a1c5492014-01-07 20:17:03 +0000514static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
515 uint8_t Type = newType;
516
517 // Propagation rules:
518 // IFUNC > FUNC > OBJECT > NOTYPE
519 // TLS_OBJECT > OBJECT > NOTYPE
520 //
521 // dont let the new type degrade the old type
522 switch (origType) {
523 default:
524 break;
525 case ELF::STT_GNU_IFUNC:
526 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
527 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
528 Type = ELF::STT_GNU_IFUNC;
529 break;
530 case ELF::STT_FUNC:
531 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
532 Type == ELF::STT_TLS)
533 Type = ELF::STT_FUNC;
534 break;
535 case ELF::STT_OBJECT:
536 if (Type == ELF::STT_NOTYPE)
537 Type = ELF::STT_OBJECT;
538 break;
539 case ELF::STT_TLS:
540 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
541 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
542 Type = ELF::STT_TLS;
543 break;
544 }
545
546 return Type;
547}
548
Rafael Espindola10be0832014-03-25 23:44:25 +0000549void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000550 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000551 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000552 assert((!OrigData.getFragment() ||
553 (&OrigData.getFragment()->getParent()->getSection() ==
554 &OrigData.getSymbol().getSection())) &&
555 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000556 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000557
558 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
559 // SHN_COMMON.
560 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000561
Jack Carter2f8d9d92013-02-19 21:57:35 +0000562 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000563 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000564 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000565 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000566 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000567 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
568 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000569 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000570 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000571
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000572 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000573 // 2 bits
574 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000575 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000576 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000577
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000578 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000579 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000580
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000581 const MCExpr *ESize = OrigData.getSize();
582 if (!ESize && Base)
583 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000584
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000585 if (ESize) {
586 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000587 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000588 report_fatal_error("Size expression must be absolute.");
589 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000590 }
591
592 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000593 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
594 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000595}
596
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000597void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000598 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000599 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000600 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000601 // The string table must be emitted first because we need the index
602 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000603
604 // FIXME: Make sure the start of the symbol table is aligned.
605
Rafael Espindola10be0832014-03-25 23:44:25 +0000606 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
607
Matt Fleming6c1ad482010-08-16 18:57:57 +0000608 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000609 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000610
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000611 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000612 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
613 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000614 }
615
Matt Fleming6c1ad482010-08-16 18:57:57 +0000616 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000617 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
618
Matt Fleming6c1ad482010-08-16 18:57:57 +0000619 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
620 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000621 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000622 }
623
Matt Fleming6c1ad482010-08-16 18:57:57 +0000624 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
625 ELFSymbolData &MSD = ExternalSymbolData[i];
626 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000627 assert(((Data.getFlags() & ELF_STB_Global) ||
628 (Data.getFlags() & ELF_STB_Weak)) &&
629 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000630 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000631 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000632 LastLocalSymbolIndex++;
633 }
634
635 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
636 ELFSymbolData &MSD = UndefinedSymbolData[i];
637 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000638 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000639 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000640 LastLocalSymbolIndex++;
641 }
642}
643
Rafael Espindola5904e122014-03-29 06:26:49 +0000644// It is always valid to create a relocation with a symbol. It is preferable
645// to use a relocation with a section if that is possible. Using the section
646// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000647bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
648 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000649 const MCSymbolData *SD,
650 uint64_t C,
651 unsigned Type) const {
652 // A PCRel relocation to an absolute value has no symbol (or section). We
653 // represent that with a relocation to a null section.
654 if (!RefA)
655 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000656
Rafael Espindola5904e122014-03-29 06:26:49 +0000657 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
658 switch (Kind) {
659 default:
660 break;
661 // The .odp creation emits a relocation against the symbol ".TOC." which
662 // create a R_PPC64_TOC relocation. However the relocation symbol name
663 // in final object creation should be NULL, since the symbol does not
664 // really exist, it is just the reference to TOC base for the current
665 // object file. Since the symbol is undefined, returning false results
666 // in a relocation with a null section which is the desired result.
667 case MCSymbolRefExpr::VK_PPC_TOCBASE:
668 return false;
669
670 // These VariantKind cause the relocation to refer to something other than
671 // the symbol itself, like a linker generated table. Since the address of
672 // symbol is not relevant, we cannot replace the symbol with the
673 // section and patch the difference in the addend.
674 case MCSymbolRefExpr::VK_GOT:
675 case MCSymbolRefExpr::VK_PLT:
676 case MCSymbolRefExpr::VK_GOTPCREL:
677 case MCSymbolRefExpr::VK_Mips_GOT:
678 case MCSymbolRefExpr::VK_PPC_GOT_LO:
679 case MCSymbolRefExpr::VK_PPC_GOT_HI:
680 case MCSymbolRefExpr::VK_PPC_GOT_HA:
681 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000682 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000683
Rafael Espindola5904e122014-03-29 06:26:49 +0000684 // An undefined symbol is not in any section, so the relocation has to point
685 // to the symbol itself.
686 const MCSymbol &Sym = SD->getSymbol();
687 if (Sym.isUndefined())
688 return true;
689
690 unsigned Binding = MCELF::GetBinding(*SD);
691 switch(Binding) {
692 default:
693 llvm_unreachable("Invalid Binding");
694 case ELF::STB_LOCAL:
695 break;
696 case ELF::STB_WEAK:
697 // If the symbol is weak, it might be overridden by a symbol in another
698 // file. The relocation has to point to the symbol so that the linker
699 // can update it.
700 return true;
701 case ELF::STB_GLOBAL:
702 // Global ELF symbols can be preempted by the dynamic linker. The relocation
703 // has to point to the symbol for a reason analogous to the STB_WEAK case.
704 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000705 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000706
Rafael Espindola5904e122014-03-29 06:26:49 +0000707 // If a relocation points to a mergeable section, we have to be careful.
708 // If the offset is zero, a relocation with the section will encode the
709 // same information. With a non-zero offset, the situation is different.
710 // For example, a relocation can point 42 bytes past the end of a string.
711 // If we change such a relocation to use the section, the linker would think
712 // that it pointed to another string and subtracting 42 at runtime will
713 // produce the wrong value.
714 auto &Sec = cast<MCSectionELF>(Sym.getSection());
715 unsigned Flags = Sec.getFlags();
716 if (Flags & ELF::SHF_MERGE) {
717 if (C != 0)
718 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000719
720 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
721 // only handle section relocations to mergeable sections if using RELA.
722 if (!hasRelocationAddend())
723 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000724 }
725
Rafael Espindola5904e122014-03-29 06:26:49 +0000726 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000727 // are just an offset (@tpoff), require a symbol in gold versions before
728 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
729 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000730 if (Flags & ELF::SHF_TLS)
731 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000732
Rafael Espindola9ef84412014-04-11 19:18:01 +0000733 // If the symbol is a thumb function the final relocation must set the lowest
734 // bit. With a symbol that is done by just having the symbol have that bit
735 // set, so we would lose the bit if we relocated with the section.
736 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000737 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000738 return true;
739
Ulrich Weigand46797c62014-07-20 23:15:06 +0000740 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000741 return true;
742 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000743}
744
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000745static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
746 const MCSymbol &Sym = Ref.getSymbol();
747
748 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
749 return &Sym;
750
751 if (!Sym.isVariable())
752 return nullptr;
753
754 const MCExpr *Expr = Sym.getVariableValue();
755 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
756 if (!Inner)
757 return nullptr;
758
759 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
760 return &Inner->getSymbol();
761 return nullptr;
762}
763
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000764// True if the assembler knows nothing about the final value of the symbol.
765// This doesn't cover the comdat issues, since in those cases the assembler
766// can at least know that all symbols in the section will move together.
Rafael Espindolac9e70682015-03-24 23:48:44 +0000767static bool isWeak(const MCSymbolData &D) {
Rafael Espindolaa635d832015-04-17 08:46:11 +0000768 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
769 return true;
770
771 switch (MCELF::GetBinding(D)) {
772 default:
773 llvm_unreachable("Unknown binding");
774 case ELF::STB_LOCAL:
775 return false;
776 case ELF::STB_GLOBAL:
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000777 return false;
Rafael Espindolaa635d832015-04-17 08:46:11 +0000778 case ELF::STB_WEAK:
779 case ELF::STB_GNU_UNIQUE:
780 return true;
781 }
Rafael Espindolac9e70682015-03-24 23:48:44 +0000782}
783
Rafael Espindola26585542015-01-19 21:11:14 +0000784void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000785 const MCAsmLayout &Layout,
786 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000787 const MCFixup &Fixup, MCValue Target,
788 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000789 const MCSectionData *FixupSection = Fragment->getParent();
790 uint64_t C = Target.getConstant();
791 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000792
Rafael Espindola5904e122014-03-29 06:26:49 +0000793 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
794 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
795 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000796
Rafael Espindola5904e122014-03-29 06:26:49 +0000797 // Let A, B and C being the components of Target and R be the location of
798 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
799 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000800
Rafael Espindola5904e122014-03-29 06:26:49 +0000801 // In general, ELF has no relocations for -B. It can only represent (A + C)
802 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
803 // replace B to implement it: (A - R - K + C)
804 if (IsPCRel)
805 Asm.getContext().FatalError(
806 Fixup.getLoc(),
807 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000808
Rafael Espindola5904e122014-03-29 06:26:49 +0000809 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000810
Rafael Espindola5904e122014-03-29 06:26:49 +0000811 if (SymB.isUndefined())
812 Asm.getContext().FatalError(
813 Fixup.getLoc(),
814 Twine("symbol '") + SymB.getName() +
815 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000816
Rafael Espindola5904e122014-03-29 06:26:49 +0000817 assert(!SymB.isAbsolute() && "Should have been folded");
818 const MCSection &SecB = SymB.getSection();
819 if (&SecB != &FixupSection->getSection())
820 Asm.getContext().FatalError(
821 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000822
Rafael Espindola5904e122014-03-29 06:26:49 +0000823 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000824 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000825 Asm.getContext().FatalError(
826 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
827
Rafael Espindola5904e122014-03-29 06:26:49 +0000828 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
829 uint64_t K = SymBOffset - FixupOffset;
830 IsPCRel = true;
831 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000832 }
833
Rafael Espindola5904e122014-03-29 06:26:49 +0000834 // We either rejected the fixup or folded B into C at this point.
835 const MCSymbolRefExpr *RefA = Target.getSymA();
836 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
837 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
838
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000839 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000840 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000841 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
842 C += Layout.getSymbolOffset(SymAD);
843
844 uint64_t Addend = 0;
845 if (hasRelocationAddend()) {
846 Addend = C;
847 C = 0;
848 }
849
850 FixedValue = C;
851
852 // FIXME: What is this!?!?
853 MCSymbolRefExpr::VariantKind Modifier =
854 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000855 if (RelocNeedsGOT(Modifier))
856 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000857
Rafael Espindola5904e122014-03-29 06:26:49 +0000858 if (!RelocateWithSymbol) {
859 const MCSection *SecA =
860 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000861 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
862 MCSymbol *SectionSymbol =
863 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
864 : nullptr;
865 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000866 Relocations[FixupSection].push_back(Rec);
867 return;
868 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000869
Rafael Espindola5904e122014-03-29 06:26:49 +0000870 if (SymA) {
871 if (const MCSymbol *R = Renames.lookup(SymA))
872 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000873
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000874 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
875 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000876 else
877 UsedInReloc.insert(SymA);
878 }
879 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
880 Relocations[FixupSection].push_back(Rec);
881 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000882}
883
884
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000885uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000886ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
887 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000888 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000889 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000890}
891
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000892bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
893 const MCSymbolData &Data, bool Used,
894 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000895 const MCSymbol &Symbol = Data.getSymbol();
896 if (Symbol.isVariable()) {
897 const MCExpr *Expr = Symbol.getVariableValue();
898 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
899 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
900 return false;
901 }
902 }
Rafael Espindola16145972010-11-01 14:28:48 +0000903
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000904 if (Used)
905 return true;
906
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000907 if (Renamed)
908 return false;
909
Rafael Espindola45834a02010-10-29 23:09:31 +0000910 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
911 return true;
912
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000913 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000914 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000915 if (Base && Base->isUndefined())
916 return false;
917 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000918
Jan Sjödin30a52de2011-02-28 21:45:04 +0000919 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000920 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000921 return false;
922
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000923 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000924 return false;
925
926 return true;
927}
928
Rafael Espindola39f50422014-04-28 14:24:44 +0000929bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000930 if (Data.isExternal())
931 return false;
932
933 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000934 if (Symbol.isDefined())
935 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000936
Rafael Espindola39f50422014-04-28 14:24:44 +0000937 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000938 return false;
939
940 return true;
941}
942
Rafael Espindolaead85492015-02-17 20:31:13 +0000943void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000944 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000945 unsigned Index = 1;
946 for (MCAssembler::iterator it = Asm.begin(),
947 ie = Asm.end(); it != ie; ++it) {
948 const MCSectionELF &Section =
949 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000950 if (Section.getType() != ELF::SHT_GROUP)
951 continue;
952 SectionIndexMap[&Section] = Index++;
953 }
954
Rafael Espindola607da972015-04-17 08:11:38 +0000955 std::vector<const MCSectionELF *> RelSections;
956
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000957 for (MCAssembler::iterator it = Asm.begin(),
958 ie = Asm.end(); it != ie; ++it) {
Rafael Espindolaead85492015-02-17 20:31:13 +0000959 const MCSectionData &SD = *it;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000960 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000961 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000962 if (Section.getType() == ELF::SHT_GROUP ||
963 Section.getType() == ELF::SHT_REL ||
964 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000965 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000966 SectionIndexMap[&Section] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000967 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
968 const MCSectionELF *RelSection =
969 static_cast<const MCSectionELF *>(&RelSD->getSection());
Rafael Espindola607da972015-04-17 08:11:38 +0000970 RelSections.push_back(RelSection);
Rafael Espindolaead85492015-02-17 20:31:13 +0000971 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000972 }
Rafael Espindola607da972015-04-17 08:11:38 +0000973
974 // Put relocation sections close together. The linker reads them
975 // first, so this improves cache locality.
976 for (const MCSectionELF * Sec: RelSections)
977 SectionIndexMap[Sec] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +0000978}
979
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000980void ELFObjectWriter::computeSymbolTable(
981 MCAssembler &Asm, const MCAsmLayout &Layout,
982 const SectionIndexMapTy &SectionIndexMap,
983 const RevGroupMapTy &RevGroupMap) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000984 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000985 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000986 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000987 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000988 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
989 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
990 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000991 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000992 }
993
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000994 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000995 for (MCSymbolData &SD : Asm.symbols()) {
996 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000997
Rafael Espindola16145972010-11-01 14:28:48 +0000998 bool Used = UsedInReloc.count(&Symbol);
999 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001000 bool isSignature = RevGroupMap.count(&Symbol);
1001
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001002 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001003 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001004 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001005 continue;
1006
Matt Fleming6c1ad482010-08-16 18:57:57 +00001007 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001008 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001009 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001010
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001011 // Undefined symbols are global, but this is the first place we
1012 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001013 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001014 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001015 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001016 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001017 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001018 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001019 }
1020
Rafael Espindola022bb762014-03-24 03:43:21 +00001021 if (!BaseSymbol) {
1022 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001023 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001024 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001025 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001026 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001027 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001028 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001029 else
1030 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001031 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001032 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001033 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001034 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001035 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001036 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001037 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001038 }
1039
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001040 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1041 // in defined ones.
1042 //
1043 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001044 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001045 // trivial.
1046 //
1047 // We thus have to be careful to not perform the symbol version replacement
1048 // blindly:
1049 //
1050 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1051 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1052 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1053 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1054 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1055 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1056 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1057 // "__imp_?" or "__imp_@?".
1058 //
1059 // It would have been interesting to perform the MS mangling prefix check
1060 // only when the target triple is of the form *-pc-windows-elf. But, it
1061 // seems that this information is not easily accessible from the
1062 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001063 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001064 if (!Name.startswith("?") && !Name.startswith("@?") &&
1065 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1066 // This symbol isn't following the MSVC C++ name mangling convention. We
1067 // can thus safely interpret the @@@ in symbol names as specifying symbol
1068 // versioning.
1069 SmallString<32> Buf;
1070 size_t Pos = Name.find("@@@");
1071 if (Pos != StringRef::npos) {
1072 Buf += Name.substr(0, Pos);
1073 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1074 Buf += Name.substr(Pos + Skip);
1075 Name = Buf;
1076 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001077 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001078
1079 // Sections have their own string table
1080 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1081 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001082
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001083 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1084 UndefinedSymbolData.push_back(MSD);
1085 else if (Local)
1086 LocalSymbolData.push_back(MSD);
1087 else
1088 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001089 }
1090
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001091 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1092 StrTabBuilder.add(*i);
1093
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001094 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001095
1096 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1097 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1098
Rafael Espindolab6613022014-10-17 01:48:58 +00001099 for (ELFSymbolData &MSD : LocalSymbolData)
1100 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1101 ? 0
1102 : StrTabBuilder.getOffset(MSD.Name);
1103 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001104 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1105 for (ELFSymbolData& MSD : UndefinedSymbolData)
1106 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1107
Matt Fleming6c1ad482010-08-16 18:57:57 +00001108 // Symbols are required to be in lexicographic order.
1109 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1110 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1111 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1112
1113 // Set the symbol indices. Local symbols must come before all other
1114 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001115 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001116 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1117 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001118
Matt Fleming6c1ad482010-08-16 18:57:57 +00001119 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1120 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1121 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1122 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1123}
1124
Rafael Espindolaead85492015-02-17 20:31:13 +00001125MCSectionData *
1126ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1127 const MCSectionData &SD) {
1128 if (Relocations[&SD].empty())
1129 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001130
Rafael Espindolaead85492015-02-17 20:31:13 +00001131 MCContext &Ctx = Asm.getContext();
1132 const MCSectionELF &Section =
1133 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001134
Rafael Espindolaead85492015-02-17 20:31:13 +00001135 const StringRef SectionName = Section.getSectionName();
1136 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1137 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001138
Rafael Espindolaead85492015-02-17 20:31:13 +00001139 unsigned EntrySize;
1140 if (hasRelocationAddend())
1141 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1142 else
1143 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001144
Rafael Espindolaead85492015-02-17 20:31:13 +00001145 unsigned Flags = 0;
Rafael Espindolac9d06922015-03-30 13:39:16 +00001146 if (Section.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001147 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001148
Rafael Espindolac9d06922015-03-30 13:39:16 +00001149 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001150 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001151 Flags, EntrySize, Section.getGroup(), &Section);
Rafael Espindolaead85492015-02-17 20:31:13 +00001152 return &Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001153}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001154
David Blaikiee06e8012014-04-11 22:11:50 +00001155static SmallVector<char, 128>
1156getUncompressedData(MCAsmLayout &Layout,
1157 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001158 SmallVector<char, 128> UncompressedData;
1159 for (const MCFragment &F : Fragments) {
1160 const SmallVectorImpl<char> *Contents;
1161 switch (F.getKind()) {
1162 case MCFragment::FT_Data:
1163 Contents = &cast<MCDataFragment>(F).getContents();
1164 break;
1165 case MCFragment::FT_Dwarf:
1166 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1167 break;
1168 case MCFragment::FT_DwarfFrame:
1169 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1170 break;
1171 default:
1172 llvm_unreachable(
1173 "Not expecting any other fragment types in a debug_* section");
1174 }
1175 UncompressedData.append(Contents->begin(), Contents->end());
1176 }
1177 return UncompressedData;
1178}
1179
1180// Include the debug info compression header:
1181// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1182// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001183static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001184prependCompressionHeader(uint64_t Size,
1185 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001186 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001187 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1188 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001189 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001190 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001191 CompressedContents.insert(CompressedContents.begin(),
1192 Magic.size() + sizeof(Size), 0);
1193 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1194 std::copy(reinterpret_cast<char *>(&Size),
1195 reinterpret_cast<char *>(&Size + 1),
1196 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001197 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001198}
1199
1200// Return a single fragment containing the compressed contents of the whole
1201// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001202static std::unique_ptr<MCDataFragment>
1203getCompressedFragment(MCAsmLayout &Layout,
1204 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001205 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1206
1207 // Gather the uncompressed data from all the fragments, recording the
1208 // alignment fragment, if seen, and any fixups.
1209 SmallVector<char, 128> UncompressedData =
1210 getUncompressedData(Layout, Fragments);
1211
1212 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1213
1214 zlib::Status Success = zlib::compress(
1215 StringRef(UncompressedData.data(), UncompressedData.size()),
1216 CompressedContents);
1217 if (Success != zlib::StatusOK)
1218 return nullptr;
1219
David Blaikie76d3a3c2014-04-18 21:52:26 +00001220 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1221 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001222
1223 return CompressedFragment;
1224}
1225
David Blaikie39fa6a22014-04-25 00:48:01 +00001226typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1227DefiningSymbolMap;
1228
1229static void UpdateSymbols(const MCAsmLayout &Layout,
1230 const std::vector<MCSymbolData *> &Symbols,
1231 MCFragment &NewFragment) {
1232 for (MCSymbolData *Sym : Symbols) {
1233 Sym->setOffset(Sym->getOffset() +
1234 Layout.getFragmentOffset(Sym->getFragment()));
1235 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001236 }
1237}
1238
David Blaikie8019bf82014-04-10 21:53:53 +00001239static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001240 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001241 const MCSectionELF &Section,
1242 MCSectionData &SD) {
1243 StringRef SectionName = Section.getSectionName();
1244 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1245
1246 std::unique_ptr<MCDataFragment> CompressedFragment =
1247 getCompressedFragment(Layout, Fragments);
1248
1249 // Leave the section as-is if the fragments could not be compressed.
1250 if (!CompressedFragment)
1251 return;
1252
David Blaikiec029ab42014-04-18 21:24:12 +00001253 // Update the fragment+offsets of any symbols referring to fragments in this
1254 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001255 auto I = DefiningSymbols.find(&SD);
1256 if (I != DefiningSymbols.end())
1257 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001258
David Blaikie8019bf82014-04-10 21:53:53 +00001259 // Invalidate the layout for the whole section since it will have new and
1260 // different fragments now.
1261 Layout.invalidateFragmentsFrom(&Fragments.front());
1262 Fragments.clear();
1263
1264 // Complete the initialization of the new fragment
1265 CompressedFragment->setParent(&SD);
1266 CompressedFragment->setLayoutOrder(0);
1267 Fragments.push_back(CompressedFragment.release());
1268
1269 // Rename from .debug_* to .zdebug_*
1270 Asm.getContext().renameELFSection(&Section,
1271 (".z" + SectionName.drop_front(1)).str());
1272}
1273
1274void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1275 MCAsmLayout &Layout) {
1276 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1277 return;
1278
David Blaikie39fa6a22014-04-25 00:48:01 +00001279 DefiningSymbolMap DefiningSymbols;
1280
1281 for (MCSymbolData &SD : Asm.symbols())
1282 if (MCFragment *F = SD.getFragment())
1283 DefiningSymbols[F->getParent()].push_back(&SD);
1284
David Blaikie8019bf82014-04-10 21:53:53 +00001285 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001286 const MCSectionELF &Section =
1287 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001288 StringRef SectionName = Section.getSectionName();
1289
1290 // Compressing debug_frame requires handling alignment fragments which is
1291 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1292 // for writing to arbitrary buffers) for little benefit.
1293 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1294 continue;
1295
David Blaikie39fa6a22014-04-25 00:48:01 +00001296 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001297 }
1298}
1299
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001300void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001301 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1302 MCSectionData &RelSD = *it;
1303 const MCSectionELF &RelSection =
1304 static_cast<const MCSectionELF &>(RelSD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001305
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001306 unsigned Type = RelSection.getType();
1307 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001308 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001309
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001310 const MCSectionELF *Section = RelSection.getAssociatedSection();
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001311 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1312 RelSD.setAlignment(is64Bit() ? 8 : 4);
1313
1314 MCDataFragment *F = new MCDataFragment(&RelSD);
1315 WriteRelocationsFragment(Asm, F, &SD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001316 }
1317}
1318
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001319void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1320 uint64_t Flags, uint64_t Address,
1321 uint64_t Offset, uint64_t Size,
1322 uint32_t Link, uint32_t Info,
1323 uint64_t Alignment,
1324 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001325 Write32(Name); // sh_name: index into string table
1326 Write32(Type); // sh_type
1327 WriteWord(Flags); // sh_flags
1328 WriteWord(Address); // sh_addr
1329 WriteWord(Offset); // sh_offset
1330 WriteWord(Size); // sh_size
1331 Write32(Link); // sh_link
1332 Write32(Info); // sh_info
1333 WriteWord(Alignment); // sh_addralign
1334 WriteWord(EntrySize); // sh_entsize
1335}
1336
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001337void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1338 MCDataFragment *F,
1339 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001340 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001341
Petar Jovanovic0380d0b2015-04-14 13:23:34 +00001342 // Sort the relocation entries. Most targets just sort by Offset, but some
1343 // (e.g., MIPS) have additional constraints.
1344 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001345
1346 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001347 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001348 unsigned Index =
1349 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001350
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001351 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001352 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001353 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001354 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001355
Rafael Espindola5904e122014-03-29 06:26:49 +00001356 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1357 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1358 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1359 write(*F, TargetObjectWriter->getRType(Entry.Type));
1360 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001361 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001362 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001363 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001364 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001365 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001366 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001367 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001368 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001369
Rafael Espindolabce26a12010-10-05 15:11:03 +00001370 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001371 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001372 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001373
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001374 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001375 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001376 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001377 }
1378}
1379
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001380void ELFObjectWriter::CreateMetadataSections(
1381 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001382 MCContext &Ctx = Asm.getContext();
1383 MCDataFragment *F;
1384
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001385 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001386
Rafael Espindola0e527b72010-09-22 19:04:41 +00001387 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001388 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001389 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001390 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1391 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001392 ShstrtabIndex = SectionIndexMap.size() + 1;
1393 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001394
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001395 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001396 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001397 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001398 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001399 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001400 SymbolTableIndex = SectionIndexMap.size() + 1;
1401 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001402
Rafael Espindola1557fd62011-03-20 18:44:20 +00001403 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001404 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001405 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1406 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001407 StringTableIndex = SectionIndexMap.size() + 1;
1408 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001409
1410 // Symbol table
1411 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001412 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001413
Matt Fleming6c1ad482010-08-16 18:57:57 +00001414 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001415 F->getContents().append(StrTabBuilder.data().begin(),
1416 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001417
Matt Fleming6c1ad482010-08-16 18:57:57 +00001418 F = new MCDataFragment(&ShstrtabSD);
1419
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001420 // Section header string table.
1421 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001422 const MCSectionELF &Section =
1423 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001424 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001425 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001426 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001427 F->getContents().append(ShStrTabBuilder.data().begin(),
1428 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001429}
1430
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001431void ELFObjectWriter::createIndexedSections(
1432 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1433 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001434 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001435
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001436 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001437 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1438 it != ie; ++it) {
1439 const MCSectionELF &Section =
1440 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001441 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001442 continue;
1443
1444 const MCSymbol *SignatureSymbol = Section.getGroup();
1445 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001446 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001447 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001448 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001449 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1450 Data.setAlignment(4);
1451 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001452 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001453 }
1454 GroupMap[Group] = SignatureSymbol;
1455 }
1456
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001457 computeIndexMap(Asm, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001458
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001459 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001460 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001461 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001462 const MCSectionELF &Section =
1463 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001464 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001465 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001466 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001467 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1468 // FIXME: we could use the previous fragment
1469 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001470 uint32_t Index = SectionIndexMap.lookup(&Section);
1471 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001472 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001473}
1474
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001475void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001476 const SectionIndexMapTy &SectionIndexMap,
1477 uint32_t GroupSymbolIndex,
1478 uint64_t Offset, uint64_t Size,
1479 uint64_t Alignment,
1480 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001481 uint64_t sh_link = 0;
1482 uint64_t sh_info = 0;
1483
1484 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001485 default:
1486 // Nothing to do.
1487 break;
1488
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001489 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001490 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001491 break;
1492
1493 case ELF::SHT_REL:
1494 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001495 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001496 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001497 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001498 sh_info = SectionIndexMap.lookup(InfoSection);
1499 break;
1500 }
1501
1502 case ELF::SHT_SYMTAB:
1503 case ELF::SHT_DYNSYM:
1504 sh_link = StringTableIndex;
1505 sh_info = LastLocalSymbolIndex;
1506 break;
1507
1508 case ELF::SHT_SYMTAB_SHNDX:
1509 sh_link = SymbolTableIndex;
1510 break;
1511
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001512 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001513 sh_link = SymbolTableIndex;
1514 sh_info = GroupSymbolIndex;
1515 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001516 }
1517
Logan Chien4b724422013-02-05 14:18:59 +00001518 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001519 Section.getType() == ELF::SHT_ARM_EXIDX)
1520 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001521
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001522 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1523 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001524 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1525 Alignment, Section.getEntrySize());
1526}
1527
Jan Sjödin30a52de2011-02-28 21:45:04 +00001528bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001529 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001530 !SD.getSection().isVirtualSection();
1531}
1532
Rafael Espindola642a2212015-04-14 22:54:16 +00001533void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001534 const MCAsmLayout &Layout,
Rafael Espindola642a2212015-04-14 22:54:16 +00001535 const MCSectionData &SD) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001536 if (IsELFMetaDataSection(SD)) {
1537 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1538 ++i) {
1539 const MCFragment &F = *i;
1540 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001541 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001542 }
1543 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001544 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001545 }
1546}
1547
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001548void ELFObjectWriter::writeSectionHeader(
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001549 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1550 const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001551 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +00001552 const SectionOffsetsTy &SectionOffsets) {
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001553 const unsigned NumSections = Asm.size();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001554
Matt Fleming6c1ad482010-08-16 18:57:57 +00001555 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001556 uint64_t FirstSectionSize =
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001557 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001558 uint32_t FirstSectionLink =
1559 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1560 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001561
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001562 for (unsigned i = 0; i < NumSections; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001563 const MCSectionELF &Section = *Sections[i];
1564 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1565 uint32_t GroupSymbolIndex;
1566 if (Section.getType() != ELF::SHT_GROUP)
1567 GroupSymbolIndex = 0;
1568 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001569 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1570 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001571
Rafael Espindolaa8201692015-04-28 15:26:21 +00001572 const std::pair<uint64_t, uint64_t> &Offsets = SectionOffsets[i];
Rafael Espindolab6417502015-04-28 15:04:09 +00001573 uint64_t Size = Section.getType() == ELF::SHT_NOBITS
1574 ? Layout.getSectionAddressSize(&SD)
1575 : Offsets.second - Offsets.first;
Rafael Espindola60ebca92010-12-02 03:09:06 +00001576
Rafael Espindolab6417502015-04-28 15:04:09 +00001577 writeSection(Asm, SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1578 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001579 }
1580}
1581
Rafael Espindola1557fd62011-03-20 18:44:20 +00001582void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1583 const MCAsmLayout &Layout) {
1584 GroupMapTy GroupMap;
1585 RevGroupMapTy RevGroupMap;
1586 SectionIndexMapTy SectionIndexMap;
1587
David Blaikiee06e8012014-04-11 22:11:50 +00001588 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001589 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1590 RevGroupMap, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001591
Rafael Espindola1557fd62011-03-20 18:44:20 +00001592 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001593 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001594
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001595 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola1557fd62011-03-20 18:44:20 +00001596
1597 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1598 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001599 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001600
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001601 unsigned NumSections = Asm.size();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001602 std::vector<const MCSectionELF*> Sections;
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001603 Sections.resize(NumSections);
1604
1605 for (auto &Pair : SectionIndexMap)
1606 Sections[Pair.second - 1] = Pair.first;
1607
Rafael Espindolaa8201692015-04-28 15:26:21 +00001608 SectionOffsetsTy SectionOffsets;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001609
Rafael Espindola1557fd62011-03-20 18:44:20 +00001610 // Write out the ELF header ...
Rafael Espindola642a2212015-04-14 22:54:16 +00001611 WriteHeader(Asm, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001612
Rafael Espindola7230f802015-04-08 11:41:24 +00001613 // ... then the sections ...
Rafael Espindola163f6722015-04-28 19:07:16 +00001614 for (const MCSectionELF *Section : Sections) {
1615 const MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
Rafael Espindola642a2212015-04-14 22:54:16 +00001616 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1617 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001618
Rafael Espindola642a2212015-04-14 22:54:16 +00001619 // Remember the offset into the file for this section.
Rafael Espindolab6417502015-04-28 15:04:09 +00001620 uint64_t SecStart = OS.tell();
Rafael Espindola642a2212015-04-14 22:54:16 +00001621 writeDataSectionData(Asm, Layout, SD);
Rafael Espindolab6417502015-04-28 15:04:09 +00001622 uint64_t SecEnd = OS.tell();
Rafael Espindolaa8201692015-04-28 15:26:21 +00001623 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
Rafael Espindola642a2212015-04-14 22:54:16 +00001624 }
1625
1626 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001627 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001628 WriteZeros(Padding);
1629
Rafael Espindola642a2212015-04-14 22:54:16 +00001630 const unsigned SectionHeaderOffset = OS.tell();
1631
Rafael Espindola1557fd62011-03-20 18:44:20 +00001632 // ... then the section header table ...
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001633 writeSectionHeader(Sections, Asm, GroupMap, Layout, SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +00001634 SectionOffsets);
Rafael Espindola642a2212015-04-14 22:54:16 +00001635
1636 if (is64Bit()) {
1637 uint64_t Val = SectionHeaderOffset;
1638 if (sys::IsLittleEndianHost != IsLittleEndian)
1639 sys::swapByteOrder(Val);
1640 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1641 offsetof(ELF::Elf64_Ehdr, e_shoff));
1642 } else {
1643 uint32_t Val = SectionHeaderOffset;
1644 if (sys::IsLittleEndianHost != IsLittleEndian)
1645 sys::swapByteOrder(Val);
1646 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1647 offsetof(ELF::Elf32_Ehdr, e_shoff));
1648 }
Rafael Espindola1557fd62011-03-20 18:44:20 +00001649}
1650
Rafael Espindola94a88d72015-04-06 15:27:57 +00001651bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola35d61892015-04-17 21:15:17 +00001652 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
1653 bool InSet, bool IsPCRel) const {
1654 if (IsPCRel) {
1655 assert(!InSet);
1656 if (::isWeak(DataA))
1657 return false;
1658 }
1659 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
1660 InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001661}
1662
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001663bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001664 if (::isWeak(SD))
1665 return true;
1666
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001667 // It is invalid to replace a reference to a global in a comdat
1668 // with a reference to a local since out of comdat references
1669 // to a local are forbidden.
1670 // We could try to return false for more cases, like the reference
1671 // being in the same comdat or Sym being an alias to another global,
1672 // but it is not clear if it is worth the effort.
Rafael Espindola29c82702015-04-20 12:44:06 +00001673 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1674 return false;
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001675
Rafael Espindola29c82702015-04-20 12:44:06 +00001676 const MCSymbol &Sym = SD.getSymbol();
1677 if (!Sym.isInSection())
1678 return false;
1679
1680 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1681 return Sec.getGroup();
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001682}
1683
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001684MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
Rafael Espindola5560a4c2015-04-14 22:14:34 +00001685 raw_pwrite_stream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001686 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001687 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001688}