blob: 27e34da6322e8a0929e08acdeaedcd6a99eaf266 [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"
Hans Wennborg83e6e1e2014-04-30 16:25:02 +000031#include "llvm/Object/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"
Rafael Espindola0ce09712014-03-25 22:43:53 +000034#include "llvm/Support/Endian.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000035#include "llvm/Support/ELF.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.
84 bool UseSymbol; // Relocate with a symbol, not the section.
85 union {
86 const MCSymbol *Symbol; // The symbol to relocate with.
87 const MCSectionData *Section; // The section to relocate with.
88 };
89 unsigned Type; // The type of the relocation.
90 uint64_t Addend; // The addend to use.
91
92 ELFRelocationEntry(uint64_t Offset, const MCSymbol *Symbol, unsigned Type,
93 uint64_t Addend)
94 : Offset(Offset), UseSymbol(true), Symbol(Symbol), Type(Type),
95 Addend(Addend) {}
96
97 ELFRelocationEntry(uint64_t Offset, const MCSectionData *Section,
98 unsigned Type, uint64_t Addend)
99 : Offset(Offset), UseSymbol(false), Section(Section), Type(Type),
100 Addend(Addend) {}
101};
102
Rafael Espindola29abd972011-12-22 03:38:00 +0000103class ELFObjectWriter : public MCObjectWriter {
Rafael Espindola0ce09712014-03-25 22:43:53 +0000104 FragmentWriter FWriter;
105
Rafael Espindola29abd972011-12-22 03:38:00 +0000106 protected:
107
108 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
109 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
110 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000111 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
Rafael Espindola29abd972011-12-22 03:38:00 +0000112 bool Used, bool Renamed);
Rafael Espindola39f50422014-04-28 14:24:44 +0000113 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
Rafael Espindola29abd972011-12-22 03:38:00 +0000114 static bool IsELFMetaDataSection(const MCSectionData &SD);
115 static uint64_t DataSectionSize(const MCSectionData &SD);
116 static uint64_t GetSectionFileSize(const MCAsmLayout &Layout,
117 const MCSectionData &SD);
118 static uint64_t GetSectionAddressSize(const MCAsmLayout &Layout,
119 const MCSectionData &SD);
120
121 void WriteDataSectionData(MCAssembler &Asm,
122 const MCAsmLayout &Layout,
123 const MCSectionELF &Section);
124
125 /*static bool isFixupKindX86RIPRel(unsigned Kind) {
126 return Kind == X86::reloc_riprel_4byte ||
127 Kind == X86::reloc_riprel_4byte_movq_load;
128 }*/
129
130 /// ELFSymbolData - Helper struct for containing some precomputed
131 /// information on symbols.
132 struct ELFSymbolData {
133 MCSymbolData *SymbolData;
134 uint64_t StringIndex;
135 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000136 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000137
138 // Support lexicographic sorting.
139 bool operator<(const ELFSymbolData &RHS) const {
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000140 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000141 }
142 };
143
Rafael Espindola29abd972011-12-22 03:38:00 +0000144 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000145 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000146
147 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
148 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
149 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
150
Rafael Espindola5904e122014-03-29 06:26:49 +0000151 llvm::DenseMap<const MCSectionData *, std::vector<ELFRelocationEntry>>
152 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000153 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000154
155 /// @}
156 /// @name Symbol Table Data
157 /// @{
158
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000159 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000160 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000161 std::vector<ELFSymbolData> LocalSymbolData;
162 std::vector<ELFSymbolData> ExternalSymbolData;
163 std::vector<ELFSymbolData> UndefinedSymbolData;
164
165 /// @}
166
167 bool NeedsGOT;
168
Rafael Espindola29abd972011-12-22 03:38:00 +0000169 // This holds the symbol table index of the last local symbol.
170 unsigned LastLocalSymbolIndex;
171 // This holds the .strtab section index.
172 unsigned StringTableIndex;
173 // This holds the .symtab section index.
174 unsigned SymbolTableIndex;
175
176 unsigned ShstrtabIndex;
177
178
Rafael Espindola29abd972011-12-22 03:38:00 +0000179 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000180 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
181 bool hasRelocationAddend() const {
182 return TargetObjectWriter->hasRelocationAddend();
183 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000184 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000185 bool IsPCRel) const {
186 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000187 }
188
Rafael Espindola29abd972011-12-22 03:38:00 +0000189 public:
Rafael Espindola0ce09712014-03-25 22:43:53 +0000190 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_ostream &_OS,
191 bool IsLittleEndian)
192 : MCObjectWriter(_OS, IsLittleEndian), FWriter(IsLittleEndian),
Rafael Espindola10be0832014-03-25 23:44:25 +0000193 TargetObjectWriter(MOTW), NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000194
195 virtual ~ELFObjectWriter();
196
197 void WriteWord(uint64_t W) {
198 if (is64Bit())
199 Write64(W);
200 else
201 Write32(W);
202 }
203
Rafael Espindola0ce09712014-03-25 22:43:53 +0000204 template <typename T> void write(MCDataFragment &F, T Value) {
205 FWriter.write(F, Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000206 }
207
Jack Carter1bd90ff2013-01-30 02:09:52 +0000208 void WriteHeader(const MCAssembler &Asm,
209 uint64_t SectionDataSize,
Rafael Espindola29abd972011-12-22 03:38:00 +0000210 unsigned NumberOfSections);
211
Rafael Espindola10be0832014-03-25 23:44:25 +0000212 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000213 const MCAsmLayout &Layout);
214
Rafael Espindola10be0832014-03-25 23:44:25 +0000215 void WriteSymbolTable(MCDataFragment *SymtabF, MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000216 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000217 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000218
Rafael Espindolab60c8292014-04-29 12:46:50 +0000219 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
220 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000221 const MCSymbolData *SD, uint64_t C,
222 unsigned Type) const;
223
Craig Topper34a61bc2014-03-08 07:02:02 +0000224 void RecordRelocation(const MCAssembler &Asm, const MCAsmLayout &Layout,
225 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000226 MCValue Target, bool &IsPCRel,
227 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000228
229 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
230 const MCSymbol *S);
231
232 // Map from a group section to the signature symbol
233 typedef DenseMap<const MCSectionELF*, const MCSymbol*> GroupMapTy;
234 // Map from a signature symbol to the group section
235 typedef DenseMap<const MCSymbol*, const MCSectionELF*> RevGroupMapTy;
236 // Map from a section to the section with the relocations
237 typedef DenseMap<const MCSectionELF*, const MCSectionELF*> RelMapTy;
238 // Map from a section to its offset
239 typedef DenseMap<const MCSectionELF*, uint64_t> SectionOffsetMapTy;
240
Rafael Espindola022bb762014-03-24 03:43:21 +0000241 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000242 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000243 /// \param Asm - The assembler.
244 /// \param SectionIndexMap - Maps a section to its index.
245 /// \param RevGroupMap - Maps a signature symbol to the group section.
246 /// \param NumRegularSections - Number of non-relocation sections.
Rafael Espindola022bb762014-03-24 03:43:21 +0000247 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000248 const SectionIndexMapTy &SectionIndexMap,
249 RevGroupMapTy RevGroupMap,
250 unsigned NumRegularSections);
251
252 void ComputeIndexMap(MCAssembler &Asm,
253 SectionIndexMapTy &SectionIndexMap,
254 const RelMapTy &RelMap);
255
256 void CreateRelocationSections(MCAssembler &Asm, MCAsmLayout &Layout,
257 RelMapTy &RelMap);
258
David Blaikie8019bf82014-04-10 21:53:53 +0000259 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
260
Rafael Espindola29abd972011-12-22 03:38:00 +0000261 void WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
262 const RelMapTy &RelMap);
263
264 void CreateMetadataSections(MCAssembler &Asm, MCAsmLayout &Layout,
265 SectionIndexMapTy &SectionIndexMap,
266 const RelMapTy &RelMap);
267
268 // Create the sections that show up in the symbol table. Currently
269 // those are the .note.GNU-stack section and the group sections.
270 void CreateIndexedSections(MCAssembler &Asm, MCAsmLayout &Layout,
271 GroupMapTy &GroupMap,
272 RevGroupMapTy &RevGroupMap,
273 SectionIndexMapTy &SectionIndexMap,
274 const RelMapTy &RelMap);
275
Craig Topper34a61bc2014-03-08 07:02:02 +0000276 void ExecutePostLayoutBinding(MCAssembler &Asm,
277 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000278
279 void WriteSectionHeader(MCAssembler &Asm, const GroupMapTy &GroupMap,
280 const MCAsmLayout &Layout,
281 const SectionIndexMapTy &SectionIndexMap,
282 const SectionOffsetMapTy &SectionOffsetMap);
283
284 void ComputeSectionOrder(MCAssembler &Asm,
285 std::vector<const MCSectionELF*> &Sections);
286
287 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
288 uint64_t Address, uint64_t Offset,
289 uint64_t Size, uint32_t Link, uint32_t Info,
290 uint64_t Alignment, uint64_t EntrySize);
291
292 void WriteRelocationsFragment(const MCAssembler &Asm,
293 MCDataFragment *F,
294 const MCSectionData *SD);
295
Craig Topper34a61bc2014-03-08 07:02:02 +0000296 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000297 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
298 const MCSymbolData &DataA,
299 const MCFragment &FB,
300 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000301 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000302
Craig Topper34a61bc2014-03-08 07:02:02 +0000303 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000304 void WriteSection(MCAssembler &Asm,
305 const SectionIndexMapTy &SectionIndexMap,
306 uint32_t GroupSymbolIndex,
307 uint64_t Offset, uint64_t Size, uint64_t Alignment,
308 const MCSectionELF &Section);
309 };
310}
311
Rafael Espindola0ce09712014-03-25 22:43:53 +0000312FragmentWriter::FragmentWriter(bool IsLittleEndian)
313 : IsLittleEndian(IsLittleEndian) {}
314
315template <typename T> void FragmentWriter::write(MCDataFragment &F, T Val) {
316 if (IsLittleEndian)
317 Val = support::endian::byte_swap<T, support::little>(Val);
318 else
319 Val = support::endian::byte_swap<T, support::big>(Val);
320 const char *Start = (const char *)&Val;
321 F.getContents().append(Start, Start + sizeof(T));
322}
323
Rafael Espindola10be0832014-03-25 23:44:25 +0000324void SymbolTableWriter::createSymtabShndx() {
325 if (ShndxF)
326 return;
327
328 MCContext &Ctx = Asm.getContext();
329 const MCSectionELF *SymtabShndxSection =
330 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0,
331 SectionKind::getReadOnly(), 4, "");
332 MCSectionData *SymtabShndxSD =
333 &Asm.getOrCreateSectionData(*SymtabShndxSection);
334 SymtabShndxSD->setAlignment(4);
335 ShndxF = new MCDataFragment(SymtabShndxSD);
336 unsigned Index = SectionIndexMap.size() + 1;
337 SectionIndexMap[SymtabShndxSection] = Index;
338
339 for (unsigned I = 0; I < NumWritten; ++I)
340 write(*ShndxF, uint32_t(0));
341}
342
343template <typename T>
344void SymbolTableWriter::write(MCDataFragment &F, T Value) {
345 FWriter.write(F, Value);
346}
347
348SymbolTableWriter::SymbolTableWriter(MCAssembler &Asm, FragmentWriter &FWriter,
349 bool Is64Bit,
350 SectionIndexMapTy &SectionIndexMap,
351 MCDataFragment *SymtabF)
352 : Asm(Asm), FWriter(FWriter), Is64Bit(Is64Bit),
353 SectionIndexMap(SectionIndexMap), SymtabF(SymtabF), ShndxF(nullptr),
354 NumWritten(0) {}
355
356void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
357 uint64_t size, uint8_t other,
358 uint32_t shndx, bool Reserved) {
359 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
360
361 if (LargeIndex)
362 createSymtabShndx();
363
364 if (ShndxF) {
365 if (LargeIndex)
366 write(*ShndxF, shndx);
367 else
368 write(*ShndxF, uint32_t(0));
369 }
370
371 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
372
373 raw_svector_ostream OS(SymtabF->getContents());
374
375 if (Is64Bit) {
376 write(*SymtabF, name); // st_name
377 write(*SymtabF, info); // st_info
378 write(*SymtabF, other); // st_other
379 write(*SymtabF, Index); // st_shndx
380 write(*SymtabF, value); // st_value
381 write(*SymtabF, size); // st_size
382 } else {
383 write(*SymtabF, name); // st_name
384 write(*SymtabF, uint32_t(value)); // st_value
385 write(*SymtabF, uint32_t(size)); // st_size
386 write(*SymtabF, info); // st_info
387 write(*SymtabF, other); // st_other
388 write(*SymtabF, Index); // st_shndx
389 }
390
391 ++NumWritten;
392}
393
Jan Sjödin30a52de2011-02-28 21:45:04 +0000394bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
395 const MCFixupKindInfo &FKI =
396 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
397
398 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
399}
400
401bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
402 switch (Variant) {
403 default:
404 return false;
405 case MCSymbolRefExpr::VK_GOT:
406 case MCSymbolRefExpr::VK_PLT:
407 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000408 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000409 case MCSymbolRefExpr::VK_TPOFF:
410 case MCSymbolRefExpr::VK_TLSGD:
411 case MCSymbolRefExpr::VK_GOTTPOFF:
412 case MCSymbolRefExpr::VK_INDNTPOFF:
413 case MCSymbolRefExpr::VK_NTPOFF:
414 case MCSymbolRefExpr::VK_GOTNTPOFF:
415 case MCSymbolRefExpr::VK_TLSLDM:
416 case MCSymbolRefExpr::VK_DTPOFF:
417 case MCSymbolRefExpr::VK_TLSLD:
418 return true;
419 }
420}
421
Jason W Kim96f4c012010-11-15 16:18:39 +0000422ELFObjectWriter::~ELFObjectWriter()
423{}
424
Matt Fleming6c1ad482010-08-16 18:57:57 +0000425// Emit the ELF header.
Jack Carter1bd90ff2013-01-30 02:09:52 +0000426void ELFObjectWriter::WriteHeader(const MCAssembler &Asm,
427 uint64_t SectionDataSize,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000428 unsigned NumberOfSections) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000429 // ELF Header
430 // ----------
431 //
432 // Note
433 // ----
434 // emitWord method behaves differently for ELF32 and ELF64, writing
435 // 4 bytes in the former and 8 in the latter.
436
437 Write8(0x7f); // e_ident[EI_MAG0]
438 Write8('E'); // e_ident[EI_MAG1]
439 Write8('L'); // e_ident[EI_MAG2]
440 Write8('F'); // e_ident[EI_MAG3]
441
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000442 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000443
444 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000445 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000446
447 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000448 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000449 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000450 Write8(0); // e_ident[EI_ABIVERSION]
451
452 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
453
454 Write16(ELF::ET_REL); // e_type
455
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000456 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000457
458 Write32(ELF::EV_CURRENT); // e_version
459 WriteWord(0); // e_entry, no entry point in .o file
460 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000461 WriteWord(SectionDataSize + (is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
Benjamin Kramer896bd7e2010-08-17 17:02:29 +0000462 sizeof(ELF::Elf32_Ehdr))); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000463
Jason W Kim4761fba2011-02-04 21:41:11 +0000464 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000465 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000466
467 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000468 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000469
470 Write16(0); // e_phentsize = prog header entry size
471 Write16(0); // e_phnum = # prog header entries = 0
472
473 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000474 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000475
476 // e_shnum = # of section header ents
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000477 if (NumberOfSections >= ELF::SHN_LORESERVE)
Nick Lewycky4eb11432011-10-07 20:56:23 +0000478 Write16(ELF::SHN_UNDEF);
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000479 else
480 Write16(NumberOfSections);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000481
482 // e_shstrndx = Section # of '.shstrtab'
Nick Lewycky8b02d362011-10-07 20:58:24 +0000483 if (ShstrtabIndex >= ELF::SHN_LORESERVE)
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000484 Write16(ELF::SHN_XINDEX);
485 else
486 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000487}
488
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000489uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &OrigData,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000490 const MCAsmLayout &Layout) {
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000491 MCSymbolData *Data = &OrigData;
492 if (Data->isCommon() && Data->isExternal())
493 return Data->getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000494
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000495 const MCSymbol *Symbol = &Data->getSymbol();
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000496 MCAssembler &Asm = Layout.getAssembler();
497 bool IsThumb = Asm.isThumbFunc(Symbol);
Roman Divacky55184dd2010-12-20 21:14:39 +0000498
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000499 // Given how we implement symver, we can end up with an symbol reference
500 // to an undefined symbol. Walk past it first.
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000501 if (Symbol->isVariable()) {
502 const MCExpr *Expr = Symbol->getVariableValue();
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000503 if (auto *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
504 if (Ref->getKind() == MCSymbolRefExpr::VK_None) {
505 Symbol = &Ref->getSymbol();
506 Data = &Asm.getOrCreateSymbolData(*Symbol);
507 }
Rafael Espindola7bbd5c22014-03-19 00:13:43 +0000508 }
Roman Divacky55184dd2010-12-20 21:14:39 +0000509 }
510
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000511 if (!Symbol->isVariable() && !Data->getFragment())
512 return 0;
513
514 uint64_t Res = Layout.getSymbolOffset(Data);
515
516 if (IsThumb)
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000517 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000518
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000519 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000520}
521
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000522void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
523 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000524 // The presence of symbol versions causes undefined symbols and
525 // versions declared with @@@ to be renamed.
526
David Blaikie583a31c2014-04-18 18:24:25 +0000527 for (MCSymbolData &OriginalData : Asm.symbols()) {
528 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000529
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000530 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000531 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000532 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000533 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
534 if (!Ref)
535 continue;
536 const MCSymbol &Symbol = Ref->getSymbol();
537 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000538
Benjamin Kramer14807272010-10-27 19:53:52 +0000539 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000540 size_t Pos = AliasName.find('@');
541 if (Pos == StringRef::npos)
542 continue;
543
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000544 // Aliases defined with .symvar copy the binding from the symbol they alias.
545 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000546 OriginalData.setExternal(SD.isExternal());
547 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000548
Benjamin Kramer14807272010-10-27 19:53:52 +0000549 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000550 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
551 continue;
552
Rafael Espindola26496e62010-10-27 17:56:18 +0000553 // FIXME: produce a better error message.
554 if (Symbol.isUndefined() && Rest.startswith("@@") &&
555 !Rest.startswith("@@@"))
556 report_fatal_error("A @@ version cannot be undefined");
557
Benjamin Kramer14807272010-10-27 19:53:52 +0000558 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000559 }
560}
561
Roman Divacky5a1c5492014-01-07 20:17:03 +0000562static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
563 uint8_t Type = newType;
564
565 // Propagation rules:
566 // IFUNC > FUNC > OBJECT > NOTYPE
567 // TLS_OBJECT > OBJECT > NOTYPE
568 //
569 // dont let the new type degrade the old type
570 switch (origType) {
571 default:
572 break;
573 case ELF::STT_GNU_IFUNC:
574 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
575 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
576 Type = ELF::STT_GNU_IFUNC;
577 break;
578 case ELF::STT_FUNC:
579 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
580 Type == ELF::STT_TLS)
581 Type = ELF::STT_FUNC;
582 break;
583 case ELF::STT_OBJECT:
584 if (Type == ELF::STT_NOTYPE)
585 Type = ELF::STT_OBJECT;
586 break;
587 case ELF::STT_TLS:
588 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
589 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
590 Type = ELF::STT_TLS;
591 break;
592 }
593
594 return Type;
595}
596
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000597static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
598 const MCSymbol &Symbol) {
599 if (!Symbol.isVariable())
600 return &Symbol;
601
602 const MCExpr *Expr = Symbol.getVariableValue();
603 MCValue Value;
Rafael Espindolabc91d7e2014-04-28 20:53:11 +0000604 if (!Expr->EvaluateAsValue(Value, &Layout))
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000605 llvm_unreachable("Invalid Expression");
Rafael Espindola96450902014-04-28 12:40:50 +0000606 const MCSymbolRefExpr *RefB = Value.getSymB();
607 if (RefB) {
608 Layout.getAssembler().getContext().FatalError(
609 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
610 "' could not be evaluated in a subtraction expression");
611 }
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000612 const MCSymbolRefExpr *A = Value.getSymA();
613 if (!A)
614 return nullptr;
615 return getBaseSymbol(Layout, A->getSymbol());
616}
617
Rafael Espindola10be0832014-03-25 23:44:25 +0000618void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000619 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000620 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000621 assert((!OrigData.getFragment() ||
622 (&OrigData.getFragment()->getParent()->getSection() ==
623 &OrigData.getSymbol().getSection())) &&
624 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola85a84912014-03-26 00:16:43 +0000625 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
626
627 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
628 // SHN_COMMON.
629 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000630
Jack Carter2f8d9d92013-02-19 21:57:35 +0000631 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000632 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000633 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000634 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000635 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000636 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
637 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000638 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000639 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000640
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000641 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000642 // 2 bits
643 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000644 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000645 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000646
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000647 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000648 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000649
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000650 const MCExpr *ESize = OrigData.getSize();
651 if (!ESize && Base)
652 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000653
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000654 if (ESize) {
655 int64_t Res;
656 if (!ESize->EvaluateAsAbsolute(Res, Layout))
657 report_fatal_error("Size expression must be absolute.");
658 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000659 }
660
661 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000662 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
663 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000664}
665
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000666void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000667 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000668 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000669 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000670 // The string table must be emitted first because we need the index
671 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000672
673 // FIXME: Make sure the start of the symbol table is aligned.
674
Rafael Espindola10be0832014-03-25 23:44:25 +0000675 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
676
Matt Fleming6c1ad482010-08-16 18:57:57 +0000677 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000678 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000679
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000680 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000681 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
682 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000683 }
684
Matt Fleming6c1ad482010-08-16 18:57:57 +0000685 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000686 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
687
Matt Fleming6c1ad482010-08-16 18:57:57 +0000688 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
689 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000690 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000691 }
692
Rafael Espindola44bf2662010-09-16 19:46:31 +0000693 // Write out a symbol table entry for each regular section.
Rafael Espindola18014102010-11-10 22:16:43 +0000694 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
695 ++i) {
Eli Friedman1fe0d532010-08-16 21:17:09 +0000696 const MCSectionELF &Section =
Rafael Espindola18014102010-11-10 22:16:43 +0000697 static_cast<const MCSectionELF&>(i->getSection());
698 if (Section.getType() == ELF::SHT_RELA ||
699 Section.getType() == ELF::SHT_REL ||
700 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewycky133a1682011-10-07 23:29:53 +0000701 Section.getType() == ELF::SHT_SYMTAB ||
702 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedman1fe0d532010-08-16 21:17:09 +0000703 continue;
Rafael Espindola10be0832014-03-25 23:44:25 +0000704 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
705 SectionIndexMap.lookup(&Section), false);
Eli Friedman1fe0d532010-08-16 21:17:09 +0000706 LastLocalSymbolIndex++;
707 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000708
709 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
710 ELFSymbolData &MSD = ExternalSymbolData[i];
711 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000712 assert(((Data.getFlags() & ELF_STB_Global) ||
713 (Data.getFlags() & ELF_STB_Weak)) &&
714 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000715 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000716 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000717 LastLocalSymbolIndex++;
718 }
719
720 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
721 ELFSymbolData &MSD = UndefinedSymbolData[i];
722 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000723 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000724 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000725 LastLocalSymbolIndex++;
726 }
727}
728
Rafael Espindola5904e122014-03-29 06:26:49 +0000729// It is always valid to create a relocation with a symbol. It is preferable
730// to use a relocation with a section if that is possible. Using the section
731// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000732bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
733 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000734 const MCSymbolData *SD,
735 uint64_t C,
736 unsigned Type) const {
737 // A PCRel relocation to an absolute value has no symbol (or section). We
738 // represent that with a relocation to a null section.
739 if (!RefA)
740 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000741
Rafael Espindola5904e122014-03-29 06:26:49 +0000742 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
743 switch (Kind) {
744 default:
745 break;
746 // The .odp creation emits a relocation against the symbol ".TOC." which
747 // create a R_PPC64_TOC relocation. However the relocation symbol name
748 // in final object creation should be NULL, since the symbol does not
749 // really exist, it is just the reference to TOC base for the current
750 // object file. Since the symbol is undefined, returning false results
751 // in a relocation with a null section which is the desired result.
752 case MCSymbolRefExpr::VK_PPC_TOCBASE:
753 return false;
754
755 // These VariantKind cause the relocation to refer to something other than
756 // the symbol itself, like a linker generated table. Since the address of
757 // symbol is not relevant, we cannot replace the symbol with the
758 // section and patch the difference in the addend.
759 case MCSymbolRefExpr::VK_GOT:
760 case MCSymbolRefExpr::VK_PLT:
761 case MCSymbolRefExpr::VK_GOTPCREL:
762 case MCSymbolRefExpr::VK_Mips_GOT:
763 case MCSymbolRefExpr::VK_PPC_GOT_LO:
764 case MCSymbolRefExpr::VK_PPC_GOT_HI:
765 case MCSymbolRefExpr::VK_PPC_GOT_HA:
766 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000767 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000768
Rafael Espindola5904e122014-03-29 06:26:49 +0000769 // An undefined symbol is not in any section, so the relocation has to point
770 // to the symbol itself.
771 const MCSymbol &Sym = SD->getSymbol();
772 if (Sym.isUndefined())
773 return true;
774
775 unsigned Binding = MCELF::GetBinding(*SD);
776 switch(Binding) {
777 default:
778 llvm_unreachable("Invalid Binding");
779 case ELF::STB_LOCAL:
780 break;
781 case ELF::STB_WEAK:
782 // If the symbol is weak, it might be overridden by a symbol in another
783 // file. The relocation has to point to the symbol so that the linker
784 // can update it.
785 return true;
786 case ELF::STB_GLOBAL:
787 // Global ELF symbols can be preempted by the dynamic linker. The relocation
788 // has to point to the symbol for a reason analogous to the STB_WEAK case.
789 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000790 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000791
Rafael Espindola5904e122014-03-29 06:26:49 +0000792 // If a relocation points to a mergeable section, we have to be careful.
793 // If the offset is zero, a relocation with the section will encode the
794 // same information. With a non-zero offset, the situation is different.
795 // For example, a relocation can point 42 bytes past the end of a string.
796 // If we change such a relocation to use the section, the linker would think
797 // that it pointed to another string and subtracting 42 at runtime will
798 // produce the wrong value.
799 auto &Sec = cast<MCSectionELF>(Sym.getSection());
800 unsigned Flags = Sec.getFlags();
801 if (Flags & ELF::SHF_MERGE) {
802 if (C != 0)
803 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000804
805 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
806 // only handle section relocations to mergeable sections if using RELA.
807 if (!hasRelocationAddend())
808 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000809 }
810
Rafael Espindola5904e122014-03-29 06:26:49 +0000811 // Most TLS relocations use a got, so they need the symbol. Even those that
812 // are just an offset (@tpoff), require a symbol in some linkers (gold,
813 // but not bfd ld).
814 if (Flags & ELF::SHF_TLS)
815 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000816
Rafael Espindola9ef84412014-04-11 19:18:01 +0000817 // If the symbol is a thumb function the final relocation must set the lowest
818 // bit. With a symbol that is done by just having the symbol have that bit
819 // set, so we would lose the bit if we relocated with the section.
820 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000821 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000822 return true;
823
Rafael Espindola5904e122014-03-29 06:26:49 +0000824 if (TargetObjectWriter->needsRelocateWithSymbol(Type))
825 return true;
826 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000827}
828
Jason W Kim495c2bb2010-12-06 21:57:34 +0000829void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
830 const MCAsmLayout &Layout,
831 const MCFragment *Fragment,
832 const MCFixup &Fixup,
833 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000834 bool &IsPCRel,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000835 uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000836 const MCSectionData *FixupSection = Fragment->getParent();
837 uint64_t C = Target.getConstant();
838 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000839
Rafael Espindola5904e122014-03-29 06:26:49 +0000840 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
841 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
842 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000843
Rafael Espindola5904e122014-03-29 06:26:49 +0000844 // Let A, B and C being the components of Target and R be the location of
845 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
846 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000847
Rafael Espindola5904e122014-03-29 06:26:49 +0000848 // In general, ELF has no relocations for -B. It can only represent (A + C)
849 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
850 // replace B to implement it: (A - R - K + C)
851 if (IsPCRel)
852 Asm.getContext().FatalError(
853 Fixup.getLoc(),
854 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000855
Rafael Espindola5904e122014-03-29 06:26:49 +0000856 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000857
Rafael Espindola5904e122014-03-29 06:26:49 +0000858 if (SymB.isUndefined())
859 Asm.getContext().FatalError(
860 Fixup.getLoc(),
861 Twine("symbol '") + SymB.getName() +
862 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000863
Rafael Espindola5904e122014-03-29 06:26:49 +0000864 assert(!SymB.isAbsolute() && "Should have been folded");
865 const MCSection &SecB = SymB.getSection();
866 if (&SecB != &FixupSection->getSection())
867 Asm.getContext().FatalError(
868 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000869
Rafael Espindola5904e122014-03-29 06:26:49 +0000870 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
871 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
872 uint64_t K = SymBOffset - FixupOffset;
873 IsPCRel = true;
874 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000875 }
876
Rafael Espindola5904e122014-03-29 06:26:49 +0000877 // We either rejected the fixup or folded B into C at this point.
878 const MCSymbolRefExpr *RefA = Target.getSymA();
879 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
880 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
881
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000882 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000883 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000884 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
885 C += Layout.getSymbolOffset(SymAD);
886
887 uint64_t Addend = 0;
888 if (hasRelocationAddend()) {
889 Addend = C;
890 C = 0;
891 }
892
893 FixedValue = C;
894
895 // FIXME: What is this!?!?
896 MCSymbolRefExpr::VariantKind Modifier =
897 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000898 if (RelocNeedsGOT(Modifier))
899 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000900
Rafael Espindola5904e122014-03-29 06:26:49 +0000901 if (!RelocateWithSymbol) {
902 const MCSection *SecA =
903 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
904 const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
905 ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
906 Relocations[FixupSection].push_back(Rec);
907 return;
908 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000909
Rafael Espindola5904e122014-03-29 06:26:49 +0000910 if (SymA) {
911 if (const MCSymbol *R = Renames.lookup(SymA))
912 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000913
Rafael Espindola5904e122014-03-29 06:26:49 +0000914 if (RefA->getKind() == MCSymbolRefExpr::VK_WEAKREF)
915 WeakrefUsedInReloc.insert(SymA);
916 else
917 UsedInReloc.insert(SymA);
918 }
919 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
920 Relocations[FixupSection].push_back(Rec);
921 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000922}
923
924
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000925uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000926ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
927 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000928 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000929 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000930}
931
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000932bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
933 const MCSymbolData &Data, bool Used,
934 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000935 const MCSymbol &Symbol = Data.getSymbol();
936 if (Symbol.isVariable()) {
937 const MCExpr *Expr = Symbol.getVariableValue();
938 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
939 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
940 return false;
941 }
942 }
Rafael Espindola16145972010-11-01 14:28:48 +0000943
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000944 if (Used)
945 return true;
946
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000947 if (Renamed)
948 return false;
949
Rafael Espindola45834a02010-10-29 23:09:31 +0000950 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
951 return true;
952
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000953 if (Symbol.isVariable()) {
954 const MCSymbol *Base = getBaseSymbol(Layout, Symbol);
955 if (Base && Base->isUndefined())
956 return false;
957 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000958
Jan Sjödin30a52de2011-02-28 21:45:04 +0000959 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000960 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000961 return false;
962
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000963 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000964 return false;
965
966 return true;
967}
968
Rafael Espindola39f50422014-04-28 14:24:44 +0000969bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000970 if (Data.isExternal())
971 return false;
972
973 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000974 if (Symbol.isDefined())
975 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000976
Rafael Espindola39f50422014-04-28 14:24:44 +0000977 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000978 return false;
979
980 return true;
981}
982
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000983void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000984 SectionIndexMapTy &SectionIndexMap,
985 const RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000986 unsigned Index = 1;
987 for (MCAssembler::iterator it = Asm.begin(),
988 ie = Asm.end(); it != ie; ++it) {
989 const MCSectionELF &Section =
990 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000991 if (Section.getType() != ELF::SHT_GROUP)
992 continue;
993 SectionIndexMap[&Section] = Index++;
994 }
995
996 for (MCAssembler::iterator it = Asm.begin(),
997 ie = Asm.end(); it != ie; ++it) {
998 const MCSectionELF &Section =
999 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001000 if (Section.getType() == ELF::SHT_GROUP ||
1001 Section.getType() == ELF::SHT_REL ||
1002 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001003 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +00001004 SectionIndexMap[&Section] = Index++;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001005 const MCSectionELF *RelSection = RelMap.lookup(&Section);
1006 if (RelSection)
1007 SectionIndexMap[RelSection] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +00001008 }
1009}
1010
Rafael Espindola022bb762014-03-24 03:43:21 +00001011void
1012ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
1013 const SectionIndexMapTy &SectionIndexMap,
1014 RevGroupMapTy RevGroupMap,
1015 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001016 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +00001017 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001018 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00001019 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001020 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1021 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1022 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001023 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001024 }
1025
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001026 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +00001027 for (MCSymbolData &SD : Asm.symbols()) {
1028 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001029
Rafael Espindola16145972010-11-01 14:28:48 +00001030 bool Used = UsedInReloc.count(&Symbol);
1031 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001032 bool isSignature = RevGroupMap.count(&Symbol);
1033
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001034 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001035 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001036 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001037 continue;
1038
Matt Fleming6c1ad482010-08-16 18:57:57 +00001039 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001040 MSD.SymbolData = &SD;
Rafael Espindola022bb762014-03-24 03:43:21 +00001041 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001042
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001043 // Undefined symbols are global, but this is the first place we
1044 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001045 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001046 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001047 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001048 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001049 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001050 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001051 }
1052
Rafael Espindola022bb762014-03-24 03:43:21 +00001053 if (!BaseSymbol) {
1054 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001055 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001056 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001057 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001058 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001059 if (isSignature && !Used)
1060 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1061 else
1062 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001063 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001064 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001065 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001066 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001067 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001068 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001069 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001070 }
1071
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001072 // The @@@ in symbol version is replaced with @ in undefined symbols and
1073 // @@ in defined ones.
1074 StringRef Name = Symbol.getName();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001075 SmallString<32> Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001076 size_t Pos = Name.find("@@@");
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001077 if (Pos != StringRef::npos) {
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001078 Buf += Name.substr(0, Pos);
1079 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1080 Buf += Name.substr(Pos + Skip);
1081 Name = Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001082 }
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001083 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001084
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001085 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1086 UndefinedSymbolData.push_back(MSD);
1087 else if (Local)
1088 LocalSymbolData.push_back(MSD);
1089 else
1090 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001091 }
1092
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001093 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1094 StrTabBuilder.add(*i);
1095
1096 StrTabBuilder.finalize();
1097
1098 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1099 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1100
1101 for (ELFSymbolData& MSD : LocalSymbolData)
1102 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1103 for (ELFSymbolData& MSD : ExternalSymbolData)
1104 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1105 for (ELFSymbolData& MSD : UndefinedSymbolData)
1106 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1107
Matt Fleming6c1ad482010-08-16 18:57:57 +00001108 // Symbols are required to be in lexicographic order.
1109 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1110 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1111 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1112
1113 // Set the symbol indices. Local symbols must come before all other
1114 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001115 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001116 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1117 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001118
1119 Index += NumRegularSections;
1120
Matt Fleming6c1ad482010-08-16 18:57:57 +00001121 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1122 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1123 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1124 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1125}
1126
Rafael Espindola1557fd62011-03-20 18:44:20 +00001127void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1128 MCAsmLayout &Layout,
1129 RelMapTy &RelMap) {
1130 for (MCAssembler::const_iterator it = Asm.begin(),
1131 ie = Asm.end(); it != ie; ++it) {
1132 const MCSectionData &SD = *it;
1133 if (Relocations[&SD].empty())
1134 continue;
1135
Matt Fleming6c1ad482010-08-16 18:57:57 +00001136 MCContext &Ctx = Asm.getContext();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001137 const MCSectionELF &Section =
1138 static_cast<const MCSectionELF&>(SD.getSection());
1139
1140 const StringRef SectionName = Section.getSectionName();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001141 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming6c1ad482010-08-16 18:57:57 +00001142 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001143
1144 unsigned EntrySize;
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001145 if (hasRelocationAddend())
1146 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramerfd054152010-08-17 17:56:13 +00001147 else
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001148 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001149
Tim Northovera630fb02013-07-10 20:58:17 +00001150 unsigned Flags = 0;
1151 StringRef Group = "";
1152 if (Section.getFlags() & ELF::SHF_GROUP) {
David Blaikie1e412ea2013-10-22 20:34:30 +00001153 Flags = ELF::SHF_GROUP;
1154 Group = Section.getGroup()->getName();
Tim Northovera630fb02013-07-10 20:58:17 +00001155 }
1156
Rafael Espindola1557fd62011-03-20 18:44:20 +00001157 const MCSectionELF *RelaSection =
1158 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
Tim Northovera630fb02013-07-10 20:58:17 +00001159 ELF::SHT_RELA : ELF::SHT_REL, Flags,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001160 SectionKind::getReadOnly(),
Tim Northovera630fb02013-07-10 20:58:17 +00001161 EntrySize, Group);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001162 RelMap[&Section] = RelaSection;
1163 Asm.getOrCreateSectionData(*RelaSection);
1164 }
1165}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001166
David Blaikiee06e8012014-04-11 22:11:50 +00001167static SmallVector<char, 128>
1168getUncompressedData(MCAsmLayout &Layout,
1169 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001170 SmallVector<char, 128> UncompressedData;
1171 for (const MCFragment &F : Fragments) {
1172 const SmallVectorImpl<char> *Contents;
1173 switch (F.getKind()) {
1174 case MCFragment::FT_Data:
1175 Contents = &cast<MCDataFragment>(F).getContents();
1176 break;
1177 case MCFragment::FT_Dwarf:
1178 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1179 break;
1180 case MCFragment::FT_DwarfFrame:
1181 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1182 break;
1183 default:
1184 llvm_unreachable(
1185 "Not expecting any other fragment types in a debug_* section");
1186 }
1187 UncompressedData.append(Contents->begin(), Contents->end());
1188 }
1189 return UncompressedData;
1190}
1191
1192// Include the debug info compression header:
1193// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1194// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001195static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001196prependCompressionHeader(uint64_t Size,
1197 SmallVectorImpl<char> &CompressedContents) {
David Blaikie8019bf82014-04-10 21:53:53 +00001198 static const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001199 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1200 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001201 if (sys::IsLittleEndianHost)
1202 Size = sys::SwapByteOrder(Size);
1203 CompressedContents.insert(CompressedContents.begin(),
1204 Magic.size() + sizeof(Size), 0);
1205 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1206 std::copy(reinterpret_cast<char *>(&Size),
1207 reinterpret_cast<char *>(&Size + 1),
1208 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001209 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001210}
1211
1212// Return a single fragment containing the compressed contents of the whole
1213// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001214static std::unique_ptr<MCDataFragment>
1215getCompressedFragment(MCAsmLayout &Layout,
1216 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001217 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1218
1219 // Gather the uncompressed data from all the fragments, recording the
1220 // alignment fragment, if seen, and any fixups.
1221 SmallVector<char, 128> UncompressedData =
1222 getUncompressedData(Layout, Fragments);
1223
1224 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1225
1226 zlib::Status Success = zlib::compress(
1227 StringRef(UncompressedData.data(), UncompressedData.size()),
1228 CompressedContents);
1229 if (Success != zlib::StatusOK)
1230 return nullptr;
1231
David Blaikie76d3a3c2014-04-18 21:52:26 +00001232 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1233 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001234
1235 return CompressedFragment;
1236}
1237
David Blaikie39fa6a22014-04-25 00:48:01 +00001238typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1239DefiningSymbolMap;
1240
1241static void UpdateSymbols(const MCAsmLayout &Layout,
1242 const std::vector<MCSymbolData *> &Symbols,
1243 MCFragment &NewFragment) {
1244 for (MCSymbolData *Sym : Symbols) {
1245 Sym->setOffset(Sym->getOffset() +
1246 Layout.getFragmentOffset(Sym->getFragment()));
1247 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001248 }
1249}
1250
David Blaikie8019bf82014-04-10 21:53:53 +00001251static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001252 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001253 const MCSectionELF &Section,
1254 MCSectionData &SD) {
1255 StringRef SectionName = Section.getSectionName();
1256 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1257
1258 std::unique_ptr<MCDataFragment> CompressedFragment =
1259 getCompressedFragment(Layout, Fragments);
1260
1261 // Leave the section as-is if the fragments could not be compressed.
1262 if (!CompressedFragment)
1263 return;
1264
David Blaikiec029ab42014-04-18 21:24:12 +00001265 // Update the fragment+offsets of any symbols referring to fragments in this
1266 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001267 auto I = DefiningSymbols.find(&SD);
1268 if (I != DefiningSymbols.end())
1269 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001270
David Blaikie8019bf82014-04-10 21:53:53 +00001271 // Invalidate the layout for the whole section since it will have new and
1272 // different fragments now.
1273 Layout.invalidateFragmentsFrom(&Fragments.front());
1274 Fragments.clear();
1275
1276 // Complete the initialization of the new fragment
1277 CompressedFragment->setParent(&SD);
1278 CompressedFragment->setLayoutOrder(0);
1279 Fragments.push_back(CompressedFragment.release());
1280
1281 // Rename from .debug_* to .zdebug_*
1282 Asm.getContext().renameELFSection(&Section,
1283 (".z" + SectionName.drop_front(1)).str());
1284}
1285
1286void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1287 MCAsmLayout &Layout) {
1288 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1289 return;
1290
David Blaikie39fa6a22014-04-25 00:48:01 +00001291 DefiningSymbolMap DefiningSymbols;
1292
1293 for (MCSymbolData &SD : Asm.symbols())
1294 if (MCFragment *F = SD.getFragment())
1295 DefiningSymbols[F->getParent()].push_back(&SD);
1296
David Blaikie8019bf82014-04-10 21:53:53 +00001297 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001298 const MCSectionELF &Section =
1299 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001300 StringRef SectionName = Section.getSectionName();
1301
1302 // Compressing debug_frame requires handling alignment fragments which is
1303 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1304 // for writing to arbitrary buffers) for little benefit.
1305 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1306 continue;
1307
David Blaikie39fa6a22014-04-25 00:48:01 +00001308 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001309 }
1310}
1311
Rafael Espindola1557fd62011-03-20 18:44:20 +00001312void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1313 const RelMapTy &RelMap) {
1314 for (MCAssembler::const_iterator it = Asm.begin(),
1315 ie = Asm.end(); it != ie; ++it) {
1316 const MCSectionData &SD = *it;
1317 const MCSectionELF &Section =
1318 static_cast<const MCSectionELF&>(SD.getSection());
1319
1320 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1321 if (!RelaSection)
1322 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001323 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001324 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001325
1326 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001327 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001328 }
1329}
1330
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001331void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1332 uint64_t Flags, uint64_t Address,
1333 uint64_t Offset, uint64_t Size,
1334 uint32_t Link, uint32_t Info,
1335 uint64_t Alignment,
1336 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001337 Write32(Name); // sh_name: index into string table
1338 Write32(Type); // sh_type
1339 WriteWord(Flags); // sh_flags
1340 WriteWord(Address); // sh_addr
1341 WriteWord(Offset); // sh_offset
1342 WriteWord(Size); // sh_size
1343 Write32(Link); // sh_link
1344 Write32(Info); // sh_info
1345 WriteWord(Alignment); // sh_addralign
1346 WriteWord(EntrySize); // sh_entsize
1347}
1348
Rafael Espindola5904e122014-03-29 06:26:49 +00001349// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1350// just to match gnu as for easier comparison. The use type is an arbitrary way
1351// of making the sort deterministic.
1352static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1353 const ELFRelocationEntry &A = *AP;
1354 const ELFRelocationEntry &B = *BP;
1355 if (A.Offset != B.Offset)
1356 return B.Offset - A.Offset;
1357 if (B.Type != A.Type)
1358 return A.Type - B.Type;
1359 llvm_unreachable("ELFRelocs might be unstable!");
1360}
1361
1362static void sortRelocs(const MCAssembler &Asm,
1363 std::vector<ELFRelocationEntry> &Relocs) {
1364 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1365}
1366
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001367void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1368 MCDataFragment *F,
1369 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001370 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001371
Rafael Espindola5904e122014-03-29 06:26:49 +00001372 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001373
1374 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001375 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001376
Rafael Espindola5904e122014-03-29 06:26:49 +00001377 unsigned Index;
1378 if (Entry.UseSymbol) {
1379 Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1380 } else {
1381 const MCSectionData *Sec = Entry.Section;
1382 if (Sec)
1383 Index = Sec->getOrdinal() + FileSymbolData.size() +
1384 LocalSymbolData.size() + 1;
1385 else
1386 Index = 0;
1387 }
1388
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001389 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001390 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001391 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001392 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001393
Rafael Espindola5904e122014-03-29 06:26:49 +00001394 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1395 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1396 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1397 write(*F, TargetObjectWriter->getRType(Entry.Type));
1398 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001399 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001400 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001401 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001402 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001403 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001404 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001405 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001406 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001407
Rafael Espindolabce26a12010-10-05 15:11:03 +00001408 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001409 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001410 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001411
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001412 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001413 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001414 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001415 }
1416}
1417
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001418void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1419 MCAsmLayout &Layout,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001420 SectionIndexMapTy &SectionIndexMap,
1421 const RelMapTy &RelMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001422 MCContext &Ctx = Asm.getContext();
1423 MCDataFragment *F;
1424
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001425 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001426
Rafael Espindola0e527b72010-09-22 19:04:41 +00001427 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001428 const MCSectionELF *ShstrtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001429 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001430 SectionKind::getReadOnly());
Rafael Espindola44bf2662010-09-16 19:46:31 +00001431 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1432 ShstrtabSD.setAlignment(1);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001433
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001434 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001435 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1436 SectionKind::getReadOnly(),
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001437 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001438 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001439 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001440
Rafael Espindola1557fd62011-03-20 18:44:20 +00001441 const MCSectionELF *StrtabSection;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001442 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001443 SectionKind::getReadOnly());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001444 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1445 StrtabSD.setAlignment(1);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001446
Rafael Espindola1557fd62011-03-20 18:44:20 +00001447 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1448
1449 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1450 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1451 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001452
1453 // Symbol table
1454 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001455 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001456
Matt Fleming6c1ad482010-08-16 18:57:57 +00001457 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001458 F->getContents().append(StrTabBuilder.data().begin(),
1459 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001460
Matt Fleming6c1ad482010-08-16 18:57:57 +00001461 F = new MCDataFragment(&ShstrtabSD);
1462
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001463 // Section header string table.
1464 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001465 const MCSectionELF &Section =
1466 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001467 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001468 }
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001469 ShStrTabBuilder.finalize();
1470 F->getContents().append(ShStrTabBuilder.data().begin(),
1471 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001472}
1473
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001474void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1475 MCAsmLayout &Layout,
1476 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001477 RevGroupMapTy &RevGroupMap,
1478 SectionIndexMapTy &SectionIndexMap,
1479 const RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001480 // Create the .note.GNU-stack section if needed.
1481 MCContext &Ctx = Asm.getContext();
1482 if (Asm.getNoExecStack()) {
1483 const MCSectionELF *GnuStackSection =
1484 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1485 SectionKind::getReadOnly());
1486 Asm.getOrCreateSectionData(*GnuStackSection);
1487 }
1488
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001489 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001490 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1491 it != ie; ++it) {
1492 const MCSectionELF &Section =
1493 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001494 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001495 continue;
1496
1497 const MCSymbol *SignatureSymbol = Section.getGroup();
1498 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001499 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001500 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001501 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001502 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1503 Data.setAlignment(4);
1504 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001505 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001506 }
1507 GroupMap[Group] = SignatureSymbol;
1508 }
1509
Rafael Espindola1557fd62011-03-20 18:44:20 +00001510 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1511
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001512 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001513 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001514 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001515 const MCSectionELF &Section =
1516 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001517 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001518 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001519 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001520 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1521 // FIXME: we could use the previous fragment
1522 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001523 uint32_t Index = SectionIndexMap.lookup(&Section);
1524 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001525 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001526}
1527
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001528void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1529 const SectionIndexMapTy &SectionIndexMap,
1530 uint32_t GroupSymbolIndex,
1531 uint64_t Offset, uint64_t Size,
1532 uint64_t Alignment,
1533 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001534 uint64_t sh_link = 0;
1535 uint64_t sh_info = 0;
1536
1537 switch(Section.getType()) {
1538 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001539 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001540 sh_info = 0;
1541 break;
1542
1543 case ELF::SHT_REL:
1544 case ELF::SHT_RELA: {
1545 const MCSectionELF *SymtabSection;
1546 const MCSectionELF *InfoSection;
1547 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1548 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001549 SectionKind::getReadOnly());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001550 sh_link = SectionIndexMap.lookup(SymtabSection);
1551 assert(sh_link && ".symtab not found");
1552
1553 // Remove ".rel" and ".rela" prefixes.
1554 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1555 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
David Blaikie15b25df2013-10-22 23:41:52 +00001556 StringRef GroupName =
1557 Section.getGroup() ? Section.getGroup()->getName() : "";
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001558
David Blaikie15b25df2013-10-22 23:41:52 +00001559 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1560 0, SectionKind::getReadOnly(),
1561 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001562 sh_info = SectionIndexMap.lookup(InfoSection);
1563 break;
1564 }
1565
1566 case ELF::SHT_SYMTAB:
1567 case ELF::SHT_DYNSYM:
1568 sh_link = StringTableIndex;
1569 sh_info = LastLocalSymbolIndex;
1570 break;
1571
1572 case ELF::SHT_SYMTAB_SHNDX:
1573 sh_link = SymbolTableIndex;
1574 break;
1575
1576 case ELF::SHT_PROGBITS:
1577 case ELF::SHT_STRTAB:
1578 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001579 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001580 case ELF::SHT_NULL:
1581 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001582 case ELF::SHT_INIT_ARRAY:
1583 case ELF::SHT_FINI_ARRAY:
1584 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001585 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001586 case ELF::SHT_MIPS_REGINFO:
1587 case ELF::SHT_MIPS_OPTIONS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001588 // Nothing to do.
1589 break;
1590
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001591 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001592 sh_link = SymbolTableIndex;
1593 sh_info = GroupSymbolIndex;
1594 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001595
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001596 default:
1597 assert(0 && "FIXME: sh_type value not supported!");
1598 break;
1599 }
1600
Logan Chien4b724422013-02-05 14:18:59 +00001601 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1602 Section.getType() == ELF::SHT_ARM_EXIDX) {
1603 StringRef SecName(Section.getSectionName());
1604 if (SecName == ".ARM.exidx") {
1605 sh_link = SectionIndexMap.lookup(
1606 Asm.getContext().getELFSection(".text",
1607 ELF::SHT_PROGBITS,
1608 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1609 SectionKind::getText()));
1610 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001611 StringRef GroupName =
1612 Section.getGroup() ? Section.getGroup()->getName() : "";
1613 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1614 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1615 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1616 GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001617 }
1618 }
1619
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001620 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1621 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001622 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1623 Alignment, Section.getEntrySize());
1624}
1625
Jan Sjödin30a52de2011-02-28 21:45:04 +00001626bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001627 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001628 !SD.getSection().isVirtualSection();
1629}
1630
Jan Sjödin30a52de2011-02-28 21:45:04 +00001631uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001632 uint64_t Ret = 0;
1633 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1634 ++i) {
1635 const MCFragment &F = *i;
1636 assert(F.getKind() == MCFragment::FT_Data);
1637 Ret += cast<MCDataFragment>(F).getContents().size();
1638 }
1639 return Ret;
1640}
1641
Jan Sjödin30a52de2011-02-28 21:45:04 +00001642uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1643 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001644 if (IsELFMetaDataSection(SD))
1645 return DataSectionSize(SD);
1646 return Layout.getSectionFileSize(&SD);
1647}
1648
Jan Sjödin30a52de2011-02-28 21:45:04 +00001649uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1650 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001651 if (IsELFMetaDataSection(SD))
1652 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001653 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001654}
1655
Rafael Espindola1557fd62011-03-20 18:44:20 +00001656void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1657 const MCAsmLayout &Layout,
1658 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001659 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1660
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001661 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001662 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001663
1664 if (IsELFMetaDataSection(SD)) {
1665 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1666 ++i) {
1667 const MCFragment &F = *i;
1668 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001669 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001670 }
1671 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001672 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001673 }
1674}
1675
Rafael Espindola1557fd62011-03-20 18:44:20 +00001676void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1677 const GroupMapTy &GroupMap,
1678 const MCAsmLayout &Layout,
1679 const SectionIndexMapTy &SectionIndexMap,
1680 const SectionOffsetMapTy &SectionOffsetMap) {
1681 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001682
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001683 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001684 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001685
1686 for (SectionIndexMapTy::const_iterator i=
1687 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1688 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001689 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001690 }
1691
Matt Fleming6c1ad482010-08-16 18:57:57 +00001692 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001693 uint64_t FirstSectionSize =
1694 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1695 uint32_t FirstSectionLink =
1696 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1697 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001698
Rafael Espindola1557fd62011-03-20 18:44:20 +00001699 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001700 const MCSectionELF &Section = *Sections[i];
1701 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1702 uint32_t GroupSymbolIndex;
1703 if (Section.getType() != ELF::SHT_GROUP)
1704 GroupSymbolIndex = 0;
1705 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001706 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1707 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001708
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001709 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001710
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001711 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001712 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001713 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001714 }
1715}
1716
Rafael Espindola1557fd62011-03-20 18:44:20 +00001717void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1718 std::vector<const MCSectionELF*> &Sections) {
1719 for (MCAssembler::iterator it = Asm.begin(),
1720 ie = Asm.end(); it != ie; ++it) {
1721 const MCSectionELF &Section =
1722 static_cast<const MCSectionELF &>(it->getSection());
1723 if (Section.getType() == ELF::SHT_GROUP)
1724 Sections.push_back(&Section);
1725 }
1726
1727 for (MCAssembler::iterator it = Asm.begin(),
1728 ie = Asm.end(); it != ie; ++it) {
1729 const MCSectionELF &Section =
1730 static_cast<const MCSectionELF &>(it->getSection());
1731 if (Section.getType() != ELF::SHT_GROUP &&
1732 Section.getType() != ELF::SHT_REL &&
1733 Section.getType() != ELF::SHT_RELA)
1734 Sections.push_back(&Section);
1735 }
1736
1737 for (MCAssembler::iterator it = Asm.begin(),
1738 ie = Asm.end(); it != ie; ++it) {
1739 const MCSectionELF &Section =
1740 static_cast<const MCSectionELF &>(it->getSection());
1741 if (Section.getType() == ELF::SHT_REL ||
1742 Section.getType() == ELF::SHT_RELA)
1743 Sections.push_back(&Section);
1744 }
1745}
1746
1747void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1748 const MCAsmLayout &Layout) {
1749 GroupMapTy GroupMap;
1750 RevGroupMapTy RevGroupMap;
1751 SectionIndexMapTy SectionIndexMap;
1752
1753 unsigned NumUserSections = Asm.size();
1754
David Blaikiee06e8012014-04-11 22:11:50 +00001755 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001756
Rafael Espindola1557fd62011-03-20 18:44:20 +00001757 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1758 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1759
1760 const unsigned NumUserAndRelocSections = Asm.size();
1761 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1762 RevGroupMap, SectionIndexMap, RelMap);
1763 const unsigned AllSections = Asm.size();
1764 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1765
1766 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1767
1768 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001769 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1770 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001771
1772 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1773
1774 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1775 const_cast<MCAsmLayout&>(Layout),
1776 SectionIndexMap,
1777 RelMap);
1778
1779 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1780 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1781 sizeof(ELF::Elf32_Ehdr);
1782 uint64_t FileOff = HeaderSize;
1783
1784 std::vector<const MCSectionELF*> Sections;
1785 ComputeSectionOrder(Asm, Sections);
1786 unsigned NumSections = Sections.size();
1787 SectionOffsetMapTy SectionOffsetMap;
1788 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1789 const MCSectionELF &Section = *Sections[i];
1790 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1791
1792 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1793
1794 // Remember the offset into the file for this section.
1795 SectionOffsetMap[&Section] = FileOff;
1796
1797 // Get the size of the section in the output file (including padding).
1798 FileOff += GetSectionFileSize(Layout, SD);
1799 }
1800
1801 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1802
1803 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1804
1805 uint64_t SectionHeaderEntrySize = is64Bit() ?
1806 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1807 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1808
1809 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1810 const MCSectionELF &Section = *Sections[i];
1811 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1812
1813 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1814
1815 // Remember the offset into the file for this section.
1816 SectionOffsetMap[&Section] = FileOff;
1817
1818 // Get the size of the section in the output file (including padding).
1819 FileOff += GetSectionFileSize(Layout, SD);
1820 }
1821
1822 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001823 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001824
1825 // ... then the regular sections ...
1826 // + because of .shstrtab
1827 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1828 WriteDataSectionData(Asm, Layout, *Sections[i]);
1829
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001830 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001831 WriteZeros(Padding);
1832
1833 // ... then the section header table ...
1834 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1835 SectionOffsetMap);
1836
Nick Lewycky4eb11432011-10-07 20:56:23 +00001837 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001838 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1839 WriteDataSectionData(Asm, Layout, *Sections[i]);
1840}
1841
Eli Friedmand92d17b2011-03-03 07:24:36 +00001842bool
1843ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1844 const MCSymbolData &DataA,
1845 const MCFragment &FB,
1846 bool InSet,
1847 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001848 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001849 return false;
1850 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1851 Asm, DataA, FB,InSet, IsPCRel);
1852}
1853
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001854MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1855 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001856 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001857 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001858}