blob: efc9cbdd89adcb9c9967680236fa284333ea554d [file] [log] [blame]
Nick Lewycky4288f9e2013-03-09 09:32:16 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
Matt Fleming6c1ad482010-08-16 18:57:57 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements ELF object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/MC/MCELFObjectWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallString.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000018#include "llvm/ADT/StringMap.h"
Evan Cheng5928e692011-07-25 23:24:55 +000019#include "llvm/MC/MCAsmBackend.h"
David Blaikie8019bf82014-04-10 21:53:53 +000020#include "llvm/MC/MCAsmInfo.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000021#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000022#include "llvm/MC/MCAssembler.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000023#include "llvm/MC/MCContext.h"
Tim Northover5cc3dc82012-12-07 16:50:23 +000024#include "llvm/MC/MCELF.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000025#include "llvm/MC/MCELFSymbolFlags.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000026#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000027#include "llvm/MC/MCFixupKindInfo.h"
28#include "llvm/MC/MCObjectWriter.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000029#include "llvm/MC/MCSectionELF.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000030#include "llvm/MC/MCValue.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000031#include "llvm/MC/StringTableBuilder.h"
David Blaikie8019bf82014-04-10 21:53:53 +000032#include "llvm/Support/Compression.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000033#include "llvm/Support/Debug.h"
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,
Benjamin Kramer04f9da82014-09-19 12:26:38 +0000249 const RevGroupMapTy &RevGroupMap,
Rafael Espindola29abd972011-12-22 03:38:00 +0000250 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 Espindola10be0832014-03-25 23:44:25 +0000579void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000580 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000581 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000582 assert((!OrigData.getFragment() ||
583 (&OrigData.getFragment()->getParent()->getSection() ==
584 &OrigData.getSymbol().getSection())) &&
585 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000586 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000587
588 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
589 // SHN_COMMON.
590 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000591
Jack Carter2f8d9d92013-02-19 21:57:35 +0000592 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000593 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000594 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000595 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000596 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000597 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
598 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000599 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000600 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000601
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000602 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000603 // 2 bits
604 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000605 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000606 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000607
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000608 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000609 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000610
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000611 const MCExpr *ESize = OrigData.getSize();
612 if (!ESize && Base)
613 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000614
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000615 if (ESize) {
616 int64_t Res;
617 if (!ESize->EvaluateAsAbsolute(Res, Layout))
618 report_fatal_error("Size expression must be absolute.");
619 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000620 }
621
622 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000623 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
624 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000625}
626
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000627void ELFObjectWriter::WriteSymbolTable(MCDataFragment *SymtabF,
Rafael Espindola10be0832014-03-25 23:44:25 +0000628 MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000629 const MCAsmLayout &Layout,
Rafael Espindola10be0832014-03-25 23:44:25 +0000630 SectionIndexMapTy &SectionIndexMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000631 // The string table must be emitted first because we need the index
632 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000633
634 // FIXME: Make sure the start of the symbol table is aligned.
635
Rafael Espindola10be0832014-03-25 23:44:25 +0000636 SymbolTableWriter Writer(Asm, FWriter, is64Bit(), SectionIndexMap, SymtabF);
637
Matt Fleming6c1ad482010-08-16 18:57:57 +0000638 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000639 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000640
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000641 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000642 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
643 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000644 }
645
Matt Fleming6c1ad482010-08-16 18:57:57 +0000646 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000647 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
648
Matt Fleming6c1ad482010-08-16 18:57:57 +0000649 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
650 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000651 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000652 }
653
Rafael Espindola44bf2662010-09-16 19:46:31 +0000654 // Write out a symbol table entry for each regular section.
Rafael Espindola18014102010-11-10 22:16:43 +0000655 for (MCAssembler::const_iterator i = Asm.begin(), e = Asm.end(); i != e;
656 ++i) {
Eli Friedman1fe0d532010-08-16 21:17:09 +0000657 const MCSectionELF &Section =
Rafael Espindola18014102010-11-10 22:16:43 +0000658 static_cast<const MCSectionELF&>(i->getSection());
659 if (Section.getType() == ELF::SHT_RELA ||
660 Section.getType() == ELF::SHT_REL ||
661 Section.getType() == ELF::SHT_STRTAB ||
Nick Lewycky133a1682011-10-07 23:29:53 +0000662 Section.getType() == ELF::SHT_SYMTAB ||
663 Section.getType() == ELF::SHT_SYMTAB_SHNDX)
Eli Friedman1fe0d532010-08-16 21:17:09 +0000664 continue;
Rafael Espindola10be0832014-03-25 23:44:25 +0000665 Writer.writeSymbol(0, ELF::STT_SECTION, 0, 0, ELF::STV_DEFAULT,
666 SectionIndexMap.lookup(&Section), false);
Eli Friedman1fe0d532010-08-16 21:17:09 +0000667 LastLocalSymbolIndex++;
668 }
Matt Fleming6c1ad482010-08-16 18:57:57 +0000669
670 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
671 ELFSymbolData &MSD = ExternalSymbolData[i];
672 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000673 assert(((Data.getFlags() & ELF_STB_Global) ||
674 (Data.getFlags() & ELF_STB_Weak)) &&
675 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000676 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000677 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000678 LastLocalSymbolIndex++;
679 }
680
681 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
682 ELFSymbolData &MSD = UndefinedSymbolData[i];
683 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000684 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000685 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000686 LastLocalSymbolIndex++;
687 }
688}
689
Rafael Espindola5904e122014-03-29 06:26:49 +0000690// It is always valid to create a relocation with a symbol. It is preferable
691// to use a relocation with a section if that is possible. Using the section
692// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000693bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
694 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000695 const MCSymbolData *SD,
696 uint64_t C,
697 unsigned Type) const {
698 // A PCRel relocation to an absolute value has no symbol (or section). We
699 // represent that with a relocation to a null section.
700 if (!RefA)
701 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000702
Rafael Espindola5904e122014-03-29 06:26:49 +0000703 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
704 switch (Kind) {
705 default:
706 break;
707 // The .odp creation emits a relocation against the symbol ".TOC." which
708 // create a R_PPC64_TOC relocation. However the relocation symbol name
709 // in final object creation should be NULL, since the symbol does not
710 // really exist, it is just the reference to TOC base for the current
711 // object file. Since the symbol is undefined, returning false results
712 // in a relocation with a null section which is the desired result.
713 case MCSymbolRefExpr::VK_PPC_TOCBASE:
714 return false;
715
716 // These VariantKind cause the relocation to refer to something other than
717 // the symbol itself, like a linker generated table. Since the address of
718 // symbol is not relevant, we cannot replace the symbol with the
719 // section and patch the difference in the addend.
720 case MCSymbolRefExpr::VK_GOT:
721 case MCSymbolRefExpr::VK_PLT:
722 case MCSymbolRefExpr::VK_GOTPCREL:
723 case MCSymbolRefExpr::VK_Mips_GOT:
724 case MCSymbolRefExpr::VK_PPC_GOT_LO:
725 case MCSymbolRefExpr::VK_PPC_GOT_HI:
726 case MCSymbolRefExpr::VK_PPC_GOT_HA:
727 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000728 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000729
Rafael Espindola5904e122014-03-29 06:26:49 +0000730 // An undefined symbol is not in any section, so the relocation has to point
731 // to the symbol itself.
732 const MCSymbol &Sym = SD->getSymbol();
733 if (Sym.isUndefined())
734 return true;
735
736 unsigned Binding = MCELF::GetBinding(*SD);
737 switch(Binding) {
738 default:
739 llvm_unreachable("Invalid Binding");
740 case ELF::STB_LOCAL:
741 break;
742 case ELF::STB_WEAK:
743 // If the symbol is weak, it might be overridden by a symbol in another
744 // file. The relocation has to point to the symbol so that the linker
745 // can update it.
746 return true;
747 case ELF::STB_GLOBAL:
748 // Global ELF symbols can be preempted by the dynamic linker. The relocation
749 // has to point to the symbol for a reason analogous to the STB_WEAK case.
750 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000751 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000752
Rafael Espindola5904e122014-03-29 06:26:49 +0000753 // If a relocation points to a mergeable section, we have to be careful.
754 // If the offset is zero, a relocation with the section will encode the
755 // same information. With a non-zero offset, the situation is different.
756 // For example, a relocation can point 42 bytes past the end of a string.
757 // If we change such a relocation to use the section, the linker would think
758 // that it pointed to another string and subtracting 42 at runtime will
759 // produce the wrong value.
760 auto &Sec = cast<MCSectionELF>(Sym.getSection());
761 unsigned Flags = Sec.getFlags();
762 if (Flags & ELF::SHF_MERGE) {
763 if (C != 0)
764 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000765
766 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
767 // only handle section relocations to mergeable sections if using RELA.
768 if (!hasRelocationAddend())
769 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000770 }
771
Rafael Espindola5904e122014-03-29 06:26:49 +0000772 // Most TLS relocations use a got, so they need the symbol. Even those that
773 // are just an offset (@tpoff), require a symbol in some linkers (gold,
774 // but not bfd ld).
775 if (Flags & ELF::SHF_TLS)
776 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000777
Rafael Espindola9ef84412014-04-11 19:18:01 +0000778 // If the symbol is a thumb function the final relocation must set the lowest
779 // bit. With a symbol that is done by just having the symbol have that bit
780 // set, so we would lose the bit if we relocated with the section.
781 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000782 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000783 return true;
784
Ulrich Weigand46797c62014-07-20 23:15:06 +0000785 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000786 return true;
787 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000788}
789
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000790static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
791 const MCSymbol &Sym = Ref.getSymbol();
792
793 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
794 return &Sym;
795
796 if (!Sym.isVariable())
797 return nullptr;
798
799 const MCExpr *Expr = Sym.getVariableValue();
800 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
801 if (!Inner)
802 return nullptr;
803
804 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
805 return &Inner->getSymbol();
806 return nullptr;
807}
808
Jason W Kim495c2bb2010-12-06 21:57:34 +0000809void ELFObjectWriter::RecordRelocation(const MCAssembler &Asm,
810 const MCAsmLayout &Layout,
811 const MCFragment *Fragment,
812 const MCFixup &Fixup,
813 MCValue Target,
Rafael Espindola5904e122014-03-29 06:26:49 +0000814 bool &IsPCRel,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000815 uint64_t &FixedValue) {
Rafael Espindola5904e122014-03-29 06:26:49 +0000816 const MCSectionData *FixupSection = Fragment->getParent();
817 uint64_t C = Target.getConstant();
818 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000819
Rafael Espindola5904e122014-03-29 06:26:49 +0000820 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
821 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
822 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000823
Rafael Espindola5904e122014-03-29 06:26:49 +0000824 // Let A, B and C being the components of Target and R be the location of
825 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
826 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000827
Rafael Espindola5904e122014-03-29 06:26:49 +0000828 // In general, ELF has no relocations for -B. It can only represent (A + C)
829 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
830 // replace B to implement it: (A - R - K + C)
831 if (IsPCRel)
832 Asm.getContext().FatalError(
833 Fixup.getLoc(),
834 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000835
Rafael Espindola5904e122014-03-29 06:26:49 +0000836 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000837
Rafael Espindola5904e122014-03-29 06:26:49 +0000838 if (SymB.isUndefined())
839 Asm.getContext().FatalError(
840 Fixup.getLoc(),
841 Twine("symbol '") + SymB.getName() +
842 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000843
Rafael Espindola5904e122014-03-29 06:26:49 +0000844 assert(!SymB.isAbsolute() && "Should have been folded");
845 const MCSection &SecB = SymB.getSection();
846 if (&SecB != &FixupSection->getSection())
847 Asm.getContext().FatalError(
848 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000849
Rafael Espindola5904e122014-03-29 06:26:49 +0000850 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
851 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
852 uint64_t K = SymBOffset - FixupOffset;
853 IsPCRel = true;
854 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000855 }
856
Rafael Espindola5904e122014-03-29 06:26:49 +0000857 // We either rejected the fixup or folded B into C at this point.
858 const MCSymbolRefExpr *RefA = Target.getSymA();
859 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
860 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
861
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000862 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000863 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000864 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
865 C += Layout.getSymbolOffset(SymAD);
866
867 uint64_t Addend = 0;
868 if (hasRelocationAddend()) {
869 Addend = C;
870 C = 0;
871 }
872
873 FixedValue = C;
874
875 // FIXME: What is this!?!?
876 MCSymbolRefExpr::VariantKind Modifier =
877 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000878 if (RelocNeedsGOT(Modifier))
879 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000880
Rafael Espindola5904e122014-03-29 06:26:49 +0000881 if (!RelocateWithSymbol) {
882 const MCSection *SecA =
883 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
884 const MCSectionData *SecAD = SecA ? &Asm.getSectionData(*SecA) : nullptr;
885 ELFRelocationEntry Rec(FixupOffset, SecAD, Type, Addend);
886 Relocations[FixupSection].push_back(Rec);
887 return;
888 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000889
Rafael Espindola5904e122014-03-29 06:26:49 +0000890 if (SymA) {
891 if (const MCSymbol *R = Renames.lookup(SymA))
892 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000893
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000894 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
895 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000896 else
897 UsedInReloc.insert(SymA);
898 }
899 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
900 Relocations[FixupSection].push_back(Rec);
901 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000902}
903
904
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000905uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000906ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
907 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000908 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000909 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000910}
911
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000912bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
913 const MCSymbolData &Data, bool Used,
914 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000915 const MCSymbol &Symbol = Data.getSymbol();
916 if (Symbol.isVariable()) {
917 const MCExpr *Expr = Symbol.getVariableValue();
918 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
919 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
920 return false;
921 }
922 }
Rafael Espindola16145972010-11-01 14:28:48 +0000923
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000924 if (Used)
925 return true;
926
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000927 if (Renamed)
928 return false;
929
Rafael Espindola45834a02010-10-29 23:09:31 +0000930 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
931 return true;
932
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000933 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000934 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000935 if (Base && Base->isUndefined())
936 return false;
937 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000938
Jan Sjödin30a52de2011-02-28 21:45:04 +0000939 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000940 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000941 return false;
942
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000943 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000944 return false;
945
946 return true;
947}
948
Rafael Espindola39f50422014-04-28 14:24:44 +0000949bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000950 if (Data.isExternal())
951 return false;
952
953 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000954 if (Symbol.isDefined())
955 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000956
Rafael Espindola39f50422014-04-28 14:24:44 +0000957 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000958 return false;
959
960 return true;
961}
962
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000963void ELFObjectWriter::ComputeIndexMap(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +0000964 SectionIndexMapTy &SectionIndexMap,
965 const RelMapTy &RelMap) {
Rafael Espindolad6340032010-11-10 21:51:05 +0000966 unsigned Index = 1;
967 for (MCAssembler::iterator it = Asm.begin(),
968 ie = Asm.end(); it != ie; ++it) {
969 const MCSectionELF &Section =
970 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000971 if (Section.getType() != ELF::SHT_GROUP)
972 continue;
973 SectionIndexMap[&Section] = Index++;
974 }
975
976 for (MCAssembler::iterator it = Asm.begin(),
977 ie = Asm.end(); it != ie; ++it) {
978 const MCSectionELF &Section =
979 static_cast<const MCSectionELF &>(it->getSection());
Rafael Espindola1557fd62011-03-20 18:44:20 +0000980 if (Section.getType() == ELF::SHT_GROUP ||
981 Section.getType() == ELF::SHT_REL ||
982 Section.getType() == ELF::SHT_RELA)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000983 continue;
Rafael Espindolad6340032010-11-10 21:51:05 +0000984 SectionIndexMap[&Section] = Index++;
Rafael Espindola1557fd62011-03-20 18:44:20 +0000985 const MCSectionELF *RelSection = RelMap.lookup(&Section);
986 if (RelSection)
987 SectionIndexMap[RelSection] = Index++;
Rafael Espindolad6340032010-11-10 21:51:05 +0000988 }
989}
990
Rafael Espindola022bb762014-03-24 03:43:21 +0000991void
992ELFObjectWriter::computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
993 const SectionIndexMapTy &SectionIndexMap,
Benjamin Kramer04f9da82014-09-19 12:26:38 +0000994 const RevGroupMapTy &RevGroupMap,
Rafael Espindola022bb762014-03-24 03:43:21 +0000995 unsigned NumRegularSections) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000996 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000997 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000998 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000999 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001000 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
1001 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
1002 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001003 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +00001004 }
1005
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001006 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +00001007 for (MCSymbolData &SD : Asm.symbols()) {
1008 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001009
Rafael Espindola16145972010-11-01 14:28:48 +00001010 bool Used = UsedInReloc.count(&Symbol);
1011 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001012 bool isSignature = RevGroupMap.count(&Symbol);
1013
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001014 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001015 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001016 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001017 continue;
1018
Matt Fleming6c1ad482010-08-16 18:57:57 +00001019 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001020 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001021 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001022
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001023 // Undefined symbols are global, but this is the first place we
1024 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001025 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001026 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001027 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001028 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001029 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001030 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001031 }
1032
Rafael Espindola022bb762014-03-24 03:43:21 +00001033 if (!BaseSymbol) {
1034 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001035 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001036 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001037 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001038 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001039 if (isSignature && !Used)
Benjamin Kramer04f9da82014-09-19 12:26:38 +00001040 MSD.SectionIndex = SectionIndexMap.lookup(RevGroupMap.lookup(&Symbol));
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001041 else
1042 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001043 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001044 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001045 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001046 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001047 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001048 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001049 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001050 }
1051
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001052 // The @@@ in symbol version is replaced with @ in undefined symbols and
1053 // @@ in defined ones.
1054 StringRef Name = Symbol.getName();
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001055 SmallString<32> Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001056 size_t Pos = Name.find("@@@");
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001057 if (Pos != StringRef::npos) {
Benjamin Kramerdcc77322010-11-12 19:26:04 +00001058 Buf += Name.substr(0, Pos);
1059 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1060 Buf += Name.substr(Pos + Skip);
1061 Name = Buf;
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001062 }
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001063 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001064
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001065 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1066 UndefinedSymbolData.push_back(MSD);
1067 else if (Local)
1068 LocalSymbolData.push_back(MSD);
1069 else
1070 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001071 }
1072
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001073 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1074 StrTabBuilder.add(*i);
1075
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001076 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001077
1078 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1079 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1080
1081 for (ELFSymbolData& MSD : LocalSymbolData)
1082 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1083 for (ELFSymbolData& MSD : ExternalSymbolData)
1084 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1085 for (ELFSymbolData& MSD : UndefinedSymbolData)
1086 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1087
Matt Fleming6c1ad482010-08-16 18:57:57 +00001088 // Symbols are required to be in lexicographic order.
1089 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1090 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1091 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1092
1093 // Set the symbol indices. Local symbols must come before all other
1094 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001095 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001096 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1097 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001098
1099 Index += NumRegularSections;
1100
Matt Fleming6c1ad482010-08-16 18:57:57 +00001101 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1102 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1103 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1104 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1105}
1106
Rafael Espindola1557fd62011-03-20 18:44:20 +00001107void ELFObjectWriter::CreateRelocationSections(MCAssembler &Asm,
1108 MCAsmLayout &Layout,
1109 RelMapTy &RelMap) {
1110 for (MCAssembler::const_iterator it = Asm.begin(),
1111 ie = Asm.end(); it != ie; ++it) {
1112 const MCSectionData &SD = *it;
1113 if (Relocations[&SD].empty())
1114 continue;
1115
Matt Fleming6c1ad482010-08-16 18:57:57 +00001116 MCContext &Ctx = Asm.getContext();
Matt Fleming6c1ad482010-08-16 18:57:57 +00001117 const MCSectionELF &Section =
1118 static_cast<const MCSectionELF&>(SD.getSection());
1119
1120 const StringRef SectionName = Section.getSectionName();
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001121 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
Matt Fleming6c1ad482010-08-16 18:57:57 +00001122 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001123
1124 unsigned EntrySize;
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001125 if (hasRelocationAddend())
1126 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
Benjamin Kramerfd054152010-08-17 17:56:13 +00001127 else
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001128 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001129
Tim Northovera630fb02013-07-10 20:58:17 +00001130 unsigned Flags = 0;
1131 StringRef Group = "";
1132 if (Section.getFlags() & ELF::SHF_GROUP) {
David Blaikie1e412ea2013-10-22 20:34:30 +00001133 Flags = ELF::SHF_GROUP;
1134 Group = Section.getGroup()->getName();
Tim Northovera630fb02013-07-10 20:58:17 +00001135 }
1136
Rafael Espindola1557fd62011-03-20 18:44:20 +00001137 const MCSectionELF *RelaSection =
1138 Ctx.getELFSection(RelaSectionName, hasRelocationAddend() ?
Tim Northovera630fb02013-07-10 20:58:17 +00001139 ELF::SHT_RELA : ELF::SHT_REL, Flags,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001140 SectionKind::getReadOnly(),
Tim Northovera630fb02013-07-10 20:58:17 +00001141 EntrySize, Group);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001142 RelMap[&Section] = RelaSection;
1143 Asm.getOrCreateSectionData(*RelaSection);
1144 }
1145}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001146
David Blaikiee06e8012014-04-11 22:11:50 +00001147static SmallVector<char, 128>
1148getUncompressedData(MCAsmLayout &Layout,
1149 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001150 SmallVector<char, 128> UncompressedData;
1151 for (const MCFragment &F : Fragments) {
1152 const SmallVectorImpl<char> *Contents;
1153 switch (F.getKind()) {
1154 case MCFragment::FT_Data:
1155 Contents = &cast<MCDataFragment>(F).getContents();
1156 break;
1157 case MCFragment::FT_Dwarf:
1158 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1159 break;
1160 case MCFragment::FT_DwarfFrame:
1161 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1162 break;
1163 default:
1164 llvm_unreachable(
1165 "Not expecting any other fragment types in a debug_* section");
1166 }
1167 UncompressedData.append(Contents->begin(), Contents->end());
1168 }
1169 return UncompressedData;
1170}
1171
1172// Include the debug info compression header:
1173// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1174// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001175static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001176prependCompressionHeader(uint64_t Size,
1177 SmallVectorImpl<char> &CompressedContents) {
David Blaikie8019bf82014-04-10 21:53:53 +00001178 static const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001179 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1180 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001181 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001182 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001183 CompressedContents.insert(CompressedContents.begin(),
1184 Magic.size() + sizeof(Size), 0);
1185 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1186 std::copy(reinterpret_cast<char *>(&Size),
1187 reinterpret_cast<char *>(&Size + 1),
1188 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001189 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001190}
1191
1192// Return a single fragment containing the compressed contents of the whole
1193// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001194static std::unique_ptr<MCDataFragment>
1195getCompressedFragment(MCAsmLayout &Layout,
1196 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001197 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1198
1199 // Gather the uncompressed data from all the fragments, recording the
1200 // alignment fragment, if seen, and any fixups.
1201 SmallVector<char, 128> UncompressedData =
1202 getUncompressedData(Layout, Fragments);
1203
1204 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1205
1206 zlib::Status Success = zlib::compress(
1207 StringRef(UncompressedData.data(), UncompressedData.size()),
1208 CompressedContents);
1209 if (Success != zlib::StatusOK)
1210 return nullptr;
1211
David Blaikie76d3a3c2014-04-18 21:52:26 +00001212 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1213 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001214
1215 return CompressedFragment;
1216}
1217
David Blaikie39fa6a22014-04-25 00:48:01 +00001218typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1219DefiningSymbolMap;
1220
1221static void UpdateSymbols(const MCAsmLayout &Layout,
1222 const std::vector<MCSymbolData *> &Symbols,
1223 MCFragment &NewFragment) {
1224 for (MCSymbolData *Sym : Symbols) {
1225 Sym->setOffset(Sym->getOffset() +
1226 Layout.getFragmentOffset(Sym->getFragment()));
1227 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001228 }
1229}
1230
David Blaikie8019bf82014-04-10 21:53:53 +00001231static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001232 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001233 const MCSectionELF &Section,
1234 MCSectionData &SD) {
1235 StringRef SectionName = Section.getSectionName();
1236 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1237
1238 std::unique_ptr<MCDataFragment> CompressedFragment =
1239 getCompressedFragment(Layout, Fragments);
1240
1241 // Leave the section as-is if the fragments could not be compressed.
1242 if (!CompressedFragment)
1243 return;
1244
David Blaikiec029ab42014-04-18 21:24:12 +00001245 // Update the fragment+offsets of any symbols referring to fragments in this
1246 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001247 auto I = DefiningSymbols.find(&SD);
1248 if (I != DefiningSymbols.end())
1249 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001250
David Blaikie8019bf82014-04-10 21:53:53 +00001251 // Invalidate the layout for the whole section since it will have new and
1252 // different fragments now.
1253 Layout.invalidateFragmentsFrom(&Fragments.front());
1254 Fragments.clear();
1255
1256 // Complete the initialization of the new fragment
1257 CompressedFragment->setParent(&SD);
1258 CompressedFragment->setLayoutOrder(0);
1259 Fragments.push_back(CompressedFragment.release());
1260
1261 // Rename from .debug_* to .zdebug_*
1262 Asm.getContext().renameELFSection(&Section,
1263 (".z" + SectionName.drop_front(1)).str());
1264}
1265
1266void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1267 MCAsmLayout &Layout) {
1268 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1269 return;
1270
David Blaikie39fa6a22014-04-25 00:48:01 +00001271 DefiningSymbolMap DefiningSymbols;
1272
1273 for (MCSymbolData &SD : Asm.symbols())
1274 if (MCFragment *F = SD.getFragment())
1275 DefiningSymbols[F->getParent()].push_back(&SD);
1276
David Blaikie8019bf82014-04-10 21:53:53 +00001277 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001278 const MCSectionELF &Section =
1279 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001280 StringRef SectionName = Section.getSectionName();
1281
1282 // Compressing debug_frame requires handling alignment fragments which is
1283 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1284 // for writing to arbitrary buffers) for little benefit.
1285 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1286 continue;
1287
David Blaikie39fa6a22014-04-25 00:48:01 +00001288 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001289 }
1290}
1291
Rafael Espindola1557fd62011-03-20 18:44:20 +00001292void ELFObjectWriter::WriteRelocations(MCAssembler &Asm, MCAsmLayout &Layout,
1293 const RelMapTy &RelMap) {
1294 for (MCAssembler::const_iterator it = Asm.begin(),
1295 ie = Asm.end(); it != ie; ++it) {
1296 const MCSectionData &SD = *it;
1297 const MCSectionELF &Section =
1298 static_cast<const MCSectionELF&>(SD.getSection());
1299
1300 const MCSectionELF *RelaSection = RelMap.lookup(&Section);
1301 if (!RelaSection)
1302 continue;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001303 MCSectionData &RelaSD = Asm.getOrCreateSectionData(*RelaSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001304 RelaSD.setAlignment(is64Bit() ? 8 : 4);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001305
1306 MCDataFragment *F = new MCDataFragment(&RelaSD);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001307 WriteRelocationsFragment(Asm, F, &*it);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001308 }
1309}
1310
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001311void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1312 uint64_t Flags, uint64_t Address,
1313 uint64_t Offset, uint64_t Size,
1314 uint32_t Link, uint32_t Info,
1315 uint64_t Alignment,
1316 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001317 Write32(Name); // sh_name: index into string table
1318 Write32(Type); // sh_type
1319 WriteWord(Flags); // sh_flags
1320 WriteWord(Address); // sh_addr
1321 WriteWord(Offset); // sh_offset
1322 WriteWord(Size); // sh_size
1323 Write32(Link); // sh_link
1324 Write32(Info); // sh_info
1325 WriteWord(Alignment); // sh_addralign
1326 WriteWord(EntrySize); // sh_entsize
1327}
1328
Rafael Espindola5904e122014-03-29 06:26:49 +00001329// ELF doesn't require relocations to be in any order. We sort by the r_offset,
1330// just to match gnu as for easier comparison. The use type is an arbitrary way
1331// of making the sort deterministic.
1332static int cmpRel(const ELFRelocationEntry *AP, const ELFRelocationEntry *BP) {
1333 const ELFRelocationEntry &A = *AP;
1334 const ELFRelocationEntry &B = *BP;
1335 if (A.Offset != B.Offset)
1336 return B.Offset - A.Offset;
1337 if (B.Type != A.Type)
1338 return A.Type - B.Type;
1339 llvm_unreachable("ELFRelocs might be unstable!");
1340}
1341
1342static void sortRelocs(const MCAssembler &Asm,
1343 std::vector<ELFRelocationEntry> &Relocs) {
1344 array_pod_sort(Relocs.begin(), Relocs.end(), cmpRel);
1345}
1346
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001347void ELFObjectWriter::WriteRelocationsFragment(const MCAssembler &Asm,
1348 MCDataFragment *F,
1349 const MCSectionData *SD) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001350 std::vector<ELFRelocationEntry> &Relocs = Relocations[SD];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001351
Rafael Espindola5904e122014-03-29 06:26:49 +00001352 sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001353
1354 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001355 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Matt Fleming6c1ad482010-08-16 18:57:57 +00001356
Rafael Espindola5904e122014-03-29 06:26:49 +00001357 unsigned Index;
1358 if (Entry.UseSymbol) {
1359 Index = getSymbolIndexInSymbolTable(Asm, Entry.Symbol);
1360 } else {
1361 const MCSectionData *Sec = Entry.Section;
1362 if (Sec)
1363 Index = Sec->getOrdinal() + FileSymbolData.size() +
1364 LocalSymbolData.size() + 1;
1365 else
1366 Index = 0;
1367 }
1368
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001369 if (is64Bit()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001370 write(*F, Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001371 if (TargetObjectWriter->isN64()) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001372 write(*F, uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001373
Rafael Espindola5904e122014-03-29 06:26:49 +00001374 write(*F, TargetObjectWriter->getRSsym(Entry.Type));
1375 write(*F, TargetObjectWriter->getRType3(Entry.Type));
1376 write(*F, TargetObjectWriter->getRType2(Entry.Type));
1377 write(*F, TargetObjectWriter->getRType(Entry.Type));
1378 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001379 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001380 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001381 write(*F, ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001382 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001383 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001384 write(*F, Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001385 } else {
Rafael Espindola5904e122014-03-29 06:26:49 +00001386 write(*F, uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001387
Rafael Espindolabce26a12010-10-05 15:11:03 +00001388 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001389 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001390 write(*F, ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001391
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001392 if (hasRelocationAddend())
Rafael Espindola5904e122014-03-29 06:26:49 +00001393 write(*F, uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001394 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001395 }
1396}
1397
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001398void ELFObjectWriter::CreateMetadataSections(MCAssembler &Asm,
1399 MCAsmLayout &Layout,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001400 SectionIndexMapTy &SectionIndexMap,
1401 const RelMapTy &RelMap) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001402 MCContext &Ctx = Asm.getContext();
1403 MCDataFragment *F;
1404
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001405 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001406
Rafael Espindola0e527b72010-09-22 19:04:41 +00001407 // We construct .shstrtab, .symtab and .strtab in this order to match gnu as.
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001408 const MCSectionELF *ShstrtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001409 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001410 SectionKind::getReadOnly());
Rafael Espindola44bf2662010-09-16 19:46:31 +00001411 MCSectionData &ShstrtabSD = Asm.getOrCreateSectionData(*ShstrtabSection);
1412 ShstrtabSD.setAlignment(1);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001413
Rafael Espindola36ef57d2010-11-10 19:05:07 +00001414 const MCSectionELF *SymtabSection =
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001415 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0,
1416 SectionKind::getReadOnly(),
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001417 EntrySize, "");
Matt Fleming6c1ad482010-08-16 18:57:57 +00001418 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001419 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001420
Rafael Espindola1557fd62011-03-20 18:44:20 +00001421 const MCSectionELF *StrtabSection;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001422 StrtabSection = Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001423 SectionKind::getReadOnly());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001424 MCSectionData &StrtabSD = Asm.getOrCreateSectionData(*StrtabSection);
1425 StrtabSD.setAlignment(1);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001426
Rafael Espindola1557fd62011-03-20 18:44:20 +00001427 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1428
1429 ShstrtabIndex = SectionIndexMap.lookup(ShstrtabSection);
1430 SymbolTableIndex = SectionIndexMap.lookup(SymtabSection);
1431 StringTableIndex = SectionIndexMap.lookup(StrtabSection);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001432
1433 // Symbol table
1434 F = new MCDataFragment(&SymtabSD);
Rafael Espindola10be0832014-03-25 23:44:25 +00001435 WriteSymbolTable(F, Asm, Layout, SectionIndexMap);
Rafael Espindola44bf2662010-09-16 19:46:31 +00001436
Matt Fleming6c1ad482010-08-16 18:57:57 +00001437 F = new MCDataFragment(&StrtabSD);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001438 F->getContents().append(StrTabBuilder.data().begin(),
1439 StrTabBuilder.data().end());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001440
Matt Fleming6c1ad482010-08-16 18:57:57 +00001441 F = new MCDataFragment(&ShstrtabSD);
1442
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001443 // Section header string table.
1444 for (auto it = Asm.begin(), ie = Asm.end(); it != ie; ++it) {
Rafael Espindolab80875e2011-04-07 23:21:52 +00001445 const MCSectionELF &Section =
1446 static_cast<const MCSectionELF&>(it->getSection());
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001447 ShStrTabBuilder.add(Section.getSectionName());
Rafael Espindolab80875e2011-04-07 23:21:52 +00001448 }
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001449 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001450 F->getContents().append(ShStrTabBuilder.data().begin(),
1451 ShStrTabBuilder.data().end());
Rafael Espindola2ebaee92010-09-30 02:22:20 +00001452}
1453
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001454void ELFObjectWriter::CreateIndexedSections(MCAssembler &Asm,
1455 MCAsmLayout &Layout,
1456 GroupMapTy &GroupMap,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001457 RevGroupMapTy &RevGroupMap,
1458 SectionIndexMapTy &SectionIndexMap,
1459 const RelMapTy &RelMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001460 // Create the .note.GNU-stack section if needed.
1461 MCContext &Ctx = Asm.getContext();
1462 if (Asm.getNoExecStack()) {
1463 const MCSectionELF *GnuStackSection =
1464 Ctx.getELFSection(".note.GNU-stack", ELF::SHT_PROGBITS, 0,
1465 SectionKind::getReadOnly());
1466 Asm.getOrCreateSectionData(*GnuStackSection);
1467 }
1468
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001469 // Build the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001470 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
1471 it != ie; ++it) {
1472 const MCSectionELF &Section =
1473 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001474 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001475 continue;
1476
1477 const MCSymbol *SignatureSymbol = Section.getGroup();
1478 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001479 const MCSectionELF *&Group = RevGroupMap[SignatureSymbol];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001480 if (!Group) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001481 Group = Ctx.CreateELFGroupSection();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001482 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1483 Data.setAlignment(4);
1484 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001485 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001486 }
1487 GroupMap[Group] = SignatureSymbol;
1488 }
1489
Rafael Espindola1557fd62011-03-20 18:44:20 +00001490 ComputeIndexMap(Asm, SectionIndexMap, RelMap);
1491
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001492 // Add sections to the groups
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001493 for (MCAssembler::const_iterator it = Asm.begin(), ie = Asm.end();
Rafael Espindola1557fd62011-03-20 18:44:20 +00001494 it != ie; ++it) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001495 const MCSectionELF &Section =
1496 static_cast<const MCSectionELF&>(it->getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001497 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001498 continue;
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001499 const MCSectionELF *Group = RevGroupMap[Section.getGroup()];
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001500 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1501 // FIXME: we could use the previous fragment
1502 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001503 uint32_t Index = SectionIndexMap.lookup(&Section);
1504 write(*F, Index);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001505 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001506}
1507
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001508void ELFObjectWriter::WriteSection(MCAssembler &Asm,
1509 const SectionIndexMapTy &SectionIndexMap,
1510 uint32_t GroupSymbolIndex,
1511 uint64_t Offset, uint64_t Size,
1512 uint64_t Alignment,
1513 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001514 uint64_t sh_link = 0;
1515 uint64_t sh_info = 0;
1516
1517 switch(Section.getType()) {
1518 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001519 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001520 sh_info = 0;
1521 break;
1522
1523 case ELF::SHT_REL:
1524 case ELF::SHT_RELA: {
1525 const MCSectionELF *SymtabSection;
1526 const MCSectionELF *InfoSection;
1527 SymtabSection = Asm.getContext().getELFSection(".symtab", ELF::SHT_SYMTAB,
1528 0,
Rafael Espindola19fa3802010-11-11 03:40:25 +00001529 SectionKind::getReadOnly());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001530 sh_link = SectionIndexMap.lookup(SymtabSection);
1531 assert(sh_link && ".symtab not found");
1532
1533 // Remove ".rel" and ".rela" prefixes.
1534 unsigned SecNameLen = (Section.getType() == ELF::SHT_REL) ? 4 : 5;
1535 StringRef SectionName = Section.getSectionName().substr(SecNameLen);
David Blaikie15b25df2013-10-22 23:41:52 +00001536 StringRef GroupName =
1537 Section.getGroup() ? Section.getGroup()->getName() : "";
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001538
David Blaikie15b25df2013-10-22 23:41:52 +00001539 InfoSection = Asm.getContext().getELFSection(SectionName, ELF::SHT_PROGBITS,
1540 0, SectionKind::getReadOnly(),
1541 0, GroupName);
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001542 sh_info = SectionIndexMap.lookup(InfoSection);
1543 break;
1544 }
1545
1546 case ELF::SHT_SYMTAB:
1547 case ELF::SHT_DYNSYM:
1548 sh_link = StringTableIndex;
1549 sh_info = LastLocalSymbolIndex;
1550 break;
1551
1552 case ELF::SHT_SYMTAB_SHNDX:
1553 sh_link = SymbolTableIndex;
1554 break;
1555
1556 case ELF::SHT_PROGBITS:
1557 case ELF::SHT_STRTAB:
1558 case ELF::SHT_NOBITS:
Rafael Espindola9ae2d052010-12-26 21:30:59 +00001559 case ELF::SHT_NOTE:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001560 case ELF::SHT_NULL:
1561 case ELF::SHT_ARM_ATTRIBUTES:
Jason W Kim9c5b65d2011-01-12 00:19:25 +00001562 case ELF::SHT_INIT_ARRAY:
1563 case ELF::SHT_FINI_ARRAY:
1564 case ELF::SHT_PREINIT_ARRAY:
Rafael Espindola4b7b7fb2011-01-23 05:43:40 +00001565 case ELF::SHT_X86_64_UNWIND:
Jack Carterc1b17ed2013-01-18 21:20:38 +00001566 case ELF::SHT_MIPS_REGINFO:
1567 case ELF::SHT_MIPS_OPTIONS:
Vladimir Medicfb8a2a92014-07-08 08:59:22 +00001568 case ELF::SHT_MIPS_ABIFLAGS:
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001569 // Nothing to do.
1570 break;
1571
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001572 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001573 sh_link = SymbolTableIndex;
1574 sh_info = GroupSymbolIndex;
1575 break;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001576
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001577 default:
Craig Topper35b2f752014-06-19 06:10:58 +00001578 llvm_unreachable("FIXME: sh_type value not supported!");
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001579 }
1580
Logan Chien4b724422013-02-05 14:18:59 +00001581 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
1582 Section.getType() == ELF::SHT_ARM_EXIDX) {
1583 StringRef SecName(Section.getSectionName());
1584 if (SecName == ".ARM.exidx") {
1585 sh_link = SectionIndexMap.lookup(
1586 Asm.getContext().getELFSection(".text",
1587 ELF::SHT_PROGBITS,
1588 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC,
1589 SectionKind::getText()));
1590 } else if (SecName.startswith(".ARM.exidx")) {
David Blaikie15b25df2013-10-22 23:41:52 +00001591 StringRef GroupName =
1592 Section.getGroup() ? Section.getGroup()->getName() : "";
1593 sh_link = SectionIndexMap.lookup(Asm.getContext().getELFSection(
1594 SecName.substr(sizeof(".ARM.exidx") - 1), ELF::SHT_PROGBITS,
1595 ELF::SHF_EXECINSTR | ELF::SHF_ALLOC, SectionKind::getText(), 0,
1596 GroupName));
Logan Chien4b724422013-02-05 14:18:59 +00001597 }
1598 }
1599
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001600 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1601 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001602 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1603 Alignment, Section.getEntrySize());
1604}
1605
Jan Sjödin30a52de2011-02-28 21:45:04 +00001606bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001607 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001608 !SD.getSection().isVirtualSection();
1609}
1610
Jan Sjödin30a52de2011-02-28 21:45:04 +00001611uint64_t ELFObjectWriter::DataSectionSize(const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001612 uint64_t Ret = 0;
1613 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1614 ++i) {
1615 const MCFragment &F = *i;
1616 assert(F.getKind() == MCFragment::FT_Data);
1617 Ret += cast<MCDataFragment>(F).getContents().size();
1618 }
1619 return Ret;
1620}
1621
Jan Sjödin30a52de2011-02-28 21:45:04 +00001622uint64_t ELFObjectWriter::GetSectionFileSize(const MCAsmLayout &Layout,
1623 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001624 if (IsELFMetaDataSection(SD))
1625 return DataSectionSize(SD);
1626 return Layout.getSectionFileSize(&SD);
1627}
1628
Jan Sjödin30a52de2011-02-28 21:45:04 +00001629uint64_t ELFObjectWriter::GetSectionAddressSize(const MCAsmLayout &Layout,
1630 const MCSectionData &SD) {
Rafael Espindola60ebca92010-12-02 03:09:06 +00001631 if (IsELFMetaDataSection(SD))
1632 return DataSectionSize(SD);
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001633 return Layout.getSectionAddressSize(&SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001634}
1635
Rafael Espindola1557fd62011-03-20 18:44:20 +00001636void ELFObjectWriter::WriteDataSectionData(MCAssembler &Asm,
1637 const MCAsmLayout &Layout,
1638 const MCSectionELF &Section) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001639 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1640
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001641 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001642 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001643
1644 if (IsELFMetaDataSection(SD)) {
1645 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1646 ++i) {
1647 const MCFragment &F = *i;
1648 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001649 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001650 }
1651 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001652 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001653 }
1654}
1655
Rafael Espindola1557fd62011-03-20 18:44:20 +00001656void ELFObjectWriter::WriteSectionHeader(MCAssembler &Asm,
1657 const GroupMapTy &GroupMap,
1658 const MCAsmLayout &Layout,
1659 const SectionIndexMapTy &SectionIndexMap,
1660 const SectionOffsetMapTy &SectionOffsetMap) {
1661 const unsigned NumSections = Asm.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001662
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001663 std::vector<const MCSectionELF*> Sections;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001664 Sections.resize(NumSections - 1);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001665
1666 for (SectionIndexMapTy::const_iterator i=
1667 SectionIndexMap.begin(), e = SectionIndexMap.end(); i != e; ++i) {
1668 const std::pair<const MCSectionELF*, uint32_t> &p = *i;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001669 Sections[p.second - 1] = p.first;
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001670 }
1671
Matt Fleming6c1ad482010-08-16 18:57:57 +00001672 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001673 uint64_t FirstSectionSize =
1674 NumSections >= ELF::SHN_LORESERVE ? NumSections : 0;
1675 uint32_t FirstSectionLink =
1676 ShstrtabIndex >= ELF::SHN_LORESERVE ? ShstrtabIndex : 0;
1677 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, FirstSectionLink, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001678
Rafael Espindola1557fd62011-03-20 18:44:20 +00001679 for (unsigned i = 0; i < NumSections - 1; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001680 const MCSectionELF &Section = *Sections[i];
1681 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1682 uint32_t GroupSymbolIndex;
1683 if (Section.getType() != ELF::SHT_GROUP)
1684 GroupSymbolIndex = 0;
1685 else
Rafael Espindola1557fd62011-03-20 18:44:20 +00001686 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm,
1687 GroupMap.lookup(&Section));
Matt Fleming6c1ad482010-08-16 18:57:57 +00001688
Rafael Espindola93e3cf02010-12-07 00:27:36 +00001689 uint64_t Size = GetSectionAddressSize(Layout, SD);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001690
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001691 WriteSection(Asm, SectionIndexMap, GroupSymbolIndex,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001692 SectionOffsetMap.lookup(&Section), Size,
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001693 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001694 }
1695}
1696
Rafael Espindola1557fd62011-03-20 18:44:20 +00001697void ELFObjectWriter::ComputeSectionOrder(MCAssembler &Asm,
1698 std::vector<const MCSectionELF*> &Sections) {
1699 for (MCAssembler::iterator it = Asm.begin(),
1700 ie = Asm.end(); it != ie; ++it) {
1701 const MCSectionELF &Section =
1702 static_cast<const MCSectionELF &>(it->getSection());
1703 if (Section.getType() == ELF::SHT_GROUP)
1704 Sections.push_back(&Section);
1705 }
1706
1707 for (MCAssembler::iterator it = Asm.begin(),
1708 ie = Asm.end(); it != ie; ++it) {
1709 const MCSectionELF &Section =
1710 static_cast<const MCSectionELF &>(it->getSection());
1711 if (Section.getType() != ELF::SHT_GROUP &&
1712 Section.getType() != ELF::SHT_REL &&
1713 Section.getType() != ELF::SHT_RELA)
1714 Sections.push_back(&Section);
1715 }
1716
1717 for (MCAssembler::iterator it = Asm.begin(),
1718 ie = Asm.end(); it != ie; ++it) {
1719 const MCSectionELF &Section =
1720 static_cast<const MCSectionELF &>(it->getSection());
1721 if (Section.getType() == ELF::SHT_REL ||
1722 Section.getType() == ELF::SHT_RELA)
1723 Sections.push_back(&Section);
1724 }
1725}
1726
1727void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1728 const MCAsmLayout &Layout) {
1729 GroupMapTy GroupMap;
1730 RevGroupMapTy RevGroupMap;
1731 SectionIndexMapTy SectionIndexMap;
1732
1733 unsigned NumUserSections = Asm.size();
1734
David Blaikiee06e8012014-04-11 22:11:50 +00001735 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
David Blaikie8019bf82014-04-10 21:53:53 +00001736
Rafael Espindola1557fd62011-03-20 18:44:20 +00001737 DenseMap<const MCSectionELF*, const MCSectionELF*> RelMap;
1738 CreateRelocationSections(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1739
1740 const unsigned NumUserAndRelocSections = Asm.size();
1741 CreateIndexedSections(Asm, const_cast<MCAsmLayout&>(Layout), GroupMap,
1742 RevGroupMap, SectionIndexMap, RelMap);
1743 const unsigned AllSections = Asm.size();
1744 const unsigned NumIndexedSections = AllSections - NumUserAndRelocSections;
1745
1746 unsigned NumRegularSections = NumUserSections + NumIndexedSections;
1747
1748 // Compute symbol table information.
Rafael Espindola022bb762014-03-24 03:43:21 +00001749 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap,
1750 NumRegularSections);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001751
1752 WriteRelocations(Asm, const_cast<MCAsmLayout&>(Layout), RelMap);
1753
1754 CreateMetadataSections(const_cast<MCAssembler&>(Asm),
1755 const_cast<MCAsmLayout&>(Layout),
1756 SectionIndexMap,
1757 RelMap);
1758
1759 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
1760 uint64_t HeaderSize = is64Bit() ? sizeof(ELF::Elf64_Ehdr) :
1761 sizeof(ELF::Elf32_Ehdr);
1762 uint64_t FileOff = HeaderSize;
1763
1764 std::vector<const MCSectionELF*> Sections;
1765 ComputeSectionOrder(Asm, Sections);
1766 unsigned NumSections = Sections.size();
1767 SectionOffsetMapTy SectionOffsetMap;
1768 for (unsigned i = 0; i < NumRegularSections + 1; ++i) {
1769 const MCSectionELF &Section = *Sections[i];
1770 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1771
1772 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1773
1774 // Remember the offset into the file for this section.
1775 SectionOffsetMap[&Section] = FileOff;
1776
1777 // Get the size of the section in the output file (including padding).
1778 FileOff += GetSectionFileSize(Layout, SD);
1779 }
1780
1781 FileOff = RoundUpToAlignment(FileOff, NaturalAlignment);
1782
1783 const unsigned SectionHeaderOffset = FileOff - HeaderSize;
1784
1785 uint64_t SectionHeaderEntrySize = is64Bit() ?
1786 sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr);
1787 FileOff += (NumSections + 1) * SectionHeaderEntrySize;
1788
1789 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i) {
1790 const MCSectionELF &Section = *Sections[i];
1791 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1792
1793 FileOff = RoundUpToAlignment(FileOff, SD.getAlignment());
1794
1795 // Remember the offset into the file for this section.
1796 SectionOffsetMap[&Section] = FileOff;
1797
1798 // Get the size of the section in the output file (including padding).
1799 FileOff += GetSectionFileSize(Layout, SD);
1800 }
1801
1802 // Write out the ELF header ...
Jack Carter1bd90ff2013-01-30 02:09:52 +00001803 WriteHeader(Asm, SectionHeaderOffset, NumSections + 1);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001804
1805 // ... then the regular sections ...
1806 // + because of .shstrtab
1807 for (unsigned i = 0; i < NumRegularSections + 1; ++i)
1808 WriteDataSectionData(Asm, Layout, *Sections[i]);
1809
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001810 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001811 WriteZeros(Padding);
1812
1813 // ... then the section header table ...
1814 WriteSectionHeader(Asm, GroupMap, Layout, SectionIndexMap,
1815 SectionOffsetMap);
1816
Nick Lewycky4eb11432011-10-07 20:56:23 +00001817 // ... and then the remaining sections ...
Rafael Espindola1557fd62011-03-20 18:44:20 +00001818 for (unsigned i = NumRegularSections + 1; i < NumSections; ++i)
1819 WriteDataSectionData(Asm, Layout, *Sections[i]);
1820}
1821
Eli Friedmand92d17b2011-03-03 07:24:36 +00001822bool
1823ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
1824 const MCSymbolData &DataA,
1825 const MCFragment &FB,
1826 bool InSet,
1827 bool IsPCRel) const {
Roman Divackyfb4d3902014-01-08 18:50:32 +00001828 if (DataA.getFlags() & ELF_STB_Weak || MCELF::GetType(DataA) == ELF::STT_GNU_IFUNC)
Eli Friedmand92d17b2011-03-03 07:24:36 +00001829 return false;
1830 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
1831 Asm, DataA, FB,InSet, IsPCRel);
1832}
1833
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001834MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
1835 raw_ostream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001836 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001837 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001838}