blob: 1646fe59ce413b311802872d28ca2802cb421f30 [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);
94 static uint64_t DataSectionSize(const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +000095 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
96 const MCSectionData &SD);
97
Rafael Espindola642a2212015-04-14 22:54:16 +000098 void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
99 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000100
Rafael Espindola6cd21802015-04-07 22:35:40 +0000101 /// Helper struct for containing some precomputed information on symbols.
Rafael Espindola29abd972011-12-22 03:38:00 +0000102 struct ELFSymbolData {
103 MCSymbolData *SymbolData;
104 uint64_t StringIndex;
105 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000106 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000107
108 // Support lexicographic sorting.
109 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolab6613022014-10-17 01:48:58 +0000110 unsigned LHSType = MCELF::GetType(*SymbolData);
111 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
112 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
113 return false;
114 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
115 return true;
116 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
117 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000118 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000119 }
120 };
121
Rafael Espindola29abd972011-12-22 03:38:00 +0000122 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000123 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000124
125 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
126 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
127 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
128
Rafael Espindola5904e122014-03-29 06:26:49 +0000129 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
130 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000131 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000132
133 /// @}
134 /// @name Symbol Table Data
135 /// @{
136
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000137 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000138 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000139 std::vector<ELFSymbolData> LocalSymbolData;
140 std::vector<ELFSymbolData> ExternalSymbolData;
141 std::vector<ELFSymbolData> UndefinedSymbolData;
142
143 /// @}
144
145 bool NeedsGOT;
146
Rafael Espindola29abd972011-12-22 03:38:00 +0000147 // This holds the symbol table index of the last local symbol.
148 unsigned LastLocalSymbolIndex;
149 // This holds the .strtab section index.
150 unsigned StringTableIndex;
151 // This holds the .symtab section index.
152 unsigned SymbolTableIndex;
153
154 unsigned ShstrtabIndex;
155
156
Rafael Espindola29abd972011-12-22 03:38:00 +0000157 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000158 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
159 bool hasRelocationAddend() const {
160 return TargetObjectWriter->hasRelocationAddend();
161 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000162 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000163 bool IsPCRel) const {
164 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000165 }
166
Rafael Espindola29abd972011-12-22 03:38:00 +0000167 public:
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000168 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
Rafael Espindola0ce09712014-03-25 22:43:53 +0000169 bool IsLittleEndian)
David Blaikie9f380a32015-03-16 18:06:57 +0000170 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000171 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000172
Yaron Keren7773a722015-03-23 18:35:01 +0000173 void reset() override {
174 UsedInReloc.clear();
175 WeakrefUsedInReloc.clear();
176 Renames.clear();
177 Relocations.clear();
178 ShStrTabBuilder.clear();
179 StrTabBuilder.clear();
180 FileSymbolData.clear();
181 LocalSymbolData.clear();
182 ExternalSymbolData.clear();
183 UndefinedSymbolData.clear();
184 MCObjectWriter::reset();
185 }
186
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000187 ~ELFObjectWriter() override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000188
189 void WriteWord(uint64_t W) {
190 if (is64Bit())
191 Write64(W);
192 else
193 Write32(W);
194 }
195
Rafael Espindola0ce09712014-03-25 22:43:53 +0000196 template <typename T> void write(MCDataFragment &F, T Value) {
197 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000198 }
199
Jack Carter1bd90ff2013-01-30 02:09:52 +0000200 void WriteHeader(const MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000201 unsigned NumberOfSections);
202
Rafael Espindola10be0832014-03-25 23:44:25 +0000203 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000204 const MCAsmLayout &Layout);
205
Rafael Espindola10be0832014-03-25 23:44:25 +0000206 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000207 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000208 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000209
Rafael Espindolab60c8292014-04-29 12:46:50 +0000210 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
211 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000212 const MCSymbolData *SD, uint64_t C,
213 unsigned Type) const;
214
Rafael Espindola26585542015-01-19 21:11:14 +0000215 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000216 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000217 MCValue Target, bool &IsPCRel,
218 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000219
220 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
221 const MCSymbol *S);
222
223 // Map from a group section to the signature symbol
224 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
225 // Map from a signature symbol to the group section
226 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
Rafael Espindola29abd972011-12-22 03:38:00 +0000227 // Map from a section to its offset
228 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
229
Rafael Espindola022bb762014-03-24 03:43:21 +0000230 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000231 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000232 /// \param Asm - The assembler.
233 /// \param SectionIndexMap - Maps a section to its index.
234 /// \param RevGroupMap - Maps a signature symbol to the group section.
Rafael Espindola022bb762014-03-24 03:43:21 +0000235 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000236 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000237 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000238
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000239 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000240
Rafael Espindolaead85492015-02-17 20:31:13 +0000241 MCSectionData *createRelocationSection(MCAssembler &Asm,
242 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000243
David Blaikie8019bf82014-04-10 21:53:53 +0000244 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
245
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000246 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
Rafael Espindola29abd972011-12-22 03:38:00 +0000247
248 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolaef6baea2015-02-11 23:11:18 +0000249 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000250
251 // Create the sections that show up in the symbol table. Currently
252 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaead85492015-02-17 20:31:13 +0000253 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000254 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
255 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000256
Craig Topper34a61bc2014-03-08 07:02:02 +0000257 void ExecutePostLayoutBinding(MCAssembler &Asm,
258 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000259
Rafael Espindolabf0db6c2015-04-15 13:07:47 +0000260 void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
261 MCAssembler &Asm, const GroupMapTy &GroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000262 const MCAsmLayout &Layout,
263 const SectionIndexMapTy &SectionIndexMap,
264 const SectionOffsetMapTy &SectionOffsetMap);
265
Rafael Espindola29abd972011-12-22 03:38:00 +0000266 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
267 uint64_t Address, uint64_t Offset,
268 uint64_t Size, uint32_t Link, uint32_t Info,
269 uint64_t Alignment, uint64_t EntrySize);
270
271 void WriteRelocationsFragment(const MCAssembler &Asm,
272 MCDataFragment *F,
273 const MCSectionData *SD);
274
Craig Topper34a61bc2014-03-08 07:02:02 +0000275 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000276 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
277 const MCSymbolData &DataA,
278 const MCFragment &FB,
279 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000280 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000281
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000282 bool isWeak(const MCSymbolData &SD) const override;
283
Craig Topper34a61bc2014-03-08 07:02:02 +0000284 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000285 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000286 const SectionIndexMapTy &SectionIndexMap,
287 uint32_t GroupSymbolIndex,
288 uint64_t Offset, uint64_t Size, uint64_t Alignment,
289 const MCSectionELF &Section);
290 };
291}
292
Rafael Espindola0ce09712014-03-25 22:43:53 +0000293FragmentWriter::FragmentWriter(bool IsLittleEndian)
294 : IsLittleEndian(IsLittleEndian) {}
295
296template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
297 if (IsLittleEndian)
298 Val = support::endian::byte_swap<T, support::little>(Val);
299 else
300 Val = support::endian::byte_swap<T, support::big>(Val);
301 const char *Start = (const char *)&Val;
302 F.getContents().append(Start, Start + sizeof(T));
303}
304
Rafael Espindola10be0832014-03-25 23:44:25 +0000305void SymbolTableWriter::createSymtabShndx() {
306 if (ShndxF)
307 return;
308
309 MCContext &Ctx = Asm.getContext();
310 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000311 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000312 MCSectionData *SymtabShndxSD =
313 &Asm.getOrCreateSectionData(*SymtabShndxSection);
314 SymtabShndxSD->setAlignment(4);
315 ShndxF = new MCDataFragment(SymtabShndxSD);
316 unsigned Index = SectionIndexMap.size() + 1;
317 SectionIndexMap[SymtabShndxSection] = Index;
318
319 for (unsigned I = 0; I < NumWritten; ++I)
320 write(*ShndxF, uint32_t(0));
321}
322
323template <typename T>
324void SymbolTableWriter::write(MCDataFragment &F, T Value) {
325 FWriter.write(F, Value);
326}
327
328SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
329 bool Is64Bit,
330 SectionIndexMapTy &SectionIndexMap,
331 MCDataFragment *SymtabF)
332 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
333 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
334 NumWritten(0) {}
335
336void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
337 uint64_t size, uint8_t other,
338 uint32_t shndx, bool Reserved) {
339 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
340
341 if (LargeIndex)
342 createSymtabShndx();
343
344 if (ShndxF) {
345 if (LargeIndex)
346 write(*ShndxF, shndx);
347 else
348 write(*ShndxF, uint32_t(0));
349 }
350
351 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
352
Rafael Espindola10be0832014-03-25 23:44:25 +0000353 if (Is64Bit) {
354 write(*SymtabF, name); // st_name
355 write(*SymtabF, info); // st_info
356 write(*SymtabF, other); // st_other
357 write(*SymtabF, Index); // st_shndx
358 write(*SymtabF, value); // st_value
359 write(*SymtabF, size); // st_size
360 } else {
361 write(*SymtabF, name); // st_name
362 write(*SymtabF, uint32_t(value)); // st_value
363 write(*SymtabF, uint32_t(size)); // st_size
364 write(*SymtabF, info); // st_info
365 write(*SymtabF, other); // st_other
366 write(*SymtabF, Index); // st_shndx
367 }
368
369 ++NumWritten;
370}
371
Jan Sjödin30a52de2011-02-28 21:45:04 +0000372bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
373 const MCFixupKindInfo &FKI =
374 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
375
376 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
377}
378
379bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
380 switch (Variant) {
381 default:
382 return false;
383 case MCSymbolRefExpr::VK_GOT:
384 case MCSymbolRefExpr::VK_PLT:
385 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000386 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000387 case MCSymbolRefExpr::VK_TPOFF:
388 case MCSymbolRefExpr::VK_TLSGD:
389 case MCSymbolRefExpr::VK_GOTTPOFF:
390 case MCSymbolRefExpr::VK_INDNTPOFF:
391 case MCSymbolRefExpr::VK_NTPOFF:
392 case MCSymbolRefExpr::VK_GOTNTPOFF:
393 case MCSymbolRefExpr::VK_TLSLDM:
394 case MCSymbolRefExpr::VK_DTPOFF:
395 case MCSymbolRefExpr::VK_TLSLD:
396 return true;
397 }
398}
399
Jason W Kim96f4c012010-11-15 16:18:39 +0000400ELFObjectWriter::~ELFObjectWriter()
401{}
402
Matt Fleming6c1ad482010-08-16 18:57:57 +0000403// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000404void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000405 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000406 // ELF Header
407 // ----------
408 //
409 // Note
410 // ----
411 // emitWord method behaves differently for ELF32 and ELF64, writing
412 // 4 bytes in the former and 8 in the latter.
413
Benjamin Kramer97fbdd52015-04-17 11:12:43 +0000414 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000415
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000416 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000417
418 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000419 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000420
421 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000422 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000423 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000424 Write8(0); // e_ident[EI_ABIVERSION]
425
426 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
427
428 Write16(ELF::ET_REL); // e_type
429
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000430 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000431
432 Write32(ELF::EV_CURRENT); // e_version
433 WriteWord(0); // e_entry, no entry point in .o file
434 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola642a2212015-04-14 22:54:16 +0000435 WriteWord(0); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000436
Jason W Kim4761fba2011-02-04 21:41:11 +0000437 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000438 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000439
440 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000441 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000442
443 Write16(0); // e_phentsize = prog header entry size
444 Write16(0); // e_phnum = # prog header entries = 0
445
446 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000447 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000448
449 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000450 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000451 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000452 else
453 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000454
455 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000456 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000457 Write16(ELF::SHN_XINDEX);
458 else
459 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000460}
461
Rafael Espindolafee224f2014-04-30 21:51:13 +0000462uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000463 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000464 if (Data.isCommon() && Data.isExternal())
465 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000466
Rafael Espindolafee224f2014-04-30 21:51:13 +0000467 uint64_t Res;
468 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000469 return 0;
470
Rafael Espindolafee224f2014-04-30 21:51:13 +0000471 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000472 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000473
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000474 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000475}
476
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000477void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
478 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000479 // The presence of symbol versions causes undefined symbols and
480 // versions declared with @@@ to be renamed.
481
David Blaikie583a31c2014-04-18 18:24:25 +0000482 for (MCSymbolData &OriginalData : Asm.symbols()) {
483 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000484
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000485 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000486 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000487 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000488 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
489 if (!Ref)
490 continue;
491 const MCSymbol &Symbol = Ref->getSymbol();
492 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000493
Benjamin Kramer14807272010-10-27 19:53:52 +0000494 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000495 size_t Pos = AliasName.find('@');
496 if (Pos == StringRef::npos)
497 continue;
498
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000499 // Aliases defined with .symvar copy the binding from the symbol they alias.
500 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000501 OriginalData.setExternal(SD.isExternal());
502 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000503
Benjamin Kramer14807272010-10-27 19:53:52 +0000504 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000505 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
506 continue;
507
Rafael Espindola26496e62010-10-27 17:56:18 +0000508 // FIXME: produce a better error message.
509 if (Symbol.isUndefined() && Rest.startswith("@@") &&
510 !Rest.startswith("@@@"))
511 report_fatal_error("A @@ version cannot be undefined");
512
Benjamin Kramer14807272010-10-27 19:53:52 +0000513 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000514 }
515}
516
Roman Divacky5a1c5492014-01-07 20:17:03 +0000517static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
518 uint8_t Type = newType;
519
520 // Propagation rules:
521 // IFUNC > FUNC > OBJECT > NOTYPE
522 // TLS_OBJECT > OBJECT > NOTYPE
523 //
524 // dont let the new type degrade the old type
525 switch (origType) {
526 default:
527 break;
528 case ELF::STT_GNU_IFUNC:
529 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
530 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
531 Type = ELF::STT_GNU_IFUNC;
532 break;
533 case ELF::STT_FUNC:
534 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
535 Type == ELF::STT_TLS)
536 Type = ELF::STT_FUNC;
537 break;
538 case ELF::STT_OBJECT:
539 if (Type == ELF::STT_NOTYPE)
540 Type = ELF::STT_OBJECT;
541 break;
542 case ELF::STT_TLS:
543 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
544 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
545 Type = ELF::STT_TLS;
546 break;
547 }
548
549 return Type;
550}
551
Rafael Espindola10be0832014-03-25 23:44:25 +0000552void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000553 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000554 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000555 assert((!OrigData.getFragment() ||
556 (&OrigData.getFragment()->getParent()->getSection() ==
557 &OrigData.getSymbol().getSection())) &&
558 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000559 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000560
561 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
562 // SHN_COMMON.
563 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000564
Jack Carter2f8d9d92013-02-19 21:57:35 +0000565 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000566 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000567 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000568 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000569 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000570 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
571 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000572 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000573 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000574
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000575 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000576 // 2 bits
577 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000578 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000579 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000580
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000581 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000582 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000583
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000584 const MCExpr *ESize = OrigData.getSize();
585 if (!ESize && Base)
586 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000587
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000588 if (ESize) {
589 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000590 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000591 report_fatal_error("Size expression must be absolute.");
592 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000593 }
594
595 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000596 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
597 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000598}
599
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000600void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000601 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000602 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000603 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000604 // The string table must be emitted first because we need the index
605 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000606
607 // FIXME: Make sure the start of the symbol table is aligned.
608
Rafael Espindola10be0832014-03-25 23:44:25 +0000609 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
610
Matt Fleming6c1ad482010-08-16 18:57:57 +0000611 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000612 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000613
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000614 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000615 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
616 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000617 }
618
Matt Fleming6c1ad482010-08-16 18:57:57 +0000619 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000620 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
621
Matt Fleming6c1ad482010-08-16 18:57:57 +0000622 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
623 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000624 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000625 }
626
Matt Fleming6c1ad482010-08-16 18:57:57 +0000627 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
628 ELFSymbolData &MSD = ExternalSymbolData[i];
629 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000630 assert(((Data.getFlags() & ELF_STB_Global) ||
631 (Data.getFlags() & ELF_STB_Weak)) &&
632 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000633 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000634 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000635 LastLocalSymbolIndex++;
636 }
637
638 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
639 ELFSymbolData &MSD = UndefinedSymbolData[i];
640 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000641 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000642 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000643 LastLocalSymbolIndex++;
644 }
645}
646
Rafael Espindola5904e122014-03-29 06:26:49 +0000647// It is always valid to create a relocation with a symbol. It is preferable
648// to use a relocation with a section if that is possible. Using the section
649// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000650bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
651 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000652 const MCSymbolData *SD,
653 uint64_t C,
654 unsigned Type) const {
655 // A PCRel relocation to an absolute value has no symbol (or section). We
656 // represent that with a relocation to a null section.
657 if (!RefA)
658 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000659
Rafael Espindola5904e122014-03-29 06:26:49 +0000660 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
661 switch (Kind) {
662 default:
663 break;
664 // The .odp creation emits a relocation against the symbol ".TOC." which
665 // create a R_PPC64_TOC relocation. However the relocation symbol name
666 // in final object creation should be NULL, since the symbol does not
667 // really exist, it is just the reference to TOC base for the current
668 // object file. Since the symbol is undefined, returning false results
669 // in a relocation with a null section which is the desired result.
670 case MCSymbolRefExpr::VK_PPC_TOCBASE:
671 return false;
672
673 // These VariantKind cause the relocation to refer to something other than
674 // the symbol itself, like a linker generated table. Since the address of
675 // symbol is not relevant, we cannot replace the symbol with the
676 // section and patch the difference in the addend.
677 case MCSymbolRefExpr::VK_GOT:
678 case MCSymbolRefExpr::VK_PLT:
679 case MCSymbolRefExpr::VK_GOTPCREL:
680 case MCSymbolRefExpr::VK_Mips_GOT:
681 case MCSymbolRefExpr::VK_PPC_GOT_LO:
682 case MCSymbolRefExpr::VK_PPC_GOT_HI:
683 case MCSymbolRefExpr::VK_PPC_GOT_HA:
684 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000685 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000686
Rafael Espindola5904e122014-03-29 06:26:49 +0000687 // An undefined symbol is not in any section, so the relocation has to point
688 // to the symbol itself.
689 const MCSymbol &Sym = SD->getSymbol();
690 if (Sym.isUndefined())
691 return true;
692
693 unsigned Binding = MCELF::GetBinding(*SD);
694 switch(Binding) {
695 default:
696 llvm_unreachable("Invalid Binding");
697 case ELF::STB_LOCAL:
698 break;
699 case ELF::STB_WEAK:
700 // If the symbol is weak, it might be overridden by a symbol in another
701 // file. The relocation has to point to the symbol so that the linker
702 // can update it.
703 return true;
704 case ELF::STB_GLOBAL:
705 // Global ELF symbols can be preempted by the dynamic linker. The relocation
706 // has to point to the symbol for a reason analogous to the STB_WEAK case.
707 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000708 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000709
Rafael Espindola5904e122014-03-29 06:26:49 +0000710 // If a relocation points to a mergeable section, we have to be careful.
711 // If the offset is zero, a relocation with the section will encode the
712 // same information. With a non-zero offset, the situation is different.
713 // For example, a relocation can point 42 bytes past the end of a string.
714 // If we change such a relocation to use the section, the linker would think
715 // that it pointed to another string and subtracting 42 at runtime will
716 // produce the wrong value.
717 auto &Sec = cast<MCSectionELF>(Sym.getSection());
718 unsigned Flags = Sec.getFlags();
719 if (Flags & ELF::SHF_MERGE) {
720 if (C != 0)
721 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000722
723 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
724 // only handle section relocations to mergeable sections if using RELA.
725 if (!hasRelocationAddend())
726 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000727 }
728
Rafael Espindola5904e122014-03-29 06:26:49 +0000729 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000730 // are just an offset (@tpoff), require a symbol in gold versions before
731 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
732 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000733 if (Flags & ELF::SHF_TLS)
734 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000735
Rafael Espindola9ef84412014-04-11 19:18:01 +0000736 // If the symbol is a thumb function the final relocation must set the lowest
737 // bit. With a symbol that is done by just having the symbol have that bit
738 // set, so we would lose the bit if we relocated with the section.
739 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000740 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000741 return true;
742
Ulrich Weigand46797c62014-07-20 23:15:06 +0000743 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000744 return true;
745 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000746}
747
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000748static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
749 const MCSymbol &Sym = Ref.getSymbol();
750
751 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
752 return &Sym;
753
754 if (!Sym.isVariable())
755 return nullptr;
756
757 const MCExpr *Expr = Sym.getVariableValue();
758 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
759 if (!Inner)
760 return nullptr;
761
762 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
763 return &Inner->getSymbol();
764 return nullptr;
765}
766
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000767// True if the assembler knows nothing about the final value of the symbol.
768// This doesn't cover the comdat issues, since in those cases the assembler
769// can at least know that all symbols in the section will move together.
Rafael Espindolac9e70682015-03-24 23:48:44 +0000770static bool isWeak(const MCSymbolData &D) {
Rafael Espindolaa635d832015-04-17 08:46:11 +0000771 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
772 return true;
773
774 switch (MCELF::GetBinding(D)) {
775 default:
776 llvm_unreachable("Unknown binding");
777 case ELF::STB_LOCAL:
778 return false;
779 case ELF::STB_GLOBAL:
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000780 return false;
Rafael Espindolaa635d832015-04-17 08:46:11 +0000781 case ELF::STB_WEAK:
782 case ELF::STB_GNU_UNIQUE:
783 return true;
784 }
Rafael Espindolac9e70682015-03-24 23:48:44 +0000785}
786
Rafael Espindola26585542015-01-19 21:11:14 +0000787void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000788 const MCAsmLayout &Layout,
789 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000790 const MCFixup &Fixup, MCValue Target,
791 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000792 const MCSectionData *FixupSection = Fragment->getParent();
793 uint64_t C = Target.getConstant();
794 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000795
Rafael Espindola5904e122014-03-29 06:26:49 +0000796 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
797 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
798 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000799
Rafael Espindola5904e122014-03-29 06:26:49 +0000800 // Let A, B and C being the components of Target and R be the location of
801 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
802 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000803
Rafael Espindola5904e122014-03-29 06:26:49 +0000804 // In general, ELF has no relocations for -B. It can only represent (A + C)
805 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
806 // replace B to implement it: (A - R - K + C)
807 if (IsPCRel)
808 Asm.getContext().FatalError(
809 Fixup.getLoc(),
810 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000811
Rafael Espindola5904e122014-03-29 06:26:49 +0000812 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000813
Rafael Espindola5904e122014-03-29 06:26:49 +0000814 if (SymB.isUndefined())
815 Asm.getContext().FatalError(
816 Fixup.getLoc(),
817 Twine("symbol '") + SymB.getName() +
818 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000819
Rafael Espindola5904e122014-03-29 06:26:49 +0000820 assert(!SymB.isAbsolute() && "Should have been folded");
821 const MCSection &SecB = SymB.getSection();
822 if (&SecB != &FixupSection->getSection())
823 Asm.getContext().FatalError(
824 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000825
Rafael Espindola5904e122014-03-29 06:26:49 +0000826 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000827 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000828 Asm.getContext().FatalError(
829 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
830
Rafael Espindola5904e122014-03-29 06:26:49 +0000831 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
832 uint64_t K = SymBOffset - FixupOffset;
833 IsPCRel = true;
834 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000835 }
836
Rafael Espindola5904e122014-03-29 06:26:49 +0000837 // We either rejected the fixup or folded B into C at this point.
838 const MCSymbolRefExpr *RefA = Target.getSymA();
839 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
840 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
841
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000842 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000843 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000844 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
845 C += Layout.getSymbolOffset(SymAD);
846
847 uint64_t Addend = 0;
848 if (hasRelocationAddend()) {
849 Addend = C;
850 C = 0;
851 }
852
853 FixedValue = C;
854
855 // FIXME: What is this!?!?
856 MCSymbolRefExpr::VariantKind Modifier =
857 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000858 if (RelocNeedsGOT(Modifier))
859 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000860
Rafael Espindola5904e122014-03-29 06:26:49 +0000861 if (!RelocateWithSymbol) {
862 const MCSection *SecA =
863 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000864 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
865 MCSymbol *SectionSymbol =
866 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
867 : nullptr;
868 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000869 Relocations[FixupSection].push_back(Rec);
870 return;
871 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000872
Rafael Espindola5904e122014-03-29 06:26:49 +0000873 if (SymA) {
874 if (const MCSymbol *R = Renames.lookup(SymA))
875 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000876
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000877 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
878 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000879 else
880 UsedInReloc.insert(SymA);
881 }
882 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
883 Relocations[FixupSection].push_back(Rec);
884 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000885}
886
887
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000888uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000889ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
890 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000891 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000892 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000893}
894
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000895bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
896 const MCSymbolData &Data, bool Used,
897 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000898 const MCSymbol &Symbol = Data.getSymbol();
899 if (Symbol.isVariable()) {
900 const MCExpr *Expr = Symbol.getVariableValue();
901 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
902 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
903 return false;
904 }
905 }
Rafael Espindola16145972010-11-01 14:28:48 +0000906
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000907 if (Used)
908 return true;
909
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000910 if (Renamed)
911 return false;
912
Rafael Espindola45834a02010-10-29 23:09:31 +0000913 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
914 return true;
915
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000916 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000917 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000918 if (Base && Base->isUndefined())
919 return false;
920 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000921
Jan Sjödin30a52de2011-02-28 21:45:04 +0000922 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000923 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000924 return false;
925
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000926 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000927 return false;
928
929 return true;
930}
931
Rafael Espindola39f50422014-04-28 14:24:44 +0000932bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000933 if (Data.isExternal())
934 return false;
935
936 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000937 if (Symbol.isDefined())
938 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000939
Rafael Espindola39f50422014-04-28 14:24:44 +0000940 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000941 return false;
942
943 return true;
944}
945
Rafael Espindolaead85492015-02-17 20:31:13 +0000946void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000947 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000948 unsigned Index = 1;
949 for (MCAssembler::iterator it = Asm.begin(),
950 ie = Asm.end(); it != ie; ++it) {
951 const MCSectionELF &Section =
952 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000953 if (Section.getType() != ELF::SHT_GROUP)
954 continue;
955 SectionIndexMap[&Section] = Index++;
956 }
957
Rafael Espindola607da972015-04-17 08:11:38 +0000958 std::vector<const MCSectionELF *> RelSections;
959
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000960 for (MCAssembler::iterator it = Asm.begin(),
961 ie = Asm.end(); it != ie; ++it) {
Rafael Espindolaead85492015-02-17 20:31:13 +0000962 const MCSectionData &SD = *it;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000963 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000964 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000965 if (Section.getType() == ELF::SHT_GROUP ||
966 Section.getType() == ELF::SHT_REL ||
967 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000968 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000969 SectionIndexMap[&Section] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000970 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
971 const MCSectionELF *RelSection =
972 static_cast<const MCSectionELF *>(&RelSD->getSection());
Rafael Espindola607da972015-04-17 08:11:38 +0000973 RelSections.push_back(RelSection);
Rafael Espindolaead85492015-02-17 20:31:13 +0000974 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000975 }
Rafael Espindola607da972015-04-17 08:11:38 +0000976
977 // Put relocation sections close together. The linker reads them
978 // first, so this improves cache locality.
979 for (const MCSectionELF * Sec: RelSections)
980 SectionIndexMap[Sec] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +0000981}
982
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000983void ELFObjectWriter::computeSymbolTable(
984 MCAssembler &Asm, const MCAsmLayout &Layout,
985 const SectionIndexMapTy &SectionIndexMap,
986 const RevGroupMapTy &RevGroupMap) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000987 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000988 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000989 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000990 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000991 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
992 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
993 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000994 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000995 }
996
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000997 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000998 for (MCSymbolData &SD : Asm.symbols()) {
999 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001000
Rafael Espindola16145972010-11-01 14:28:48 +00001001 bool Used = UsedInReloc.count(&Symbol);
1002 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001003 bool isSignature = RevGroupMap.count(&Symbol);
1004
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001005 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001006 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001007 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001008 continue;
1009
Matt Fleming6c1ad482010-08-16 18:57:57 +00001010 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001011 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001012 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001013
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001014 // Undefined symbols are global, but this is the first place we
1015 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001016 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001017 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001018 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001019 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001020 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001021 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001022 }
1023
Rafael Espindola022bb762014-03-24 03:43:21 +00001024 if (!BaseSymbol) {
1025 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001026 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001027 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001028 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001029 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001030 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001031 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001032 else
1033 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001034 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001035 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001036 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001037 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001038 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001039 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001040 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001041 }
1042
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001043 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1044 // in defined ones.
1045 //
1046 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001047 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001048 // trivial.
1049 //
1050 // We thus have to be careful to not perform the symbol version replacement
1051 // blindly:
1052 //
1053 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1054 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1055 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1056 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1057 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1058 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1059 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1060 // "__imp_?" or "__imp_@?".
1061 //
1062 // It would have been interesting to perform the MS mangling prefix check
1063 // only when the target triple is of the form *-pc-windows-elf. But, it
1064 // seems that this information is not easily accessible from the
1065 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001066 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001067 if (!Name.startswith("?") && !Name.startswith("@?") &&
1068 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1069 // This symbol isn't following the MSVC C++ name mangling convention. We
1070 // can thus safely interpret the @@@ in symbol names as specifying symbol
1071 // versioning.
1072 SmallString<32> Buf;
1073 size_t Pos = Name.find("@@@");
1074 if (Pos != StringRef::npos) {
1075 Buf += Name.substr(0, Pos);
1076 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1077 Buf += Name.substr(Pos + Skip);
1078 Name = Buf;
1079 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001080 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001081
1082 // Sections have their own string table
1083 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1084 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001085
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001086 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1087 UndefinedSymbolData.push_back(MSD);
1088 else if (Local)
1089 LocalSymbolData.push_back(MSD);
1090 else
1091 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001092 }
1093
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001094 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1095 StrTabBuilder.add(*i);
1096
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001097 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001098
1099 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1100 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1101
Rafael Espindolab6613022014-10-17 01:48:58 +00001102 for (ELFSymbolData &MSD : LocalSymbolData)
1103 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1104 ? 0
1105 : StrTabBuilder.getOffset(MSD.Name);
1106 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001107 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1108 for (ELFSymbolData& MSD : UndefinedSymbolData)
1109 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1110
Matt Fleming6c1ad482010-08-16 18:57:57 +00001111 // Symbols are required to be in lexicographic order.
1112 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1113 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1114 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1115
1116 // Set the symbol indices. Local symbols must come before all other
1117 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001118 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001119 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1120 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001121
Matt Fleming6c1ad482010-08-16 18:57:57 +00001122 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1123 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1124 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1125 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1126}
1127
Rafael Espindolaead85492015-02-17 20:31:13 +00001128MCSectionData *
1129ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1130 const MCSectionData &SD) {
1131 if (Relocations[&SD].empty())
1132 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001133
Rafael Espindolaead85492015-02-17 20:31:13 +00001134 MCContext &Ctx = Asm.getContext();
1135 const MCSectionELF &Section =
1136 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001137
Rafael Espindolaead85492015-02-17 20:31:13 +00001138 const StringRef SectionName = Section.getSectionName();
1139 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1140 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001141
Rafael Espindolaead85492015-02-17 20:31:13 +00001142 unsigned EntrySize;
1143 if (hasRelocationAddend())
1144 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1145 else
1146 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001147
Rafael Espindolaead85492015-02-17 20:31:13 +00001148 unsigned Flags = 0;
Rafael Espindolac9d06922015-03-30 13:39:16 +00001149 if (Section.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001150 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001151
Rafael Espindolac9d06922015-03-30 13:39:16 +00001152 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001153 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001154 Flags, EntrySize, Section.getGroup(), &Section);
Rafael Espindolaead85492015-02-17 20:31:13 +00001155 return &Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001156}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001157
David Blaikiee06e8012014-04-11 22:11:50 +00001158static SmallVector<char, 128>
1159getUncompressedData(MCAsmLayout &Layout,
1160 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001161 SmallVector<char, 128> UncompressedData;
1162 for (const MCFragment &F : Fragments) {
1163 const SmallVectorImpl<char> *Contents;
1164 switch (F.getKind()) {
1165 case MCFragment::FT_Data:
1166 Contents = &cast<MCDataFragment>(F).getContents();
1167 break;
1168 case MCFragment::FT_Dwarf:
1169 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1170 break;
1171 case MCFragment::FT_DwarfFrame:
1172 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1173 break;
1174 default:
1175 llvm_unreachable(
1176 "Not expecting any other fragment types in a debug_* section");
1177 }
1178 UncompressedData.append(Contents->begin(), Contents->end());
1179 }
1180 return UncompressedData;
1181}
1182
1183// Include the debug info compression header:
1184// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1185// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001186static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001187prependCompressionHeader(uint64_t Size,
1188 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001189 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001190 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1191 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001192 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001193 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001194 CompressedContents.insert(CompressedContents.begin(),
1195 Magic.size() + sizeof(Size), 0);
1196 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1197 std::copy(reinterpret_cast<char *>(&Size),
1198 reinterpret_cast<char *>(&Size + 1),
1199 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001200 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001201}
1202
1203// Return a single fragment containing the compressed contents of the whole
1204// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001205static std::unique_ptr<MCDataFragment>
1206getCompressedFragment(MCAsmLayout &Layout,
1207 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001208 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1209
1210 // Gather the uncompressed data from all the fragments, recording the
1211 // alignment fragment, if seen, and any fixups.
1212 SmallVector<char, 128> UncompressedData =
1213 getUncompressedData(Layout, Fragments);
1214
1215 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1216
1217 zlib::Status Success = zlib::compress(
1218 StringRef(UncompressedData.data(), UncompressedData.size()),
1219 CompressedContents);
1220 if (Success != zlib::StatusOK)
1221 return nullptr;
1222
David Blaikie76d3a3c2014-04-18 21:52:26 +00001223 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1224 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001225
1226 return CompressedFragment;
1227}
1228
David Blaikie39fa6a22014-04-25 00:48:01 +00001229typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1230DefiningSymbolMap;
1231
1232static void UpdateSymbols(const MCAsmLayout &Layout,
1233 const std::vector<MCSymbolData *> &Symbols,
1234 MCFragment &NewFragment) {
1235 for (MCSymbolData *Sym : Symbols) {
1236 Sym->setOffset(Sym->getOffset() +
1237 Layout.getFragmentOffset(Sym->getFragment()));
1238 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001239 }
1240}
1241
David Blaikie8019bf82014-04-10 21:53:53 +00001242static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001243 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001244 const MCSectionELF &Section,
1245 MCSectionData &SD) {
1246 StringRef SectionName = Section.getSectionName();
1247 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1248
1249 std::unique_ptr<MCDataFragment> CompressedFragment =
1250 getCompressedFragment(Layout, Fragments);
1251
1252 // Leave the section as-is if the fragments could not be compressed.
1253 if (!CompressedFragment)
1254 return;
1255
David Blaikiec029ab42014-04-18 21:24:12 +00001256 // Update the fragment+offsets of any symbols referring to fragments in this
1257 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001258 auto I = DefiningSymbols.find(&SD);
1259 if (I != DefiningSymbols.end())
1260 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001261
David Blaikie8019bf82014-04-10 21:53:53 +00001262 // Invalidate the layout for the whole section since it will have new and
1263 // different fragments now.
1264 Layout.invalidateFragmentsFrom(&Fragments.front());
1265 Fragments.clear();
1266
1267 // Complete the initialization of the new fragment
1268 CompressedFragment->setParent(&SD);
1269 CompressedFragment->setLayoutOrder(0);
1270 Fragments.push_back(CompressedFragment.release());
1271
1272 // Rename from .debug_* to .zdebug_*
1273 Asm.getContext().renameELFSection(&Section,
1274 (".z" + SectionName.drop_front(1)).str());
1275}
1276
1277void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1278 MCAsmLayout &Layout) {
1279 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1280 return;
1281
David Blaikie39fa6a22014-04-25 00:48:01 +00001282 DefiningSymbolMap DefiningSymbols;
1283
1284 for (MCSymbolData &SD : Asm.symbols())
1285 if (MCFragment *F = SD.getFragment())
1286 DefiningSymbols[F->getParent()].push_back(&SD);
1287
David Blaikie8019bf82014-04-10 21:53:53 +00001288 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001289 const MCSectionELF &Section =
1290 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001291 StringRef SectionName = Section.getSectionName();
1292
1293 // Compressing debug_frame requires handling alignment fragments which is
1294 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1295 // for writing to arbitrary buffers) for little benefit.
1296 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1297 continue;
1298
David Blaikie39fa6a22014-04-25 00:48:01 +00001299 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001300 }
1301}
1302
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001303void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001304 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1305 MCSectionData &RelSD = *it;
1306 const MCSectionELF &RelSection =
1307 static_cast<const MCSectionELF &>(RelSD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001308
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001309 unsigned Type = RelSection.getType();
1310 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001311 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001312
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001313 const MCSectionELF *Section = RelSection.getAssociatedSection();
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001314 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1315 RelSD.setAlignment(is64Bit() ? 8 : 4);
1316
1317 MCDataFragment *F = new MCDataFragment(&RelSD);
1318 WriteRelocationsFragment(Asm, F, &SD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001319 }
1320}
1321
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001322void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1323 uint64_t Flags, uint64_t Address,
1324 uint64_t Offset, uint64_t Size,
1325 uint32_t Link, uint32_t Info,
1326 uint64_t Alignment,
1327 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001328 Write32(Name); // sh_name: index into string table
1329 Write32(Type); // sh_type
1330 WriteWord(Flags); // sh_flags
1331 WriteWord(Address); // sh_addr
1332 WriteWord(Offset); // sh_offset
1333 WriteWord(Size); // sh_size
1334 Write32(Link); // sh_link
1335 Write32(Info); // sh_info
1336 WriteWord(Alignment); // sh_addralign
1337 WriteWord(EntrySize); // sh_entsize
1338}
1339
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001340void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1341 MCDataFragment *F,
1342 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001343 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001344
Petar Jovanovic0380d0b2015-04-14 13:23:34 +00001345 // Sort the relocation entries. Most targets just sort by Offset, but some
1346 // (e.g., MIPS) have additional constraints.
1347 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001348
1349 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001350 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001351 unsigned Index =
1352 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001353
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001354 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001355 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001356 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001357 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001358
Rafael Espindola5904e122014-03-29 06:26:49 +00001359 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1360 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1361 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1362 write(*F, TargetObjectWriter->getRType(Entry.Type));
1363 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001364 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001365 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001366 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001367 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001368 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001369 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001370 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001371 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001372
Rafael Espindolabce26a12010-10-05 15:11:03 +00001373 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001374 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001375 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001376
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001377 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001378 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001379 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001380 }
1381}
1382
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001383void ELFObjectWriter::CreateMetadataSections(
1384 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001385 MCContext &Ctx = Asm.getContext();
1386 MCDataFragment *F;
1387
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001388 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001389
Rafael Espindola0e527b72010-09-22 19:04:41 +00001390 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001391 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001392 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001393 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1394 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001395 ShstrtabIndex = SectionIndexMap.size() + 1;
1396 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001397
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001398 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001399 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001400 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001401 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001402 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001403 SymbolTableIndex = SectionIndexMap.size() + 1;
1404 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001405
Rafael Espindola1557fd62011-03-20 18:44:20 +00001406 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001407 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001408 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1409 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001410 StringTableIndex = SectionIndexMap.size() + 1;
1411 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001412
1413 // Symbol table
1414 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001415 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001416
Matt Fleming6c1ad482010-08-16 18:57:57 +00001417 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001418 F->getContents().append(StrTabBuilder.data().begin(),
1419 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001420
Matt Fleming6c1ad482010-08-16 18:57:57 +00001421 F = new MCDataFragment(&ShstrtabSD);
1422
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001423 // Section header string table.
1424 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001425 const MCSectionELF &Section =
1426 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001427 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001428 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001429 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001430 F->getContents().append(ShStrTabBuilder.data().begin(),
1431 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001432}
1433
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001434void ELFObjectWriter::createIndexedSections(
1435 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1436 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001437 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001438
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001439 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001440 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1441 it != ie; ++it) {
1442 const MCSectionELF &Section =
1443 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001444 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001445 continue;
1446
1447 const MCSymbol *SignatureSymbol = Section.getGroup();
1448 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001449 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001450 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001451 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001452 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1453 Data.setAlignment(4);
1454 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001455 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001456 }
1457 GroupMap[Group] = SignatureSymbol;
1458 }
1459
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001460 computeIndexMap(Asm, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001461
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001462 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001463 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001464 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001465 const MCSectionELF &Section =
1466 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001467 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001468 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001469 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001470 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1471 // FIXME: we could use the previous fragment
1472 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001473 uint32_t Index = SectionIndexMap.lookup(&Section);
1474 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001475 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001476}
1477
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001478void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001479 const SectionIndexMapTy &SectionIndexMap,
1480 uint32_t GroupSymbolIndex,
1481 uint64_t Offset, uint64_t Size,
1482 uint64_t Alignment,
1483 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001484 uint64_t sh_link = 0;
1485 uint64_t sh_info = 0;
1486
1487 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001488 default:
1489 // Nothing to do.
1490 break;
1491
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001492 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001493 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001494 break;
1495
1496 case ELF::SHT_REL:
1497 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001498 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001499 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001500 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001501 sh_info = SectionIndexMap.lookup(InfoSection);
1502 break;
1503 }
1504
1505 case ELF::SHT_SYMTAB:
1506 case ELF::SHT_DYNSYM:
1507 sh_link = StringTableIndex;
1508 sh_info = LastLocalSymbolIndex;
1509 break;
1510
1511 case ELF::SHT_SYMTAB_SHNDX:
1512 sh_link = SymbolTableIndex;
1513 break;
1514
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001515 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001516 sh_link = SymbolTableIndex;
1517 sh_info = GroupSymbolIndex;
1518 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001519 }
1520
Logan Chien4b724422013-02-05 14:18:59 +00001521 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001522 Section.getType() == ELF::SHT_ARM_EXIDX)
1523 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001524
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001525 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1526 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001527 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1528 Alignment, Section.getEntrySize());
1529}
1530
Jan Sjödin30a52de2011-02-28 21:45:04 +00001531bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001532 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001533 !SD.getSection().isVirtualSection();
1534}
1535
Jan Sjödin30a52de2011-02-28 21:45:04 +00001536uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001537 uint64_t Ret = 0;
1538 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1539 ++i) {
1540 const MCFragment &F = *i;
1541 assert(F.getKind() == MCFragment::FT_Data);
1542 Ret += cast<MCDataFragment>(F).getContents().size();
1543 }
1544 return Ret;
1545}
1546
Jan Sjödin30a52de2011-02-28 21:45:04 +00001547uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1548 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001549 if (IsELFMetaDataSection(SD))
1550 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001551 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001552}
1553
Rafael Espindola642a2212015-04-14 22:54:16 +00001554void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001555 const MCAsmLayout &Layout,
Rafael Espindola642a2212015-04-14 22:54:16 +00001556 const MCSectionData &SD) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001557 if (IsELFMetaDataSection(SD)) {
1558 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1559 ++i) {
1560 const MCFragment &F = *i;
1561 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001562 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001563 }
1564 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001565 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001566 }
1567}
1568
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001569void ELFObjectWriter::writeSectionHeader(
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001570 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1571 const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001572 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001573 const SectionOffsetMapTy &SectionOffsetMap) {
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001574 const unsigned NumSections = Asm.size();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001575
Matt Fleming6c1ad482010-08-16 18:57:57 +00001576 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001577 uint64_t FirstSectionSize =
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001578 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001579 uint32_t FirstSectionLink =
1580 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1581 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001582
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001583 for (unsigned i = 0; i < NumSections; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001584 const MCSectionELF &Section = *Sections[i];
1585 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1586 uint32_t GroupSymbolIndex;
1587 if (Section.getType() != ELF::SHT_GROUP)
1588 GroupSymbolIndex = 0;
1589 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001590 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1591 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001592
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001593 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001594
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001595 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1596 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1597 Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001598 }
1599}
1600
Rafael Espindola1557fd62011-03-20 18:44:20 +00001601void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1602 const MCAsmLayout &Layout) {
1603 GroupMapTy GroupMap;
1604 RevGroupMapTy RevGroupMap;
1605 SectionIndexMapTy SectionIndexMap;
1606
David Blaikiee06e8012014-04-11 22:11:50 +00001607 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001608 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1609 RevGroupMap, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001610
Rafael Espindola1557fd62011-03-20 18:44:20 +00001611 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001612 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001613
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001614 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola1557fd62011-03-20 18:44:20 +00001615
1616 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1617 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001618 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001619
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001620 unsigned NumSections = Asm.size();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001621 std::vector<const MCSectionELF*> Sections;
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001622 Sections.resize(NumSections);
1623
1624 for (auto &Pair : SectionIndexMap)
1625 Sections[Pair.second - 1] = Pair.first;
1626
Rafael Espindola1557fd62011-03-20 18:44:20 +00001627 SectionOffsetMapTy SectionOffsetMap;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001628
Rafael Espindola1557fd62011-03-20 18:44:20 +00001629 // Write out the ELF header ...
Rafael Espindola642a2212015-04-14 22:54:16 +00001630 WriteHeader(Asm, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001631
Rafael Espindola7230f802015-04-08 11:41:24 +00001632 // ... then the sections ...
Rafael Espindola642a2212015-04-14 22:54:16 +00001633 for (unsigned i = 0; i < NumSections; ++i) {
1634 const MCSectionELF &Section = *Sections[i];
1635 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1636 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1637 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001638
Rafael Espindola642a2212015-04-14 22:54:16 +00001639 // Remember the offset into the file for this section.
1640 SectionOffsetMap[&Section] = OS.tell();
1641
1642 writeDataSectionData(Asm, Layout, SD);
1643 }
1644
1645 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001646 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001647 WriteZeros(Padding);
1648
Rafael Espindola642a2212015-04-14 22:54:16 +00001649 const unsigned SectionHeaderOffset = OS.tell();
1650
Rafael Espindola1557fd62011-03-20 18:44:20 +00001651 // ... then the section header table ...
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001652 writeSectionHeader(Sections, Asm, GroupMap, Layout, SectionIndexMap,
1653 SectionOffsetMap);
Rafael Espindola642a2212015-04-14 22:54:16 +00001654
1655 if (is64Bit()) {
1656 uint64_t Val = SectionHeaderOffset;
1657 if (sys::IsLittleEndianHost != IsLittleEndian)
1658 sys::swapByteOrder(Val);
1659 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1660 offsetof(ELF::Elf64_Ehdr, e_shoff));
1661 } else {
1662 uint32_t Val = SectionHeaderOffset;
1663 if (sys::IsLittleEndianHost != IsLittleEndian)
1664 sys::swapByteOrder(Val);
1665 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1666 offsetof(ELF::Elf32_Ehdr, e_shoff));
1667 }
Rafael Espindola1557fd62011-03-20 18:44:20 +00001668}
1669
Rafael Espindola94a88d72015-04-06 15:27:57 +00001670bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola35d61892015-04-17 21:15:17 +00001671 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
1672 bool InSet, bool IsPCRel) const {
1673 if (IsPCRel) {
1674 assert(!InSet);
1675 if (::isWeak(DataA))
1676 return false;
1677 }
1678 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
1679 InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001680}
1681
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001682bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001683 if (::isWeak(SD))
1684 return true;
1685
1686 const MCSymbol &Sym = SD.getSymbol();
1687 if (!Sym.isInSection())
1688 return false;
1689
1690 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1691 if (!Sec.getGroup())
1692 return false;
1693
1694 // It is invalid to replace a reference to a global in a comdat
1695 // with a reference to a local since out of comdat references
1696 // to a local are forbidden.
1697 // We could try to return false for more cases, like the reference
1698 // being in the same comdat or Sym being an alias to another global,
1699 // but it is not clear if it is worth the effort.
1700 return true;
1701
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001702}
1703
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001704MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
Rafael Espindola5560a4c2015-04-14 22:14:34 +00001705 raw_pwrite_stream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001706 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001707 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001708}