blob: 5e24f9148211215a087dad882740706d158b6c63 [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 Espindolafee224f2014-04-30 21:51:13 +0000489uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000490 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000491 if (Data.isCommon() && Data.isExternal())
492 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000493
Rafael Espindolafee224f2014-04-30 21:51:13 +0000494 uint64_t Res;
495 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000496 return 0;
497
Rafael Espindolafee224f2014-04-30 21:51:13 +0000498 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000499 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000500
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000501 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000502}
503
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000504void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
505 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000506 // The presence of symbol versions causes undefined symbols and
507 // versions declared with @@@ to be renamed.
508
David Blaikie583a31c2014-04-18 18:24:25 +0000509 for (MCSymbolData &OriginalData : Asm.symbols()) {
510 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000511
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000512 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000513 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000514 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000515 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
516 if (!Ref)
517 continue;
518 const MCSymbol &Symbol = Ref->getSymbol();
519 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000520
Benjamin Kramer14807272010-10-27 19:53:52 +0000521 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000522 size_t Pos = AliasName.find('@');
523 if (Pos == StringRef::npos)
524 continue;
525
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000526 // Aliases defined with .symvar copy the binding from the symbol they alias.
527 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000528 OriginalData.setExternal(SD.isExternal());
529 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000530
Benjamin Kramer14807272010-10-27 19:53:52 +0000531 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000532 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
533 continue;
534
Rafael Espindola26496e62010-10-27 17:56:18 +0000535 // FIXME: produce a better error message.
536 if (Symbol.isUndefined() && Rest.startswith("@@") &&
537 !Rest.startswith("@@@"))
538 report_fatal_error("A @@ version cannot be undefined");
539
Benjamin Kramer14807272010-10-27 19:53:52 +0000540 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000541 }
542}
543
Roman Divacky5a1c5492014-01-07 20:17:03 +0000544static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
545 uint8_t Type = newType;
546
547 // Propagation rules:
548 // IFUNC > FUNC > OBJECT > NOTYPE
549 // TLS_OBJECT > OBJECT > NOTYPE
550 //
551 // dont let the new type degrade the old type
552 switch (origType) {
553 default:
554 break;
555 case ELF::STT_GNU_IFUNC:
556 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
557 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
558 Type = ELF::STT_GNU_IFUNC;
559 break;
560 case ELF::STT_FUNC:
561 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
562 Type == ELF::STT_TLS)
563 Type = ELF::STT_FUNC;
564 break;
565 case ELF::STT_OBJECT:
566 if (Type == ELF::STT_NOTYPE)
567 Type = ELF::STT_OBJECT;
568 break;
569 case ELF::STT_TLS:
570 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
571 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
572 Type = ELF::STT_TLS;
573 break;
574 }
575
576 return Type;
577}
578
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000579static const MCSymbol *getBaseSymbol(const MCAsmLayout &Layout,
580 const MCSymbol &Symbol) {
581 if (!Symbol.isVariable())
582 return &Symbol;
583
584 const MCExpr *Expr = Symbol.getVariableValue();
585 MCValue Value;
Rafael Espindolabc91d7e2014-04-28 20:53:11 +0000586 if (!Expr->EvaluateAsValue(Value, &Layout))
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000587 llvm_unreachable("Invalid Expression");
Rafael Espindolad5bbf362014-05-01 13:09:42 +0000588
Rafael Espindola96450902014-04-28 12:40:50 +0000589 const MCSymbolRefExpr *RefB = Value.getSymB();
Rafael Espindolad5bbf362014-05-01 13:09:42 +0000590 if (RefB)
Rafael Espindola96450902014-04-28 12:40:50 +0000591 Layout.getAssembler().getContext().FatalError(
592 SMLoc(), Twine("symbol '") + RefB->getSymbol().getName() +
593 "' could not be evaluated in a subtraction expression");
Rafael Espindolad5bbf362014-05-01 13:09:42 +0000594
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000595 const MCSymbolRefExpr *A = Value.getSymA();
596 if (!A)
597 return nullptr;
Rafael Espindolad5bbf362014-05-01 13:09:42 +0000598
599 return &A->getSymbol();
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000600}
601
Rafael Espindola10be0832014-03-25 23:44:25 +0000602void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000603 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000604 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000605 assert((!OrigData.getFragment() ||
606 (&OrigData.getFragment()->getParent()->getSection() ==
607 &OrigData.getSymbol().getSection())) &&
608 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola85a84912014-03-26 00:16:43 +0000609 const MCSymbol *Base = getBaseSymbol(Layout, OrigData.getSymbol());
610
611 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
612 // SHN_COMMON.
613 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000614
Jack Carter2f8d9d92013-02-19 21:57:35 +0000615 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000616 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000617 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000618 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000619 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000620 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
621 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000622 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000623 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000624
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000625 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000626 // 2 bits
627 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000628 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000629 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000630
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000631 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000632 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000633
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000634 const MCExpr *ESize = OrigData.getSize();
635 if (!ESize && Base)
636 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000637
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000638 if (ESize) {
639 int64_t Res;
640 if (!ESize->EvaluateAsAbsolute(Res, Layout))
641 report_fatal_error("Size expression must be absolute.");
642 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000643 }
644
645 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000646 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
647 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000648}
649
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000650void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000651 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000652 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000653 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000654 // The string table must be emitted first because we need the index
655 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000656
657 // FIXME: Make sure the start of the symbol table is aligned.
658
Rafael Espindola10be0832014-03-25 23:44:25 +0000659 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
660
Matt Fleming6c1ad482010-08-16 18:57:57 +0000661 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000662 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000663
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000664 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000665 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
666 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000667 }
668
Matt Fleming6c1ad482010-08-16 18:57:57 +0000669 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000670 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
671
Matt Fleming6c1ad482010-08-16 18:57:57 +0000672 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
673 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000674 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000675 }
676
Rafael Espindola44bf2662010-09-16 19:46:31 +0000677 // Write out a symbol table entry for each regular section.
Rafael Espindola18014102010-11-10 22:16:43 +0000678 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
679 ++i) {
Eli Friedman1fe0d532010-08-16 21:17:09 +0000680 const MCSectionELF &Section =
Rafael Espindola18014102010-11-10 22:16:43 +0000681 static_cast<const MCSectionELF&>(i->getSection());
682 if (Section.getType() == ELF::SHT_RELA ||
683 Section.getType() == ELF::SHT_REL ||
684 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewycky133a1682011-10-07 23:29:53 +0000685 Section.getType() == ELF::SHT_SYMTAB ||
686 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedman1fe0d532010-08-16 21:17:09 +0000687 continue;
Rafael Espindola10be0832014-03-25 23:44:25 +0000688 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
689 SectionIndexMap.lookup(&Section), false);
Eli Friedman1fe0d532010-08-16 21:17:09 +0000690 LastLocalSymbolIndex++;
691 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000692
693 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
694 ELFSymbolData &MSD = ExternalSymbolData[i];
695 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000696 assert(((Data.getFlags() & ELF_STB_Global) ||
697 (Data.getFlags() & ELF_STB_Weak)) &&
698 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000699 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000700 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000701 LastLocalSymbolIndex++;
702 }
703
704 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
705 ELFSymbolData &MSD = UndefinedSymbolData[i];
706 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000707 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000708 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000709 LastLocalSymbolIndex++;
710 }
711}
712
Rafael Espindola5904e122014-03-29 06:26:49 +0000713// It is always valid to create a relocation with a symbol. It is preferable
714// to use a relocation with a section if that is possible. Using the section
715// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000716bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
717 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000718 const MCSymbolData *SD,
719 uint64_t C,
720 unsigned Type) const {
721 // A PCRel relocation to an absolute value has no symbol (or section). We
722 // represent that with a relocation to a null section.
723 if (!RefA)
724 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000725
Rafael Espindola5904e122014-03-29 06:26:49 +0000726 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
727 switch (Kind) {
728 default:
729 break;
730 // The .odp creation emits a relocation against the symbol ".TOC." which
731 // create a R_PPC64_TOC relocation. However the relocation symbol name
732 // in final object creation should be NULL, since the symbol does not
733 // really exist, it is just the reference to TOC base for the current
734 // object file. Since the symbol is undefined, returning false results
735 // in a relocation with a null section which is the desired result.
736 case MCSymbolRefExpr::VK_PPC_TOCBASE:
737 return false;
738
739 // These VariantKind cause the relocation to refer to something other than
740 // the symbol itself, like a linker generated table. Since the address of
741 // symbol is not relevant, we cannot replace the symbol with the
742 // section and patch the difference in the addend.
743 case MCSymbolRefExpr::VK_GOT:
744 case MCSymbolRefExpr::VK_PLT:
745 case MCSymbolRefExpr::VK_GOTPCREL:
746 case MCSymbolRefExpr::VK_Mips_GOT:
747 case MCSymbolRefExpr::VK_PPC_GOT_LO:
748 case MCSymbolRefExpr::VK_PPC_GOT_HI:
749 case MCSymbolRefExpr::VK_PPC_GOT_HA:
750 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000751 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000752
Rafael Espindola5904e122014-03-29 06:26:49 +0000753 // An undefined symbol is not in any section, so the relocation has to point
754 // to the symbol itself.
755 const MCSymbol &Sym = SD->getSymbol();
756 if (Sym.isUndefined())
757 return true;
758
759 unsigned Binding = MCELF::GetBinding(*SD);
760 switch(Binding) {
761 default:
762 llvm_unreachable("Invalid Binding");
763 case ELF::STB_LOCAL:
764 break;
765 case ELF::STB_WEAK:
766 // If the symbol is weak, it might be overridden by a symbol in another
767 // file. The relocation has to point to the symbol so that the linker
768 // can update it.
769 return true;
770 case ELF::STB_GLOBAL:
771 // Global ELF symbols can be preempted by the dynamic linker. The relocation
772 // has to point to the symbol for a reason analogous to the STB_WEAK case.
773 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000774 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000775
Rafael Espindola5904e122014-03-29 06:26:49 +0000776 // If a relocation points to a mergeable section, we have to be careful.
777 // If the offset is zero, a relocation with the section will encode the
778 // same information. With a non-zero offset, the situation is different.
779 // For example, a relocation can point 42 bytes past the end of a string.
780 // If we change such a relocation to use the section, the linker would think
781 // that it pointed to another string and subtracting 42 at runtime will
782 // produce the wrong value.
783 auto &Sec = cast<MCSectionELF>(Sym.getSection());
784 unsigned Flags = Sec.getFlags();
785 if (Flags & ELF::SHF_MERGE) {
786 if (C != 0)
787 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000788
789 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
790 // only handle section relocations to mergeable sections if using RELA.
791 if (!hasRelocationAddend())
792 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000793 }
794
Rafael Espindola5904e122014-03-29 06:26:49 +0000795 // Most TLS relocations use a got, so they need the symbol. Even those that
796 // are just an offset (@tpoff), require a symbol in some linkers (gold,
797 // but not bfd ld).
798 if (Flags & ELF::SHF_TLS)
799 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000800
Rafael Espindola9ef84412014-04-11 19:18:01 +0000801 // If the symbol is a thumb function the final relocation must set the lowest
802 // bit. With a symbol that is done by just having the symbol have that bit
803 // set, so we would lose the bit if we relocated with the section.
804 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000805 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000806 return true;
807
Rafael Espindola5904e122014-03-29 06:26:49 +0000808 if (TargetObjectWriter->needsRelocateWithSymbol(Type))
809 return true;
810 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000811}
812
Jason W Kim495c2bb2010-12-06 21:57:34 +0000813void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
814 const MCAsmLayout &Layout,
815 const MCFragment *Fragment,
816 const MCFixup &Fixup,
817 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000818 bool &IsPCRel,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000819 uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000820 const MCSectionData *FixupSection = Fragment->getParent();
821 uint64_t C = Target.getConstant();
822 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000823
Rafael Espindola5904e122014-03-29 06:26:49 +0000824 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
825 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
826 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000827
Rafael Espindola5904e122014-03-29 06:26:49 +0000828 // Let A, B and C being the components of Target and R be the location of
829 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
830 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000831
Rafael Espindola5904e122014-03-29 06:26:49 +0000832 // In general, ELF has no relocations for -B. It can only represent (A + C)
833 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
834 // replace B to implement it: (A - R - K + C)
835 if (IsPCRel)
836 Asm.getContext().FatalError(
837 Fixup.getLoc(),
838 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000839
Rafael Espindola5904e122014-03-29 06:26:49 +0000840 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000841
Rafael Espindola5904e122014-03-29 06:26:49 +0000842 if (SymB.isUndefined())
843 Asm.getContext().FatalError(
844 Fixup.getLoc(),
845 Twine("symbol '") + SymB.getName() +
846 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000847
Rafael Espindola5904e122014-03-29 06:26:49 +0000848 assert(!SymB.isAbsolute() && "Should have been folded");
849 const MCSection &SecB = SymB.getSection();
850 if (&SecB != &FixupSection->getSection())
851 Asm.getContext().FatalError(
852 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000853
Rafael Espindola5904e122014-03-29 06:26:49 +0000854 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
855 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
856 uint64_t K = SymBOffset - FixupOffset;
857 IsPCRel = true;
858 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000859 }
860
Rafael Espindola5904e122014-03-29 06:26:49 +0000861 // We either rejected the fixup or folded B into C at this point.
862 const MCSymbolRefExpr *RefA = Target.getSymA();
863 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
864 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
865
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000866 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000867 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000868 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
869 C += Layout.getSymbolOffset(SymAD);
870
871 uint64_t Addend = 0;
872 if (hasRelocationAddend()) {
873 Addend = C;
874 C = 0;
875 }
876
877 FixedValue = C;
878
879 // FIXME: What is this!?!?
880 MCSymbolRefExpr::VariantKind Modifier =
881 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000882 if (RelocNeedsGOT(Modifier))
883 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000884
Rafael Espindola5904e122014-03-29 06:26:49 +0000885 if (!RelocateWithSymbol) {
886 const MCSection *SecA =
887 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
888 const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
889 ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
890 Relocations[FixupSection].push_back(Rec);
891 return;
892 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000893
Rafael Espindola5904e122014-03-29 06:26:49 +0000894 if (SymA) {
895 if (const MCSymbol *R = Renames.lookup(SymA))
896 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000897
Rafael Espindola5904e122014-03-29 06:26:49 +0000898 if (RefA->getKind() == MCSymbolRefExpr::VK_WEAKREF)
899 WeakrefUsedInReloc.insert(SymA);
900 else
901 UsedInReloc.insert(SymA);
902 }
903 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
904 Relocations[FixupSection].push_back(Rec);
905 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000906}
907
908
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000909uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000910ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
911 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000912 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000913 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000914}
915
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000916bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
917 const MCSymbolData &Data, bool Used,
918 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000919 const MCSymbol &Symbol = Data.getSymbol();
920 if (Symbol.isVariable()) {
921 const MCExpr *Expr = Symbol.getVariableValue();
922 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
923 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
924 return false;
925 }
926 }
Rafael Espindola16145972010-11-01 14:28:48 +0000927
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000928 if (Used)
929 return true;
930
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000931 if (Renamed)
932 return false;
933
Rafael Espindola45834a02010-10-29 23:09:31 +0000934 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
935 return true;
936
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000937 if (Symbol.isVariable()) {
938 const MCSymbol *Base = getBaseSymbol(Layout, Symbol);
939 if (Base && Base->isUndefined())
940 return false;
941 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000942
Jan Sjödin30a52de2011-02-28 21:45:04 +0000943 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000944 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000945 return false;
946
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000947 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000948 return false;
949
950 return true;
951}
952
Rafael Espindola39f50422014-04-28 14:24:44 +0000953bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000954 if (Data.isExternal())
955 return false;
956
957 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000958 if (Symbol.isDefined())
959 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000960
Rafael Espindola39f50422014-04-28 14:24:44 +0000961 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000962 return false;
963
964 return true;
965}
966
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000967void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000968 SectionIndexMapTy &SectionIndexMap,
969 const RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000970 unsigned Index = 1;
971 for (MCAssembler::iterator it = Asm.begin(),
972 ie = Asm.end(); it != ie; ++it) {
973 const MCSectionELF &Section =
974 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000975 if (Section.getType() != ELF::SHT_GROUP)
976 continue;
977 SectionIndexMap[&Section] = Index++;
978 }
979
980 for (MCAssembler::iterator it = Asm.begin(),
981 ie = Asm.end(); it != ie; ++it) {
982 const MCSectionELF &Section =
983 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000984 if (Section.getType() == ELF::SHT_GROUP ||
985 Section.getType() == ELF::SHT_REL ||
986 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000987 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000988 SectionIndexMap[&Section] = Index++;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000989 const MCSectionELF *RelSection = RelMap.lookup(&Section);
990 if (RelSection)
991 SectionIndexMap[RelSection] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +0000992 }
993}
994
Rafael Espindola022bb762014-03-24 03:43:21 +0000995void
996ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
997 const SectionIndexMapTy &SectionIndexMap,
998 RevGroupMapTy RevGroupMap,
999 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001000 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +00001001 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001002 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +00001003 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001004 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1005 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1006 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001007 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001008 }
1009
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001010 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +00001011 for (MCSymbolData &SD : Asm.symbols()) {
1012 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001013
Rafael Espindola16145972010-11-01 14:28:48 +00001014 bool Used = UsedInReloc.count(&Symbol);
1015 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001016 bool isSignature = RevGroupMap.count(&Symbol);
1017
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001018 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001019 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001020 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001021 continue;
1022
Matt Fleming6c1ad482010-08-16 18:57:57 +00001023 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001024 MSD.SymbolData = &SD;
Rafael Espindola022bb762014-03-24 03:43:21 +00001025 const MCSymbol *BaseSymbol = getBaseSymbol(Layout, Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001026
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001027 // Undefined symbols are global, but this is the first place we
1028 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001029 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001030 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001031 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001032 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001033 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001034 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001035 }
1036
Rafael Espindola022bb762014-03-24 03:43:21 +00001037 if (!BaseSymbol) {
1038 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001039 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001040 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001041 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001042 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001043 if (isSignature && !Used)
1044 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap[&Symbol]);
1045 else
1046 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001047 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001048 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001049 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001050 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001051 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001052 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001053 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001054 }
1055
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001056 // The @@@ in symbol version is replaced with @ in undefined symbols and
1057 // @@ in defined ones.
1058 StringRef Name = Symbol.getName();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001059 SmallString<32> Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001060 size_t Pos = Name.find("@@@");
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001061 if (Pos != StringRef::npos) {
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001062 Buf += Name.substr(0, Pos);
1063 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1064 Buf += Name.substr(Pos + Skip);
1065 Name = Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001066 }
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001067 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001068
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001069 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1070 UndefinedSymbolData.push_back(MSD);
1071 else if (Local)
1072 LocalSymbolData.push_back(MSD);
1073 else
1074 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001075 }
1076
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001077 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1078 StrTabBuilder.add(*i);
1079
1080 StrTabBuilder.finalize();
1081
1082 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1083 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1084
1085 for (ELFSymbolData& MSD : LocalSymbolData)
1086 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1087 for (ELFSymbolData& MSD : ExternalSymbolData)
1088 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1089 for (ELFSymbolData& MSD : UndefinedSymbolData)
1090 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1091
Matt Fleming6c1ad482010-08-16 18:57:57 +00001092 // Symbols are required to be in lexicographic order.
1093 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1094 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1095 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1096
1097 // Set the symbol indices. Local symbols must come before all other
1098 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001099 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001100 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1101 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001102
1103 Index += NumRegularSections;
1104
Matt Fleming6c1ad482010-08-16 18:57:57 +00001105 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1106 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1107 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1108 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1109}
1110
Rafael Espindola1557fd62011-03-20 18:44:20 +00001111void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1112 MCAsmLayout &Layout,
1113 RelMapTy &RelMap) {
1114 for (MCAssembler::const_iterator it = Asm.begin(),
1115 ie = Asm.end(); it != ie; ++it) {
1116 const MCSectionData &SD = *it;
1117 if (Relocations[&SD].empty())
1118 continue;
1119
Matt Fleming6c1ad482010-08-16 18:57:57 +00001120 MCContext &Ctx = Asm.getContext();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001121 const MCSectionELF &Section =
1122 static_cast<const MCSectionELF&>(SD.getSection());
1123
1124 const StringRef SectionName = Section.getSectionName();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001125 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming6c1ad482010-08-16 18:57:57 +00001126 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001127
1128 unsigned EntrySize;
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001129 if (hasRelocationAddend())
1130 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramerfd054152010-08-17 17:56:13 +00001131 else
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001132 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001133
Tim Northovera630fb02013-07-10 20:58:17 +00001134 unsigned Flags = 0;
1135 StringRef Group = "";
1136 if (Section.getFlags() & ELF::SHF_GROUP) {
David Blaikie1e412ea2013-10-22 20:34:30 +00001137 Flags = ELF::SHF_GROUP;
1138 Group = Section.getGroup()->getName();
Tim Northovera630fb02013-07-10 20:58:17 +00001139 }
1140
Rafael Espindola1557fd62011-03-20 18:44:20 +00001141 const MCSectionELF *RelaSection =
1142 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
Tim Northovera630fb02013-07-10 20:58:17 +00001143 ELF::SHT_RELA : ELF::SHT_REL, Flags,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001144 SectionKind::getReadOnly(),
Tim Northovera630fb02013-07-10 20:58:17 +00001145 EntrySize, Group);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001146 RelMap[&Section] = RelaSection;
1147 Asm.getOrCreateSectionData(*RelaSection);
1148 }
1149}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001150
David Blaikiee06e8012014-04-11 22:11:50 +00001151static SmallVector<char, 128>
1152getUncompressedData(MCAsmLayout &Layout,
1153 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001154 SmallVector<char, 128> UncompressedData;
1155 for (const MCFragment &F : Fragments) {
1156 const SmallVectorImpl<char> *Contents;
1157 switch (F.getKind()) {
1158 case MCFragment::FT_Data:
1159 Contents = &cast<MCDataFragment>(F).getContents();
1160 break;
1161 case MCFragment::FT_Dwarf:
1162 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1163 break;
1164 case MCFragment::FT_DwarfFrame:
1165 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1166 break;
1167 default:
1168 llvm_unreachable(
1169 "Not expecting any other fragment types in a debug_* section");
1170 }
1171 UncompressedData.append(Contents->begin(), Contents->end());
1172 }
1173 return UncompressedData;
1174}
1175
1176// Include the debug info compression header:
1177// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1178// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001179static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001180prependCompressionHeader(uint64_t Size,
1181 SmallVectorImpl<char> &CompressedContents) {
David Blaikie8019bf82014-04-10 21:53:53 +00001182 static const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001183 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1184 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001185 if (sys::IsLittleEndianHost)
1186 Size = sys::SwapByteOrder(Size);
1187 CompressedContents.insert(CompressedContents.begin(),
1188 Magic.size() + sizeof(Size), 0);
1189 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1190 std::copy(reinterpret_cast<char *>(&Size),
1191 reinterpret_cast<char *>(&Size + 1),
1192 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001193 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001194}
1195
1196// Return a single fragment containing the compressed contents of the whole
1197// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001198static std::unique_ptr<MCDataFragment>
1199getCompressedFragment(MCAsmLayout &Layout,
1200 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001201 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1202
1203 // Gather the uncompressed data from all the fragments, recording the
1204 // alignment fragment, if seen, and any fixups.
1205 SmallVector<char, 128> UncompressedData =
1206 getUncompressedData(Layout, Fragments);
1207
1208 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1209
1210 zlib::Status Success = zlib::compress(
1211 StringRef(UncompressedData.data(), UncompressedData.size()),
1212 CompressedContents);
1213 if (Success != zlib::StatusOK)
1214 return nullptr;
1215
David Blaikie76d3a3c2014-04-18 21:52:26 +00001216 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1217 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001218
1219 return CompressedFragment;
1220}
1221
David Blaikie39fa6a22014-04-25 00:48:01 +00001222typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1223DefiningSymbolMap;
1224
1225static void UpdateSymbols(const MCAsmLayout &Layout,
1226 const std::vector<MCSymbolData *> &Symbols,
1227 MCFragment &NewFragment) {
1228 for (MCSymbolData *Sym : Symbols) {
1229 Sym->setOffset(Sym->getOffset() +
1230 Layout.getFragmentOffset(Sym->getFragment()));
1231 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001232 }
1233}
1234
David Blaikie8019bf82014-04-10 21:53:53 +00001235static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001236 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001237 const MCSectionELF &Section,
1238 MCSectionData &SD) {
1239 StringRef SectionName = Section.getSectionName();
1240 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1241
1242 std::unique_ptr<MCDataFragment> CompressedFragment =
1243 getCompressedFragment(Layout, Fragments);
1244
1245 // Leave the section as-is if the fragments could not be compressed.
1246 if (!CompressedFragment)
1247 return;
1248
David Blaikiec029ab42014-04-18 21:24:12 +00001249 // Update the fragment+offsets of any symbols referring to fragments in this
1250 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001251 auto I = DefiningSymbols.find(&SD);
1252 if (I != DefiningSymbols.end())
1253 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001254
David Blaikie8019bf82014-04-10 21:53:53 +00001255 // Invalidate the layout for the whole section since it will have new and
1256 // different fragments now.
1257 Layout.invalidateFragmentsFrom(&Fragments.front());
1258 Fragments.clear();
1259
1260 // Complete the initialization of the new fragment
1261 CompressedFragment->setParent(&SD);
1262 CompressedFragment->setLayoutOrder(0);
1263 Fragments.push_back(CompressedFragment.release());
1264
1265 // Rename from .debug_* to .zdebug_*
1266 Asm.getContext().renameELFSection(&Section,
1267 (".z" + SectionName.drop_front(1)).str());
1268}
1269
1270void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1271 MCAsmLayout &Layout) {
1272 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1273 return;
1274
David Blaikie39fa6a22014-04-25 00:48:01 +00001275 DefiningSymbolMap DefiningSymbols;
1276
1277 for (MCSymbolData &SD : Asm.symbols())
1278 if (MCFragment *F = SD.getFragment())
1279 DefiningSymbols[F->getParent()].push_back(&SD);
1280
David Blaikie8019bf82014-04-10 21:53:53 +00001281 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001282 const MCSectionELF &Section =
1283 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001284 StringRef SectionName = Section.getSectionName();
1285
1286 // Compressing debug_frame requires handling alignment fragments which is
1287 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1288 // for writing to arbitrary buffers) for little benefit.
1289 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1290 continue;
1291
David Blaikie39fa6a22014-04-25 00:48:01 +00001292 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001293 }
1294}
1295
Rafael Espindola1557fd62011-03-20 18:44:20 +00001296void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1297 const RelMapTy &RelMap) {
1298 for (MCAssembler::const_iterator it = Asm.begin(),
1299 ie = Asm.end(); it != ie; ++it) {
1300 const MCSectionData &SD = *it;
1301 const MCSectionELF &Section =
1302 static_cast<const MCSectionELF&>(SD.getSection());
1303
1304 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1305 if (!RelaSection)
1306 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001307 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001308 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001309
1310 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001311 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001312 }
1313}
1314
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001315void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1316 uint64_t Flags, uint64_t Address,
1317 uint64_t Offset, uint64_t Size,
1318 uint32_t Link, uint32_t Info,
1319 uint64_t Alignment,
1320 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001321 Write32(Name); // sh_name: index into string table
1322 Write32(Type); // sh_type
1323 WriteWord(Flags); // sh_flags
1324 WriteWord(Address); // sh_addr
1325 WriteWord(Offset); // sh_offset
1326 WriteWord(Size); // sh_size
1327 Write32(Link); // sh_link
1328 Write32(Info); // sh_info
1329 WriteWord(Alignment); // sh_addralign
1330 WriteWord(EntrySize); // sh_entsize
1331}
1332
Rafael Espindola5904e122014-03-29 06:26:49 +00001333// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1334// just to match gnu as for easier comparison. The use type is an arbitrary way
1335// of making the sort deterministic.
1336static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1337 const ELFRelocationEntry &A = *AP;
1338 const ELFRelocationEntry &B = *BP;
1339 if (A.Offset != B.Offset)
1340 return B.Offset - A.Offset;
1341 if (B.Type != A.Type)
1342 return A.Type - B.Type;
1343 llvm_unreachable("ELFRelocs might be unstable!");
1344}
1345
1346static void sortRelocs(const MCAssembler &Asm,
1347 std::vector<ELFRelocationEntry> &Relocs) {
1348 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1349}
1350
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001351void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1352 MCDataFragment *F,
1353 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001354 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001355
Rafael Espindola5904e122014-03-29 06:26:49 +00001356 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001357
1358 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001359 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001360
Rafael Espindola5904e122014-03-29 06:26:49 +00001361 unsigned Index;
1362 if (Entry.UseSymbol) {
1363 Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1364 } else {
1365 const MCSectionData *Sec = Entry.Section;
1366 if (Sec)
1367 Index = Sec->getOrdinal() + FileSymbolData.size() +
1368 LocalSymbolData.size() + 1;
1369 else
1370 Index = 0;
1371 }
1372
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001373 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001374 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001375 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001376 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001377
Rafael Espindola5904e122014-03-29 06:26:49 +00001378 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1379 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1380 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1381 write(*F, TargetObjectWriter->getRType(Entry.Type));
1382 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001383 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001384 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001385 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001386 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001387 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001388 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001389 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001390 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001391
Rafael Espindolabce26a12010-10-05 15:11:03 +00001392 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001393 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001394 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001395
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001396 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001397 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001398 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001399 }
1400}
1401
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001402void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1403 MCAsmLayout &Layout,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001404 SectionIndexMapTy &SectionIndexMap,
1405 const RelMapTy &RelMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001406 MCContext &Ctx = Asm.getContext();
1407 MCDataFragment *F;
1408
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001409 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001410
Rafael Espindola0e527b72010-09-22 19:04:41 +00001411 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001412 const MCSectionELF *ShstrtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001413 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001414 SectionKind::getReadOnly());
Rafael Espindola44bf2662010-09-16 19:46:31 +00001415 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1416 ShstrtabSD.setAlignment(1);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001417
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001418 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001419 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1420 SectionKind::getReadOnly(),
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001421 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001422 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001423 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001424
Rafael Espindola1557fd62011-03-20 18:44:20 +00001425 const MCSectionELF *StrtabSection;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001426 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001427 SectionKind::getReadOnly());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001428 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1429 StrtabSD.setAlignment(1);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001430
Rafael Espindola1557fd62011-03-20 18:44:20 +00001431 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1432
1433 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1434 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1435 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001436
1437 // Symbol table
1438 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001439 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001440
Matt Fleming6c1ad482010-08-16 18:57:57 +00001441 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001442 F->getContents().append(StrTabBuilder.data().begin(),
1443 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001444
Matt Fleming6c1ad482010-08-16 18:57:57 +00001445 F = new MCDataFragment(&ShstrtabSD);
1446
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001447 // Section header string table.
1448 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001449 const MCSectionELF &Section =
1450 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001451 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001452 }
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001453 ShStrTabBuilder.finalize();
1454 F->getContents().append(ShStrTabBuilder.data().begin(),
1455 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001456}
1457
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001458void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1459 MCAsmLayout &Layout,
1460 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001461 RevGroupMapTy &RevGroupMap,
1462 SectionIndexMapTy &SectionIndexMap,
1463 const RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001464 // Create the .note.GNU-stack section if needed.
1465 MCContext &Ctx = Asm.getContext();
1466 if (Asm.getNoExecStack()) {
1467 const MCSectionELF *GnuStackSection =
1468 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1469 SectionKind::getReadOnly());
1470 Asm.getOrCreateSectionData(*GnuStackSection);
1471 }
1472
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001473 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001474 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1475 it != ie; ++it) {
1476 const MCSectionELF &Section =
1477 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001478 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001479 continue;
1480
1481 const MCSymbol *SignatureSymbol = Section.getGroup();
1482 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001483 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001484 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001485 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001486 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1487 Data.setAlignment(4);
1488 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001489 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001490 }
1491 GroupMap[Group] = SignatureSymbol;
1492 }
1493
Rafael Espindola1557fd62011-03-20 18:44:20 +00001494 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1495
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001496 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001497 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001498 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001499 const MCSectionELF &Section =
1500 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001501 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001502 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001503 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001504 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1505 // FIXME: we could use the previous fragment
1506 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001507 uint32_t Index = SectionIndexMap.lookup(&Section);
1508 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001509 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001510}
1511
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001512void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1513 const SectionIndexMapTy &SectionIndexMap,
1514 uint32_t GroupSymbolIndex,
1515 uint64_t Offset, uint64_t Size,
1516 uint64_t Alignment,
1517 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001518 uint64_t sh_link = 0;
1519 uint64_t sh_info = 0;
1520
1521 switch(Section.getType()) {
1522 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001523 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001524 sh_info = 0;
1525 break;
1526
1527 case ELF::SHT_REL:
1528 case ELF::SHT_RELA: {
1529 const MCSectionELF *SymtabSection;
1530 const MCSectionELF *InfoSection;
1531 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1532 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001533 SectionKind::getReadOnly());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001534 sh_link = SectionIndexMap.lookup(SymtabSection);
1535 assert(sh_link && ".symtab not found");
1536
1537 // Remove ".rel" and ".rela" prefixes.
1538 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1539 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
David Blaikie15b25df2013-10-22 23:41:52 +00001540 StringRef GroupName =
1541 Section.getGroup() ? Section.getGroup()->getName() : "";
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001542
David Blaikie15b25df2013-10-22 23:41:52 +00001543 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1544 0, SectionKind::getReadOnly(),
1545 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001546 sh_info = SectionIndexMap.lookup(InfoSection);
1547 break;
1548 }
1549
1550 case ELF::SHT_SYMTAB:
1551 case ELF::SHT_DYNSYM:
1552 sh_link = StringTableIndex;
1553 sh_info = LastLocalSymbolIndex;
1554 break;
1555
1556 case ELF::SHT_SYMTAB_SHNDX:
1557 sh_link = SymbolTableIndex;
1558 break;
1559
1560 case ELF::SHT_PROGBITS:
1561 case ELF::SHT_STRTAB:
1562 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001563 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001564 case ELF::SHT_NULL:
1565 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001566 case ELF::SHT_INIT_ARRAY:
1567 case ELF::SHT_FINI_ARRAY:
1568 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001569 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001570 case ELF::SHT_MIPS_REGINFO:
1571 case ELF::SHT_MIPS_OPTIONS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001572 // Nothing to do.
1573 break;
1574
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001575 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001576 sh_link = SymbolTableIndex;
1577 sh_info = GroupSymbolIndex;
1578 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001579
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001580 default:
1581 assert(0 && "FIXME: sh_type value not supported!");
1582 break;
1583 }
1584
Logan Chien4b724422013-02-05 14:18:59 +00001585 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1586 Section.getType() == ELF::SHT_ARM_EXIDX) {
1587 StringRef SecName(Section.getSectionName());
1588 if (SecName == ".ARM.exidx") {
1589 sh_link = SectionIndexMap.lookup(
1590 Asm.getContext().getELFSection(".text",
1591 ELF::SHT_PROGBITS,
1592 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1593 SectionKind::getText()));
1594 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001595 StringRef GroupName =
1596 Section.getGroup() ? Section.getGroup()->getName() : "";
1597 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1598 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1599 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1600 GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001601 }
1602 }
1603
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001604 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1605 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001606 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1607 Alignment, Section.getEntrySize());
1608}
1609
Jan Sjödin30a52de2011-02-28 21:45:04 +00001610bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001611 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001612 !SD.getSection().isVirtualSection();
1613}
1614
Jan Sjödin30a52de2011-02-28 21:45:04 +00001615uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001616 uint64_t Ret = 0;
1617 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1618 ++i) {
1619 const MCFragment &F = *i;
1620 assert(F.getKind() == MCFragment::FT_Data);
1621 Ret += cast<MCDataFragment>(F).getContents().size();
1622 }
1623 return Ret;
1624}
1625
Jan Sjödin30a52de2011-02-28 21:45:04 +00001626uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1627 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001628 if (IsELFMetaDataSection(SD))
1629 return DataSectionSize(SD);
1630 return Layout.getSectionFileSize(&SD);
1631}
1632
Jan Sjödin30a52de2011-02-28 21:45:04 +00001633uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1634 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001635 if (IsELFMetaDataSection(SD))
1636 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001637 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001638}
1639
Rafael Espindola1557fd62011-03-20 18:44:20 +00001640void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1641 const MCAsmLayout &Layout,
1642 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001643 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1644
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001645 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001646 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001647
1648 if (IsELFMetaDataSection(SD)) {
1649 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1650 ++i) {
1651 const MCFragment &F = *i;
1652 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001653 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001654 }
1655 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001656 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001657 }
1658}
1659
Rafael Espindola1557fd62011-03-20 18:44:20 +00001660void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1661 const GroupMapTy &GroupMap,
1662 const MCAsmLayout &Layout,
1663 const SectionIndexMapTy &SectionIndexMap,
1664 const SectionOffsetMapTy &SectionOffsetMap) {
1665 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001666
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001667 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001668 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001669
1670 for (SectionIndexMapTy::const_iterator i=
1671 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1672 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001673 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001674 }
1675
Matt Fleming6c1ad482010-08-16 18:57:57 +00001676 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001677 uint64_t FirstSectionSize =
1678 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1679 uint32_t FirstSectionLink =
1680 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1681 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001682
Rafael Espindola1557fd62011-03-20 18:44:20 +00001683 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001684 const MCSectionELF &Section = *Sections[i];
1685 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1686 uint32_t GroupSymbolIndex;
1687 if (Section.getType() != ELF::SHT_GROUP)
1688 GroupSymbolIndex = 0;
1689 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001690 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1691 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001692
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001693 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001694
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001695 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001696 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001697 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001698 }
1699}
1700
Rafael Espindola1557fd62011-03-20 18:44:20 +00001701void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1702 std::vector<const MCSectionELF*> &Sections) {
1703 for (MCAssembler::iterator it = Asm.begin(),
1704 ie = Asm.end(); it != ie; ++it) {
1705 const MCSectionELF &Section =
1706 static_cast<const MCSectionELF &>(it->getSection());
1707 if (Section.getType() == ELF::SHT_GROUP)
1708 Sections.push_back(&Section);
1709 }
1710
1711 for (MCAssembler::iterator it = Asm.begin(),
1712 ie = Asm.end(); it != ie; ++it) {
1713 const MCSectionELF &Section =
1714 static_cast<const MCSectionELF &>(it->getSection());
1715 if (Section.getType() != ELF::SHT_GROUP &&
1716 Section.getType() != ELF::SHT_REL &&
1717 Section.getType() != ELF::SHT_RELA)
1718 Sections.push_back(&Section);
1719 }
1720
1721 for (MCAssembler::iterator it = Asm.begin(),
1722 ie = Asm.end(); it != ie; ++it) {
1723 const MCSectionELF &Section =
1724 static_cast<const MCSectionELF &>(it->getSection());
1725 if (Section.getType() == ELF::SHT_REL ||
1726 Section.getType() == ELF::SHT_RELA)
1727 Sections.push_back(&Section);
1728 }
1729}
1730
1731void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1732 const MCAsmLayout &Layout) {
1733 GroupMapTy GroupMap;
1734 RevGroupMapTy RevGroupMap;
1735 SectionIndexMapTy SectionIndexMap;
1736
1737 unsigned NumUserSections = Asm.size();
1738
David Blaikiee06e8012014-04-11 22:11:50 +00001739 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001740
Rafael Espindola1557fd62011-03-20 18:44:20 +00001741 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1742 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1743
1744 const unsigned NumUserAndRelocSections = Asm.size();
1745 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1746 RevGroupMap, SectionIndexMap, RelMap);
1747 const unsigned AllSections = Asm.size();
1748 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1749
1750 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1751
1752 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001753 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1754 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001755
1756 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1757
1758 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1759 const_cast<MCAsmLayout&>(Layout),
1760 SectionIndexMap,
1761 RelMap);
1762
1763 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1764 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1765 sizeof(ELF::Elf32_Ehdr);
1766 uint64_t FileOff = HeaderSize;
1767
1768 std::vector<const MCSectionELF*> Sections;
1769 ComputeSectionOrder(Asm, Sections);
1770 unsigned NumSections = Sections.size();
1771 SectionOffsetMapTy SectionOffsetMap;
1772 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1773 const MCSectionELF &Section = *Sections[i];
1774 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1775
1776 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1777
1778 // Remember the offset into the file for this section.
1779 SectionOffsetMap[&Section] = FileOff;
1780
1781 // Get the size of the section in the output file (including padding).
1782 FileOff += GetSectionFileSize(Layout, SD);
1783 }
1784
1785 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1786
1787 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1788
1789 uint64_t SectionHeaderEntrySize = is64Bit() ?
1790 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1791 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1792
1793 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1794 const MCSectionELF &Section = *Sections[i];
1795 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1796
1797 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1798
1799 // Remember the offset into the file for this section.
1800 SectionOffsetMap[&Section] = FileOff;
1801
1802 // Get the size of the section in the output file (including padding).
1803 FileOff += GetSectionFileSize(Layout, SD);
1804 }
1805
1806 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001807 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001808
1809 // ... then the regular sections ...
1810 // + because of .shstrtab
1811 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1812 WriteDataSectionData(Asm, Layout, *Sections[i]);
1813
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001814 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001815 WriteZeros(Padding);
1816
1817 // ... then the section header table ...
1818 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1819 SectionOffsetMap);
1820
Nick Lewycky4eb11432011-10-07 20:56:23 +00001821 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001822 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1823 WriteDataSectionData(Asm, Layout, *Sections[i]);
1824}
1825
Eli Friedmand92d17b2011-03-03 07:24:36 +00001826bool
1827ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1828 const MCSymbolData &DataA,
1829 const MCFragment &FB,
1830 bool InSet,
1831 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001832 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001833 return false;
1834 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1835 Asm, DataA, FB,InSet, IsPCRel);
1836}
1837
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001838MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1839 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001840 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001841 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001842}