blob: b2a83993f90284b088cdd9656f1a9796625f296c [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);
95 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
96 const MCSectionData &SD);
97 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
98 const MCSectionData &SD);
99
100 void WriteDataSectionData(MCAssembler &Asm,
101 const MCAsmLayout &Layout,
102 const MCSectionELF &Section);
103
Rafael Espindola6cd21802015-04-07 22:35:40 +0000104 /// Helper struct for containing some precomputed information on symbols.
Rafael Espindola29abd972011-12-22 03:38:00 +0000105 struct ELFSymbolData {
106 MCSymbolData *SymbolData;
107 uint64_t StringIndex;
108 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000109 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000110
111 // Support lexicographic sorting.
112 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolab6613022014-10-17 01:48:58 +0000113 unsigned LHSType = MCELF::GetType(*SymbolData);
114 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
115 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
116 return false;
117 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
118 return true;
119 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
120 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000121 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000122 }
123 };
124
Rafael Espindola29abd972011-12-22 03:38:00 +0000125 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000126 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000127
128 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
129 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
130 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
131
Rafael Espindola5904e122014-03-29 06:26:49 +0000132 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
133 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000134 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000135
136 /// @}
137 /// @name Symbol Table Data
138 /// @{
139
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000140 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000141 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000142 std::vector<ELFSymbolData> LocalSymbolData;
143 std::vector<ELFSymbolData> ExternalSymbolData;
144 std::vector<ELFSymbolData> UndefinedSymbolData;
145
146 /// @}
147
148 bool NeedsGOT;
149
Rafael Espindola29abd972011-12-22 03:38:00 +0000150 // This holds the symbol table index of the last local symbol.
151 unsigned LastLocalSymbolIndex;
152 // This holds the .strtab section index.
153 unsigned StringTableIndex;
154 // This holds the .symtab section index.
155 unsigned SymbolTableIndex;
156
157 unsigned ShstrtabIndex;
158
159
Rafael Espindola29abd972011-12-22 03:38:00 +0000160 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000161 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
162 bool hasRelocationAddend() const {
163 return TargetObjectWriter->hasRelocationAddend();
164 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000165 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000166 bool IsPCRel) const {
167 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000168 }
169
Rafael Espindola29abd972011-12-22 03:38:00 +0000170 public:
David Blaikie9f380a32015-03-16 18:06:57 +0000171 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &OS,
Rafael Espindola0ce09712014-03-25 22:43:53 +0000172 bool IsLittleEndian)
David Blaikie9f380a32015-03-16 18:06:57 +0000173 : MCObjectWriter(OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000174 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000175
Yaron Keren7773a722015-03-23 18:35:01 +0000176 void reset() override {
177 UsedInReloc.clear();
178 WeakrefUsedInReloc.clear();
179 Renames.clear();
180 Relocations.clear();
181 ShStrTabBuilder.clear();
182 StrTabBuilder.clear();
183 FileSymbolData.clear();
184 LocalSymbolData.clear();
185 ExternalSymbolData.clear();
186 UndefinedSymbolData.clear();
187 MCObjectWriter::reset();
188 }
189
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000190 ~ELFObjectWriter() override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000191
192 void WriteWord(uint64_t W) {
193 if (is64Bit())
194 Write64(W);
195 else
196 Write32(W);
197 }
198
Rafael Espindola0ce09712014-03-25 22:43:53 +0000199 template <typename T> void write(MCDataFragment &F, T Value) {
200 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000201 }
202
Jack Carter1bd90ff2013-01-30 02:09:52 +0000203 void WriteHeader(const MCAssembler &Asm,
Rafael Espindola01f4c6c2015-04-07 21:51:41 +0000204 uint64_t SectionHeaderOffset,
Rafael Espindola29abd972011-12-22 03:38:00 +0000205 unsigned NumberOfSections);
206
Rafael Espindola10be0832014-03-25 23:44:25 +0000207 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000208 const MCAsmLayout &Layout);
209
Rafael Espindola10be0832014-03-25 23:44:25 +0000210 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000211 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000212 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000213
Rafael Espindolab60c8292014-04-29 12:46:50 +0000214 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
215 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000216 const MCSymbolData *SD, uint64_t C,
217 unsigned Type) const;
218
Rafael Espindola26585542015-01-19 21:11:14 +0000219 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000220 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000221 MCValue Target, bool &IsPCRel,
222 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000223
224 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
225 const MCSymbol *S);
226
227 // Map from a group section to the signature symbol
228 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
229 // Map from a signature symbol to the group section
230 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
Rafael Espindola29abd972011-12-22 03:38:00 +0000231 // Map from a section to its offset
232 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
233
Rafael Espindola022bb762014-03-24 03:43:21 +0000234 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000235 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000236 /// \param Asm - The assembler.
237 /// \param SectionIndexMap - Maps a section to its index.
238 /// \param RevGroupMap - Maps a signature symbol to the group section.
Rafael Espindola022bb762014-03-24 03:43:21 +0000239 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000240 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000241 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000242
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000243 void computeIndexMap(MCAssembler &Asm, SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000244
Rafael Espindolaead85492015-02-17 20:31:13 +0000245 MCSectionData *createRelocationSection(MCAssembler &Asm,
246 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +0000247
David Blaikie8019bf82014-04-10 21:53:53 +0000248 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
249
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000250 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout);
Rafael Espindola29abd972011-12-22 03:38:00 +0000251
252 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolaef6baea2015-02-11 23:11:18 +0000253 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000254
255 // Create the sections that show up in the symbol table. Currently
256 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaead85492015-02-17 20:31:13 +0000257 void createIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000258 GroupMapTy &GroupMap, RevGroupMapTy &RevGroupMap,
259 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000260
Craig Topper34a61bc2014-03-08 07:02:02 +0000261 void ExecutePostLayoutBinding(MCAssembler &Asm,
262 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000263
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000264 void writeSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000265 const MCAsmLayout &Layout,
266 const SectionIndexMapTy &SectionIndexMap,
267 const SectionOffsetMapTy &SectionOffsetMap);
268
269 void ComputeSectionOrder(MCAssembler &Asm,
270 std::vector<const MCSectionELF*> &Sections);
271
272 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
273 uint64_t Address, uint64_t Offset,
274 uint64_t Size, uint32_t Link, uint32_t Info,
275 uint64_t Alignment, uint64_t EntrySize);
276
277 void WriteRelocationsFragment(const MCAssembler &Asm,
278 MCDataFragment *F,
279 const MCSectionData *SD);
280
Craig Topper34a61bc2014-03-08 07:02:02 +0000281 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000282 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
283 const MCSymbolData &DataA,
Rafael Espindola94a88d72015-04-06 15:27:57 +0000284 const MCSymbolData *DataB,
Rafael Espindola29abd972011-12-22 03:38:00 +0000285 const MCFragment &FB,
286 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000287 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000288
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000289 bool isWeak(const MCSymbolData &SD) const override;
290
Craig Topper34a61bc2014-03-08 07:02:02 +0000291 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000292 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000293 const SectionIndexMapTy &SectionIndexMap,
294 uint32_t GroupSymbolIndex,
295 uint64_t Offset, uint64_t Size, uint64_t Alignment,
296 const MCSectionELF &Section);
297 };
298}
299
Rafael Espindola0ce09712014-03-25 22:43:53 +0000300FragmentWriter::FragmentWriter(bool IsLittleEndian)
301 : IsLittleEndian(IsLittleEndian) {}
302
303template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
304 if (IsLittleEndian)
305 Val = support::endian::byte_swap<T, support::little>(Val);
306 else
307 Val = support::endian::byte_swap<T, support::big>(Val);
308 const char *Start = (const char *)&Val;
309 F.getContents().append(Start, Start + sizeof(T));
310}
311
Rafael Espindola10be0832014-03-25 23:44:25 +0000312void SymbolTableWriter::createSymtabShndx() {
313 if (ShndxF)
314 return;
315
316 MCContext &Ctx = Asm.getContext();
317 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000318 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000319 MCSectionData *SymtabShndxSD =
320 &Asm.getOrCreateSectionData(*SymtabShndxSection);
321 SymtabShndxSD->setAlignment(4);
322 ShndxF = new MCDataFragment(SymtabShndxSD);
323 unsigned Index = SectionIndexMap.size() + 1;
324 SectionIndexMap[SymtabShndxSection] = Index;
325
326 for (unsigned I = 0; I < NumWritten; ++I)
327 write(*ShndxF, uint32_t(0));
328}
329
330template <typename T>
331void SymbolTableWriter::write(MCDataFragment &F, T Value) {
332 FWriter.write(F, Value);
333}
334
335SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
336 bool Is64Bit,
337 SectionIndexMapTy &SectionIndexMap,
338 MCDataFragment *SymtabF)
339 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
340 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
341 NumWritten(0) {}
342
343void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
344 uint64_t size, uint8_t other,
345 uint32_t shndx, bool Reserved) {
346 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
347
348 if (LargeIndex)
349 createSymtabShndx();
350
351 if (ShndxF) {
352 if (LargeIndex)
353 write(*ShndxF, shndx);
354 else
355 write(*ShndxF, uint32_t(0));
356 }
357
358 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
359
Rafael Espindola10be0832014-03-25 23:44:25 +0000360 if (Is64Bit) {
361 write(*SymtabF, name); // st_name
362 write(*SymtabF, info); // st_info
363 write(*SymtabF, other); // st_other
364 write(*SymtabF, Index); // st_shndx
365 write(*SymtabF, value); // st_value
366 write(*SymtabF, size); // st_size
367 } else {
368 write(*SymtabF, name); // st_name
369 write(*SymtabF, uint32_t(value)); // st_value
370 write(*SymtabF, uint32_t(size)); // st_size
371 write(*SymtabF, info); // st_info
372 write(*SymtabF, other); // st_other
373 write(*SymtabF, Index); // st_shndx
374 }
375
376 ++NumWritten;
377}
378
Jan Sjödin30a52de2011-02-28 21:45:04 +0000379bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
380 const MCFixupKindInfo &FKI =
381 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
382
383 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
384}
385
386bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
387 switch (Variant) {
388 default:
389 return false;
390 case MCSymbolRefExpr::VK_GOT:
391 case MCSymbolRefExpr::VK_PLT:
392 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000393 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000394 case MCSymbolRefExpr::VK_TPOFF:
395 case MCSymbolRefExpr::VK_TLSGD:
396 case MCSymbolRefExpr::VK_GOTTPOFF:
397 case MCSymbolRefExpr::VK_INDNTPOFF:
398 case MCSymbolRefExpr::VK_NTPOFF:
399 case MCSymbolRefExpr::VK_GOTNTPOFF:
400 case MCSymbolRefExpr::VK_TLSLDM:
401 case MCSymbolRefExpr::VK_DTPOFF:
402 case MCSymbolRefExpr::VK_TLSLD:
403 return true;
404 }
405}
406
Jason W Kim96f4c012010-11-15 16:18:39 +0000407ELFObjectWriter::~ELFObjectWriter()
408{}
409
Matt Fleming6c1ad482010-08-16 18:57:57 +0000410// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000411void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
Rafael Espindola01f4c6c2015-04-07 21:51:41 +0000412 uint64_t SectionHeaderOffset,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000413 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000414 // ELF Header
415 // ----------
416 //
417 // Note
418 // ----
419 // emitWord method behaves differently for ELF32 and ELF64, writing
420 // 4 bytes in the former and 8 in the latter.
421
422 Write8(0x7f); // e_ident[EI_MAG0]
423 Write8('E'); // e_ident[EI_MAG1]
424 Write8('L'); // e_ident[EI_MAG2]
425 Write8('F'); // e_ident[EI_MAG3]
426
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000427 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000428
429 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000430 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000431
432 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000433 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000434 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000435 Write8(0); // e_ident[EI_ABIVERSION]
436
437 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
438
439 Write16(ELF::ET_REL); // e_type
440
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000441 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000442
443 Write32(ELF::EV_CURRENT); // e_version
444 WriteWord(0); // e_entry, no entry point in .o file
445 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola01f4c6c2015-04-07 21:51:41 +0000446 WriteWord(SectionHeaderOffset); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000447
Jason W Kim4761fba2011-02-04 21:41:11 +0000448 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000449 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000450
451 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000452 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000453
454 Write16(0); // e_phentsize = prog header entry size
455 Write16(0); // e_phnum = # prog header entries = 0
456
457 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000458 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000459
460 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000461 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000462 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000463 else
464 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000465
466 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000467 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000468 Write16(ELF::SHN_XINDEX);
469 else
470 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000471}
472
Rafael Espindolafee224f2014-04-30 21:51:13 +0000473uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000474 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000475 if (Data.isCommon() && Data.isExternal())
476 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000477
Rafael Espindolafee224f2014-04-30 21:51:13 +0000478 uint64_t Res;
479 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000480 return 0;
481
Rafael Espindolafee224f2014-04-30 21:51:13 +0000482 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000483 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000484
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000485 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000486}
487
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000488void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
489 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000490 // The presence of symbol versions causes undefined symbols and
491 // versions declared with @@@ to be renamed.
492
David Blaikie583a31c2014-04-18 18:24:25 +0000493 for (MCSymbolData &OriginalData : Asm.symbols()) {
494 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000495
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000496 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000497 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000498 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000499 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
500 if (!Ref)
501 continue;
502 const MCSymbol &Symbol = Ref->getSymbol();
503 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000504
Benjamin Kramer14807272010-10-27 19:53:52 +0000505 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000506 size_t Pos = AliasName.find('@');
507 if (Pos == StringRef::npos)
508 continue;
509
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000510 // Aliases defined with .symvar copy the binding from the symbol they alias.
511 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000512 OriginalData.setExternal(SD.isExternal());
513 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000514
Benjamin Kramer14807272010-10-27 19:53:52 +0000515 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000516 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
517 continue;
518
Rafael Espindola26496e62010-10-27 17:56:18 +0000519 // FIXME: produce a better error message.
520 if (Symbol.isUndefined() && Rest.startswith("@@") &&
521 !Rest.startswith("@@@"))
522 report_fatal_error("A @@ version cannot be undefined");
523
Benjamin Kramer14807272010-10-27 19:53:52 +0000524 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000525 }
526}
527
Roman Divacky5a1c5492014-01-07 20:17:03 +0000528static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
529 uint8_t Type = newType;
530
531 // Propagation rules:
532 // IFUNC > FUNC > OBJECT > NOTYPE
533 // TLS_OBJECT > OBJECT > NOTYPE
534 //
535 // dont let the new type degrade the old type
536 switch (origType) {
537 default:
538 break;
539 case ELF::STT_GNU_IFUNC:
540 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
541 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
542 Type = ELF::STT_GNU_IFUNC;
543 break;
544 case ELF::STT_FUNC:
545 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
546 Type == ELF::STT_TLS)
547 Type = ELF::STT_FUNC;
548 break;
549 case ELF::STT_OBJECT:
550 if (Type == ELF::STT_NOTYPE)
551 Type = ELF::STT_OBJECT;
552 break;
553 case ELF::STT_TLS:
554 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
555 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
556 Type = ELF::STT_TLS;
557 break;
558 }
559
560 return Type;
561}
562
Rafael Espindola10be0832014-03-25 23:44:25 +0000563void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000564 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000565 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000566 assert((!OrigData.getFragment() ||
567 (&OrigData.getFragment()->getParent()->getSection() ==
568 &OrigData.getSymbol().getSection())) &&
569 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000570 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000571
572 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
573 // SHN_COMMON.
574 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000575
Jack Carter2f8d9d92013-02-19 21:57:35 +0000576 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000577 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000578 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000579 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000580 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000581 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
582 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000583 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000584 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000585
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000586 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000587 // 2 bits
588 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000589 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000590 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000591
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000592 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000593 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000594
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000595 const MCExpr *ESize = OrigData.getSize();
596 if (!ESize && Base)
597 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000598
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000599 if (ESize) {
600 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000601 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000602 report_fatal_error("Size expression must be absolute.");
603 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000604 }
605
606 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000607 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
608 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000609}
610
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000611void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000612 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000613 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000614 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000615 // The string table must be emitted first because we need the index
616 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000617
618 // FIXME: Make sure the start of the symbol table is aligned.
619
Rafael Espindola10be0832014-03-25 23:44:25 +0000620 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
621
Matt Fleming6c1ad482010-08-16 18:57:57 +0000622 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000623 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000624
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000625 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000626 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
627 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000628 }
629
Matt Fleming6c1ad482010-08-16 18:57:57 +0000630 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000631 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
632
Matt Fleming6c1ad482010-08-16 18:57:57 +0000633 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
634 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000635 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000636 }
637
Matt Fleming6c1ad482010-08-16 18:57:57 +0000638 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
639 ELFSymbolData &MSD = ExternalSymbolData[i];
640 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000641 assert(((Data.getFlags() & ELF_STB_Global) ||
642 (Data.getFlags() & ELF_STB_Weak)) &&
643 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000644 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000645 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000646 LastLocalSymbolIndex++;
647 }
648
649 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
650 ELFSymbolData &MSD = UndefinedSymbolData[i];
651 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000652 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000653 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000654 LastLocalSymbolIndex++;
655 }
656}
657
Rafael Espindola5904e122014-03-29 06:26:49 +0000658// It is always valid to create a relocation with a symbol. It is preferable
659// to use a relocation with a section if that is possible. Using the section
660// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000661bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
662 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000663 const MCSymbolData *SD,
664 uint64_t C,
665 unsigned Type) const {
666 // A PCRel relocation to an absolute value has no symbol (or section). We
667 // represent that with a relocation to a null section.
668 if (!RefA)
669 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000670
Rafael Espindola5904e122014-03-29 06:26:49 +0000671 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
672 switch (Kind) {
673 default:
674 break;
675 // The .odp creation emits a relocation against the symbol ".TOC." which
676 // create a R_PPC64_TOC relocation. However the relocation symbol name
677 // in final object creation should be NULL, since the symbol does not
678 // really exist, it is just the reference to TOC base for the current
679 // object file. Since the symbol is undefined, returning false results
680 // in a relocation with a null section which is the desired result.
681 case MCSymbolRefExpr::VK_PPC_TOCBASE:
682 return false;
683
684 // These VariantKind cause the relocation to refer to something other than
685 // the symbol itself, like a linker generated table. Since the address of
686 // symbol is not relevant, we cannot replace the symbol with the
687 // section and patch the difference in the addend.
688 case MCSymbolRefExpr::VK_GOT:
689 case MCSymbolRefExpr::VK_PLT:
690 case MCSymbolRefExpr::VK_GOTPCREL:
691 case MCSymbolRefExpr::VK_Mips_GOT:
692 case MCSymbolRefExpr::VK_PPC_GOT_LO:
693 case MCSymbolRefExpr::VK_PPC_GOT_HI:
694 case MCSymbolRefExpr::VK_PPC_GOT_HA:
695 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000696 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000697
Rafael Espindola5904e122014-03-29 06:26:49 +0000698 // An undefined symbol is not in any section, so the relocation has to point
699 // to the symbol itself.
700 const MCSymbol &Sym = SD->getSymbol();
701 if (Sym.isUndefined())
702 return true;
703
704 unsigned Binding = MCELF::GetBinding(*SD);
705 switch(Binding) {
706 default:
707 llvm_unreachable("Invalid Binding");
708 case ELF::STB_LOCAL:
709 break;
710 case ELF::STB_WEAK:
711 // If the symbol is weak, it might be overridden by a symbol in another
712 // file. The relocation has to point to the symbol so that the linker
713 // can update it.
714 return true;
715 case ELF::STB_GLOBAL:
716 // Global ELF symbols can be preempted by the dynamic linker. The relocation
717 // has to point to the symbol for a reason analogous to the STB_WEAK case.
718 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000719 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000720
Rafael Espindola5904e122014-03-29 06:26:49 +0000721 // If a relocation points to a mergeable section, we have to be careful.
722 // If the offset is zero, a relocation with the section will encode the
723 // same information. With a non-zero offset, the situation is different.
724 // For example, a relocation can point 42 bytes past the end of a string.
725 // If we change such a relocation to use the section, the linker would think
726 // that it pointed to another string and subtracting 42 at runtime will
727 // produce the wrong value.
728 auto &Sec = cast<MCSectionELF>(Sym.getSection());
729 unsigned Flags = Sec.getFlags();
730 if (Flags & ELF::SHF_MERGE) {
731 if (C != 0)
732 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000733
734 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
735 // only handle section relocations to mergeable sections if using RELA.
736 if (!hasRelocationAddend())
737 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000738 }
739
Rafael Espindola5904e122014-03-29 06:26:49 +0000740 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000741 // are just an offset (@tpoff), require a symbol in gold versions before
742 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
743 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000744 if (Flags & ELF::SHF_TLS)
745 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000746
Rafael Espindola9ef84412014-04-11 19:18:01 +0000747 // If the symbol is a thumb function the final relocation must set the lowest
748 // bit. With a symbol that is done by just having the symbol have that bit
749 // set, so we would lose the bit if we relocated with the section.
750 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000751 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000752 return true;
753
Ulrich Weigand46797c62014-07-20 23:15:06 +0000754 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000755 return true;
756 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000757}
758
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000759static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
760 const MCSymbol &Sym = Ref.getSymbol();
761
762 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
763 return &Sym;
764
765 if (!Sym.isVariable())
766 return nullptr;
767
768 const MCExpr *Expr = Sym.getVariableValue();
769 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
770 if (!Inner)
771 return nullptr;
772
773 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
774 return &Inner->getSymbol();
775 return nullptr;
776}
777
Rafael Espindolac9e70682015-03-24 23:48:44 +0000778static bool isWeak(const MCSymbolData &D) {
779 return D.getFlags() & ELF_STB_Weak || MCELF::GetType(D) == ELF::STT_GNU_IFUNC;
780}
781
Rafael Espindola26585542015-01-19 21:11:14 +0000782void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000783 const MCAsmLayout &Layout,
784 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000785 const MCFixup &Fixup, MCValue Target,
786 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000787 const MCSectionData *FixupSection = Fragment->getParent();
788 uint64_t C = Target.getConstant();
789 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000790
Rafael Espindola5904e122014-03-29 06:26:49 +0000791 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
792 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
793 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000794
Rafael Espindola5904e122014-03-29 06:26:49 +0000795 // Let A, B and C being the components of Target and R be the location of
796 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
797 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000798
Rafael Espindola5904e122014-03-29 06:26:49 +0000799 // In general, ELF has no relocations for -B. It can only represent (A + C)
800 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
801 // replace B to implement it: (A - R - K + C)
802 if (IsPCRel)
803 Asm.getContext().FatalError(
804 Fixup.getLoc(),
805 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000806
Rafael Espindola5904e122014-03-29 06:26:49 +0000807 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000808
Rafael Espindola5904e122014-03-29 06:26:49 +0000809 if (SymB.isUndefined())
810 Asm.getContext().FatalError(
811 Fixup.getLoc(),
812 Twine("symbol '") + SymB.getName() +
813 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000814
Rafael Espindola5904e122014-03-29 06:26:49 +0000815 assert(!SymB.isAbsolute() && "Should have been folded");
816 const MCSection &SecB = SymB.getSection();
817 if (&SecB != &FixupSection->getSection())
818 Asm.getContext().FatalError(
819 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000820
Rafael Espindola5904e122014-03-29 06:26:49 +0000821 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000822 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000823 Asm.getContext().FatalError(
824 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
825
Rafael Espindola5904e122014-03-29 06:26:49 +0000826 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
827 uint64_t K = SymBOffset - FixupOffset;
828 IsPCRel = true;
829 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000830 }
831
Rafael Espindola5904e122014-03-29 06:26:49 +0000832 // We either rejected the fixup or folded B into C at this point.
833 const MCSymbolRefExpr *RefA = Target.getSymA();
834 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
835 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
836
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000837 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000838 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000839 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
840 C += Layout.getSymbolOffset(SymAD);
841
842 uint64_t Addend = 0;
843 if (hasRelocationAddend()) {
844 Addend = C;
845 C = 0;
846 }
847
848 FixedValue = C;
849
850 // FIXME: What is this!?!?
851 MCSymbolRefExpr::VariantKind Modifier =
852 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000853 if (RelocNeedsGOT(Modifier))
854 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000855
Rafael Espindola5904e122014-03-29 06:26:49 +0000856 if (!RelocateWithSymbol) {
857 const MCSection *SecA =
858 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000859 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
860 MCSymbol *SectionSymbol =
861 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
862 : nullptr;
863 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000864 Relocations[FixupSection].push_back(Rec);
865 return;
866 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000867
Rafael Espindola5904e122014-03-29 06:26:49 +0000868 if (SymA) {
869 if (const MCSymbol *R = Renames.lookup(SymA))
870 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000871
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000872 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
873 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000874 else
875 UsedInReloc.insert(SymA);
876 }
877 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
878 Relocations[FixupSection].push_back(Rec);
879 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000880}
881
882
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000883uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000884ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
885 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000886 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000887 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000888}
889
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000890bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
891 const MCSymbolData &Data, bool Used,
892 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000893 const MCSymbol &Symbol = Data.getSymbol();
894 if (Symbol.isVariable()) {
895 const MCExpr *Expr = Symbol.getVariableValue();
896 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
897 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
898 return false;
899 }
900 }
Rafael Espindola16145972010-11-01 14:28:48 +0000901
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000902 if (Used)
903 return true;
904
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000905 if (Renamed)
906 return false;
907
Rafael Espindola45834a02010-10-29 23:09:31 +0000908 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
909 return true;
910
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000911 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000912 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000913 if (Base && Base->isUndefined())
914 return false;
915 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000916
Jan Sjödin30a52de2011-02-28 21:45:04 +0000917 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000918 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000919 return false;
920
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000921 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000922 return false;
923
924 return true;
925}
926
Rafael Espindola39f50422014-04-28 14:24:44 +0000927bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000928 if (Data.isExternal())
929 return false;
930
931 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000932 if (Symbol.isDefined())
933 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000934
Rafael Espindola39f50422014-04-28 14:24:44 +0000935 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000936 return false;
937
938 return true;
939}
940
Rafael Espindolaead85492015-02-17 20:31:13 +0000941void ELFObjectWriter::computeIndexMap(MCAssembler &Asm,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000942 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000943 unsigned Index = 1;
944 for (MCAssembler::iterator it = Asm.begin(),
945 ie = Asm.end(); it != ie; ++it) {
946 const MCSectionELF &Section =
947 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000948 if (Section.getType() != ELF::SHT_GROUP)
949 continue;
950 SectionIndexMap[&Section] = Index++;
951 }
952
953 for (MCAssembler::iterator it = Asm.begin(),
954 ie = Asm.end(); it != ie; ++it) {
Rafael Espindolaead85492015-02-17 20:31:13 +0000955 const MCSectionData &SD = *it;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000956 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000957 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000958 if (Section.getType() == ELF::SHT_GROUP ||
959 Section.getType() == ELF::SHT_REL ||
960 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000961 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000962 SectionIndexMap[&Section] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000963 if (MCSectionData *RelSD = createRelocationSection(Asm, SD)) {
964 const MCSectionELF *RelSection =
965 static_cast<const MCSectionELF *>(&RelSD->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000966 SectionIndexMap[RelSection] = Index++;
Rafael Espindolaead85492015-02-17 20:31:13 +0000967 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000968 }
969}
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::GetSectionFileSize(const MCAsmLayout &Layout,
1536 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001537 if (IsELFMetaDataSection(SD))
1538 return DataSectionSize(SD);
1539 return Layout.getSectionFileSize(&SD);
1540}
1541
Jan Sjödin30a52de2011-02-28 21:45:04 +00001542uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1543 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001544 if (IsELFMetaDataSection(SD))
1545 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001546 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001547}
1548
Rafael Espindola1557fd62011-03-20 18:44:20 +00001549void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1550 const MCAsmLayout &Layout,
1551 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001552 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1553
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001554 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001555 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001556
1557 if (IsELFMetaDataSection(SD)) {
1558 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1559 ++i) {
1560 const MCFragment &F = *i;
1561 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001562 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001563 }
1564 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001565 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001566 }
1567}
1568
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001569void ELFObjectWriter::writeSectionHeader(
1570 MCAssembler &Asm, const GroupMapTy &GroupMap, const MCAsmLayout &Layout,
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001571 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001572 const SectionOffsetMapTy &SectionOffsetMap) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001573 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001574
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001575 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001576 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001577
1578 for (SectionIndexMapTy::const_iterator i=
1579 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1580 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001581 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001582 }
1583
Matt Fleming6c1ad482010-08-16 18:57:57 +00001584 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001585 uint64_t FirstSectionSize =
1586 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1587 uint32_t FirstSectionLink =
1588 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1589 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001590
Rafael Espindola1557fd62011-03-20 18:44:20 +00001591 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001592 const MCSectionELF &Section = *Sections[i];
1593 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1594 uint32_t GroupSymbolIndex;
1595 if (Section.getType() != ELF::SHT_GROUP)
1596 GroupSymbolIndex = 0;
1597 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001598 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1599 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001600
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001601 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001602
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001603 writeSection(Asm, SectionIndexMap, GroupSymbolIndex,
1604 SectionOffsetMap.lookup(&Section), Size, SD.getAlignment(),
1605 Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001606 }
1607}
1608
Rafael Espindola1557fd62011-03-20 18:44:20 +00001609void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1610 std::vector<const MCSectionELF*> &Sections) {
1611 for (MCAssembler::iterator it = Asm.begin(),
1612 ie = Asm.end(); it != ie; ++it) {
1613 const MCSectionELF &Section =
1614 static_cast<const MCSectionELF &>(it->getSection());
1615 if (Section.getType() == ELF::SHT_GROUP)
1616 Sections.push_back(&Section);
1617 }
1618
1619 for (MCAssembler::iterator it = Asm.begin(),
1620 ie = Asm.end(); it != ie; ++it) {
1621 const MCSectionELF &Section =
1622 static_cast<const MCSectionELF &>(it->getSection());
1623 if (Section.getType() != ELF::SHT_GROUP &&
1624 Section.getType() != ELF::SHT_REL &&
1625 Section.getType() != ELF::SHT_RELA)
1626 Sections.push_back(&Section);
1627 }
1628
1629 for (MCAssembler::iterator it = Asm.begin(),
1630 ie = Asm.end(); it != ie; ++it) {
1631 const MCSectionELF &Section =
1632 static_cast<const MCSectionELF &>(it->getSection());
1633 if (Section.getType() == ELF::SHT_REL ||
1634 Section.getType() == ELF::SHT_RELA)
1635 Sections.push_back(&Section);
1636 }
1637}
1638
1639void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1640 const MCAsmLayout &Layout) {
1641 GroupMapTy GroupMap;
1642 RevGroupMapTy RevGroupMap;
1643 SectionIndexMapTy SectionIndexMap;
1644
David Blaikiee06e8012014-04-11 22:11:50 +00001645 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001646 createIndexedSections(Asm, const_cast<MCAsmLayout &>(Layout), GroupMap,
1647 RevGroupMap, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001648
Rafael Espindola1557fd62011-03-20 18:44:20 +00001649 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001650 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001651
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001652 WriteRelocations(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola1557fd62011-03-20 18:44:20 +00001653
1654 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1655 const_cast<MCAsmLayout&>(Layout),
Rafael Espindolaef6baea2015-02-11 23:11:18 +00001656 SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001657
1658 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1659 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1660 sizeof(ELF::Elf32_Ehdr);
1661 uint64_t FileOff = HeaderSize;
1662
1663 std::vector<const MCSectionELF*> Sections;
1664 ComputeSectionOrder(Asm, Sections);
1665 unsigned NumSections = Sections.size();
1666 SectionOffsetMapTy SectionOffsetMap;
Rafael Espindola7230f802015-04-08 11:41:24 +00001667 for (unsigned i = 0; i < NumSections; ++i) {
1668
Rafael Espindola1557fd62011-03-20 18:44:20 +00001669 const MCSectionELF &Section = *Sections[i];
1670 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1671
1672 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1673
1674 // Remember the offset into the file for this section.
1675 SectionOffsetMap[&Section] = FileOff;
1676
1677 // Get the size of the section in the output file (including padding).
1678 FileOff += GetSectionFileSize(Layout, SD);
1679 }
1680
1681 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1682
Rafael Espindola01f4c6c2015-04-07 21:51:41 +00001683 const unsigned SectionHeaderOffset = FileOff;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001684
Rafael Espindola1557fd62011-03-20 18:44:20 +00001685 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001686 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001687
Rafael Espindola7230f802015-04-08 11:41:24 +00001688 // ... then the sections ...
1689 for (unsigned i = 0; i < NumSections; ++i)
Rafael Espindola1557fd62011-03-20 18:44:20 +00001690 WriteDataSectionData(Asm, Layout, *Sections[i]);
1691
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001692 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001693 WriteZeros(Padding);
1694
1695 // ... then the section header table ...
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001696 writeSectionHeader(Asm, GroupMap, Layout, SectionIndexMap, SectionOffsetMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001697}
1698
Rafael Espindola94a88d72015-04-06 15:27:57 +00001699bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1700 const MCAssembler &Asm, const MCSymbolData &DataA,
1701 const MCSymbolData *DataB, const MCFragment &FB, bool InSet,
1702 bool IsPCRel) const {
1703 if (!InSet && (::isWeak(DataA) || (DataB && ::isWeak(*DataB))))
Eli Friedmand92d17b2011-03-03 07:24:36 +00001704 return false;
1705 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola94a88d72015-04-06 15:27:57 +00001706 Asm, DataA, DataB, FB, InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001707}
1708
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001709bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
1710 return ::isWeak(SD);
1711}
1712
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001713MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1714 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001715 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001716 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001717}