blob: b293afc56a0d4ca27c6f9ac82ef78594c88621b1 [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,
Rafael Espindola94a88d72015-04-06 15:27:57 +0000278 const MCSymbolData *DataB,
Rafael Espindola29abd972011-12-22 03:38:00 +0000279 const MCFragment &FB,
280 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000281 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000282
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000283 bool isWeak(const MCSymbolData &SD) const override;
284
Craig Topper34a61bc2014-03-08 07:02:02 +0000285 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000286 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000287 const SectionIndexMapTy &SectionIndexMap,
288 uint32_t GroupSymbolIndex,
289 uint64_t Offset, uint64_t Size, uint64_t Alignment,
290 const MCSectionELF &Section);
291 };
292}
293
Rafael Espindola0ce09712014-03-25 22:43:53 +0000294FragmentWriter::FragmentWriter(bool IsLittleEndian)
295 : IsLittleEndian(IsLittleEndian) {}
296
297template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
298 if (IsLittleEndian)
299 Val = support::endian::byte_swap<T, support::little>(Val);
300 else
301 Val = support::endian::byte_swap<T, support::big>(Val);
302 const char *Start = (const char *)&Val;
303 F.getContents().append(Start, Start + sizeof(T));
304}
305
Rafael Espindola10be0832014-03-25 23:44:25 +0000306void SymbolTableWriter::createSymtabShndx() {
307 if (ShndxF)
308 return;
309
310 MCContext &Ctx = Asm.getContext();
311 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000312 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000313 MCSectionData *SymtabShndxSD =
314 &Asm.getOrCreateSectionData(*SymtabShndxSection);
315 SymtabShndxSD->setAlignment(4);
316 ShndxF = new MCDataFragment(SymtabShndxSD);
317 unsigned Index = SectionIndexMap.size() + 1;
318 SectionIndexMap[SymtabShndxSection] = Index;
319
320 for (unsigned I = 0; I < NumWritten; ++I)
321 write(*ShndxF, uint32_t(0));
322}
323
324template <typename T>
325void SymbolTableWriter::write(MCDataFragment &F, T Value) {
326 FWriter.write(F, Value);
327}
328
329SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
330 bool Is64Bit,
331 SectionIndexMapTy &SectionIndexMap,
332 MCDataFragment *SymtabF)
333 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
334 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
335 NumWritten(0) {}
336
337void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
338 uint64_t size, uint8_t other,
339 uint32_t shndx, bool Reserved) {
340 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
341
342 if (LargeIndex)
343 createSymtabShndx();
344
345 if (ShndxF) {
346 if (LargeIndex)
347 write(*ShndxF, shndx);
348 else
349 write(*ShndxF, uint32_t(0));
350 }
351
352 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
353
Rafael Espindola10be0832014-03-25 23:44:25 +0000354 if (Is64Bit) {
355 write(*SymtabF, name); // st_name
356 write(*SymtabF, info); // st_info
357 write(*SymtabF, other); // st_other
358 write(*SymtabF, Index); // st_shndx
359 write(*SymtabF, value); // st_value
360 write(*SymtabF, size); // st_size
361 } else {
362 write(*SymtabF, name); // st_name
363 write(*SymtabF, uint32_t(value)); // st_value
364 write(*SymtabF, uint32_t(size)); // st_size
365 write(*SymtabF, info); // st_info
366 write(*SymtabF, other); // st_other
367 write(*SymtabF, Index); // st_shndx
368 }
369
370 ++NumWritten;
371}
372
Jan Sjödin30a52de2011-02-28 21:45:04 +0000373bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
374 const MCFixupKindInfo &FKI =
375 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
376
377 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
378}
379
380bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
381 switch (Variant) {
382 default:
383 return false;
384 case MCSymbolRefExpr::VK_GOT:
385 case MCSymbolRefExpr::VK_PLT:
386 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000387 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000388 case MCSymbolRefExpr::VK_TPOFF:
389 case MCSymbolRefExpr::VK_TLSGD:
390 case MCSymbolRefExpr::VK_GOTTPOFF:
391 case MCSymbolRefExpr::VK_INDNTPOFF:
392 case MCSymbolRefExpr::VK_NTPOFF:
393 case MCSymbolRefExpr::VK_GOTNTPOFF:
394 case MCSymbolRefExpr::VK_TLSLDM:
395 case MCSymbolRefExpr::VK_DTPOFF:
396 case MCSymbolRefExpr::VK_TLSLD:
397 return true;
398 }
399}
400
Jason W Kim96f4c012010-11-15 16:18:39 +0000401ELFObjectWriter::~ELFObjectWriter()
402{}
403
Matt Fleming6c1ad482010-08-16 18:57:57 +0000404// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000405void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000406 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000407 // ELF Header
408 // ----------
409 //
410 // Note
411 // ----
412 // emitWord method behaves differently for ELF32 and ELF64, writing
413 // 4 bytes in the former and 8 in the latter.
414
415 Write8(0x7f); // e_ident[EI_MAG0]
416 Write8('E'); // e_ident[EI_MAG1]
417 Write8('L'); // e_ident[EI_MAG2]
418 Write8('F'); // e_ident[EI_MAG3]
419
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000420 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000421
422 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000423 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000424
425 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000426 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000427 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000428 Write8(0); // e_ident[EI_ABIVERSION]
429
430 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
431
432 Write16(ELF::ET_REL); // e_type
433
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000434 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000435
436 Write32(ELF::EV_CURRENT); // e_version
437 WriteWord(0); // e_entry, no entry point in .o file
438 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola642a2212015-04-14 22:54:16 +0000439 WriteWord(0); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000440
Jason W Kim4761fba2011-02-04 21:41:11 +0000441 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000442 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000443
444 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000445 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000446
447 Write16(0); // e_phentsize = prog header entry size
448 Write16(0); // e_phnum = # prog header entries = 0
449
450 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000451 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000452
453 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000454 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000455 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000456 else
457 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000458
459 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000460 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000461 Write16(ELF::SHN_XINDEX);
462 else
463 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000464}
465
Rafael Espindolafee224f2014-04-30 21:51:13 +0000466uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000467 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000468 if (Data.isCommon() && Data.isExternal())
469 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000470
Rafael Espindolafee224f2014-04-30 21:51:13 +0000471 uint64_t Res;
472 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000473 return 0;
474
Rafael Espindolafee224f2014-04-30 21:51:13 +0000475 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000476 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000477
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000478 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000479}
480
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000481void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
482 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000483 // The presence of symbol versions causes undefined symbols and
484 // versions declared with @@@ to be renamed.
485
David Blaikie583a31c2014-04-18 18:24:25 +0000486 for (MCSymbolData &OriginalData : Asm.symbols()) {
487 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000488
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000489 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000490 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000491 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000492 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
493 if (!Ref)
494 continue;
495 const MCSymbol &Symbol = Ref->getSymbol();
496 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000497
Benjamin Kramer14807272010-10-27 19:53:52 +0000498 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000499 size_t Pos = AliasName.find('@');
500 if (Pos == StringRef::npos)
501 continue;
502
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000503 // Aliases defined with .symvar copy the binding from the symbol they alias.
504 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000505 OriginalData.setExternal(SD.isExternal());
506 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000507
Benjamin Kramer14807272010-10-27 19:53:52 +0000508 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000509 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
510 continue;
511
Rafael Espindola26496e62010-10-27 17:56:18 +0000512 // FIXME: produce a better error message.
513 if (Symbol.isUndefined() && Rest.startswith("@@") &&
514 !Rest.startswith("@@@"))
515 report_fatal_error("A @@ version cannot be undefined");
516
Benjamin Kramer14807272010-10-27 19:53:52 +0000517 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000518 }
519}
520
Roman Divacky5a1c5492014-01-07 20:17:03 +0000521static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
522 uint8_t Type = newType;
523
524 // Propagation rules:
525 // IFUNC > FUNC > OBJECT > NOTYPE
526 // TLS_OBJECT > OBJECT > NOTYPE
527 //
528 // dont let the new type degrade the old type
529 switch (origType) {
530 default:
531 break;
532 case ELF::STT_GNU_IFUNC:
533 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
534 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
535 Type = ELF::STT_GNU_IFUNC;
536 break;
537 case ELF::STT_FUNC:
538 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
539 Type == ELF::STT_TLS)
540 Type = ELF::STT_FUNC;
541 break;
542 case ELF::STT_OBJECT:
543 if (Type == ELF::STT_NOTYPE)
544 Type = ELF::STT_OBJECT;
545 break;
546 case ELF::STT_TLS:
547 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
548 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
549 Type = ELF::STT_TLS;
550 break;
551 }
552
553 return Type;
554}
555
Rafael Espindola10be0832014-03-25 23:44:25 +0000556void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000557 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000558 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000559 assert((!OrigData.getFragment() ||
560 (&OrigData.getFragment()->getParent()->getSection() ==
561 &OrigData.getSymbol().getSection())) &&
562 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000563 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000564
565 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
566 // SHN_COMMON.
567 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000568
Jack Carter2f8d9d92013-02-19 21:57:35 +0000569 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000570 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000571 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000572 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000573 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000574 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
575 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000576 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000577 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000578
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000579 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000580 // 2 bits
581 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000582 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000583 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000584
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000585 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000586 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000587
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000588 const MCExpr *ESize = OrigData.getSize();
589 if (!ESize && Base)
590 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000591
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000592 if (ESize) {
593 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000594 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000595 report_fatal_error("Size expression must be absolute.");
596 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000597 }
598
599 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000600 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
601 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000602}
603
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000604void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000605 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000606 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000607 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000608 // The string table must be emitted first because we need the index
609 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000610
611 // FIXME: Make sure the start of the symbol table is aligned.
612
Rafael Espindola10be0832014-03-25 23:44:25 +0000613 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
614
Matt Fleming6c1ad482010-08-16 18:57:57 +0000615 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000616 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000617
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000618 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000619 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
620 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000621 }
622
Matt Fleming6c1ad482010-08-16 18:57:57 +0000623 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000624 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
625
Matt Fleming6c1ad482010-08-16 18:57:57 +0000626 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
627 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000628 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000629 }
630
Matt Fleming6c1ad482010-08-16 18:57:57 +0000631 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
632 ELFSymbolData &MSD = ExternalSymbolData[i];
633 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000634 assert(((Data.getFlags() & ELF_STB_Global) ||
635 (Data.getFlags() & ELF_STB_Weak)) &&
636 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000637 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000638 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000639 LastLocalSymbolIndex++;
640 }
641
642 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
643 ELFSymbolData &MSD = UndefinedSymbolData[i];
644 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000645 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000646 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000647 LastLocalSymbolIndex++;
648 }
649}
650
Rafael Espindola5904e122014-03-29 06:26:49 +0000651// It is always valid to create a relocation with a symbol. It is preferable
652// to use a relocation with a section if that is possible. Using the section
653// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000654bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
655 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000656 const MCSymbolData *SD,
657 uint64_t C,
658 unsigned Type) const {
659 // A PCRel relocation to an absolute value has no symbol (or section). We
660 // represent that with a relocation to a null section.
661 if (!RefA)
662 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000663
Rafael Espindola5904e122014-03-29 06:26:49 +0000664 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
665 switch (Kind) {
666 default:
667 break;
668 // The .odp creation emits a relocation against the symbol ".TOC." which
669 // create a R_PPC64_TOC relocation. However the relocation symbol name
670 // in final object creation should be NULL, since the symbol does not
671 // really exist, it is just the reference to TOC base for the current
672 // object file. Since the symbol is undefined, returning false results
673 // in a relocation with a null section which is the desired result.
674 case MCSymbolRefExpr::VK_PPC_TOCBASE:
675 return false;
676
677 // These VariantKind cause the relocation to refer to something other than
678 // the symbol itself, like a linker generated table. Since the address of
679 // symbol is not relevant, we cannot replace the symbol with the
680 // section and patch the difference in the addend.
681 case MCSymbolRefExpr::VK_GOT:
682 case MCSymbolRefExpr::VK_PLT:
683 case MCSymbolRefExpr::VK_GOTPCREL:
684 case MCSymbolRefExpr::VK_Mips_GOT:
685 case MCSymbolRefExpr::VK_PPC_GOT_LO:
686 case MCSymbolRefExpr::VK_PPC_GOT_HI:
687 case MCSymbolRefExpr::VK_PPC_GOT_HA:
688 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000689 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000690
Rafael Espindola5904e122014-03-29 06:26:49 +0000691 // An undefined symbol is not in any section, so the relocation has to point
692 // to the symbol itself.
693 const MCSymbol &Sym = SD->getSymbol();
694 if (Sym.isUndefined())
695 return true;
696
697 unsigned Binding = MCELF::GetBinding(*SD);
698 switch(Binding) {
699 default:
700 llvm_unreachable("Invalid Binding");
701 case ELF::STB_LOCAL:
702 break;
703 case ELF::STB_WEAK:
704 // If the symbol is weak, it might be overridden by a symbol in another
705 // file. The relocation has to point to the symbol so that the linker
706 // can update it.
707 return true;
708 case ELF::STB_GLOBAL:
709 // Global ELF symbols can be preempted by the dynamic linker. The relocation
710 // has to point to the symbol for a reason analogous to the STB_WEAK case.
711 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000712 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000713
Rafael Espindola5904e122014-03-29 06:26:49 +0000714 // If a relocation points to a mergeable section, we have to be careful.
715 // If the offset is zero, a relocation with the section will encode the
716 // same information. With a non-zero offset, the situation is different.
717 // For example, a relocation can point 42 bytes past the end of a string.
718 // If we change such a relocation to use the section, the linker would think
719 // that it pointed to another string and subtracting 42 at runtime will
720 // produce the wrong value.
721 auto &Sec = cast<MCSectionELF>(Sym.getSection());
722 unsigned Flags = Sec.getFlags();
723 if (Flags & ELF::SHF_MERGE) {
724 if (C != 0)
725 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000726
727 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
728 // only handle section relocations to mergeable sections if using RELA.
729 if (!hasRelocationAddend())
730 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000731 }
732
Rafael Espindola5904e122014-03-29 06:26:49 +0000733 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000734 // are just an offset (@tpoff), require a symbol in gold versions before
735 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
736 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000737 if (Flags & ELF::SHF_TLS)
738 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000739
Rafael Espindola9ef84412014-04-11 19:18:01 +0000740 // If the symbol is a thumb function the final relocation must set the lowest
741 // bit. With a symbol that is done by just having the symbol have that bit
742 // set, so we would lose the bit if we relocated with the section.
743 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000744 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000745 return true;
746
Ulrich Weigand46797c62014-07-20 23:15:06 +0000747 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000748 return true;
749 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000750}
751
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000752static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
753 const MCSymbol &Sym = Ref.getSymbol();
754
755 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
756 return &Sym;
757
758 if (!Sym.isVariable())
759 return nullptr;
760
761 const MCExpr *Expr = Sym.getVariableValue();
762 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
763 if (!Inner)
764 return nullptr;
765
766 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
767 return &Inner->getSymbol();
768 return nullptr;
769}
770
Rafael Espindolac9e70682015-03-24 23:48:44 +0000771static bool isWeak(const MCSymbolData &D) {
772 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
773}
774
Rafael Espindola26585542015-01-19 21:11:14 +0000775void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000776 const MCAsmLayout &Layout,
777 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000778 const MCFixup &Fixup, MCValue Target,
779 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000780 const MCSectionData *FixupSection = Fragment->getParent();
781 uint64_t C = Target.getConstant();
782 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000783
Rafael Espindola5904e122014-03-29 06:26:49 +0000784 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
785 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
786 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000787
Rafael Espindola5904e122014-03-29 06:26:49 +0000788 // Let A, B and C being the components of Target and R be the location of
789 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
790 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000791
Rafael Espindola5904e122014-03-29 06:26:49 +0000792 // In general, ELF has no relocations for -B. It can only represent (A + C)
793 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
794 // replace B to implement it: (A - R - K + C)
795 if (IsPCRel)
796 Asm.getContext().FatalError(
797 Fixup.getLoc(),
798 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000799
Rafael Espindola5904e122014-03-29 06:26:49 +0000800 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000801
Rafael Espindola5904e122014-03-29 06:26:49 +0000802 if (SymB.isUndefined())
803 Asm.getContext().FatalError(
804 Fixup.getLoc(),
805 Twine("symbol '") + SymB.getName() +
806 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000807
Rafael Espindola5904e122014-03-29 06:26:49 +0000808 assert(!SymB.isAbsolute() && "Should have been folded");
809 const MCSection &SecB = SymB.getSection();
810 if (&SecB != &FixupSection->getSection())
811 Asm.getContext().FatalError(
812 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000813
Rafael Espindola5904e122014-03-29 06:26:49 +0000814 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000815 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000816 Asm.getContext().FatalError(
817 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
818
Rafael Espindola5904e122014-03-29 06:26:49 +0000819 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
820 uint64_t K = SymBOffset - FixupOffset;
821 IsPCRel = true;
822 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000823 }
824
Rafael Espindola5904e122014-03-29 06:26:49 +0000825 // We either rejected the fixup or folded B into C at this point.
826 const MCSymbolRefExpr *RefA = Target.getSymA();
827 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
828 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
829
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000830 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000831 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000832 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
833 C += Layout.getSymbolOffset(SymAD);
834
835 uint64_t Addend = 0;
836 if (hasRelocationAddend()) {
837 Addend = C;
838 C = 0;
839 }
840
841 FixedValue = C;
842
843 // FIXME: What is this!?!?
844 MCSymbolRefExpr::VariantKind Modifier =
845 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000846 if (RelocNeedsGOT(Modifier))
847 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000848
Rafael Espindola5904e122014-03-29 06:26:49 +0000849 if (!RelocateWithSymbol) {
850 const MCSection *SecA =
851 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000852 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
853 MCSymbol *SectionSymbol =
854 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
855 : nullptr;
856 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000857 Relocations[FixupSection].push_back(Rec);
858 return;
859 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000860
Rafael Espindola5904e122014-03-29 06:26:49 +0000861 if (SymA) {
862 if (const MCSymbol *R = Renames.lookup(SymA))
863 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000864
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000865 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
866 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000867 else
868 UsedInReloc.insert(SymA);
869 }
870 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
871 Relocations[FixupSection].push_back(Rec);
872 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000873}
874
875
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000876uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000877ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
878 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000879 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000880 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000881}
882
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000883bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
884 const MCSymbolData &Data, bool Used,
885 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000886 const MCSymbol &Symbol = Data.getSymbol();
887 if (Symbol.isVariable()) {
888 const MCExpr *Expr = Symbol.getVariableValue();
889 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
890 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
891 return false;
892 }
893 }
Rafael Espindola16145972010-11-01 14:28:48 +0000894
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000895 if (Used)
896 return true;
897
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000898 if (Renamed)
899 return false;
900
Rafael Espindola45834a02010-10-29 23:09:31 +0000901 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
902 return true;
903
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000904 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000905 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000906 if (Base && Base->isUndefined())
907 return false;
908 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000909
Jan Sjödin30a52de2011-02-28 21:45:04 +0000910 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000911 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000912 return false;
913
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000914 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000915 return false;
916
917 return true;
918}
919
Rafael Espindola39f50422014-04-28 14:24:44 +0000920bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000921 if (Data.isExternal())
922 return false;
923
924 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000925 if (Symbol.isDefined())
926 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000927
Rafael Espindola39f50422014-04-28 14:24:44 +0000928 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000929 return false;
930
931 return true;
932}
933
Rafael Espindolaead85492015-02-17 20:31:13 +0000934void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000935 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000936 unsigned Index = 1;
937 for (MCAssembler::iterator it = Asm.begin(),
938 ie = Asm.end(); it != ie; ++it) {
939 const MCSectionELF &Section =
940 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000941 if (Section.getType() != ELF::SHT_GROUP)
942 continue;
943 SectionIndexMap[&Section] = Index++;
944 }
945
Rafael Espindola607da972015-04-17 08:11:38 +0000946 std::vector<const MCSectionELF *> RelSections;
947
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000948 for (MCAssembler::iterator it = Asm.begin(),
949 ie = Asm.end(); it != ie; ++it) {
Rafael Espindolaead85492015-02-17 20:31:13 +0000950 const MCSectionData &SD = *it;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000951 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000952 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000953 if (Section.getType() == ELF::SHT_GROUP ||
954 Section.getType() == ELF::SHT_REL ||
955 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000956 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000957 SectionIndexMap[&Section] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000958 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
959 const MCSectionELF *RelSection =
960 static_cast<const MCSectionELF *>(&RelSD->getSection());
Rafael Espindola607da972015-04-17 08:11:38 +0000961 RelSections.push_back(RelSection);
Rafael Espindolaead85492015-02-17 20:31:13 +0000962 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000963 }
Rafael Espindola607da972015-04-17 08:11:38 +0000964
965 // Put relocation sections close together. The linker reads them
966 // first, so this improves cache locality.
967 for (const MCSectionELF * Sec: RelSections)
968 SectionIndexMap[Sec] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +0000969}
970
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000971void ELFObjectWriter::computeSymbolTable(
972 MCAssembler &Asm, const MCAsmLayout &Layout,
973 const SectionIndexMapTy &SectionIndexMap,
974 const RevGroupMapTy &RevGroupMap) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000975 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000976 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000977 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000978 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000979 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
980 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
981 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000982 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000983 }
984
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000985 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000986 for (MCSymbolData &SD : Asm.symbols()) {
987 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000988
Rafael Espindola16145972010-11-01 14:28:48 +0000989 bool Used = UsedInReloc.count(&Symbol);
990 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000991 bool isSignature = RevGroupMap.count(&Symbol);
992
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000993 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000994 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000995 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +0000996 continue;
997
Matt Fleming6c1ad482010-08-16 18:57:57 +0000998 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +0000999 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001000 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001001
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001002 // Undefined symbols are global, but this is the first place we
1003 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001004 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001005 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001006 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001007 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001008 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001009 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001010 }
1011
Rafael Espindola022bb762014-03-24 03:43:21 +00001012 if (!BaseSymbol) {
1013 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001014 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001015 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001016 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001017 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001018 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001019 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001020 else
1021 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001022 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001023 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001024 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001025 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001026 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001027 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001028 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001029 }
1030
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001031 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1032 // in defined ones.
1033 //
1034 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001035 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001036 // trivial.
1037 //
1038 // We thus have to be careful to not perform the symbol version replacement
1039 // blindly:
1040 //
1041 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1042 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1043 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1044 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1045 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1046 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1047 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1048 // "__imp_?" or "__imp_@?".
1049 //
1050 // It would have been interesting to perform the MS mangling prefix check
1051 // only when the target triple is of the form *-pc-windows-elf. But, it
1052 // seems that this information is not easily accessible from the
1053 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001054 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001055 if (!Name.startswith("?") && !Name.startswith("@?") &&
1056 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1057 // This symbol isn't following the MSVC C++ name mangling convention. We
1058 // can thus safely interpret the @@@ in symbol names as specifying symbol
1059 // versioning.
1060 SmallString<32> Buf;
1061 size_t Pos = Name.find("@@@");
1062 if (Pos != StringRef::npos) {
1063 Buf += Name.substr(0, Pos);
1064 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1065 Buf += Name.substr(Pos + Skip);
1066 Name = Buf;
1067 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001068 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001069
1070 // Sections have their own string table
1071 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1072 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001073
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001074 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1075 UndefinedSymbolData.push_back(MSD);
1076 else if (Local)
1077 LocalSymbolData.push_back(MSD);
1078 else
1079 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001080 }
1081
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001082 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1083 StrTabBuilder.add(*i);
1084
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001085 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001086
1087 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1088 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1089
Rafael Espindolab6613022014-10-17 01:48:58 +00001090 for (ELFSymbolData &MSD : LocalSymbolData)
1091 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1092 ? 0
1093 : StrTabBuilder.getOffset(MSD.Name);
1094 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001095 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1096 for (ELFSymbolData& MSD : UndefinedSymbolData)
1097 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1098
Matt Fleming6c1ad482010-08-16 18:57:57 +00001099 // Symbols are required to be in lexicographic order.
1100 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1101 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1102 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1103
1104 // Set the symbol indices. Local symbols must come before all other
1105 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001106 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001107 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1108 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001109
Matt Fleming6c1ad482010-08-16 18:57:57 +00001110 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1111 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1112 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1113 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1114}
1115
Rafael Espindolaead85492015-02-17 20:31:13 +00001116MCSectionData *
1117ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
1118 const MCSectionData &SD) {
1119 if (Relocations[&SD].empty())
1120 return nullptr;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001121
Rafael Espindolaead85492015-02-17 20:31:13 +00001122 MCContext &Ctx = Asm.getContext();
1123 const MCSectionELF &Section =
1124 static_cast<const MCSectionELF &>(SD.getSection());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001125
Rafael Espindolaead85492015-02-17 20:31:13 +00001126 const StringRef SectionName = Section.getSectionName();
1127 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1128 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001129
Rafael Espindolaead85492015-02-17 20:31:13 +00001130 unsigned EntrySize;
1131 if (hasRelocationAddend())
1132 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1133 else
1134 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001135
Rafael Espindolaead85492015-02-17 20:31:13 +00001136 unsigned Flags = 0;
Rafael Espindolac9d06922015-03-30 13:39:16 +00001137 if (Section.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001138 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001139
Rafael Espindolac9d06922015-03-30 13:39:16 +00001140 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001141 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001142 Flags, EntrySize, Section.getGroup(), &Section);
Rafael Espindolaead85492015-02-17 20:31:13 +00001143 return &Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001144}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001145
David Blaikiee06e8012014-04-11 22:11:50 +00001146static SmallVector<char, 128>
1147getUncompressedData(MCAsmLayout &Layout,
1148 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001149 SmallVector<char, 128> UncompressedData;
1150 for (const MCFragment &F : Fragments) {
1151 const SmallVectorImpl<char> *Contents;
1152 switch (F.getKind()) {
1153 case MCFragment::FT_Data:
1154 Contents = &cast<MCDataFragment>(F).getContents();
1155 break;
1156 case MCFragment::FT_Dwarf:
1157 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1158 break;
1159 case MCFragment::FT_DwarfFrame:
1160 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1161 break;
1162 default:
1163 llvm_unreachable(
1164 "Not expecting any other fragment types in a debug_* section");
1165 }
1166 UncompressedData.append(Contents->begin(), Contents->end());
1167 }
1168 return UncompressedData;
1169}
1170
1171// Include the debug info compression header:
1172// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1173// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001174static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001175prependCompressionHeader(uint64_t Size,
1176 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001177 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001178 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1179 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001180 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001181 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001182 CompressedContents.insert(CompressedContents.begin(),
1183 Magic.size() + sizeof(Size), 0);
1184 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1185 std::copy(reinterpret_cast<char *>(&Size),
1186 reinterpret_cast<char *>(&Size + 1),
1187 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001188 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001189}
1190
1191// Return a single fragment containing the compressed contents of the whole
1192// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001193static std::unique_ptr<MCDataFragment>
1194getCompressedFragment(MCAsmLayout &Layout,
1195 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001196 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1197
1198 // Gather the uncompressed data from all the fragments, recording the
1199 // alignment fragment, if seen, and any fixups.
1200 SmallVector<char, 128> UncompressedData =
1201 getUncompressedData(Layout, Fragments);
1202
1203 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1204
1205 zlib::Status Success = zlib::compress(
1206 StringRef(UncompressedData.data(), UncompressedData.size()),
1207 CompressedContents);
1208 if (Success != zlib::StatusOK)
1209 return nullptr;
1210
David Blaikie76d3a3c2014-04-18 21:52:26 +00001211 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1212 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001213
1214 return CompressedFragment;
1215}
1216
David Blaikie39fa6a22014-04-25 00:48:01 +00001217typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1218DefiningSymbolMap;
1219
1220static void UpdateSymbols(const MCAsmLayout &Layout,
1221 const std::vector<MCSymbolData *> &Symbols,
1222 MCFragment &NewFragment) {
1223 for (MCSymbolData *Sym : Symbols) {
1224 Sym->setOffset(Sym->getOffset() +
1225 Layout.getFragmentOffset(Sym->getFragment()));
1226 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001227 }
1228}
1229
David Blaikie8019bf82014-04-10 21:53:53 +00001230static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001231 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001232 const MCSectionELF &Section,
1233 MCSectionData &SD) {
1234 StringRef SectionName = Section.getSectionName();
1235 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1236
1237 std::unique_ptr<MCDataFragment> CompressedFragment =
1238 getCompressedFragment(Layout, Fragments);
1239
1240 // Leave the section as-is if the fragments could not be compressed.
1241 if (!CompressedFragment)
1242 return;
1243
David Blaikiec029ab42014-04-18 21:24:12 +00001244 // Update the fragment+offsets of any symbols referring to fragments in this
1245 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001246 auto I = DefiningSymbols.find(&SD);
1247 if (I != DefiningSymbols.end())
1248 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001249
David Blaikie8019bf82014-04-10 21:53:53 +00001250 // Invalidate the layout for the whole section since it will have new and
1251 // different fragments now.
1252 Layout.invalidateFragmentsFrom(&Fragments.front());
1253 Fragments.clear();
1254
1255 // Complete the initialization of the new fragment
1256 CompressedFragment->setParent(&SD);
1257 CompressedFragment->setLayoutOrder(0);
1258 Fragments.push_back(CompressedFragment.release());
1259
1260 // Rename from .debug_* to .zdebug_*
1261 Asm.getContext().renameELFSection(&Section,
1262 (".z" + SectionName.drop_front(1)).str());
1263}
1264
1265void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1266 MCAsmLayout &Layout) {
1267 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1268 return;
1269
David Blaikie39fa6a22014-04-25 00:48:01 +00001270 DefiningSymbolMap DefiningSymbols;
1271
1272 for (MCSymbolData &SD : Asm.symbols())
1273 if (MCFragment *F = SD.getFragment())
1274 DefiningSymbols[F->getParent()].push_back(&SD);
1275
David Blaikie8019bf82014-04-10 21:53:53 +00001276 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001277 const MCSectionELF &Section =
1278 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001279 StringRef SectionName = Section.getSectionName();
1280
1281 // Compressing debug_frame requires handling alignment fragments which is
1282 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1283 // for writing to arbitrary buffers) for little benefit.
1284 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1285 continue;
1286
David Blaikie39fa6a22014-04-25 00:48:01 +00001287 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001288 }
1289}
1290
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001291void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout) {
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001292 for (MCAssembler::iterator it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
1293 MCSectionData &RelSD = *it;
1294 const MCSectionELF &RelSection =
1295 static_cast<const MCSectionELF &>(RelSD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001296
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001297 unsigned Type = RelSection.getType();
1298 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001299 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001300
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001301 const MCSectionELF *Section = RelSection.getAssociatedSection();
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001302 MCSectionData &SD = Asm.getOrCreateSectionData(*Section);
1303 RelSD.setAlignment(is64Bit() ? 8 : 4);
1304
1305 MCDataFragment *F = new MCDataFragment(&RelSD);
1306 WriteRelocationsFragment(Asm, F, &SD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001307 }
1308}
1309
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001310void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1311 uint64_t Flags, uint64_t Address,
1312 uint64_t Offset, uint64_t Size,
1313 uint32_t Link, uint32_t Info,
1314 uint64_t Alignment,
1315 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001316 Write32(Name); // sh_name: index into string table
1317 Write32(Type); // sh_type
1318 WriteWord(Flags); // sh_flags
1319 WriteWord(Address); // sh_addr
1320 WriteWord(Offset); // sh_offset
1321 WriteWord(Size); // sh_size
1322 Write32(Link); // sh_link
1323 Write32(Info); // sh_info
1324 WriteWord(Alignment); // sh_addralign
1325 WriteWord(EntrySize); // sh_entsize
1326}
1327
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001328void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1329 MCDataFragment *F,
1330 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001331 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001332
Petar Jovanovic0380d0b2015-04-14 13:23:34 +00001333 // Sort the relocation entries. Most targets just sort by Offset, but some
1334 // (e.g., MIPS) have additional constraints.
1335 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001336
1337 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001338 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001339 unsigned Index =
1340 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001341
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001342 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001343 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001344 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001345 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001346
Rafael Espindola5904e122014-03-29 06:26:49 +00001347 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1348 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1349 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1350 write(*F, TargetObjectWriter->getRType(Entry.Type));
1351 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001352 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001353 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001354 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001355 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001356 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001357 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001358 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001359 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001360
Rafael Espindolabce26a12010-10-05 15:11:03 +00001361 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001362 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001363 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001364
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001365 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001366 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001367 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001368 }
1369}
1370
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001371void ELFObjectWriter::CreateMetadataSections(
1372 MCAssembler &Asm, MCAsmLayout &Layout, SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001373 MCContext &Ctx = Asm.getContext();
1374 MCDataFragment *F;
1375
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001376 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001377
Rafael Espindola0e527b72010-09-22 19:04:41 +00001378 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001379 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001380 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001381 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1382 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001383 ShstrtabIndex = SectionIndexMap.size() + 1;
1384 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001385
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001386 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001387 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001388 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001389 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001390 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001391 SymbolTableIndex = SectionIndexMap.size() + 1;
1392 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001393
Rafael Espindola1557fd62011-03-20 18:44:20 +00001394 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001395 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001396 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1397 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001398 StringTableIndex = SectionIndexMap.size() + 1;
1399 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001400
1401 // Symbol table
1402 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001403 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001404
Matt Fleming6c1ad482010-08-16 18:57:57 +00001405 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001406 F->getContents().append(StrTabBuilder.data().begin(),
1407 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001408
Matt Fleming6c1ad482010-08-16 18:57:57 +00001409 F = new MCDataFragment(&ShstrtabSD);
1410
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001411 // Section header string table.
1412 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001413 const MCSectionELF &Section =
1414 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001415 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001416 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001417 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001418 F->getContents().append(ShStrTabBuilder.data().begin(),
1419 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001420}
1421
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001422void ELFObjectWriter::createIndexedSections(
1423 MCAssembler &Asm, MCAsmLayout &Layout, GroupMapTy &GroupMap,
1424 RevGroupMapTy &RevGroupMap, SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001425 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001426
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001427 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001428 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1429 it != ie; ++it) {
1430 const MCSectionELF &Section =
1431 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001432 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001433 continue;
1434
1435 const MCSymbol *SignatureSymbol = Section.getGroup();
1436 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001437 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001438 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001439 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001440 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1441 Data.setAlignment(4);
1442 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001443 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001444 }
1445 GroupMap[Group] = SignatureSymbol;
1446 }
1447
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001448 computeIndexMap(Asm, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001449
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001450 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001451 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001452 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001453 const MCSectionELF &Section =
1454 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001455 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001456 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001457 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001458 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1459 // FIXME: we could use the previous fragment
1460 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001461 uint32_t Index = SectionIndexMap.lookup(&Section);
1462 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001463 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001464}
1465
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001466void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001467 const SectionIndexMapTy &SectionIndexMap,
1468 uint32_t GroupSymbolIndex,
1469 uint64_t Offset, uint64_t Size,
1470 uint64_t Alignment,
1471 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001472 uint64_t sh_link = 0;
1473 uint64_t sh_info = 0;
1474
1475 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001476 default:
1477 // Nothing to do.
1478 break;
1479
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001480 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001481 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001482 break;
1483
1484 case ELF::SHT_REL:
1485 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001486 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001487 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001488 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001489 sh_info = SectionIndexMap.lookup(InfoSection);
1490 break;
1491 }
1492
1493 case ELF::SHT_SYMTAB:
1494 case ELF::SHT_DYNSYM:
1495 sh_link = StringTableIndex;
1496 sh_info = LastLocalSymbolIndex;
1497 break;
1498
1499 case ELF::SHT_SYMTAB_SHNDX:
1500 sh_link = SymbolTableIndex;
1501 break;
1502
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001503 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001504 sh_link = SymbolTableIndex;
1505 sh_info = GroupSymbolIndex;
1506 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001507 }
1508
Logan Chien4b724422013-02-05 14:18:59 +00001509 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001510 Section.getType() == ELF::SHT_ARM_EXIDX)
1511 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001512
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001513 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1514 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001515 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1516 Alignment, Section.getEntrySize());
1517}
1518
Jan Sjödin30a52de2011-02-28 21:45:04 +00001519bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001520 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001521 !SD.getSection().isVirtualSection();
1522}
1523
Jan Sjödin30a52de2011-02-28 21:45:04 +00001524uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001525 uint64_t Ret = 0;
1526 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1527 ++i) {
1528 const MCFragment &F = *i;
1529 assert(F.getKind() == MCFragment::FT_Data);
1530 Ret += cast<MCDataFragment>(F).getContents().size();
1531 }
1532 return Ret;
1533}
1534
Jan Sjödin30a52de2011-02-28 21:45:04 +00001535uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1536 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001537 if (IsELFMetaDataSection(SD))
1538 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001539 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001540}
1541
Rafael Espindola642a2212015-04-14 22:54:16 +00001542void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001543 const MCAsmLayout &Layout,
Rafael Espindola642a2212015-04-14 22:54:16 +00001544 const MCSectionData &SD) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001545 if (IsELFMetaDataSection(SD)) {
1546 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1547 ++i) {
1548 const MCFragment &F = *i;
1549 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001550 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001551 }
1552 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001553 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001554 }
1555}
1556
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001557void ELFObjectWriter::writeSectionHeader(
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001558 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
1559 const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001560 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001561 const SectionOffsetMapTy &SectionOffsetMap) {
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001562 const unsigned NumSections = Asm.size();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001563
Matt Fleming6c1ad482010-08-16 18:57:57 +00001564 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001565 uint64_t FirstSectionSize =
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001566 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001567 uint32_t FirstSectionLink =
1568 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1569 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001570
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001571 for (unsigned i = 0; i < NumSections; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001572 const MCSectionELF &Section = *Sections[i];
1573 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1574 uint32_t GroupSymbolIndex;
1575 if (Section.getType() != ELF::SHT_GROUP)
1576 GroupSymbolIndex = 0;
1577 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001578 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1579 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001580
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001581 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001582
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001583 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1584 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1585 Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001586 }
1587}
1588
Rafael Espindola1557fd62011-03-20 18:44:20 +00001589void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1590 const MCAsmLayout &Layout) {
1591 GroupMapTy GroupMap;
1592 RevGroupMapTy RevGroupMap;
1593 SectionIndexMapTy SectionIndexMap;
1594
David Blaikiee06e8012014-04-11 22:11:50 +00001595 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001596 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1597 RevGroupMap, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001598
Rafael Espindola1557fd62011-03-20 18:44:20 +00001599 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001600 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001601
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001602 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola1557fd62011-03-20 18:44:20 +00001603
1604 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1605 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001606 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001607
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001608 unsigned NumSections = Asm.size();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001609 std::vector<const MCSectionELF*> Sections;
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001610 Sections.resize(NumSections);
1611
1612 for (auto &Pair : SectionIndexMap)
1613 Sections[Pair.second - 1] = Pair.first;
1614
Rafael Espindola1557fd62011-03-20 18:44:20 +00001615 SectionOffsetMapTy SectionOffsetMap;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001616
Rafael Espindola1557fd62011-03-20 18:44:20 +00001617 // Write out the ELF header ...
Rafael Espindola642a2212015-04-14 22:54:16 +00001618 WriteHeader(Asm, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001619
Rafael Espindola7230f802015-04-08 11:41:24 +00001620 // ... then the sections ...
Rafael Espindola642a2212015-04-14 22:54:16 +00001621 for (unsigned i = 0; i < NumSections; ++i) {
1622 const MCSectionELF &Section = *Sections[i];
1623 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1624 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1625 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001626
Rafael Espindola642a2212015-04-14 22:54:16 +00001627 // Remember the offset into the file for this section.
1628 SectionOffsetMap[&Section] = OS.tell();
1629
1630 writeDataSectionData(Asm, Layout, SD);
1631 }
1632
1633 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001634 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001635 WriteZeros(Padding);
1636
Rafael Espindola642a2212015-04-14 22:54:16 +00001637 const unsigned SectionHeaderOffset = OS.tell();
1638
Rafael Espindola1557fd62011-03-20 18:44:20 +00001639 // ... then the section header table ...
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001640 writeSectionHeader(Sections, Asm, GroupMap, Layout, SectionIndexMap,
1641 SectionOffsetMap);
Rafael Espindola642a2212015-04-14 22:54:16 +00001642
1643 if (is64Bit()) {
1644 uint64_t Val = SectionHeaderOffset;
1645 if (sys::IsLittleEndianHost != IsLittleEndian)
1646 sys::swapByteOrder(Val);
1647 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1648 offsetof(ELF::Elf64_Ehdr, e_shoff));
1649 } else {
1650 uint32_t Val = SectionHeaderOffset;
1651 if (sys::IsLittleEndianHost != IsLittleEndian)
1652 sys::swapByteOrder(Val);
1653 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1654 offsetof(ELF::Elf32_Ehdr, e_shoff));
1655 }
Rafael Espindola1557fd62011-03-20 18:44:20 +00001656}
1657
Rafael Espindola94a88d72015-04-06 15:27:57 +00001658bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1659 const MCAssembler &Asm, const MCSymbolData &DataA,
1660 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1661 bool IsPCRel) const {
1662 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
Eli Friedmand92d17b2011-03-03 07:24:36 +00001663 return false;
1664 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola94a88d72015-04-06 15:27:57 +00001665 Asm, DataA, DataB, FB, InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001666}
1667
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001668bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1669 return ::isWeak(SD);
1670}
1671
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001672MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
Rafael Espindola5560a4c2015-04-14 22:14:34 +00001673 raw_pwrite_stream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001674 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001675 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001676}