blob: 0b8f752d0764f405b7f09b4fc1c5b86042dafe6d [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;
Rafael Espindolae3ff9302015-04-28 20:09:13 +000058 std::vector<const MCSectionELF *> &Sections;
Rafael Espindola10be0832014-03-25 23:44:25 +000059
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,
Rafael Espindolae3ff9302015-04-28 20:09:13 +000075 std::vector<const MCSectionELF *> &Sections,
Rafael Espindola10be0832014-03-25 23:44:25 +000076 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 Espindolae3ff9302015-04-28 20:09:13 +0000205 std::vector<const MCSectionELF *> &Sections);
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
Rafael Espindola89feff32015-04-28 22:59:58 +0000220 // Map from a signature symbol to the group section index
221 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
Rafael Espindolaa8201692015-04-28 15:26:21 +0000222 // Start and end offset of each section
223 typedef std::vector<std::pair<uint64_t, uint64_t>> SectionOffsetsTy;
Rafael Espindola29abd972011-12-22 03:38:00 +0000224
Rafael Espindola022bb762014-03-24 03:43:21 +0000225 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000226 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000227 /// \param Asm - The assembler.
228 /// \param SectionIndexMap - Maps a section to its index.
229 /// \param RevGroupMap - Maps a signature symbol to the group section.
Rafael Espindola022bb762014-03-24 03:43:21 +0000230 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000231 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000232 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000233
Rafael Espindola89feff32015-04-28 22:59:58 +0000234 void maybeAddToGroup(MCAssembler &Asm,
235 ArrayRef<const MCSectionELF *> Sections,
236 const RevGroupMapTy &RevGroupMap,
Rafael Espindola8a90d872015-04-28 21:52:33 +0000237 const MCSectionELF &Section, unsigned Index);
238
239 void computeIndexMap(MCAssembler &Asm,
240 std::vector<const MCSectionELF *> &Sections,
241 SectionIndexMapTy &SectionIndexMap,
242 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000243
Rafael Espindolacf6d5a92015-04-28 22:26:19 +0000244 void createRelocationSection(MCAssembler &Asm, const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000245
David Blaikie8019bf82014-04-10 21:53:53 +0000246 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
247
Rafael Espindolaae7e4992015-04-29 19:20:10 +0000248 void WriteRelocations(MCAssembler &Asm, const MCAsmLayout &Layout);
Rafael Espindola29abd972011-12-22 03:38:00 +0000249
Rafael Espindola88d1f632015-04-29 20:25:24 +0000250 void
251 createSectionHeaderStringTable(MCAssembler &Asm,
252 std::vector<const MCSectionELF *> &Sections);
Rafael Espindolaae7e4992015-04-29 19:20:10 +0000253 void CreateMetadataSections(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindolae3ff9302015-04-28 20:09:13 +0000254 std::vector<const MCSectionELF *> &Sections);
Rafael Espindola29abd972011-12-22 03:38:00 +0000255
256 // Create the sections that show up in the symbol table. Currently
257 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaae7e4992015-04-29 19:20:10 +0000258 void createIndexedSections(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola55a3afb2015-04-28 21:07:28 +0000259 RevGroupMapTy &RevGroupMap,
Rafael Espindola8a90d872015-04-28 21:52:33 +0000260 std::vector<const MCSectionELF *> &Sections,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000261 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000262
Craig Topper34a61bc2014-03-08 07:02:02 +0000263 void ExecutePostLayoutBinding(MCAssembler &Asm,
264 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000265
Rafael Espindolabf0db6c2015-04-15 13:07:47 +0000266 void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
Rafael Espindola55a3afb2015-04-28 21:07:28 +0000267 MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000268 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +0000269 const SectionOffsetsTy &SectionOffsets);
Rafael Espindola29abd972011-12-22 03:38:00 +0000270
Rafael Espindola29abd972011-12-22 03:38:00 +0000271 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
272 uint64_t Address, uint64_t Offset,
273 uint64_t Size, uint32_t Link, uint32_t Info,
274 uint64_t Alignment, uint64_t EntrySize);
275
276 void WriteRelocationsFragment(const MCAssembler &Asm,
277 MCDataFragment *F,
278 const MCSectionData *SD);
279
Craig Topper34a61bc2014-03-08 07:02:02 +0000280 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000281 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
282 const MCSymbolData &DataA,
283 const MCFragment &FB,
284 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000285 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000286
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000287 bool isWeak(const MCSymbolData &SD) const override;
288
Craig Topper34a61bc2014-03-08 07:02:02 +0000289 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000290 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000291 const SectionIndexMapTy &SectionIndexMap,
292 uint32_t GroupSymbolIndex,
293 uint64_t Offset, uint64_t Size, uint64_t Alignment,
294 const MCSectionELF &Section);
295 };
296}
297
Rafael Espindola0ce09712014-03-25 22:43:53 +0000298FragmentWriter::FragmentWriter(bool IsLittleEndian)
299 : IsLittleEndian(IsLittleEndian) {}
300
301template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
302 if (IsLittleEndian)
303 Val = support::endian::byte_swap<T, support::little>(Val);
304 else
305 Val = support::endian::byte_swap<T, support::big>(Val);
306 const char *Start = (const char *)&Val;
307 F.getContents().append(Start, Start + sizeof(T));
308}
309
Rafael Espindola10be0832014-03-25 23:44:25 +0000310void SymbolTableWriter::createSymtabShndx() {
311 if (ShndxF)
312 return;
313
314 MCContext &Ctx = Asm.getContext();
315 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000316 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000317 MCSectionData *SymtabShndxSD =
318 &Asm.getOrCreateSectionData(*SymtabShndxSection);
319 SymtabShndxSD->setAlignment(4);
320 ShndxF = new MCDataFragment(SymtabShndxSD);
Rafael Espindolae3ff9302015-04-28 20:09:13 +0000321 Sections.push_back(SymtabShndxSection);
Rafael Espindola10be0832014-03-25 23:44:25 +0000322
323 for (unsigned I = 0; I < NumWritten; ++I)
324 write(*ShndxF, uint32_t(0));
325}
326
327template <typename T>
328void SymbolTableWriter::write(MCDataFragment &F, T Value) {
329 FWriter.write(F, Value);
330}
331
Rafael Espindolae3ff9302015-04-28 20:09:13 +0000332SymbolTableWriter::SymbolTableWriter(
333 MCAssembler &Asm, FragmentWriter &FWriter, bool Is64Bit,
334 std::vector<const MCSectionELF *> &Sections, MCDataFragment *SymtabF)
335 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit), Sections(Sections),
336 SymtabF(SymtabF), ShndxF(nullptr), NumWritten(0) {}
Rafael Espindola10be0832014-03-25 23:44:25 +0000337
338void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
339 uint64_t size, uint8_t other,
340 uint32_t shndx, bool Reserved) {
341 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
342
343 if (LargeIndex)
344 createSymtabShndx();
345
346 if (ShndxF) {
347 if (LargeIndex)
348 write(*ShndxF, shndx);
349 else
350 write(*ShndxF, uint32_t(0));
351 }
352
353 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
354
Rafael Espindola10be0832014-03-25 23:44:25 +0000355 if (Is64Bit) {
356 write(*SymtabF, name); // st_name
357 write(*SymtabF, info); // st_info
358 write(*SymtabF, other); // st_other
359 write(*SymtabF, Index); // st_shndx
360 write(*SymtabF, value); // st_value
361 write(*SymtabF, size); // st_size
362 } else {
363 write(*SymtabF, name); // st_name
364 write(*SymtabF, uint32_t(value)); // st_value
365 write(*SymtabF, uint32_t(size)); // st_size
366 write(*SymtabF, info); // st_info
367 write(*SymtabF, other); // st_other
368 write(*SymtabF, Index); // st_shndx
369 }
370
371 ++NumWritten;
372}
373
Jan Sjödin30a52de2011-02-28 21:45:04 +0000374bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
375 const MCFixupKindInfo &FKI =
376 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
377
378 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
379}
380
381bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
382 switch (Variant) {
383 default:
384 return false;
385 case MCSymbolRefExpr::VK_GOT:
386 case MCSymbolRefExpr::VK_PLT:
387 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000388 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000389 case MCSymbolRefExpr::VK_TPOFF:
390 case MCSymbolRefExpr::VK_TLSGD:
391 case MCSymbolRefExpr::VK_GOTTPOFF:
392 case MCSymbolRefExpr::VK_INDNTPOFF:
393 case MCSymbolRefExpr::VK_NTPOFF:
394 case MCSymbolRefExpr::VK_GOTNTPOFF:
395 case MCSymbolRefExpr::VK_TLSLDM:
396 case MCSymbolRefExpr::VK_DTPOFF:
397 case MCSymbolRefExpr::VK_TLSLD:
398 return true;
399 }
400}
401
Jason W Kim96f4c012010-11-15 16:18:39 +0000402ELFObjectWriter::~ELFObjectWriter()
403{}
404
Matt Fleming6c1ad482010-08-16 18:57:57 +0000405// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000406void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000407 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000408 // ELF Header
409 // ----------
410 //
411 // Note
412 // ----
413 // emitWord method behaves differently for ELF32 and ELF64, writing
414 // 4 bytes in the former and 8 in the latter.
415
Benjamin Kramer97fbdd52015-04-17 11:12:43 +0000416 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000417
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000418 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000419
420 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000421 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000422
423 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000424 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000425 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000426 Write8(0); // e_ident[EI_ABIVERSION]
427
428 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
429
430 Write16(ELF::ET_REL); // e_type
431
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000432 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000433
434 Write32(ELF::EV_CURRENT); // e_version
435 WriteWord(0); // e_entry, no entry point in .o file
436 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola642a2212015-04-14 22:54:16 +0000437 WriteWord(0); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000438
Jason W Kim4761fba2011-02-04 21:41:11 +0000439 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000440 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000441
442 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000443 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000444
445 Write16(0); // e_phentsize = prog header entry size
446 Write16(0); // e_phnum = # prog header entries = 0
447
448 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000449 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000450
451 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000452 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000453 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000454 else
455 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000456
457 // e_shstrndx = Section # of '.shstrtab'
Rafael Espindola88d1f632015-04-29 20:25:24 +0000458 assert(ShstrtabIndex < ELF::SHN_LORESERVE);
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
Rafael Espindolae3ff9302015-04-28 20:09:13 +0000600void ELFObjectWriter::WriteSymbolTable(
601 MCDataFragment *SymtabF, MCAssembler &Asm, const MCAsmLayout &Layout,
602 std::vector<const MCSectionELF *> &Sections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000603 // The string table must be emitted first because we need the index
604 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000605
606 // FIXME: Make sure the start of the symbol table is aligned.
607
Rafael Espindolae3ff9302015-04-28 20:09:13 +0000608 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), Sections, SymtabF);
Rafael Espindola10be0832014-03-25 23:44:25 +0000609
Matt Fleming6c1ad482010-08-16 18:57:57 +0000610 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000611 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000612
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000613 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000614 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
615 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000616 }
617
Matt Fleming6c1ad482010-08-16 18:57:57 +0000618 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000619 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
620
Matt Fleming6c1ad482010-08-16 18:57:57 +0000621 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
622 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000623 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000624 }
625
Matt Fleming6c1ad482010-08-16 18:57:57 +0000626 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
627 ELFSymbolData &MSD = ExternalSymbolData[i];
628 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000629 assert(((Data.getFlags() & ELF_STB_Global) ||
630 (Data.getFlags() & ELF_STB_Weak)) &&
631 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000632 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000633 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000634 LastLocalSymbolIndex++;
635 }
636
637 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
638 ELFSymbolData &MSD = UndefinedSymbolData[i];
639 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000640 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000641 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000642 LastLocalSymbolIndex++;
643 }
644}
645
Rafael Espindola5904e122014-03-29 06:26:49 +0000646// It is always valid to create a relocation with a symbol. It is preferable
647// to use a relocation with a section if that is possible. Using the section
648// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000649bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
650 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000651 const MCSymbolData *SD,
652 uint64_t C,
653 unsigned Type) const {
654 // A PCRel relocation to an absolute value has no symbol (or section). We
655 // represent that with a relocation to a null section.
656 if (!RefA)
657 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000658
Rafael Espindola5904e122014-03-29 06:26:49 +0000659 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
660 switch (Kind) {
661 default:
662 break;
663 // The .odp creation emits a relocation against the symbol ".TOC." which
664 // create a R_PPC64_TOC relocation. However the relocation symbol name
665 // in final object creation should be NULL, since the symbol does not
666 // really exist, it is just the reference to TOC base for the current
667 // object file. Since the symbol is undefined, returning false results
668 // in a relocation with a null section which is the desired result.
669 case MCSymbolRefExpr::VK_PPC_TOCBASE:
670 return false;
671
672 // These VariantKind cause the relocation to refer to something other than
673 // the symbol itself, like a linker generated table. Since the address of
674 // symbol is not relevant, we cannot replace the symbol with the
675 // section and patch the difference in the addend.
676 case MCSymbolRefExpr::VK_GOT:
677 case MCSymbolRefExpr::VK_PLT:
678 case MCSymbolRefExpr::VK_GOTPCREL:
679 case MCSymbolRefExpr::VK_Mips_GOT:
680 case MCSymbolRefExpr::VK_PPC_GOT_LO:
681 case MCSymbolRefExpr::VK_PPC_GOT_HI:
682 case MCSymbolRefExpr::VK_PPC_GOT_HA:
683 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000684 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000685
Rafael Espindola5904e122014-03-29 06:26:49 +0000686 // An undefined symbol is not in any section, so the relocation has to point
687 // to the symbol itself.
688 const MCSymbol &Sym = SD->getSymbol();
689 if (Sym.isUndefined())
690 return true;
691
692 unsigned Binding = MCELF::GetBinding(*SD);
693 switch(Binding) {
694 default:
695 llvm_unreachable("Invalid Binding");
696 case ELF::STB_LOCAL:
697 break;
698 case ELF::STB_WEAK:
699 // If the symbol is weak, it might be overridden by a symbol in another
700 // file. The relocation has to point to the symbol so that the linker
701 // can update it.
702 return true;
703 case ELF::STB_GLOBAL:
704 // Global ELF symbols can be preempted by the dynamic linker. The relocation
705 // has to point to the symbol for a reason analogous to the STB_WEAK case.
706 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000707 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000708
Rafael Espindola5904e122014-03-29 06:26:49 +0000709 // If a relocation points to a mergeable section, we have to be careful.
710 // If the offset is zero, a relocation with the section will encode the
711 // same information. With a non-zero offset, the situation is different.
712 // For example, a relocation can point 42 bytes past the end of a string.
713 // If we change such a relocation to use the section, the linker would think
714 // that it pointed to another string and subtracting 42 at runtime will
715 // produce the wrong value.
716 auto &Sec = cast<MCSectionELF>(Sym.getSection());
717 unsigned Flags = Sec.getFlags();
718 if (Flags & ELF::SHF_MERGE) {
719 if (C != 0)
720 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000721
722 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
723 // only handle section relocations to mergeable sections if using RELA.
724 if (!hasRelocationAddend())
725 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000726 }
727
Rafael Espindola5904e122014-03-29 06:26:49 +0000728 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000729 // are just an offset (@tpoff), require a symbol in gold versions before
730 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
731 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000732 if (Flags & ELF::SHF_TLS)
733 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000734
Rafael Espindola9ef84412014-04-11 19:18:01 +0000735 // If the symbol is a thumb function the final relocation must set the lowest
736 // bit. With a symbol that is done by just having the symbol have that bit
737 // set, so we would lose the bit if we relocated with the section.
738 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000739 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000740 return true;
741
Ulrich Weigand46797c62014-07-20 23:15:06 +0000742 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000743 return true;
744 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000745}
746
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000747static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
748 const MCSymbol &Sym = Ref.getSymbol();
749
750 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
751 return &Sym;
752
753 if (!Sym.isVariable())
754 return nullptr;
755
756 const MCExpr *Expr = Sym.getVariableValue();
757 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
758 if (!Inner)
759 return nullptr;
760
761 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
762 return &Inner->getSymbol();
763 return nullptr;
764}
765
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000766// True if the assembler knows nothing about the final value of the symbol.
767// This doesn't cover the comdat issues, since in those cases the assembler
768// can at least know that all symbols in the section will move together.
Rafael Espindolac9e70682015-03-24 23:48:44 +0000769static bool isWeak(const MCSymbolData &D) {
Rafael Espindolaa635d832015-04-17 08:46:11 +0000770 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
771 return true;
772
773 switch (MCELF::GetBinding(D)) {
774 default:
775 llvm_unreachable("Unknown binding");
776 case ELF::STB_LOCAL:
777 return false;
778 case ELF::STB_GLOBAL:
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000779 return false;
Rafael Espindolaa635d832015-04-17 08:46:11 +0000780 case ELF::STB_WEAK:
781 case ELF::STB_GNU_UNIQUE:
782 return true;
783 }
Rafael Espindolac9e70682015-03-24 23:48:44 +0000784}
785
Rafael Espindola26585542015-01-19 21:11:14 +0000786void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000787 const MCAsmLayout &Layout,
788 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000789 const MCFixup &Fixup, MCValue Target,
790 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000791 const MCSectionData *FixupSection = Fragment->getParent();
792 uint64_t C = Target.getConstant();
793 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000794
Rafael Espindola5904e122014-03-29 06:26:49 +0000795 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
796 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
797 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000798
Rafael Espindola5904e122014-03-29 06:26:49 +0000799 // Let A, B and C being the components of Target and R be the location of
800 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
801 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000802
Rafael Espindola5904e122014-03-29 06:26:49 +0000803 // In general, ELF has no relocations for -B. It can only represent (A + C)
804 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
805 // replace B to implement it: (A - R - K + C)
806 if (IsPCRel)
807 Asm.getContext().FatalError(
808 Fixup.getLoc(),
809 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000810
Rafael Espindola5904e122014-03-29 06:26:49 +0000811 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000812
Rafael Espindola5904e122014-03-29 06:26:49 +0000813 if (SymB.isUndefined())
814 Asm.getContext().FatalError(
815 Fixup.getLoc(),
816 Twine("symbol '") + SymB.getName() +
817 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000818
Rafael Espindola5904e122014-03-29 06:26:49 +0000819 assert(!SymB.isAbsolute() && "Should have been folded");
820 const MCSection &SecB = SymB.getSection();
821 if (&SecB != &FixupSection->getSection())
822 Asm.getContext().FatalError(
823 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000824
Rafael Espindola5904e122014-03-29 06:26:49 +0000825 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000826 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000827 Asm.getContext().FatalError(
828 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
829
Rafael Espindola5904e122014-03-29 06:26:49 +0000830 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
831 uint64_t K = SymBOffset - FixupOffset;
832 IsPCRel = true;
833 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000834 }
835
Rafael Espindola5904e122014-03-29 06:26:49 +0000836 // We either rejected the fixup or folded B into C at this point.
837 const MCSymbolRefExpr *RefA = Target.getSymA();
838 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
839 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
840
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000841 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000842 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000843 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
844 C += Layout.getSymbolOffset(SymAD);
845
846 uint64_t Addend = 0;
847 if (hasRelocationAddend()) {
848 Addend = C;
849 C = 0;
850 }
851
852 FixedValue = C;
853
854 // FIXME: What is this!?!?
855 MCSymbolRefExpr::VariantKind Modifier =
856 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000857 if (RelocNeedsGOT(Modifier))
858 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000859
Rafael Espindola5904e122014-03-29 06:26:49 +0000860 if (!RelocateWithSymbol) {
861 const MCSection *SecA =
862 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000863 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
864 MCSymbol *SectionSymbol =
865 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
866 : nullptr;
867 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000868 Relocations[FixupSection].push_back(Rec);
869 return;
870 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000871
Rafael Espindola5904e122014-03-29 06:26:49 +0000872 if (SymA) {
873 if (const MCSymbol *R = Renames.lookup(SymA))
874 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000875
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000876 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
877 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000878 else
879 UsedInReloc.insert(SymA);
880 }
881 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
882 Relocations[FixupSection].push_back(Rec);
883 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000884}
885
886
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000887uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000888ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
889 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000890 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000891 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000892}
893
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000894bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
895 const MCSymbolData &Data, bool Used,
896 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000897 const MCSymbol &Symbol = Data.getSymbol();
898 if (Symbol.isVariable()) {
899 const MCExpr *Expr = Symbol.getVariableValue();
900 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
901 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
902 return false;
903 }
904 }
Rafael Espindola16145972010-11-01 14:28:48 +0000905
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000906 if (Used)
907 return true;
908
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000909 if (Renamed)
910 return false;
911
Rafael Espindola45834a02010-10-29 23:09:31 +0000912 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
913 return true;
914
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000915 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000916 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000917 if (Base && Base->isUndefined())
918 return false;
919 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000920
Jan Sjödin30a52de2011-02-28 21:45:04 +0000921 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000922 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000923 return false;
924
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000925 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000926 return false;
927
928 return true;
929}
930
Rafael Espindola39f50422014-04-28 14:24:44 +0000931bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000932 if (Data.isExternal())
933 return false;
934
935 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000936 if (Symbol.isDefined())
937 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000938
Rafael Espindola39f50422014-04-28 14:24:44 +0000939 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000940 return false;
941
942 return true;
943}
944
Rafael Espindola8a90d872015-04-28 21:52:33 +0000945void ELFObjectWriter::maybeAddToGroup(MCAssembler &Asm,
Rafael Espindola89feff32015-04-28 22:59:58 +0000946 ArrayRef<const MCSectionELF *> Sections,
Rafael Espindola8a90d872015-04-28 21:52:33 +0000947 const RevGroupMapTy &RevGroupMap,
948 const MCSectionELF &Section,
949 unsigned Index) {
950 const MCSymbol *Sym = Section.getGroup();
951 if (!Sym)
952 return;
Rafael Espindola89feff32015-04-28 22:59:58 +0000953 const MCSectionELF *Group = Sections[RevGroupMap.lookup(Sym) - 1];
Rafael Espindola8a90d872015-04-28 21:52:33 +0000954 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
955 // FIXME: we could use the previous fragment
956 MCDataFragment *F = new MCDataFragment(&Data);
957 write(*F, Index);
958}
959
960void ELFObjectWriter::computeIndexMap(
961 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections,
962 SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap) {
Rafael Espindolaad3cfaa2015-04-28 20:23:35 +0000963 for (const MCSectionData &SD : Asm) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000964 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000965 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindolacf6d5a92015-04-28 22:26:19 +0000966 if (Section.getType() == ELF::SHT_GROUP)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000967 continue;
Rafael Espindola8a90d872015-04-28 21:52:33 +0000968 Sections.push_back(&Section);
969 unsigned Index = Sections.size();
970 SectionIndexMap[&Section] = Index;
Rafael Espindola89feff32015-04-28 22:59:58 +0000971 maybeAddToGroup(Asm, Sections, RevGroupMap, Section, Index);
Rafael Espindolacf6d5a92015-04-28 22:26:19 +0000972 createRelocationSection(Asm, SD);
Rafael Espindola8a90d872015-04-28 21:52:33 +0000973 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000974}
975
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000976void ELFObjectWriter::computeSymbolTable(
977 MCAssembler &Asm, const MCAsmLayout &Layout,
978 const SectionIndexMapTy &SectionIndexMap,
979 const RevGroupMapTy &RevGroupMap) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000980 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000981 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000982 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000983 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000984 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
985 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
986 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000987 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000988 }
989
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000990 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000991 for (MCSymbolData &SD : Asm.symbols()) {
992 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000993
Rafael Espindola16145972010-11-01 14:28:48 +0000994 bool Used = UsedInReloc.count(&Symbol);
995 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000996 bool isSignature = RevGroupMap.count(&Symbol);
997
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000998 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000999 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001000 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001001 continue;
1002
Matt Fleming6c1ad482010-08-16 18:57:57 +00001003 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001004 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001005 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001006
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001007 // Undefined symbols are global, but this is the first place we
1008 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001009 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001010 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001011 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001012 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001013 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001014 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001015 }
1016
Rafael Espindola022bb762014-03-24 03:43:21 +00001017 if (!BaseSymbol) {
1018 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001019 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001020 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001021 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001022 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001023 if (isSignature && !Used)
Rafael Espindola89feff32015-04-28 22:59:58 +00001024 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001025 else
1026 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001027 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001028 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001029 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001030 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001031 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001032 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001033 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001034 }
1035
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001036 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1037 // in defined ones.
1038 //
1039 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001040 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001041 // trivial.
1042 //
1043 // We thus have to be careful to not perform the symbol version replacement
1044 // blindly:
1045 //
1046 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1047 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1048 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1049 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1050 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1051 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1052 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1053 // "__imp_?" or "__imp_@?".
1054 //
1055 // It would have been interesting to perform the MS mangling prefix check
1056 // only when the target triple is of the form *-pc-windows-elf. But, it
1057 // seems that this information is not easily accessible from the
1058 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001059 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001060 if (!Name.startswith("?") && !Name.startswith("@?") &&
1061 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1062 // This symbol isn't following the MSVC C++ name mangling convention. We
1063 // can thus safely interpret the @@@ in symbol names as specifying symbol
1064 // versioning.
1065 SmallString<32> Buf;
1066 size_t Pos = Name.find("@@@");
1067 if (Pos != StringRef::npos) {
1068 Buf += Name.substr(0, Pos);
1069 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1070 Buf += Name.substr(Pos + Skip);
1071 Name = Buf;
1072 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001073 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001074
1075 // Sections have their own string table
1076 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1077 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001078
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001079 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1080 UndefinedSymbolData.push_back(MSD);
1081 else if (Local)
1082 LocalSymbolData.push_back(MSD);
1083 else
1084 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001085 }
1086
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001087 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1088 StrTabBuilder.add(*i);
1089
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001090 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001091
1092 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1093 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1094
Rafael Espindolab6613022014-10-17 01:48:58 +00001095 for (ELFSymbolData &MSD : LocalSymbolData)
1096 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1097 ? 0
1098 : StrTabBuilder.getOffset(MSD.Name);
1099 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001100 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1101 for (ELFSymbolData& MSD : UndefinedSymbolData)
1102 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1103
Matt Fleming6c1ad482010-08-16 18:57:57 +00001104 // Symbols are required to be in lexicographic order.
1105 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1106 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1107 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1108
1109 // Set the symbol indices. Local symbols must come before all other
1110 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001111 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001112 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1113 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001114
Matt Fleming6c1ad482010-08-16 18:57:57 +00001115 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1116 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1117 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1118 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1119}
1120
Rafael Espindolacf6d5a92015-04-28 22:26:19 +00001121void ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1122 const MCSectionData &SD) {
Rafael Espindolaead85492015-02-17 20:31:13 +00001123 if (Relocations[&SD].empty())
Rafael Espindolacf6d5a92015-04-28 22:26:19 +00001124 return;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001125
Rafael Espindolaead85492015-02-17 20:31:13 +00001126 MCContext &Ctx = Asm.getContext();
1127 const MCSectionELF &Section =
1128 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001129
Rafael Espindolaead85492015-02-17 20:31:13 +00001130 const StringRef SectionName = Section.getSectionName();
1131 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1132 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001133
Rafael Espindolaead85492015-02-17 20:31:13 +00001134 unsigned EntrySize;
1135 if (hasRelocationAddend())
1136 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1137 else
1138 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001139
Rafael Espindolaead85492015-02-17 20:31:13 +00001140 unsigned Flags = 0;
Rafael Espindolac9d06922015-03-30 13:39:16 +00001141 if (Section.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001142 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001143
Rafael Espindolac9d06922015-03-30 13:39:16 +00001144 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001145 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001146 Flags, EntrySize, Section.getGroup(), &Section);
Rafael Espindolacf6d5a92015-04-28 22:26:19 +00001147 Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001148}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001149
David Blaikiee06e8012014-04-11 22:11:50 +00001150static SmallVector<char, 128>
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001151getUncompressedData(const MCAsmLayout &Layout,
David Blaikiee06e8012014-04-11 22:11:50 +00001152 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001153 SmallVector<char, 128> UncompressedData;
1154 for (const MCFragment &F : Fragments) {
1155 const SmallVectorImpl<char> *Contents;
1156 switch (F.getKind()) {
1157 case MCFragment::FT_Data:
1158 Contents = &cast<MCDataFragment>(F).getContents();
1159 break;
1160 case MCFragment::FT_Dwarf:
1161 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1162 break;
1163 case MCFragment::FT_DwarfFrame:
1164 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1165 break;
1166 default:
1167 llvm_unreachable(
1168 "Not expecting any other fragment types in a debug_* section");
1169 }
1170 UncompressedData.append(Contents->begin(), Contents->end());
1171 }
1172 return UncompressedData;
1173}
1174
1175// Include the debug info compression header:
1176// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1177// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001178static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001179prependCompressionHeader(uint64_t Size,
1180 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001181 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001182 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1183 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001184 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001185 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001186 CompressedContents.insert(CompressedContents.begin(),
1187 Magic.size() + sizeof(Size), 0);
1188 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1189 std::copy(reinterpret_cast<char *>(&Size),
1190 reinterpret_cast<char *>(&Size + 1),
1191 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001192 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001193}
1194
1195// Return a single fragment containing the compressed contents of the whole
1196// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001197static std::unique_ptr<MCDataFragment>
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001198getCompressedFragment(const MCAsmLayout &Layout,
David Blaikiee06e8012014-04-11 22:11:50 +00001199 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001200 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1201
1202 // Gather the uncompressed data from all the fragments, recording the
1203 // alignment fragment, if seen, and any fixups.
1204 SmallVector<char, 128> UncompressedData =
1205 getUncompressedData(Layout, Fragments);
1206
1207 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1208
1209 zlib::Status Success = zlib::compress(
1210 StringRef(UncompressedData.data(), UncompressedData.size()),
1211 CompressedContents);
1212 if (Success != zlib::StatusOK)
1213 return nullptr;
1214
David Blaikie76d3a3c2014-04-18 21:52:26 +00001215 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1216 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001217
1218 return CompressedFragment;
1219}
1220
David Blaikie39fa6a22014-04-25 00:48:01 +00001221typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1222DefiningSymbolMap;
1223
1224static void UpdateSymbols(const MCAsmLayout &Layout,
1225 const std::vector<MCSymbolData *> &Symbols,
1226 MCFragment &NewFragment) {
1227 for (MCSymbolData *Sym : Symbols) {
1228 Sym->setOffset(Sym->getOffset() +
1229 Layout.getFragmentOffset(Sym->getFragment()));
1230 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001231 }
1232}
1233
David Blaikie8019bf82014-04-10 21:53:53 +00001234static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001235 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001236 const MCSectionELF &Section,
1237 MCSectionData &SD) {
1238 StringRef SectionName = Section.getSectionName();
1239 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1240
1241 std::unique_ptr<MCDataFragment> CompressedFragment =
1242 getCompressedFragment(Layout, Fragments);
1243
1244 // Leave the section as-is if the fragments could not be compressed.
1245 if (!CompressedFragment)
1246 return;
1247
David Blaikiec029ab42014-04-18 21:24:12 +00001248 // Update the fragment+offsets of any symbols referring to fragments in this
1249 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001250 auto I = DefiningSymbols.find(&SD);
1251 if (I != DefiningSymbols.end())
1252 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001253
David Blaikie8019bf82014-04-10 21:53:53 +00001254 // Invalidate the layout for the whole section since it will have new and
1255 // different fragments now.
1256 Layout.invalidateFragmentsFrom(&Fragments.front());
1257 Fragments.clear();
1258
1259 // Complete the initialization of the new fragment
1260 CompressedFragment->setParent(&SD);
1261 CompressedFragment->setLayoutOrder(0);
1262 Fragments.push_back(CompressedFragment.release());
1263
1264 // Rename from .debug_* to .zdebug_*
1265 Asm.getContext().renameELFSection(&Section,
1266 (".z" + SectionName.drop_front(1)).str());
1267}
1268
1269void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1270 MCAsmLayout &Layout) {
1271 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1272 return;
1273
David Blaikie39fa6a22014-04-25 00:48:01 +00001274 DefiningSymbolMap DefiningSymbols;
1275
1276 for (MCSymbolData &SD : Asm.symbols())
1277 if (MCFragment *F = SD.getFragment())
1278 DefiningSymbols[F->getParent()].push_back(&SD);
1279
David Blaikie8019bf82014-04-10 21:53:53 +00001280 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001281 const MCSectionELF &Section =
1282 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001283 StringRef SectionName = Section.getSectionName();
1284
1285 // Compressing debug_frame requires handling alignment fragments which is
1286 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1287 // for writing to arbitrary buffers) for little benefit.
1288 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1289 continue;
1290
David Blaikie39fa6a22014-04-25 00:48:01 +00001291 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001292 }
1293}
1294
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001295void ELFObjectWriter::WriteRelocations(MCAssembler &Asm,
1296 const MCAsmLayout &Layout) {
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001297 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1298 MCSectionData &RelSD = *it;
1299 const MCSectionELF &RelSection =
1300 static_cast<const MCSectionELF &>(RelSD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001301
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001302 unsigned Type = RelSection.getType();
1303 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001304 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001305
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001306 const MCSectionELF *Section = RelSection.getAssociatedSection();
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001307 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1308 RelSD.setAlignment(is64Bit() ? 8 : 4);
1309
1310 MCDataFragment *F = new MCDataFragment(&RelSD);
1311 WriteRelocationsFragment(Asm, F, &SD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001312 }
1313}
1314
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001315void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1316 uint64_t Flags, uint64_t Address,
1317 uint64_t Offset, uint64_t Size,
1318 uint32_t Link, uint32_t Info,
1319 uint64_t Alignment,
1320 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001321 Write32(Name); // sh_name: index into string table
1322 Write32(Type); // sh_type
1323 WriteWord(Flags); // sh_flags
1324 WriteWord(Address); // sh_addr
1325 WriteWord(Offset); // sh_offset
1326 WriteWord(Size); // sh_size
1327 Write32(Link); // sh_link
1328 Write32(Info); // sh_info
1329 WriteWord(Alignment); // sh_addralign
1330 WriteWord(EntrySize); // sh_entsize
1331}
1332
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001333void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1334 MCDataFragment *F,
1335 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001336 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001337
Petar Jovanovic0380d0b2015-04-14 13:23:34 +00001338 // Sort the relocation entries. Most targets just sort by Offset, but some
1339 // (e.g., MIPS) have additional constraints.
1340 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001341
1342 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001343 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001344 unsigned Index =
1345 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001346
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001347 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001348 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001349 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001350 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001351
Rafael Espindola5904e122014-03-29 06:26:49 +00001352 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1353 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1354 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1355 write(*F, TargetObjectWriter->getRType(Entry.Type));
1356 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001357 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001358 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001359 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001360 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001361 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001362 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001363 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001364 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001365
Rafael Espindolabce26a12010-10-05 15:11:03 +00001366 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001367 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001368 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001369
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001370 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001371 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001372 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001373 }
1374}
1375
Rafael Espindola88d1f632015-04-29 20:25:24 +00001376void ELFObjectWriter::createSectionHeaderStringTable(
1377 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections) {
1378 const MCSectionELF *ShstrtabSection = Sections[ShstrtabIndex - 1];
1379
1380 Asm.getOrCreateSectionData(*ShstrtabSection);
1381
1382 for (MCSectionData &SD : Asm) {
1383 const MCSectionELF &Section =
1384 static_cast<const MCSectionELF &>(SD.getSection());
1385 ShStrTabBuilder.add(Section.getSectionName());
1386 }
1387 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1388 OS << ShStrTabBuilder.data();
1389}
1390
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001391void ELFObjectWriter::CreateMetadataSections(
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001392 MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindolae3ff9302015-04-28 20:09:13 +00001393 std::vector<const MCSectionELF *> &Sections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001394 MCContext &Ctx = Asm.getContext();
1395 MCDataFragment *F;
1396
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001397 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001398
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001399 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001400 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001401 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001402 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001403 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolae3ff9302015-04-28 20:09:13 +00001404 SymbolTableIndex = Sections.size() + 1;
1405 Sections.push_back(SymtabSection);
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001406
Rafael Espindola1557fd62011-03-20 18:44:20 +00001407 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001408 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001409 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1410 StrtabSD.setAlignment(1);
Rafael Espindolae3ff9302015-04-28 20:09:13 +00001411 StringTableIndex = Sections.size() + 1;
1412 Sections.push_back(StrtabSection);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001413
1414 // Symbol table
1415 F = new MCDataFragment(&SymtabSD);
Rafael Espindolae3ff9302015-04-28 20:09:13 +00001416 WriteSymbolTable(F, Asm, Layout, Sections);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001417
Matt Fleming6c1ad482010-08-16 18:57:57 +00001418 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001419 F->getContents().append(StrTabBuilder.data().begin(),
1420 StrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001421}
1422
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001423void ELFObjectWriter::createIndexedSections(
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001424 MCAssembler &Asm, const MCAsmLayout &Layout, RevGroupMapTy &RevGroupMap,
Rafael Espindola8a90d872015-04-28 21:52:33 +00001425 std::vector<const MCSectionELF *> &Sections,
Rafael Espindola55a3afb2015-04-28 21:07:28 +00001426 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001427 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001428
Rafael Espindola88d1f632015-04-29 20:25:24 +00001429 const MCSectionELF *ShstrtabSection =
1430 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1431 Sections.push_back(ShstrtabSection);
1432 ShstrtabIndex = Sections.size();
1433 assert(ShstrtabIndex == 1);
1434
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001435 // Build the groups
Rafael Espindolafac3fbc2015-04-28 21:58:05 +00001436 for (const MCSectionData &SD : Asm) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001437 const MCSectionELF &Section =
Rafael Espindolafac3fbc2015-04-28 21:58:05 +00001438 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001439 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001440 continue;
1441
1442 const MCSymbol *SignatureSymbol = Section.getGroup();
1443 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola89feff32015-04-28 22:59:58 +00001444 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1445 if (!GroupIdx) {
1446 const MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
Rafael Espindola41920d02015-04-28 22:03:22 +00001447 Sections.push_back(Group);
Rafael Espindola89feff32015-04-28 22:59:58 +00001448 GroupIdx = Sections.size();
Rafael Espindola41920d02015-04-28 22:03:22 +00001449
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001450 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1451 Data.setAlignment(4);
1452 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001453 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001454 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001455 }
1456
Rafael Espindola8a90d872015-04-28 21:52:33 +00001457 computeIndexMap(Asm, Sections, SectionIndexMap, RevGroupMap);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001458}
1459
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001460void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001461 const SectionIndexMapTy &SectionIndexMap,
1462 uint32_t GroupSymbolIndex,
1463 uint64_t Offset, uint64_t Size,
1464 uint64_t Alignment,
1465 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001466 uint64_t sh_link = 0;
1467 uint64_t sh_info = 0;
1468
1469 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001470 default:
1471 // Nothing to do.
1472 break;
1473
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001474 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001475 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001476 break;
1477
1478 case ELF::SHT_REL:
1479 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001480 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001481 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001482 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001483 sh_info = SectionIndexMap.lookup(InfoSection);
1484 break;
1485 }
1486
1487 case ELF::SHT_SYMTAB:
1488 case ELF::SHT_DYNSYM:
1489 sh_link = StringTableIndex;
1490 sh_info = LastLocalSymbolIndex;
1491 break;
1492
1493 case ELF::SHT_SYMTAB_SHNDX:
1494 sh_link = SymbolTableIndex;
1495 break;
1496
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001497 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001498 sh_link = SymbolTableIndex;
1499 sh_info = GroupSymbolIndex;
1500 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001501 }
1502
Logan Chien4b724422013-02-05 14:18:59 +00001503 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001504 Section.getType() == ELF::SHT_ARM_EXIDX)
1505 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001506
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001507 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1508 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001509 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1510 Alignment, Section.getEntrySize());
1511}
1512
Jan Sjödin30a52de2011-02-28 21:45:04 +00001513bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001514 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001515 !SD.getSection().isVirtualSection();
1516}
1517
Rafael Espindola642a2212015-04-14 22:54:16 +00001518void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001519 const MCAsmLayout &Layout,
Rafael Espindola642a2212015-04-14 22:54:16 +00001520 const MCSectionData &SD) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001521 if (IsELFMetaDataSection(SD)) {
1522 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1523 ++i) {
1524 const MCFragment &F = *i;
1525 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001526 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001527 }
1528 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001529 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001530 }
1531}
1532
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001533void ELFObjectWriter::writeSectionHeader(
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001534 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
Rafael Espindola55a3afb2015-04-28 21:07:28 +00001535 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +00001536 const SectionOffsetsTy &SectionOffsets) {
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001537 const unsigned NumSections = Asm.size();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001538
Matt Fleming6c1ad482010-08-16 18:57:57 +00001539 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001540 uint64_t FirstSectionSize =
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001541 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
Rafael Espindola88d1f632015-04-29 20:25:24 +00001542 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001543
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001544 for (unsigned i = 0; i < NumSections; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001545 const MCSectionELF &Section = *Sections[i];
1546 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1547 uint32_t GroupSymbolIndex;
1548 if (Section.getType() != ELF::SHT_GROUP)
1549 GroupSymbolIndex = 0;
1550 else
Rafael Espindola55a3afb2015-04-28 21:07:28 +00001551 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section.getGroup());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001552
Rafael Espindolaa8201692015-04-28 15:26:21 +00001553 const std::pair<uint64_t, uint64_t> &Offsets = SectionOffsets[i];
Rafael Espindolab6417502015-04-28 15:04:09 +00001554 uint64_t Size = Section.getType() == ELF::SHT_NOBITS
1555 ? Layout.getSectionAddressSize(&SD)
1556 : Offsets.second - Offsets.first;
Rafael Espindola60ebca92010-12-02 03:09:06 +00001557
Rafael Espindolab6417502015-04-28 15:04:09 +00001558 writeSection(Asm, SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1559 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001560 }
1561}
1562
Rafael Espindola1557fd62011-03-20 18:44:20 +00001563void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1564 const MCAsmLayout &Layout) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001565 RevGroupMapTy RevGroupMap;
1566 SectionIndexMapTy SectionIndexMap;
1567
David Blaikiee06e8012014-04-11 22:11:50 +00001568 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola8a90d872015-04-28 21:52:33 +00001569 std::vector<const MCSectionELF *> Sections;
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001570 createIndexedSections(Asm, Layout, RevGroupMap, Sections, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001571
Rafael Espindola1557fd62011-03-20 18:44:20 +00001572 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001573 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001574
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001575 WriteRelocations(Asm, Layout);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001576
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001577 CreateMetadataSections(Asm, Layout, Sections);
Rafael Espindolae3ff9302015-04-28 20:09:13 +00001578
Rafael Espindola88d1f632015-04-29 20:25:24 +00001579 unsigned NumSections = Asm.size() + 1;
Rafael Espindolaa8201692015-04-28 15:26:21 +00001580 SectionOffsetsTy SectionOffsets;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001581
Rafael Espindola1557fd62011-03-20 18:44:20 +00001582 // Write out the ELF header ...
Rafael Espindola642a2212015-04-14 22:54:16 +00001583 WriteHeader(Asm, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001584
Rafael Espindola7230f802015-04-08 11:41:24 +00001585 // ... then the sections ...
Rafael Espindola88d1f632015-04-29 20:25:24 +00001586 SectionOffsets.push_back(std::make_pair(0, 0));
1587 for (auto I = ++Sections.begin(), E = Sections.end(); I != E; ++I) {
1588 const MCSectionData &SD = Asm.getOrCreateSectionData(**I);
Rafael Espindola642a2212015-04-14 22:54:16 +00001589 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1590 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001591
Rafael Espindola642a2212015-04-14 22:54:16 +00001592 // Remember the offset into the file for this section.
Rafael Espindolab6417502015-04-28 15:04:09 +00001593 uint64_t SecStart = OS.tell();
Rafael Espindola642a2212015-04-14 22:54:16 +00001594 writeDataSectionData(Asm, Layout, SD);
Rafael Espindolab6417502015-04-28 15:04:09 +00001595 uint64_t SecEnd = OS.tell();
Rafael Espindolaa8201692015-04-28 15:26:21 +00001596 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
Rafael Espindola642a2212015-04-14 22:54:16 +00001597 }
1598
Rafael Espindola88d1f632015-04-29 20:25:24 +00001599 {
1600 uint64_t SecStart = OS.tell();
1601 createSectionHeaderStringTable(Asm, Sections);
1602 uint64_t SecEnd = OS.tell();
1603 SectionOffsets[0] = std::make_pair(SecStart, SecEnd);
1604 }
1605
Rafael Espindola642a2212015-04-14 22:54:16 +00001606 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001607 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001608 WriteZeros(Padding);
1609
Rafael Espindola642a2212015-04-14 22:54:16 +00001610 const unsigned SectionHeaderOffset = OS.tell();
1611
Rafael Espindola1557fd62011-03-20 18:44:20 +00001612 // ... then the section header table ...
Rafael Espindola55a3afb2015-04-28 21:07:28 +00001613 writeSectionHeader(Sections, Asm, Layout, SectionIndexMap, SectionOffsets);
Rafael Espindola642a2212015-04-14 22:54:16 +00001614
1615 if (is64Bit()) {
1616 uint64_t Val = SectionHeaderOffset;
1617 if (sys::IsLittleEndianHost != IsLittleEndian)
1618 sys::swapByteOrder(Val);
1619 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1620 offsetof(ELF::Elf64_Ehdr, e_shoff));
1621 } else {
1622 uint32_t Val = SectionHeaderOffset;
1623 if (sys::IsLittleEndianHost != IsLittleEndian)
1624 sys::swapByteOrder(Val);
1625 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1626 offsetof(ELF::Elf32_Ehdr, e_shoff));
1627 }
Rafael Espindola1557fd62011-03-20 18:44:20 +00001628}
1629
Rafael Espindola94a88d72015-04-06 15:27:57 +00001630bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola35d61892015-04-17 21:15:17 +00001631 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
1632 bool InSet, bool IsPCRel) const {
1633 if (IsPCRel) {
1634 assert(!InSet);
1635 if (::isWeak(DataA))
1636 return false;
1637 }
1638 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
1639 InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001640}
1641
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001642bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001643 if (::isWeak(SD))
1644 return true;
1645
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001646 // It is invalid to replace a reference to a global in a comdat
1647 // with a reference to a local since out of comdat references
1648 // to a local are forbidden.
1649 // We could try to return false for more cases, like the reference
1650 // being in the same comdat or Sym being an alias to another global,
1651 // but it is not clear if it is worth the effort.
Rafael Espindola29c82702015-04-20 12:44:06 +00001652 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1653 return false;
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001654
Rafael Espindola29c82702015-04-20 12:44:06 +00001655 const MCSymbol &Sym = SD.getSymbol();
1656 if (!Sym.isInSection())
1657 return false;
1658
1659 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1660 return Sec.getGroup();
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001661}
1662
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001663MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
Rafael Espindola5560a4c2015-04-14 22:14:34 +00001664 raw_pwrite_stream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001665 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001666 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001667}