blob: c6033e2fd430675927560570b0ac2b435f999a16 [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 Espindola5904e122014-03-29 06:26:49 +000082struct ELFRelocationEntry {
83 uint64_t Offset; // Where is the relocation.
Rafael Espindolab6613022014-10-17 01:48:58 +000084 const MCSymbol *Symbol; // The symbol to relocate with.
Rafael Espindola5904e122014-03-29 06:26:49 +000085 unsigned Type; // The type of the relocation.
86 uint64_t Addend; // The addend to use.
87
88 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
89 uint64_t Addend)
Rafael Espindolab6613022014-10-17 01:48:58 +000090 : Offset(Offset), Symbol(Symbol), Type(Type), Addend(Addend) {}
Rafael Espindola5904e122014-03-29 06:26:49 +000091};
92
Rafael Espindola29abd972011-12-22 03:38:00 +000093class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola0ce09712014-03-25 22:43:53 +000094 FragmentWriter FWriter;
95
Rafael Espindola29abd972011-12-22 03:38:00 +000096 protected:
97
98 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
99 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
100 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000101 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
Rafael Espindola29abd972011-12-22 03:38:00 +0000102 bool Used, bool Renamed);
Rafael Espindola39f50422014-04-28 14:24:44 +0000103 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
Rafael Espindola29abd972011-12-22 03:38:00 +0000104 static bool IsELFMetaDataSection(const MCSectionData &SD);
105 static uint64_t DataSectionSize(const MCSectionData &SD);
106 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
107 const MCSectionData &SD);
108 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
109 const MCSectionData &SD);
110
111 void WriteDataSectionData(MCAssembler &Asm,
112 const MCAsmLayout &Layout,
113 const MCSectionELF &Section);
114
115 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
116 return Kind == X86::reloc_riprel_4byte ||
117 Kind == X86::reloc_riprel_4byte_movq_load;
118 }*/
119
120 /// ELFSymbolData - Helper struct for containing some precomputed
121 /// information on symbols.
122 struct ELFSymbolData {
123 MCSymbolData *SymbolData;
124 uint64_t StringIndex;
125 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000126 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000127
128 // Support lexicographic sorting.
129 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolab6613022014-10-17 01:48:58 +0000130 unsigned LHSType = MCELF::GetType(*SymbolData);
131 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
132 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
133 return false;
134 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
135 return true;
136 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
137 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000138 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000139 }
140 };
141
Rafael Espindola29abd972011-12-22 03:38:00 +0000142 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000143 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000144
145 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
146 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
147 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
148
Rafael Espindola5904e122014-03-29 06:26:49 +0000149 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
150 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000151 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000152
153 /// @}
154 /// @name Symbol Table Data
155 /// @{
156
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000157 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000158 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000159 std::vector<ELFSymbolData> LocalSymbolData;
160 std::vector<ELFSymbolData> ExternalSymbolData;
161 std::vector<ELFSymbolData> UndefinedSymbolData;
162
163 /// @}
164
165 bool NeedsGOT;
166
Rafael Espindola29abd972011-12-22 03:38:00 +0000167 // This holds the symbol table index of the last local symbol.
168 unsigned LastLocalSymbolIndex;
169 // This holds the .strtab section index.
170 unsigned StringTableIndex;
171 // This holds the .symtab section index.
172 unsigned SymbolTableIndex;
173
174 unsigned ShstrtabIndex;
175
176
Rafael Espindola29abd972011-12-22 03:38:00 +0000177 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000178 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
179 bool hasRelocationAddend() const {
180 return TargetObjectWriter->hasRelocationAddend();
181 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000182 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000183 bool IsPCRel) const {
184 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000185 }
186
Rafael Espindola29abd972011-12-22 03:38:00 +0000187 public:
Rafael Espindola0ce09712014-03-25 22:43:53 +0000188 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
189 bool IsLittleEndian)
190 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000191 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000192
193 virtual ~ELFObjectWriter();
194
195 void WriteWord(uint64_t W) {
196 if (is64Bit())
197 Write64(W);
198 else
199 Write32(W);
200 }
201
Rafael Espindola0ce09712014-03-25 22:43:53 +0000202 template <typename T> void write(MCDataFragment &F, T Value) {
203 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000204 }
205
Jack Carter1bd90ff2013-01-30 02:09:52 +0000206 void WriteHeader(const MCAssembler &Asm,
207 uint64_t SectionDataSize,
Rafael Espindola29abd972011-12-22 03:38:00 +0000208 unsigned NumberOfSections);
209
Rafael Espindola10be0832014-03-25 23:44:25 +0000210 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000211 const MCAsmLayout &Layout);
212
Rafael Espindola10be0832014-03-25 23:44:25 +0000213 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000214 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000215 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000216
Rafael Espindolab60c8292014-04-29 12:46:50 +0000217 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
218 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000219 const MCSymbolData *SD, uint64_t C,
220 unsigned Type) const;
221
Rafael Espindola26585542015-01-19 21:11:14 +0000222 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000223 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000224 MCValue Target, bool &IsPCRel,
225 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000226
227 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
228 const MCSymbol *S);
229
230 // Map from a group section to the signature symbol
231 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
232 // Map from a signature symbol to the group section
233 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
234 // Map from a section to the section with the relocations
235 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
236 // Map from a section to its offset
237 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
238
Rafael Espindola022bb762014-03-24 03:43:21 +0000239 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000240 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000241 /// \param Asm - The assembler.
242 /// \param SectionIndexMap - Maps a section to its index.
243 /// \param RevGroupMap - Maps a signature symbol to the group section.
244 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000245 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000246 const SectionIndexMapTy &SectionIndexMap,
Benjamin Kramer04f9da82014-09-19 12:26:38 +0000247 const RevGroupMapTy &RevGroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000248 unsigned NumRegularSections);
249
250 void ComputeIndexMap(MCAssembler &Asm,
251 SectionIndexMapTy &SectionIndexMap,
252 const RelMapTy &RelMap);
253
Rafael Espindolad9665222015-02-11 21:08:00 +0000254 void CreateRelocationSections(MCAssembler &Asm, RelMapTy &RelMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000255
David Blaikie8019bf82014-04-10 21:53:53 +0000256 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
257
Rafael Espindola29abd972011-12-22 03:38:00 +0000258 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
259 const RelMapTy &RelMap);
260
261 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
262 SectionIndexMapTy &SectionIndexMap,
263 const RelMapTy &RelMap);
264
265 // Create the sections that show up in the symbol table. Currently
266 // those are the .note.GNU-stack section and the group sections.
267 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
268 GroupMapTy &GroupMap,
269 RevGroupMapTy &RevGroupMap,
270 SectionIndexMapTy &SectionIndexMap,
271 const RelMapTy &RelMap);
272
Craig Topper34a61bc2014-03-08 07:02:02 +0000273 void ExecutePostLayoutBinding(MCAssembler &Asm,
274 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000275
276 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
277 const MCAsmLayout &Layout,
278 const SectionIndexMapTy &SectionIndexMap,
279 const SectionOffsetMapTy &SectionOffsetMap);
280
281 void ComputeSectionOrder(MCAssembler &Asm,
282 std::vector<const MCSectionELF*> &Sections);
283
284 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
285 uint64_t Address, uint64_t Offset,
286 uint64_t Size, uint32_t Link, uint32_t Info,
287 uint64_t Alignment, uint64_t EntrySize);
288
289 void WriteRelocationsFragment(const MCAssembler &Asm,
290 MCDataFragment *F,
291 const MCSectionData *SD);
292
Craig Topper34a61bc2014-03-08 07:02:02 +0000293 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000294 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
295 const MCSymbolData &DataA,
296 const MCFragment &FB,
297 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000298 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000299
Craig Topper34a61bc2014-03-08 07:02:02 +0000300 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000301 void WriteSection(MCAssembler &Asm,
302 const SectionIndexMapTy &SectionIndexMap,
303 uint32_t GroupSymbolIndex,
304 uint64_t Offset, uint64_t Size, uint64_t Alignment,
305 const MCSectionELF &Section);
306 };
307}
308
Rafael Espindola0ce09712014-03-25 22:43:53 +0000309FragmentWriter::FragmentWriter(bool IsLittleEndian)
310 : IsLittleEndian(IsLittleEndian) {}
311
312template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
313 if (IsLittleEndian)
314 Val = support::endian::byte_swap<T, support::little>(Val);
315 else
316 Val = support::endian::byte_swap<T, support::big>(Val);
317 const char *Start = (const char *)&Val;
318 F.getContents().append(Start, Start + sizeof(T));
319}
320
Rafael Espindola10be0832014-03-25 23:44:25 +0000321void SymbolTableWriter::createSymtabShndx() {
322 if (ShndxF)
323 return;
324
325 MCContext &Ctx = Asm.getContext();
326 const MCSectionELF *SymtabShndxSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +0000327 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
Rafael Espindola10be0832014-03-25 23:44:25 +0000328 MCSectionData *SymtabShndxSD =
329 &Asm.getOrCreateSectionData(*SymtabShndxSection);
330 SymtabShndxSD->setAlignment(4);
331 ShndxF = new MCDataFragment(SymtabShndxSD);
332 unsigned Index = SectionIndexMap.size() + 1;
333 SectionIndexMap[SymtabShndxSection] = Index;
334
335 for (unsigned I = 0; I < NumWritten; ++I)
336 write(*ShndxF, uint32_t(0));
337}
338
339template <typename T>
340void SymbolTableWriter::write(MCDataFragment &F, T Value) {
341 FWriter.write(F, Value);
342}
343
344SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
345 bool Is64Bit,
346 SectionIndexMapTy &SectionIndexMap,
347 MCDataFragment *SymtabF)
348 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
349 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
350 NumWritten(0) {}
351
352void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
353 uint64_t size, uint8_t other,
354 uint32_t shndx, bool Reserved) {
355 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
356
357 if (LargeIndex)
358 createSymtabShndx();
359
360 if (ShndxF) {
361 if (LargeIndex)
362 write(*ShndxF, shndx);
363 else
364 write(*ShndxF, uint32_t(0));
365 }
366
367 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
368
369 raw_svector_ostream OS(SymtabF->getContents());
370
371 if (Is64Bit) {
372 write(*SymtabF, name); // st_name
373 write(*SymtabF, info); // st_info
374 write(*SymtabF, other); // st_other
375 write(*SymtabF, Index); // st_shndx
376 write(*SymtabF, value); // st_value
377 write(*SymtabF, size); // st_size
378 } else {
379 write(*SymtabF, name); // st_name
380 write(*SymtabF, uint32_t(value)); // st_value
381 write(*SymtabF, uint32_t(size)); // st_size
382 write(*SymtabF, info); // st_info
383 write(*SymtabF, other); // st_other
384 write(*SymtabF, Index); // st_shndx
385 }
386
387 ++NumWritten;
388}
389
Jan Sjödin30a52de2011-02-28 21:45:04 +0000390bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
391 const MCFixupKindInfo &FKI =
392 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
393
394 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
395}
396
397bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
398 switch (Variant) {
399 default:
400 return false;
401 case MCSymbolRefExpr::VK_GOT:
402 case MCSymbolRefExpr::VK_PLT:
403 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000404 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000405 case MCSymbolRefExpr::VK_TPOFF:
406 case MCSymbolRefExpr::VK_TLSGD:
407 case MCSymbolRefExpr::VK_GOTTPOFF:
408 case MCSymbolRefExpr::VK_INDNTPOFF:
409 case MCSymbolRefExpr::VK_NTPOFF:
410 case MCSymbolRefExpr::VK_GOTNTPOFF:
411 case MCSymbolRefExpr::VK_TLSLDM:
412 case MCSymbolRefExpr::VK_DTPOFF:
413 case MCSymbolRefExpr::VK_TLSLD:
414 return true;
415 }
416}
417
Jason W Kim96f4c012010-11-15 16:18:39 +0000418ELFObjectWriter::~ELFObjectWriter()
419{}
420
Matt Fleming6c1ad482010-08-16 18:57:57 +0000421// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000422void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
423 uint64_t SectionDataSize,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000424 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000425 // ELF Header
426 // ----------
427 //
428 // Note
429 // ----
430 // emitWord method behaves differently for ELF32 and ELF64, writing
431 // 4 bytes in the former and 8 in the latter.
432
433 Write8(0x7f); // e_ident[EI_MAG0]
434 Write8('E'); // e_ident[EI_MAG1]
435 Write8('L'); // e_ident[EI_MAG2]
436 Write8('F'); // e_ident[EI_MAG3]
437
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000438 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000439
440 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000441 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000442
443 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000444 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000445 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000446 Write8(0); // e_ident[EI_ABIVERSION]
447
448 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
449
450 Write16(ELF::ET_REL); // e_type
451
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000452 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000453
454 Write32(ELF::EV_CURRENT); // e_version
455 WriteWord(0); // e_entry, no entry point in .o file
456 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000457 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramer896bd7e2010-08-17 17:02:29 +0000458 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000459
Jason W Kim4761fba2011-02-04 21:41:11 +0000460 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000461 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000462
463 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000464 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000465
466 Write16(0); // e_phentsize = prog header entry size
467 Write16(0); // e_phnum = # prog header entries = 0
468
469 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000470 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000471
472 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000473 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000474 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000475 else
476 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000477
478 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000479 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000480 Write16(ELF::SHN_XINDEX);
481 else
482 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000483}
484
Rafael Espindolafee224f2014-04-30 21:51:13 +0000485uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000486 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000487 if (Data.isCommon() && Data.isExternal())
488 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000489
Rafael Espindolafee224f2014-04-30 21:51:13 +0000490 uint64_t Res;
491 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000492 return 0;
493
Rafael Espindolafee224f2014-04-30 21:51:13 +0000494 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000495 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000496
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000497 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000498}
499
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000500void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
501 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000502 // The presence of symbol versions causes undefined symbols and
503 // versions declared with @@@ to be renamed.
504
David Blaikie583a31c2014-04-18 18:24:25 +0000505 for (MCSymbolData &OriginalData : Asm.symbols()) {
506 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000507
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000508 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000509 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000510 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000511 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
512 if (!Ref)
513 continue;
514 const MCSymbol &Symbol = Ref->getSymbol();
515 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000516
Benjamin Kramer14807272010-10-27 19:53:52 +0000517 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000518 size_t Pos = AliasName.find('@');
519 if (Pos == StringRef::npos)
520 continue;
521
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000522 // Aliases defined with .symvar copy the binding from the symbol they alias.
523 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000524 OriginalData.setExternal(SD.isExternal());
525 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000526
Benjamin Kramer14807272010-10-27 19:53:52 +0000527 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000528 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
529 continue;
530
Rafael Espindola26496e62010-10-27 17:56:18 +0000531 // FIXME: produce a better error message.
532 if (Symbol.isUndefined() && Rest.startswith("@@") &&
533 !Rest.startswith("@@@"))
534 report_fatal_error("A @@ version cannot be undefined");
535
Benjamin Kramer14807272010-10-27 19:53:52 +0000536 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000537 }
538}
539
Roman Divacky5a1c5492014-01-07 20:17:03 +0000540static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
541 uint8_t Type = newType;
542
543 // Propagation rules:
544 // IFUNC > FUNC > OBJECT > NOTYPE
545 // TLS_OBJECT > OBJECT > NOTYPE
546 //
547 // dont let the new type degrade the old type
548 switch (origType) {
549 default:
550 break;
551 case ELF::STT_GNU_IFUNC:
552 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
553 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
554 Type = ELF::STT_GNU_IFUNC;
555 break;
556 case ELF::STT_FUNC:
557 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
558 Type == ELF::STT_TLS)
559 Type = ELF::STT_FUNC;
560 break;
561 case ELF::STT_OBJECT:
562 if (Type == ELF::STT_NOTYPE)
563 Type = ELF::STT_OBJECT;
564 break;
565 case ELF::STT_TLS:
566 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
567 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
568 Type = ELF::STT_TLS;
569 break;
570 }
571
572 return Type;
573}
574
Rafael Espindola10be0832014-03-25 23:44:25 +0000575void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000576 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000577 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000578 assert((!OrigData.getFragment() ||
579 (&OrigData.getFragment()->getParent()->getSection() ==
580 &OrigData.getSymbol().getSection())) &&
581 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000582 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000583
584 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
585 // SHN_COMMON.
586 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000587
Jack Carter2f8d9d92013-02-19 21:57:35 +0000588 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000589 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000590 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000591 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000592 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000593 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
594 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000595 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000596 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000597
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000598 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000599 // 2 bits
600 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000601 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000602 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000603
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000604 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000605 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000606
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000607 const MCExpr *ESize = OrigData.getSize();
608 if (!ESize && Base)
609 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000610
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000611 if (ESize) {
612 int64_t Res;
613 if (!ESize->EvaluateAsAbsolute(Res, Layout))
614 report_fatal_error("Size expression must be absolute.");
615 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000616 }
617
618 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000619 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
620 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000621}
622
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000623void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000624 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000625 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000626 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000627 // The string table must be emitted first because we need the index
628 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000629
630 // FIXME: Make sure the start of the symbol table is aligned.
631
Rafael Espindola10be0832014-03-25 23:44:25 +0000632 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
633
Matt Fleming6c1ad482010-08-16 18:57:57 +0000634 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000635 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000636
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000637 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000638 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
639 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000640 }
641
Matt Fleming6c1ad482010-08-16 18:57:57 +0000642 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000643 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
644
Matt Fleming6c1ad482010-08-16 18:57:57 +0000645 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
646 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000647 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000648 }
649
Matt Fleming6c1ad482010-08-16 18:57:57 +0000650 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
651 ELFSymbolData &MSD = ExternalSymbolData[i];
652 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000653 assert(((Data.getFlags() & ELF_STB_Global) ||
654 (Data.getFlags() & ELF_STB_Weak)) &&
655 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000656 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000657 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000658 LastLocalSymbolIndex++;
659 }
660
661 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
662 ELFSymbolData &MSD = UndefinedSymbolData[i];
663 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000664 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000665 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000666 LastLocalSymbolIndex++;
667 }
668}
669
Rafael Espindola5904e122014-03-29 06:26:49 +0000670// It is always valid to create a relocation with a symbol. It is preferable
671// to use a relocation with a section if that is possible. Using the section
672// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000673bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
674 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000675 const MCSymbolData *SD,
676 uint64_t C,
677 unsigned Type) const {
678 // A PCRel relocation to an absolute value has no symbol (or section). We
679 // represent that with a relocation to a null section.
680 if (!RefA)
681 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000682
Rafael Espindola5904e122014-03-29 06:26:49 +0000683 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
684 switch (Kind) {
685 default:
686 break;
687 // The .odp creation emits a relocation against the symbol ".TOC." which
688 // create a R_PPC64_TOC relocation. However the relocation symbol name
689 // in final object creation should be NULL, since the symbol does not
690 // really exist, it is just the reference to TOC base for the current
691 // object file. Since the symbol is undefined, returning false results
692 // in a relocation with a null section which is the desired result.
693 case MCSymbolRefExpr::VK_PPC_TOCBASE:
694 return false;
695
696 // These VariantKind cause the relocation to refer to something other than
697 // the symbol itself, like a linker generated table. Since the address of
698 // symbol is not relevant, we cannot replace the symbol with the
699 // section and patch the difference in the addend.
700 case MCSymbolRefExpr::VK_GOT:
701 case MCSymbolRefExpr::VK_PLT:
702 case MCSymbolRefExpr::VK_GOTPCREL:
703 case MCSymbolRefExpr::VK_Mips_GOT:
704 case MCSymbolRefExpr::VK_PPC_GOT_LO:
705 case MCSymbolRefExpr::VK_PPC_GOT_HI:
706 case MCSymbolRefExpr::VK_PPC_GOT_HA:
707 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000708 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000709
Rafael Espindola5904e122014-03-29 06:26:49 +0000710 // An undefined symbol is not in any section, so the relocation has to point
711 // to the symbol itself.
712 const MCSymbol &Sym = SD->getSymbol();
713 if (Sym.isUndefined())
714 return true;
715
716 unsigned Binding = MCELF::GetBinding(*SD);
717 switch(Binding) {
718 default:
719 llvm_unreachable("Invalid Binding");
720 case ELF::STB_LOCAL:
721 break;
722 case ELF::STB_WEAK:
723 // If the symbol is weak, it might be overridden by a symbol in another
724 // file. The relocation has to point to the symbol so that the linker
725 // can update it.
726 return true;
727 case ELF::STB_GLOBAL:
728 // Global ELF symbols can be preempted by the dynamic linker. The relocation
729 // has to point to the symbol for a reason analogous to the STB_WEAK case.
730 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000731 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000732
Rafael Espindola5904e122014-03-29 06:26:49 +0000733 // If a relocation points to a mergeable section, we have to be careful.
734 // If the offset is zero, a relocation with the section will encode the
735 // same information. With a non-zero offset, the situation is different.
736 // For example, a relocation can point 42 bytes past the end of a string.
737 // If we change such a relocation to use the section, the linker would think
738 // that it pointed to another string and subtracting 42 at runtime will
739 // produce the wrong value.
740 auto &Sec = cast<MCSectionELF>(Sym.getSection());
741 unsigned Flags = Sec.getFlags();
742 if (Flags & ELF::SHF_MERGE) {
743 if (C != 0)
744 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000745
746 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
747 // only handle section relocations to mergeable sections if using RELA.
748 if (!hasRelocationAddend())
749 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000750 }
751
Rafael Espindola5904e122014-03-29 06:26:49 +0000752 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000753 // are just an offset (@tpoff), require a symbol in gold versions before
754 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
755 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000756 if (Flags & ELF::SHF_TLS)
757 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000758
Rafael Espindola9ef84412014-04-11 19:18:01 +0000759 // If the symbol is a thumb function the final relocation must set the lowest
760 // bit. With a symbol that is done by just having the symbol have that bit
761 // set, so we would lose the bit if we relocated with the section.
762 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000763 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000764 return true;
765
Ulrich Weigand46797c62014-07-20 23:15:06 +0000766 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000767 return true;
768 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000769}
770
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000771static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
772 const MCSymbol &Sym = Ref.getSymbol();
773
774 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
775 return &Sym;
776
777 if (!Sym.isVariable())
778 return nullptr;
779
780 const MCExpr *Expr = Sym.getVariableValue();
781 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
782 if (!Inner)
783 return nullptr;
784
785 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
786 return &Inner->getSymbol();
787 return nullptr;
788}
789
Rafael Espindola26585542015-01-19 21:11:14 +0000790void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000791 const MCAsmLayout &Layout,
792 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000793 const MCFixup &Fixup, MCValue Target,
794 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000795 const MCSectionData *FixupSection = Fragment->getParent();
796 uint64_t C = Target.getConstant();
797 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000798
Rafael Espindola5904e122014-03-29 06:26:49 +0000799 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
800 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
801 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000802
Rafael Espindola5904e122014-03-29 06:26:49 +0000803 // Let A, B and C being the components of Target and R be the location of
804 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
805 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000806
Rafael Espindola5904e122014-03-29 06:26:49 +0000807 // In general, ELF has no relocations for -B. It can only represent (A + C)
808 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
809 // replace B to implement it: (A - R - K + C)
810 if (IsPCRel)
811 Asm.getContext().FatalError(
812 Fixup.getLoc(),
813 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000814
Rafael Espindola5904e122014-03-29 06:26:49 +0000815 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000816
Rafael Espindola5904e122014-03-29 06:26:49 +0000817 if (SymB.isUndefined())
818 Asm.getContext().FatalError(
819 Fixup.getLoc(),
820 Twine("symbol '") + SymB.getName() +
821 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000822
Rafael Espindola5904e122014-03-29 06:26:49 +0000823 assert(!SymB.isAbsolute() && "Should have been folded");
824 const MCSection &SecB = SymB.getSection();
825 if (&SecB != &FixupSection->getSection())
826 Asm.getContext().FatalError(
827 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000828
Rafael Espindola5904e122014-03-29 06:26:49 +0000829 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
830 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
831 uint64_t K = SymBOffset - FixupOffset;
832 IsPCRel = true;
833 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000834 }
835
Rafael Espindola5904e122014-03-29 06:26:49 +0000836 // We either rejected the fixup or folded B into C at this point.
837 const MCSymbolRefExpr *RefA = Target.getSymA();
838 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
839 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
840
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000841 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000842 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000843 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
844 C += Layout.getSymbolOffset(SymAD);
845
846 uint64_t Addend = 0;
847 if (hasRelocationAddend()) {
848 Addend = C;
849 C = 0;
850 }
851
852 FixedValue = C;
853
854 // FIXME: What is this!?!?
855 MCSymbolRefExpr::VariantKind Modifier =
856 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000857 if (RelocNeedsGOT(Modifier))
858 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000859
Rafael Espindola5904e122014-03-29 06:26:49 +0000860 if (!RelocateWithSymbol) {
861 const MCSection *SecA =
862 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000863 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
864 MCSymbol *SectionSymbol =
865 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
866 : nullptr;
867 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola5904e122014-03-29 06:26:49 +0000868 Relocations[FixupSection].push_back(Rec);
869 return;
870 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000871
Rafael Espindola5904e122014-03-29 06:26:49 +0000872 if (SymA) {
873 if (const MCSymbol *R = Renames.lookup(SymA))
874 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000875
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000876 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
877 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000878 else
879 UsedInReloc.insert(SymA);
880 }
881 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
882 Relocations[FixupSection].push_back(Rec);
883 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000884}
885
886
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000887uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000888ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
889 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000890 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000891 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000892}
893
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000894bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
895 const MCSymbolData &Data, bool Used,
896 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000897 const MCSymbol &Symbol = Data.getSymbol();
898 if (Symbol.isVariable()) {
899 const MCExpr *Expr = Symbol.getVariableValue();
900 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
901 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
902 return false;
903 }
904 }
Rafael Espindola16145972010-11-01 14:28:48 +0000905
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000906 if (Used)
907 return true;
908
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000909 if (Renamed)
910 return false;
911
Rafael Espindola45834a02010-10-29 23:09:31 +0000912 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
913 return true;
914
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000915 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000916 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000917 if (Base && Base->isUndefined())
918 return false;
919 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000920
Jan Sjödin30a52de2011-02-28 21:45:04 +0000921 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000922 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000923 return false;
924
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000925 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000926 return false;
927
928 return true;
929}
930
Rafael Espindola39f50422014-04-28 14:24:44 +0000931bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000932 if (Data.isExternal())
933 return false;
934
935 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000936 if (Symbol.isDefined())
937 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000938
Rafael Espindola39f50422014-04-28 14:24:44 +0000939 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000940 return false;
941
942 return true;
943}
944
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000945void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000946 SectionIndexMapTy &SectionIndexMap,
947 const RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000948 unsigned Index = 1;
949 for (MCAssembler::iterator it = Asm.begin(),
950 ie = Asm.end(); it != ie; ++it) {
951 const MCSectionELF &Section =
952 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000953 if (Section.getType() != ELF::SHT_GROUP)
954 continue;
955 SectionIndexMap[&Section] = Index++;
956 }
957
958 for (MCAssembler::iterator it = Asm.begin(),
959 ie = Asm.end(); it != ie; ++it) {
960 const MCSectionELF &Section =
961 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000962 if (Section.getType() == ELF::SHT_GROUP ||
963 Section.getType() == ELF::SHT_REL ||
964 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000965 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000966 SectionIndexMap[&Section] = Index++;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000967 const MCSectionELF *RelSection = RelMap.lookup(&Section);
968 if (RelSection)
969 SectionIndexMap[RelSection] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +0000970 }
971}
972
Rafael Espindola022bb762014-03-24 03:43:21 +0000973void
974ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
975 const SectionIndexMapTy &SectionIndexMap,
Benjamin Kramer04f9da82014-09-19 12:26:38 +0000976 const RevGroupMapTy &RevGroupMap,
Rafael Espindola022bb762014-03-24 03:43:21 +0000977 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000978 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000979 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000980 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000981 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000982 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
983 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
984 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000985 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000986 }
987
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000988 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000989 for (MCSymbolData &SD : Asm.symbols()) {
990 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000991
Rafael Espindola16145972010-11-01 14:28:48 +0000992 bool Used = UsedInReloc.count(&Symbol);
993 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000994 bool isSignature = RevGroupMap.count(&Symbol);
995
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000996 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000997 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000998 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +0000999 continue;
1000
Matt Fleming6c1ad482010-08-16 18:57:57 +00001001 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001002 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001003 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001004
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001005 // Undefined symbols are global, but this is the first place we
1006 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001007 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001008 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001009 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001010 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001011 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001012 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001013 }
1014
Rafael Espindola022bb762014-03-24 03:43:21 +00001015 if (!BaseSymbol) {
1016 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001017 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001018 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001019 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001020 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001021 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001022 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001023 else
1024 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001025 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001026 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001027 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001028 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001029 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001030 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001031 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001032 }
1033
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001034 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1035 // in defined ones.
1036 //
1037 // FIXME: All name handling should be done before we get to the writer,
1038 // including dealing with GNU-style version suffixes. Fixing this isn’t
1039 // trivial.
1040 //
1041 // We thus have to be careful to not perform the symbol version replacement
1042 // blindly:
1043 //
1044 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1045 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1046 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1047 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1048 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1049 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1050 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1051 // "__imp_?" or "__imp_@?".
1052 //
1053 // It would have been interesting to perform the MS mangling prefix check
1054 // only when the target triple is of the form *-pc-windows-elf. But, it
1055 // seems that this information is not easily accessible from the
1056 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001057 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001058 if (!Name.startswith("?") && !Name.startswith("@?") &&
1059 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1060 // This symbol isn't following the MSVC C++ name mangling convention. We
1061 // can thus safely interpret the @@@ in symbol names as specifying symbol
1062 // versioning.
1063 SmallString<32> Buf;
1064 size_t Pos = Name.find("@@@");
1065 if (Pos != StringRef::npos) {
1066 Buf += Name.substr(0, Pos);
1067 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1068 Buf += Name.substr(Pos + Skip);
1069 Name = Buf;
1070 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001071 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001072
1073 // Sections have their own string table
1074 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1075 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001076
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001077 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1078 UndefinedSymbolData.push_back(MSD);
1079 else if (Local)
1080 LocalSymbolData.push_back(MSD);
1081 else
1082 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001083 }
1084
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001085 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1086 StrTabBuilder.add(*i);
1087
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001088 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001089
1090 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1091 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1092
Rafael Espindolab6613022014-10-17 01:48:58 +00001093 for (ELFSymbolData &MSD : LocalSymbolData)
1094 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1095 ? 0
1096 : StrTabBuilder.getOffset(MSD.Name);
1097 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001098 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1099 for (ELFSymbolData& MSD : UndefinedSymbolData)
1100 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1101
Matt Fleming6c1ad482010-08-16 18:57:57 +00001102 // Symbols are required to be in lexicographic order.
1103 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1104 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1105 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1106
1107 // Set the symbol indices. Local symbols must come before all other
1108 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001109 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001110 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1111 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001112
Matt Fleming6c1ad482010-08-16 18:57:57 +00001113 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1114 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1115 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1116 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1117}
1118
Rafael Espindola1557fd62011-03-20 18:44:20 +00001119void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001120 RelMapTy &RelMap) {
1121 for (MCAssembler::const_iterator it = Asm.begin(),
1122 ie = Asm.end(); it != ie; ++it) {
1123 const MCSectionData &SD = *it;
1124 if (Relocations[&SD].empty())
1125 continue;
1126
Matt Fleming6c1ad482010-08-16 18:57:57 +00001127 MCContext &Ctx = Asm.getContext();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001128 const MCSectionELF &Section =
1129 static_cast<const MCSectionELF&>(SD.getSection());
1130
1131 const StringRef SectionName = Section.getSectionName();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001132 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming6c1ad482010-08-16 18:57:57 +00001133 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001134
1135 unsigned EntrySize;
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001136 if (hasRelocationAddend())
1137 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramerfd054152010-08-17 17:56:13 +00001138 else
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001139 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001140
Tim Northovera630fb02013-07-10 20:58:17 +00001141 unsigned Flags = 0;
1142 StringRef Group = "";
1143 if (Section.getFlags() & ELF::SHF_GROUP) {
David Blaikie1e412ea2013-10-22 20:34:30 +00001144 Flags = ELF::SHF_GROUP;
1145 Group = Section.getGroup()->getName();
Tim Northovera630fb02013-07-10 20:58:17 +00001146 }
1147
Rafael Espindola1557fd62011-03-20 18:44:20 +00001148 const MCSectionELF *RelaSection =
1149 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
Tim Northovera630fb02013-07-10 20:58:17 +00001150 ELF::SHT_RELA : ELF::SHT_REL, Flags,
Tim Northovera630fb02013-07-10 20:58:17 +00001151 EntrySize, Group);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001152 RelMap[&Section] = RelaSection;
1153 Asm.getOrCreateSectionData(*RelaSection);
1154 }
1155}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001156
David Blaikiee06e8012014-04-11 22:11:50 +00001157static SmallVector<char, 128>
1158getUncompressedData(MCAsmLayout &Layout,
1159 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001160 SmallVector<char, 128> UncompressedData;
1161 for (const MCFragment &F : Fragments) {
1162 const SmallVectorImpl<char> *Contents;
1163 switch (F.getKind()) {
1164 case MCFragment::FT_Data:
1165 Contents = &cast<MCDataFragment>(F).getContents();
1166 break;
1167 case MCFragment::FT_Dwarf:
1168 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1169 break;
1170 case MCFragment::FT_DwarfFrame:
1171 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1172 break;
1173 default:
1174 llvm_unreachable(
1175 "Not expecting any other fragment types in a debug_* section");
1176 }
1177 UncompressedData.append(Contents->begin(), Contents->end());
1178 }
1179 return UncompressedData;
1180}
1181
1182// Include the debug info compression header:
1183// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1184// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001185static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001186prependCompressionHeader(uint64_t Size,
1187 SmallVectorImpl<char> &CompressedContents) {
David Blaikie8019bf82014-04-10 21:53:53 +00001188 static const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001189 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1190 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001191 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001192 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001193 CompressedContents.insert(CompressedContents.begin(),
1194 Magic.size() + sizeof(Size), 0);
1195 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1196 std::copy(reinterpret_cast<char *>(&Size),
1197 reinterpret_cast<char *>(&Size + 1),
1198 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001199 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001200}
1201
1202// Return a single fragment containing the compressed contents of the whole
1203// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001204static std::unique_ptr<MCDataFragment>
1205getCompressedFragment(MCAsmLayout &Layout,
1206 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001207 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1208
1209 // Gather the uncompressed data from all the fragments, recording the
1210 // alignment fragment, if seen, and any fixups.
1211 SmallVector<char, 128> UncompressedData =
1212 getUncompressedData(Layout, Fragments);
1213
1214 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1215
1216 zlib::Status Success = zlib::compress(
1217 StringRef(UncompressedData.data(), UncompressedData.size()),
1218 CompressedContents);
1219 if (Success != zlib::StatusOK)
1220 return nullptr;
1221
David Blaikie76d3a3c2014-04-18 21:52:26 +00001222 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1223 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001224
1225 return CompressedFragment;
1226}
1227
David Blaikie39fa6a22014-04-25 00:48:01 +00001228typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1229DefiningSymbolMap;
1230
1231static void UpdateSymbols(const MCAsmLayout &Layout,
1232 const std::vector<MCSymbolData *> &Symbols,
1233 MCFragment &NewFragment) {
1234 for (MCSymbolData *Sym : Symbols) {
1235 Sym->setOffset(Sym->getOffset() +
1236 Layout.getFragmentOffset(Sym->getFragment()));
1237 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001238 }
1239}
1240
David Blaikie8019bf82014-04-10 21:53:53 +00001241static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001242 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001243 const MCSectionELF &Section,
1244 MCSectionData &SD) {
1245 StringRef SectionName = Section.getSectionName();
1246 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1247
1248 std::unique_ptr<MCDataFragment> CompressedFragment =
1249 getCompressedFragment(Layout, Fragments);
1250
1251 // Leave the section as-is if the fragments could not be compressed.
1252 if (!CompressedFragment)
1253 return;
1254
David Blaikiec029ab42014-04-18 21:24:12 +00001255 // Update the fragment+offsets of any symbols referring to fragments in this
1256 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001257 auto I = DefiningSymbols.find(&SD);
1258 if (I != DefiningSymbols.end())
1259 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001260
David Blaikie8019bf82014-04-10 21:53:53 +00001261 // Invalidate the layout for the whole section since it will have new and
1262 // different fragments now.
1263 Layout.invalidateFragmentsFrom(&Fragments.front());
1264 Fragments.clear();
1265
1266 // Complete the initialization of the new fragment
1267 CompressedFragment->setParent(&SD);
1268 CompressedFragment->setLayoutOrder(0);
1269 Fragments.push_back(CompressedFragment.release());
1270
1271 // Rename from .debug_* to .zdebug_*
1272 Asm.getContext().renameELFSection(&Section,
1273 (".z" + SectionName.drop_front(1)).str());
1274}
1275
1276void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1277 MCAsmLayout &Layout) {
1278 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1279 return;
1280
David Blaikie39fa6a22014-04-25 00:48:01 +00001281 DefiningSymbolMap DefiningSymbols;
1282
1283 for (MCSymbolData &SD : Asm.symbols())
1284 if (MCFragment *F = SD.getFragment())
1285 DefiningSymbols[F->getParent()].push_back(&SD);
1286
David Blaikie8019bf82014-04-10 21:53:53 +00001287 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001288 const MCSectionELF &Section =
1289 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001290 StringRef SectionName = Section.getSectionName();
1291
1292 // Compressing debug_frame requires handling alignment fragments which is
1293 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1294 // for writing to arbitrary buffers) for little benefit.
1295 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1296 continue;
1297
David Blaikie39fa6a22014-04-25 00:48:01 +00001298 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001299 }
1300}
1301
Rafael Espindola1557fd62011-03-20 18:44:20 +00001302void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1303 const RelMapTy &RelMap) {
1304 for (MCAssembler::const_iterator it = Asm.begin(),
1305 ie = Asm.end(); it != ie; ++it) {
1306 const MCSectionData &SD = *it;
1307 const MCSectionELF &Section =
1308 static_cast<const MCSectionELF&>(SD.getSection());
1309
1310 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1311 if (!RelaSection)
1312 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001313 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001314 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001315
1316 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001317 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001318 }
1319}
1320
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001321void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1322 uint64_t Flags, uint64_t Address,
1323 uint64_t Offset, uint64_t Size,
1324 uint32_t Link, uint32_t Info,
1325 uint64_t Alignment,
1326 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001327 Write32(Name); // sh_name: index into string table
1328 Write32(Type); // sh_type
1329 WriteWord(Flags); // sh_flags
1330 WriteWord(Address); // sh_addr
1331 WriteWord(Offset); // sh_offset
1332 WriteWord(Size); // sh_size
1333 Write32(Link); // sh_link
1334 Write32(Info); // sh_info
1335 WriteWord(Alignment); // sh_addralign
1336 WriteWord(EntrySize); // sh_entsize
1337}
1338
Rafael Espindola5904e122014-03-29 06:26:49 +00001339// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1340// just to match gnu as for easier comparison. The use type is an arbitrary way
1341// of making the sort deterministic.
1342static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1343 const ELFRelocationEntry &A = *AP;
1344 const ELFRelocationEntry &B = *BP;
1345 if (A.Offset != B.Offset)
1346 return B.Offset - A.Offset;
1347 if (B.Type != A.Type)
1348 return A.Type - B.Type;
1349 llvm_unreachable("ELFRelocs might be unstable!");
1350}
1351
1352static void sortRelocs(const MCAssembler &Asm,
1353 std::vector<ELFRelocationEntry> &Relocs) {
1354 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1355}
1356
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001357void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1358 MCDataFragment *F,
1359 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001360 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001361
Rafael Espindola5904e122014-03-29 06:26:49 +00001362 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001363
1364 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001365 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001366 unsigned Index =
1367 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001368
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001369 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001370 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001371 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001372 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001373
Rafael Espindola5904e122014-03-29 06:26:49 +00001374 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1375 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1376 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1377 write(*F, TargetObjectWriter->getRType(Entry.Type));
1378 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001379 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001380 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001381 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001382 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001383 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001384 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001385 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001386 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001387
Rafael Espindolabce26a12010-10-05 15:11:03 +00001388 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001389 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001390 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001391
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001392 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001393 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001394 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001395 }
1396}
1397
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001398void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1399 MCAsmLayout &Layout,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001400 SectionIndexMapTy &SectionIndexMap,
1401 const RelMapTy &RelMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001402 MCContext &Ctx = Asm.getContext();
1403 MCDataFragment *F;
1404
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001405 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001406
Rafael Espindola0e527b72010-09-22 19:04:41 +00001407 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001408 const MCSectionELF *ShstrtabSection =
Rafael Espindolaba31e272015-01-29 17:33:21 +00001409 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001410 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1411 ShstrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001412 ShstrtabIndex = SectionIndexMap.size() + 1;
1413 SectionIndexMap[ShstrtabSection] = ShstrtabIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001414
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001415 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001416 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001417 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001418 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001419 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001420 SymbolTableIndex = SectionIndexMap.size() + 1;
1421 SectionIndexMap[SymtabSection] = SymbolTableIndex;
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001422
Rafael Espindola1557fd62011-03-20 18:44:20 +00001423 const MCSectionELF *StrtabSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001424 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001425 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1426 StrtabSD.setAlignment(1);
Rafael Espindolafbd0ddf2015-02-11 22:41:26 +00001427 StringTableIndex = SectionIndexMap.size() + 1;
1428 SectionIndexMap[StrtabSection] = StringTableIndex;
Rafael Espindola44bf2662010-09-16 19:46:31 +00001429
1430 // Symbol table
1431 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001432 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001433
Matt Fleming6c1ad482010-08-16 18:57:57 +00001434 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001435 F->getContents().append(StrTabBuilder.data().begin(),
1436 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001437
Matt Fleming6c1ad482010-08-16 18:57:57 +00001438 F = new MCDataFragment(&ShstrtabSD);
1439
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001440 // Section header string table.
1441 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001442 const MCSectionELF &Section =
1443 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001444 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001445 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001446 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001447 F->getContents().append(ShStrTabBuilder.data().begin(),
1448 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001449}
1450
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001451void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1452 MCAsmLayout &Layout,
1453 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001454 RevGroupMapTy &RevGroupMap,
1455 SectionIndexMapTy &SectionIndexMap,
1456 const RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001457 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001458
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001459 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001460 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1461 it != ie; ++it) {
1462 const MCSectionELF &Section =
1463 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001464 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001465 continue;
1466
1467 const MCSymbol *SignatureSymbol = Section.getGroup();
1468 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001469 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001470 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001471 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001472 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1473 Data.setAlignment(4);
1474 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001475 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001476 }
1477 GroupMap[Group] = SignatureSymbol;
1478 }
1479
Rafael Espindola1557fd62011-03-20 18:44:20 +00001480 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1481
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001482 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001483 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001484 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001485 const MCSectionELF &Section =
1486 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001487 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001488 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001489 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001490 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1491 // FIXME: we could use the previous fragment
1492 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001493 uint32_t Index = SectionIndexMap.lookup(&Section);
1494 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001495 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001496}
1497
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001498void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1499 const SectionIndexMapTy &SectionIndexMap,
1500 uint32_t GroupSymbolIndex,
1501 uint64_t Offset, uint64_t Size,
1502 uint64_t Alignment,
1503 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001504 uint64_t sh_link = 0;
1505 uint64_t sh_info = 0;
1506
1507 switch(Section.getType()) {
1508 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001509 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001510 sh_info = 0;
1511 break;
1512
1513 case ELF::SHT_REL:
1514 case ELF::SHT_RELA: {
1515 const MCSectionELF *SymtabSection;
1516 const MCSectionELF *InfoSection;
Rafael Espindolaba31e272015-01-29 17:33:21 +00001517 SymtabSection =
1518 Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB, 0);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001519 sh_link = SectionIndexMap.lookup(SymtabSection);
1520 assert(sh_link && ".symtab not found");
1521
1522 // Remove ".rel" and ".rela" prefixes.
1523 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1524 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
David Blaikie15b25df2013-10-22 23:41:52 +00001525 StringRef GroupName =
1526 Section.getGroup() ? Section.getGroup()->getName() : "";
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001527
David Blaikie15b25df2013-10-22 23:41:52 +00001528 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
Rafael Espindolaba31e272015-01-29 17:33:21 +00001529 0, 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001530 sh_info = SectionIndexMap.lookup(InfoSection);
1531 break;
1532 }
1533
1534 case ELF::SHT_SYMTAB:
1535 case ELF::SHT_DYNSYM:
1536 sh_link = StringTableIndex;
1537 sh_info = LastLocalSymbolIndex;
1538 break;
1539
1540 case ELF::SHT_SYMTAB_SHNDX:
1541 sh_link = SymbolTableIndex;
1542 break;
1543
1544 case ELF::SHT_PROGBITS:
1545 case ELF::SHT_STRTAB:
1546 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001547 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001548 case ELF::SHT_NULL:
1549 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001550 case ELF::SHT_INIT_ARRAY:
1551 case ELF::SHT_FINI_ARRAY:
1552 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001553 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001554 case ELF::SHT_MIPS_REGINFO:
1555 case ELF::SHT_MIPS_OPTIONS:
Vladimir Medicfb8a2a92014-07-08 08:59:22 +00001556 case ELF::SHT_MIPS_ABIFLAGS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001557 // Nothing to do.
1558 break;
1559
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001560 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001561 sh_link = SymbolTableIndex;
1562 sh_info = GroupSymbolIndex;
1563 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001564
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001565 default:
Craig Topper35b2f752014-06-19 06:10:58 +00001566 llvm_unreachable("FIXME: sh_type value not supported!");
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001567 }
1568
Logan Chien4b724422013-02-05 14:18:59 +00001569 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1570 Section.getType() == ELF::SHT_ARM_EXIDX) {
1571 StringRef SecName(Section.getSectionName());
1572 if (SecName == ".ARM.exidx") {
Rafael Espindolaba31e272015-01-29 17:33:21 +00001573 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1574 ".text", ELF::SHT_PROGBITS, ELF::SHF_EXECINSTR | ELF::SHF_ALLOC));
Logan Chien4b724422013-02-05 14:18:59 +00001575 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001576 StringRef GroupName =
1577 Section.getGroup() ? Section.getGroup()->getName() : "";
1578 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1579 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
Rafael Espindolaba31e272015-01-29 17:33:21 +00001580 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, 0, GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001581 }
1582 }
1583
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001584 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1585 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001586 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1587 Alignment, Section.getEntrySize());
1588}
1589
Jan Sjödin30a52de2011-02-28 21:45:04 +00001590bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001591 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001592 !SD.getSection().isVirtualSection();
1593}
1594
Jan Sjödin30a52de2011-02-28 21:45:04 +00001595uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001596 uint64_t Ret = 0;
1597 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1598 ++i) {
1599 const MCFragment &F = *i;
1600 assert(F.getKind() == MCFragment::FT_Data);
1601 Ret += cast<MCDataFragment>(F).getContents().size();
1602 }
1603 return Ret;
1604}
1605
Jan Sjödin30a52de2011-02-28 21:45:04 +00001606uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1607 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001608 if (IsELFMetaDataSection(SD))
1609 return DataSectionSize(SD);
1610 return Layout.getSectionFileSize(&SD);
1611}
1612
Jan Sjödin30a52de2011-02-28 21:45:04 +00001613uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1614 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001615 if (IsELFMetaDataSection(SD))
1616 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001617 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001618}
1619
Rafael Espindola1557fd62011-03-20 18:44:20 +00001620void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1621 const MCAsmLayout &Layout,
1622 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001623 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1624
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001625 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001626 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001627
1628 if (IsELFMetaDataSection(SD)) {
1629 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1630 ++i) {
1631 const MCFragment &F = *i;
1632 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001633 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001634 }
1635 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001636 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001637 }
1638}
1639
Rafael Espindola1557fd62011-03-20 18:44:20 +00001640void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1641 const GroupMapTy &GroupMap,
1642 const MCAsmLayout &Layout,
1643 const SectionIndexMapTy &SectionIndexMap,
1644 const SectionOffsetMapTy &SectionOffsetMap) {
1645 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001646
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001647 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001648 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001649
1650 for (SectionIndexMapTy::const_iterator i=
1651 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1652 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001653 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001654 }
1655
Matt Fleming6c1ad482010-08-16 18:57:57 +00001656 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001657 uint64_t FirstSectionSize =
1658 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1659 uint32_t FirstSectionLink =
1660 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1661 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001662
Rafael Espindola1557fd62011-03-20 18:44:20 +00001663 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001664 const MCSectionELF &Section = *Sections[i];
1665 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1666 uint32_t GroupSymbolIndex;
1667 if (Section.getType() != ELF::SHT_GROUP)
1668 GroupSymbolIndex = 0;
1669 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001670 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1671 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001672
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001673 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001674
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001675 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001676 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001677 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001678 }
1679}
1680
Rafael Espindola1557fd62011-03-20 18:44:20 +00001681void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1682 std::vector<const MCSectionELF*> &Sections) {
1683 for (MCAssembler::iterator it = Asm.begin(),
1684 ie = Asm.end(); it != ie; ++it) {
1685 const MCSectionELF &Section =
1686 static_cast<const MCSectionELF &>(it->getSection());
1687 if (Section.getType() == ELF::SHT_GROUP)
1688 Sections.push_back(&Section);
1689 }
1690
1691 for (MCAssembler::iterator it = Asm.begin(),
1692 ie = Asm.end(); it != ie; ++it) {
1693 const MCSectionELF &Section =
1694 static_cast<const MCSectionELF &>(it->getSection());
1695 if (Section.getType() != ELF::SHT_GROUP &&
1696 Section.getType() != ELF::SHT_REL &&
1697 Section.getType() != ELF::SHT_RELA)
1698 Sections.push_back(&Section);
1699 }
1700
1701 for (MCAssembler::iterator it = Asm.begin(),
1702 ie = Asm.end(); it != ie; ++it) {
1703 const MCSectionELF &Section =
1704 static_cast<const MCSectionELF &>(it->getSection());
1705 if (Section.getType() == ELF::SHT_REL ||
1706 Section.getType() == ELF::SHT_RELA)
1707 Sections.push_back(&Section);
1708 }
1709}
1710
1711void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1712 const MCAsmLayout &Layout) {
1713 GroupMapTy GroupMap;
1714 RevGroupMapTy RevGroupMap;
1715 SectionIndexMapTy SectionIndexMap;
1716
1717 unsigned NumUserSections = Asm.size();
1718
David Blaikiee06e8012014-04-11 22:11:50 +00001719 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001720
Rafael Espindola1557fd62011-03-20 18:44:20 +00001721 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
Rafael Espindolad9665222015-02-11 21:08:00 +00001722 CreateRelocationSections(Asm, RelMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001723
1724 const unsigned NumUserAndRelocSections = Asm.size();
1725 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1726 RevGroupMap, SectionIndexMap, RelMap);
1727 const unsigned AllSections = Asm.size();
1728 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1729
1730 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1731
1732 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001733 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1734 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001735
1736 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1737
1738 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1739 const_cast<MCAsmLayout&>(Layout),
1740 SectionIndexMap,
1741 RelMap);
1742
1743 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1744 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1745 sizeof(ELF::Elf32_Ehdr);
1746 uint64_t FileOff = HeaderSize;
1747
1748 std::vector<const MCSectionELF*> Sections;
1749 ComputeSectionOrder(Asm, Sections);
1750 unsigned NumSections = Sections.size();
1751 SectionOffsetMapTy SectionOffsetMap;
1752 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1753 const MCSectionELF &Section = *Sections[i];
1754 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1755
1756 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1757
1758 // Remember the offset into the file for this section.
1759 SectionOffsetMap[&Section] = FileOff;
1760
1761 // Get the size of the section in the output file (including padding).
1762 FileOff += GetSectionFileSize(Layout, SD);
1763 }
1764
1765 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1766
1767 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1768
1769 uint64_t SectionHeaderEntrySize = is64Bit() ?
1770 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1771 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1772
1773 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1774 const MCSectionELF &Section = *Sections[i];
1775 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1776
1777 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1778
1779 // Remember the offset into the file for this section.
1780 SectionOffsetMap[&Section] = FileOff;
1781
1782 // Get the size of the section in the output file (including padding).
1783 FileOff += GetSectionFileSize(Layout, SD);
1784 }
1785
1786 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001787 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001788
1789 // ... then the regular sections ...
1790 // + because of .shstrtab
1791 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1792 WriteDataSectionData(Asm, Layout, *Sections[i]);
1793
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001794 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001795 WriteZeros(Padding);
1796
1797 // ... then the section header table ...
1798 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1799 SectionOffsetMap);
1800
Nick Lewycky4eb11432011-10-07 20:56:23 +00001801 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001802 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1803 WriteDataSectionData(Asm, Layout, *Sections[i]);
1804}
1805
Eli Friedmand92d17b2011-03-03 07:24:36 +00001806bool
1807ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1808 const MCSymbolData &DataA,
1809 const MCFragment &FB,
1810 bool InSet,
1811 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001812 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001813 return false;
1814 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1815 Asm, DataA, FB,InSet, IsPCRel);
1816}
1817
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001818MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1819 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001820 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001821 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001822}