blob: ae57f9521e02283433638d963bdb68ad3ad61937 [file] [log] [blame]
Nick Lewycky4288f9e2013-03-09 09:32:16 +00001//===- lib/MC/ELFObjectWriter.cpp - ELF File Writer -----------------------===//
Matt Fleming6c1ad482010-08-16 18:57:57 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements ELF object file writer information.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruthed0881b2012-12-03 16:50:05 +000014#include "llvm/MC/MCELFObjectWriter.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/STLExtras.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000016#include "llvm/ADT/SmallPtrSet.h"
17#include "llvm/ADT/SmallString.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000018#include "llvm/ADT/StringMap.h"
Evan Cheng5928e692011-07-25 23:24:55 +000019#include "llvm/MC/MCAsmBackend.h"
David Blaikie8019bf82014-04-10 21:53:53 +000020#include "llvm/MC/MCAsmInfo.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000021#include "llvm/MC/MCAsmLayout.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000022#include "llvm/MC/MCAssembler.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000023#include "llvm/MC/MCContext.h"
Tim Northover5cc3dc82012-12-07 16:50:23 +000024#include "llvm/MC/MCELF.h"
Rafael Espindola29abd972011-12-22 03:38:00 +000025#include "llvm/MC/MCELFSymbolFlags.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000026#include "llvm/MC/MCExpr.h"
Craig Topper6e80c282012-03-26 06:58:25 +000027#include "llvm/MC/MCFixupKindInfo.h"
28#include "llvm/MC/MCObjectWriter.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000029#include "llvm/MC/MCSectionELF.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000030#include "llvm/MC/MCValue.h"
Rafael Espindola97de4742014-07-03 02:01:39 +000031#include "llvm/MC/StringTableBuilder.h"
David Blaikie8019bf82014-04-10 21:53:53 +000032#include "llvm/Support/Compression.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000033#include "llvm/Support/Debug.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000034#include "llvm/Support/ELF.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000035#include "llvm/Support/Endian.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Support/ErrorHandling.h"
Matt Fleming6c1ad482010-08-16 18:57:57 +000037#include <vector>
38using namespace llvm;
39
Jason W Kimc09e7262011-05-11 22:53:06 +000040#undef DEBUG_TYPE
41#define DEBUG_TYPE "reloc-info"
42
Rafael Espindola29abd972011-12-22 03:38:00 +000043namespace {
Rafael Espindola0ce09712014-03-25 22:43:53 +000044
Rafael Espindola10be0832014-03-25 23:44:25 +000045typedef DenseMap<const MCSectionELF *, uint32_t> SectionIndexMapTy;
46
Rafael Espindola91fd2772015-04-29 21:09:32 +000047class ELFObjectWriter;
48
Rafael Espindola10be0832014-03-25 23:44:25 +000049class SymbolTableWriter {
Rafael Espindola91fd2772015-04-29 21:09:32 +000050 ELFObjectWriter &EWriter;
Rafael Espindola10be0832014-03-25 23:44:25 +000051 bool Is64Bit;
Rafael Espindola10be0832014-03-25 23:44:25 +000052
Rafael Espindola91fd2772015-04-29 21:09:32 +000053 // indexes we are going to write to .symtab_shndx.
54 std::vector<uint32_t> ShndxIndexes;
Rafael Espindola10be0832014-03-25 23:44:25 +000055
56 // The numbel of symbols written so far.
57 unsigned NumWritten;
58
59 void createSymtabShndx();
60
Rafael Espindola91fd2772015-04-29 21:09:32 +000061 template <typename T> void write(T Value);
Rafael Espindola10be0832014-03-25 23:44:25 +000062
63public:
Rafael Espindola91fd2772015-04-29 21:09:32 +000064 SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit);
Rafael Espindola10be0832014-03-25 23:44:25 +000065
66 void writeSymbol(uint32_t name, uint8_t info, uint64_t value, uint64_t size,
67 uint8_t other, uint32_t shndx, bool Reserved);
Rafael Espindola91fd2772015-04-29 21:09:32 +000068
69 ArrayRef<uint32_t> getShndxIndexes() const { return ShndxIndexes; }
Rafael Espindola10be0832014-03-25 23:44:25 +000070};
71
Rafael Espindola29abd972011-12-22 03:38:00 +000072class ELFObjectWriter : public MCObjectWriter {
73 protected:
74
75 static bool isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind);
76 static bool RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant);
77 static uint64_t SymbolValue(MCSymbolData &Data, const MCAsmLayout &Layout);
Rafael Espindola3b5ee552014-04-28 13:39:57 +000078 static bool isInSymtab(const MCAsmLayout &Layout, const MCSymbolData &Data,
Rafael Espindola29abd972011-12-22 03:38:00 +000079 bool Used, bool Renamed);
Rafael Espindola39f50422014-04-28 14:24:44 +000080 static bool isLocal(const MCSymbolData &Data, bool isUsedInReloc);
Rafael Espindola29abd972011-12-22 03:38:00 +000081 static bool IsELFMetaDataSection(const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +000082
Rafael Espindola642a2212015-04-14 22:54:16 +000083 void writeDataSectionData(MCAssembler &Asm, const MCAsmLayout &Layout,
84 const MCSectionData &SD);
Rafael Espindola29abd972011-12-22 03:38:00 +000085
Rafael Espindola6cd21802015-04-07 22:35:40 +000086 /// Helper struct for containing some precomputed information on symbols.
Rafael Espindola29abd972011-12-22 03:38:00 +000087 struct ELFSymbolData {
88 MCSymbolData *SymbolData;
89 uint64_t StringIndex;
90 uint32_t SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +000091 StringRef Name;
Rafael Espindola29abd972011-12-22 03:38:00 +000092
93 // Support lexicographic sorting.
94 bool operator<(const ELFSymbolData &RHS) const {
Rafael Espindolab6613022014-10-17 01:48:58 +000095 unsigned LHSType = MCELF::GetType(*SymbolData);
96 unsigned RHSType = MCELF::GetType(*RHS.SymbolData);
97 if (LHSType == ELF::STT_SECTION && RHSType != ELF::STT_SECTION)
98 return false;
99 if (LHSType != ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
100 return true;
101 if (LHSType == ELF::STT_SECTION && RHSType == ELF::STT_SECTION)
102 return SectionIndex < RHS.SectionIndex;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000103 return Name < RHS.Name;
Rafael Espindola29abd972011-12-22 03:38:00 +0000104 }
105 };
106
Rafael Espindola29abd972011-12-22 03:38:00 +0000107 /// The target specific ELF writer instance.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000108 std::unique_ptr<MCELFObjectTargetWriter> TargetObjectWriter;
Rafael Espindola29abd972011-12-22 03:38:00 +0000109
110 SmallPtrSet<const MCSymbol *, 16> UsedInReloc;
111 SmallPtrSet<const MCSymbol *, 16> WeakrefUsedInReloc;
112 DenseMap<const MCSymbol *, const MCSymbol *> Renames;
113
Rafael Espindola34948e52015-04-30 00:45:46 +0000114 llvm::DenseMap<const MCSectionELF *, std::vector<ELFRelocationEntry>>
115 Relocations;
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000116 StringTableBuilder ShStrTabBuilder;
Rafael Espindola29abd972011-12-22 03:38:00 +0000117
118 /// @}
119 /// @name Symbol Table Data
120 /// @{
121
Hans Wennborg83e6e1e2014-04-30 16:25:02 +0000122 StringTableBuilder StrTabBuilder;
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000123 std::vector<uint64_t> FileSymbolData;
Rafael Espindola29abd972011-12-22 03:38:00 +0000124 std::vector<ELFSymbolData> LocalSymbolData;
125 std::vector<ELFSymbolData> ExternalSymbolData;
126 std::vector<ELFSymbolData> UndefinedSymbolData;
127
128 /// @}
129
130 bool NeedsGOT;
131
Rafael Espindola29abd972011-12-22 03:38:00 +0000132 // This holds the symbol table index of the last local symbol.
133 unsigned LastLocalSymbolIndex;
134 // This holds the .strtab section index.
135 unsigned StringTableIndex;
136 // This holds the .symtab section index.
137 unsigned SymbolTableIndex;
138
139 unsigned ShstrtabIndex;
140
141
Rafael Espindola29abd972011-12-22 03:38:00 +0000142 // TargetObjectWriter wrappers.
Rafael Espindola29abd972011-12-22 03:38:00 +0000143 bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
144 bool hasRelocationAddend() const {
145 return TargetObjectWriter->hasRelocationAddend();
146 }
Rafael Espindola29abd972011-12-22 03:38:00 +0000147 unsigned GetRelocType(const MCValue &Target, const MCFixup &Fixup,
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000148 bool IsPCRel) const {
149 return TargetObjectWriter->GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindola29abd972011-12-22 03:38:00 +0000150 }
151
Rafael Espindola29abd972011-12-22 03:38:00 +0000152 public:
Rafael Espindola5560a4c2015-04-14 22:14:34 +0000153 ELFObjectWriter(MCELFObjectTargetWriter *MOTW, raw_pwrite_stream &OS,
Rafael Espindola0ce09712014-03-25 22:43:53 +0000154 bool IsLittleEndian)
Rafael Espindola59f0e312015-04-29 21:13:30 +0000155 : MCObjectWriter(OS, IsLittleEndian), TargetObjectWriter(MOTW),
156 NeedsGOT(false) {}
Rafael Espindola29abd972011-12-22 03:38:00 +0000157
Yaron Keren7773a722015-03-23 18:35:01 +0000158 void reset() override {
159 UsedInReloc.clear();
160 WeakrefUsedInReloc.clear();
161 Renames.clear();
162 Relocations.clear();
163 ShStrTabBuilder.clear();
164 StrTabBuilder.clear();
165 FileSymbolData.clear();
166 LocalSymbolData.clear();
167 ExternalSymbolData.clear();
168 UndefinedSymbolData.clear();
169 MCObjectWriter::reset();
170 }
171
Alexander Kornienkof817c1c2015-04-11 02:11:45 +0000172 ~ELFObjectWriter() override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000173
174 void WriteWord(uint64_t W) {
175 if (is64Bit())
176 Write64(W);
177 else
178 Write32(W);
179 }
180
Rafael Espindola91fd2772015-04-29 21:09:32 +0000181 template <typename T> void write(T Val) {
182 if (IsLittleEndian)
183 support::endian::Writer<support::little>(OS).write(Val);
184 else
185 support::endian::Writer<support::big>(OS).write(Val);
186 }
187
Rafael Espindola59f0e312015-04-29 21:13:30 +0000188 template <typename T> void write(MCDataFragment &F, T Value);
Rafael Espindola29abd972011-12-22 03:38:00 +0000189
Rafael Espindola8c7829b2015-04-29 20:39:37 +0000190 void writeHeader(const MCAssembler &Asm);
Rafael Espindola29abd972011-12-22 03:38:00 +0000191
Rafael Espindola10be0832014-03-25 23:44:25 +0000192 void WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Rafael Espindola29abd972011-12-22 03:38:00 +0000193 const MCAsmLayout &Layout);
194
Rafael Espindola91fd2772015-04-29 21:09:32 +0000195 // Start and end offset of each section
196 typedef std::vector<std::pair<uint64_t, uint64_t>> SectionOffsetsTy;
197
198 void WriteSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
199 std::vector<const MCSectionELF *> &Sections,
200 SectionOffsetsTy &SectionOffsets);
Rafael Espindola29abd972011-12-22 03:38:00 +0000201
Rafael Espindolab60c8292014-04-29 12:46:50 +0000202 bool shouldRelocateWithSymbol(const MCAssembler &Asm,
203 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000204 const MCSymbolData *SD, uint64_t C,
205 unsigned Type) const;
206
Rafael Espindola26585542015-01-19 21:11:14 +0000207 void RecordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
Craig Topper34a61bc2014-03-08 07:02:02 +0000208 const MCFragment *Fragment, const MCFixup &Fixup,
Rafael Espindola5904e122014-03-29 06:26:49 +0000209 MCValue Target, bool &IsPCRel,
210 uint64_t &FixedValue) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000211
212 uint64_t getSymbolIndexInSymbolTable(const MCAssembler &Asm,
213 const MCSymbol *S);
214
Rafael Espindola89feff32015-04-28 22:59:58 +0000215 // Map from a signature symbol to the group section index
216 typedef DenseMap<const MCSymbol *, unsigned> RevGroupMapTy;
Rafael Espindola29abd972011-12-22 03:38:00 +0000217
Rafael Espindola022bb762014-03-24 03:43:21 +0000218 /// Compute the symbol table data
Rafael Espindola29abd972011-12-22 03:38:00 +0000219 ///
Rafael Espindola073ee7d2012-08-27 16:04:24 +0000220 /// \param Asm - The assembler.
221 /// \param SectionIndexMap - Maps a section to its index.
222 /// \param RevGroupMap - Maps a signature symbol to the group section.
Rafael Espindola022bb762014-03-24 03:43:21 +0000223 void computeSymbolTable(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000224 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000225 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000226
Rafael Espindola89feff32015-04-28 22:59:58 +0000227 void maybeAddToGroup(MCAssembler &Asm,
228 ArrayRef<const MCSectionELF *> Sections,
229 const RevGroupMapTy &RevGroupMap,
Rafael Espindola8a90d872015-04-28 21:52:33 +0000230 const MCSectionELF &Section, unsigned Index);
231
232 void computeIndexMap(MCAssembler &Asm,
233 std::vector<const MCSectionELF *> &Sections,
234 SectionIndexMapTy &SectionIndexMap,
235 const RevGroupMapTy &RevGroupMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000236
Rafael Espindola34948e52015-04-30 00:45:46 +0000237 void createRelocationSection(MCAssembler &Asm, const MCSectionELF &Sec);
Rafael Espindola29abd972011-12-22 03:38:00 +0000238
David Blaikie8019bf82014-04-10 21:53:53 +0000239 void CompressDebugSections(MCAssembler &Asm, MCAsmLayout &Layout);
240
Rafael Espindola88d1f632015-04-29 20:25:24 +0000241 void
242 createSectionHeaderStringTable(MCAssembler &Asm,
243 std::vector<const MCSectionELF *> &Sections);
Rafael Espindola88abc392015-04-29 20:34:31 +0000244 void createStringTable(MCAssembler &Asm,
245 std::vector<const MCSectionELF *> &Sections);
Rafael Espindola29abd972011-12-22 03:38:00 +0000246
247 // Create the sections that show up in the symbol table. Currently
248 // those are the .note.GNU-stack section and the group sections.
Rafael Espindolaae7e4992015-04-29 19:20:10 +0000249 void createIndexedSections(MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola55a3afb2015-04-28 21:07:28 +0000250 RevGroupMapTy &RevGroupMap,
Rafael Espindola8a90d872015-04-28 21:52:33 +0000251 std::vector<const MCSectionELF *> &Sections,
Rafael Espindolab73b70e2015-04-06 03:09:30 +0000252 SectionIndexMapTy &SectionIndexMap);
Rafael Espindola29abd972011-12-22 03:38:00 +0000253
Craig Topper34a61bc2014-03-08 07:02:02 +0000254 void ExecutePostLayoutBinding(MCAssembler &Asm,
255 const MCAsmLayout &Layout) override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000256
Rafael Espindolabf0db6c2015-04-15 13:07:47 +0000257 void writeSectionHeader(ArrayRef<const MCSectionELF *> Sections,
Rafael Espindola55a3afb2015-04-28 21:07:28 +0000258 MCAssembler &Asm, const MCAsmLayout &Layout,
Rafael Espindola29abd972011-12-22 03:38:00 +0000259 const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +0000260 const SectionOffsetsTy &SectionOffsets);
Rafael Espindola29abd972011-12-22 03:38:00 +0000261
Rafael Espindola29abd972011-12-22 03:38:00 +0000262 void WriteSecHdrEntry(uint32_t Name, uint32_t Type, uint64_t Flags,
263 uint64_t Address, uint64_t Offset,
264 uint64_t Size, uint32_t Link, uint32_t Info,
265 uint64_t Alignment, uint64_t EntrySize);
266
Rafael Espindola34948e52015-04-30 00:45:46 +0000267 void writeRelocations(const MCAssembler &Asm, const MCSectionELF &Sec);
Rafael Espindola29abd972011-12-22 03:38:00 +0000268
Craig Topper34a61bc2014-03-08 07:02:02 +0000269 bool
Rafael Espindola29abd972011-12-22 03:38:00 +0000270 IsSymbolRefDifferenceFullyResolvedImpl(const MCAssembler &Asm,
271 const MCSymbolData &DataA,
272 const MCFragment &FB,
273 bool InSet,
Craig Topper34a61bc2014-03-08 07:02:02 +0000274 bool IsPCRel) const override;
Rafael Espindola29abd972011-12-22 03:38:00 +0000275
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000276 bool isWeak(const MCSymbolData &SD) const override;
277
Craig Topper34a61bc2014-03-08 07:02:02 +0000278 void WriteObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
Rafael Espindola7fe7e052015-02-17 20:40:59 +0000279 void writeSection(MCAssembler &Asm,
Rafael Espindola29abd972011-12-22 03:38:00 +0000280 const SectionIndexMapTy &SectionIndexMap,
281 uint32_t GroupSymbolIndex,
282 uint64_t Offset, uint64_t Size, uint64_t Alignment,
283 const MCSectionELF &Section);
284 };
285}
286
Rafael Espindola59f0e312015-04-29 21:13:30 +0000287template <typename T> void ELFObjectWriter::write(MCDataFragment &F, T Val) {
Rafael Espindola0ce09712014-03-25 22:43:53 +0000288 if (IsLittleEndian)
289 Val = support::endian::byte_swap<T, support::little>(Val);
290 else
291 Val = support::endian::byte_swap<T, support::big>(Val);
292 const char *Start = (const char *)&Val;
293 F.getContents().append(Start, Start + sizeof(T));
294}
295
Rafael Espindola10be0832014-03-25 23:44:25 +0000296void SymbolTableWriter::createSymtabShndx() {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000297 if (!ShndxIndexes.empty())
Rafael Espindola10be0832014-03-25 23:44:25 +0000298 return;
299
Rafael Espindola91fd2772015-04-29 21:09:32 +0000300 ShndxIndexes.resize(NumWritten);
Rafael Espindola10be0832014-03-25 23:44:25 +0000301}
302
Rafael Espindola91fd2772015-04-29 21:09:32 +0000303template <typename T> void SymbolTableWriter::write(T Value) {
304 EWriter.write(Value);
Rafael Espindola10be0832014-03-25 23:44:25 +0000305}
306
Rafael Espindola91fd2772015-04-29 21:09:32 +0000307SymbolTableWriter::SymbolTableWriter(ELFObjectWriter &EWriter, bool Is64Bit)
308 : EWriter(EWriter), Is64Bit(Is64Bit), NumWritten(0) {}
Rafael Espindola10be0832014-03-25 23:44:25 +0000309
310void SymbolTableWriter::writeSymbol(uint32_t name, uint8_t info, uint64_t value,
311 uint64_t size, uint8_t other,
312 uint32_t shndx, bool Reserved) {
313 bool LargeIndex = shndx >= ELF::SHN_LORESERVE && !Reserved;
314
315 if (LargeIndex)
316 createSymtabShndx();
317
Rafael Espindola91fd2772015-04-29 21:09:32 +0000318 if (!ShndxIndexes.empty()) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000319 if (LargeIndex)
Rafael Espindola91fd2772015-04-29 21:09:32 +0000320 ShndxIndexes.push_back(shndx);
Rafael Espindola10be0832014-03-25 23:44:25 +0000321 else
Rafael Espindola91fd2772015-04-29 21:09:32 +0000322 ShndxIndexes.push_back(0);
Rafael Espindola10be0832014-03-25 23:44:25 +0000323 }
324
325 uint16_t Index = LargeIndex ? uint16_t(ELF::SHN_XINDEX) : shndx;
326
Rafael Espindola10be0832014-03-25 23:44:25 +0000327 if (Is64Bit) {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000328 write(name); // st_name
329 write(info); // st_info
330 write(other); // st_other
331 write(Index); // st_shndx
332 write(value); // st_value
333 write(size); // st_size
Rafael Espindola10be0832014-03-25 23:44:25 +0000334 } else {
Rafael Espindola91fd2772015-04-29 21:09:32 +0000335 write(name); // st_name
336 write(uint32_t(value)); // st_value
337 write(uint32_t(size)); // st_size
338 write(info); // st_info
339 write(other); // st_other
340 write(Index); // st_shndx
Rafael Espindola10be0832014-03-25 23:44:25 +0000341 }
342
343 ++NumWritten;
344}
345
Jan Sjödin30a52de2011-02-28 21:45:04 +0000346bool ELFObjectWriter::isFixupKindPCRel(const MCAssembler &Asm, unsigned Kind) {
347 const MCFixupKindInfo &FKI =
348 Asm.getBackend().getFixupKindInfo((MCFixupKind) Kind);
349
350 return FKI.Flags & MCFixupKindInfo::FKF_IsPCRel;
351}
352
353bool ELFObjectWriter::RelocNeedsGOT(MCSymbolRefExpr::VariantKind Variant) {
354 switch (Variant) {
355 default:
356 return false;
357 case MCSymbolRefExpr::VK_GOT:
358 case MCSymbolRefExpr::VK_PLT:
359 case MCSymbolRefExpr::VK_GOTPCREL:
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000360 case MCSymbolRefExpr::VK_GOTOFF:
Jan Sjödin30a52de2011-02-28 21:45:04 +0000361 case MCSymbolRefExpr::VK_TPOFF:
362 case MCSymbolRefExpr::VK_TLSGD:
363 case MCSymbolRefExpr::VK_GOTTPOFF:
364 case MCSymbolRefExpr::VK_INDNTPOFF:
365 case MCSymbolRefExpr::VK_NTPOFF:
366 case MCSymbolRefExpr::VK_GOTNTPOFF:
367 case MCSymbolRefExpr::VK_TLSLDM:
368 case MCSymbolRefExpr::VK_DTPOFF:
369 case MCSymbolRefExpr::VK_TLSLD:
370 return true;
371 }
372}
373
Jason W Kim96f4c012010-11-15 16:18:39 +0000374ELFObjectWriter::~ELFObjectWriter()
375{}
376
Matt Fleming6c1ad482010-08-16 18:57:57 +0000377// Emit the ELF header.
Rafael Espindola8c7829b2015-04-29 20:39:37 +0000378void ELFObjectWriter::writeHeader(const MCAssembler &Asm) {
Matt Fleming6c1ad482010-08-16 18:57:57 +0000379 // ELF Header
380 // ----------
381 //
382 // Note
383 // ----
384 // emitWord method behaves differently for ELF32 and ELF64, writing
385 // 4 bytes in the former and 8 in the latter.
386
Benjamin Kramer97fbdd52015-04-17 11:12:43 +0000387 WriteBytes(ELF::ElfMagic); // e_ident[EI_MAG0] to e_ident[EI_MAG3]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000388
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000389 Write8(is64Bit() ? ELF::ELFCLASS64 : ELF::ELFCLASS32); // e_ident[EI_CLASS]
Matt Fleming6c1ad482010-08-16 18:57:57 +0000390
391 // e_ident[EI_DATA]
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000392 Write8(isLittleEndian() ? ELF::ELFDATA2LSB : ELF::ELFDATA2MSB);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000393
394 Write8(ELF::EV_CURRENT); // e_ident[EI_VERSION]
Roman Divacky3b727f52010-09-09 17:57:50 +0000395 // e_ident[EI_OSABI]
Rafael Espindola1ad40952011-12-21 17:00:36 +0000396 Write8(TargetObjectWriter->getOSABI());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000397 Write8(0); // e_ident[EI_ABIVERSION]
398
399 WriteZeros(ELF::EI_NIDENT - ELF::EI_PAD);
400
401 Write16(ELF::ET_REL); // e_type
402
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000403 Write16(TargetObjectWriter->getEMachine()); // e_machine = target
Matt Fleming6c1ad482010-08-16 18:57:57 +0000404
405 Write32(ELF::EV_CURRENT); // e_version
406 WriteWord(0); // e_entry, no entry point in .o file
407 WriteWord(0); // e_phoff, no program header for .o
Rafael Espindola642a2212015-04-14 22:54:16 +0000408 WriteWord(0); // e_shoff = sec hdr table off in bytes
Matt Fleming6c1ad482010-08-16 18:57:57 +0000409
Jason W Kim4761fba2011-02-04 21:41:11 +0000410 // e_flags = whatever the target wants
Jack Carter1bd90ff2013-01-30 02:09:52 +0000411 Write32(Asm.getELFHeaderEFlags());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000412
413 // e_ehsize = ELF header size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000414 Write16(is64Bit() ? sizeof(ELF::Elf64_Ehdr) : sizeof(ELF::Elf32_Ehdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000415
416 Write16(0); // e_phentsize = prog header entry size
417 Write16(0); // e_phnum = # prog header entries = 0
418
419 // e_shentsize = Section header entry size
Rafael Espindolafdaae0d2010-12-18 03:27:34 +0000420 Write16(is64Bit() ? sizeof(ELF::Elf64_Shdr) : sizeof(ELF::Elf32_Shdr));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000421
422 // e_shnum = # of section header ents
Rafael Espindola8c7829b2015-04-29 20:39:37 +0000423 Write16(0);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000424
425 // e_shstrndx = Section # of '.shstrtab'
Rafael Espindola88d1f632015-04-29 20:25:24 +0000426 assert(ShstrtabIndex < ELF::SHN_LORESERVE);
427 Write16(ShstrtabIndex);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000428}
429
Rafael Espindolafee224f2014-04-30 21:51:13 +0000430uint64_t ELFObjectWriter::SymbolValue(MCSymbolData &Data,
Jan Sjödin30a52de2011-02-28 21:45:04 +0000431 const MCAsmLayout &Layout) {
Rafael Espindolafee224f2014-04-30 21:51:13 +0000432 if (Data.isCommon() && Data.isExternal())
433 return Data.getCommonAlignment();
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000434
Rafael Espindolafee224f2014-04-30 21:51:13 +0000435 uint64_t Res;
436 if (!Layout.getSymbolOffset(&Data, Res))
Rafael Espindola553e5eb2014-04-30 16:59:35 +0000437 return 0;
438
Rafael Espindolafee224f2014-04-30 21:51:13 +0000439 if (Layout.getAssembler().isThumbFunc(&Data.getSymbol()))
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000440 Res |= 1;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000441
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000442 return Res;
Rafael Espindola9735f4f2010-09-27 21:23:02 +0000443}
444
Rafael Espindola93e3cf02010-12-07 00:27:36 +0000445void ELFObjectWriter::ExecutePostLayoutBinding(MCAssembler &Asm,
446 const MCAsmLayout &Layout) {
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000447 // The presence of symbol versions causes undefined symbols and
448 // versions declared with @@@ to be renamed.
449
David Blaikie583a31c2014-04-18 18:24:25 +0000450 for (MCSymbolData &OriginalData : Asm.symbols()) {
451 const MCSymbol &Alias = OriginalData.getSymbol();
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000452
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000453 // Not an alias.
Rafael Espindola6efaf112014-04-28 17:05:36 +0000454 if (!Alias.isVariable())
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000455 continue;
Rafael Espindola6efaf112014-04-28 17:05:36 +0000456 auto *Ref = dyn_cast<MCSymbolRefExpr>(Alias.getVariableValue());
457 if (!Ref)
458 continue;
459 const MCSymbol &Symbol = Ref->getSymbol();
460 MCSymbolData &SD = Asm.getSymbolData(Symbol);
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000461
Benjamin Kramer14807272010-10-27 19:53:52 +0000462 StringRef AliasName = Alias.getName();
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000463 size_t Pos = AliasName.find('@');
464 if (Pos == StringRef::npos)
465 continue;
466
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000467 // Aliases defined with .symvar copy the binding from the symbol they alias.
468 // This is the first place we are able to copy this information.
David Blaikie583a31c2014-04-18 18:24:25 +0000469 OriginalData.setExternal(SD.isExternal());
470 MCELF::SetBinding(OriginalData, MCELF::GetBinding(SD));
Rafael Espindola6cd76e62010-10-28 18:33:03 +0000471
Benjamin Kramer14807272010-10-27 19:53:52 +0000472 StringRef Rest = AliasName.substr(Pos);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000473 if (!Symbol.isUndefined() && !Rest.startswith("@@@"))
474 continue;
475
Rafael Espindola26496e62010-10-27 17:56:18 +0000476 // FIXME: produce a better error message.
477 if (Symbol.isUndefined() && Rest.startswith("@@") &&
478 !Rest.startswith("@@@"))
479 report_fatal_error("A @@ version cannot be undefined");
480
Benjamin Kramer14807272010-10-27 19:53:52 +0000481 Renames.insert(std::make_pair(&Symbol, &Alias));
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000482 }
483}
484
Roman Divacky5a1c5492014-01-07 20:17:03 +0000485static uint8_t mergeTypeForSet(uint8_t origType, uint8_t newType) {
486 uint8_t Type = newType;
487
488 // Propagation rules:
489 // IFUNC > FUNC > OBJECT > NOTYPE
490 // TLS_OBJECT > OBJECT > NOTYPE
491 //
492 // dont let the new type degrade the old type
493 switch (origType) {
494 default:
495 break;
496 case ELF::STT_GNU_IFUNC:
497 if (Type == ELF::STT_FUNC || Type == ELF::STT_OBJECT ||
498 Type == ELF::STT_NOTYPE || Type == ELF::STT_TLS)
499 Type = ELF::STT_GNU_IFUNC;
500 break;
501 case ELF::STT_FUNC:
502 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
503 Type == ELF::STT_TLS)
504 Type = ELF::STT_FUNC;
505 break;
506 case ELF::STT_OBJECT:
507 if (Type == ELF::STT_NOTYPE)
508 Type = ELF::STT_OBJECT;
509 break;
510 case ELF::STT_TLS:
511 if (Type == ELF::STT_OBJECT || Type == ELF::STT_NOTYPE ||
512 Type == ELF::STT_GNU_IFUNC || Type == ELF::STT_FUNC)
513 Type = ELF::STT_TLS;
514 break;
515 }
516
517 return Type;
518}
519
Rafael Espindola10be0832014-03-25 23:44:25 +0000520void ELFObjectWriter::WriteSymbol(SymbolTableWriter &Writer, ELFSymbolData &MSD,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000521 const MCAsmLayout &Layout) {
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000522 MCSymbolData &OrigData = *MSD.SymbolData;
David Blaikieb5956d22014-04-19 00:50:15 +0000523 assert((!OrigData.getFragment() ||
524 (&OrigData.getFragment()->getParent()->getSection() ==
525 &OrigData.getSymbol().getSection())) &&
526 "The symbol's section doesn't match the fragment's symbol");
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000527 const MCSymbol *Base = Layout.getBaseSymbol(OrigData.getSymbol());
Rafael Espindola85a84912014-03-26 00:16:43 +0000528
529 // This has to be in sync with when computeSymbolTable uses SHN_ABS or
530 // SHN_COMMON.
531 bool IsReserved = !Base || OrigData.isCommon();
Rafael Espindola3fe87a12010-10-31 00:16:26 +0000532
Jack Carter2f8d9d92013-02-19 21:57:35 +0000533 // Binding and Type share the same byte as upper and lower nibbles
Jan Sjödin30a52de2011-02-28 21:45:04 +0000534 uint8_t Binding = MCELF::GetBinding(OrigData);
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000535 uint8_t Type = MCELF::GetType(OrigData);
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000536 MCSymbolData *BaseSD = nullptr;
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000537 if (Base) {
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000538 BaseSD = &Layout.getAssembler().getSymbolData(*Base);
539 Type = mergeTypeForSet(Type, MCELF::GetType(*BaseSD));
Rafael Espindolaa6e3a592014-03-23 03:33:20 +0000540 }
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000541 uint8_t Info = (Binding << ELF_STB_Shift) | (Type << ELF_STT_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000542
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000543 // Other and Visibility share the same byte with Visibility using the lower
Jack Carter2f8d9d92013-02-19 21:57:35 +0000544 // 2 bits
545 uint8_t Visibility = MCELF::GetVisibility(OrigData);
Logan Chienee365952013-12-05 00:34:11 +0000546 uint8_t Other = MCELF::getOther(OrigData) << (ELF_STO_Shift - ELF_STV_Shift);
Jack Carter2f8d9d92013-02-19 21:57:35 +0000547 Other |= Visibility;
Rafael Espindola5f2d6a52010-10-06 21:02:29 +0000548
Rafael Espindola66f96fe2014-03-21 22:00:29 +0000549 uint64_t Value = SymbolValue(OrigData, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000550 uint64_t Size = 0;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000551
Rafael Espindolaa041ef12014-03-27 00:28:24 +0000552 const MCExpr *ESize = OrigData.getSize();
553 if (!ESize && Base)
554 ESize = BaseSD->getSize();
Rafael Espindolaf0591c12010-09-21 00:24:38 +0000555
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000556 if (ESize) {
557 int64_t Res;
Rafael Espindola94a88d72015-04-06 15:27:57 +0000558 if (!ESize->evaluateKnownAbsolute(Res, Layout))
Rafael Espindola73c0ae72010-12-22 16:03:00 +0000559 report_fatal_error("Size expression must be absolute.");
560 Size = Res;
Matt Fleming6c1ad482010-08-16 18:57:57 +0000561 }
562
563 // Write out the symbol table entry
Rafael Espindola10be0832014-03-25 23:44:25 +0000564 Writer.writeSymbol(MSD.StringIndex, Info, Value, Size, Other,
565 MSD.SectionIndex, IsReserved);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000566}
567
Rafael Espindolae3ff9302015-04-28 20:09:13 +0000568void ELFObjectWriter::WriteSymbolTable(
Rafael Espindola91fd2772015-04-29 21:09:32 +0000569 MCAssembler &Asm, const MCAsmLayout &Layout,
570 std::vector<const MCSectionELF *> &Sections,
571 SectionOffsetsTy &SectionOffsets) {
572
573 MCContext &Ctx = Asm.getContext();
574
575 unsigned EntrySize = is64Bit() ? ELF::SYMENTRY_SIZE64 : ELF::SYMENTRY_SIZE32;
576
577 // Symbol table
578 const MCSectionELF *SymtabSection =
579 Ctx.getELFSection(".symtab", ELF::SHT_SYMTAB, 0, EntrySize, "");
580 MCSectionData &SymtabSD = Asm.getOrCreateSectionData(*SymtabSection);
581 SymtabSD.setAlignment(is64Bit() ? 8 : 4);
582 SymbolTableIndex = Sections.size() + 1;
583 Sections.push_back(SymtabSection);
584
Matt Fleming6c1ad482010-08-16 18:57:57 +0000585 // The string table must be emitted first because we need the index
586 // into the string table for all the symbol names.
Matt Fleming6c1ad482010-08-16 18:57:57 +0000587
Rafael Espindola91fd2772015-04-29 21:09:32 +0000588 SymbolTableWriter Writer(*this, is64Bit());
Matt Fleming6c1ad482010-08-16 18:57:57 +0000589
Rafael Espindola91fd2772015-04-29 21:09:32 +0000590 uint64_t Padding = OffsetToAlignment(OS.tell(), SymtabSD.getAlignment());
591 WriteZeros(Padding);
592
593 uint64_t SecStart = OS.tell();
Rafael Espindola10be0832014-03-25 23:44:25 +0000594
Matt Fleming6c1ad482010-08-16 18:57:57 +0000595 // The first entry is the undefined symbol entry.
Rafael Espindola10be0832014-03-25 23:44:25 +0000596 Writer.writeSymbol(0, 0, 0, 0, 0, 0, false);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000597
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000598 for (unsigned i = 0, e = FileSymbolData.size(); i != e; ++i) {
Rafael Espindola10be0832014-03-25 23:44:25 +0000599 Writer.writeSymbol(FileSymbolData[i], ELF::STT_FILE | ELF::STB_LOCAL, 0, 0,
600 ELF::STV_DEFAULT, ELF::SHN_ABS, true);
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000601 }
602
Matt Fleming6c1ad482010-08-16 18:57:57 +0000603 // Write the symbol table entries.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +0000604 LastLocalSymbolIndex = FileSymbolData.size() + LocalSymbolData.size() + 1;
605
Matt Fleming6c1ad482010-08-16 18:57:57 +0000606 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i) {
607 ELFSymbolData &MSD = LocalSymbolData[i];
Rafael Espindola10be0832014-03-25 23:44:25 +0000608 WriteSymbol(Writer, MSD, Layout);
Matt Fleming6c1ad482010-08-16 18:57:57 +0000609 }
610
Matt Fleming6c1ad482010-08-16 18:57:57 +0000611 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i) {
612 ELFSymbolData &MSD = ExternalSymbolData[i];
613 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola83b2a332010-10-06 16:47:31 +0000614 assert(((Data.getFlags() & ELF_STB_Global) ||
615 (Data.getFlags() & ELF_STB_Weak)) &&
616 "External symbol requires STB_GLOBAL or STB_WEAK flag");
Rafael Espindola10be0832014-03-25 23:44:25 +0000617 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000618 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000619 LastLocalSymbolIndex++;
620 }
621
622 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i) {
623 ELFSymbolData &MSD = UndefinedSymbolData[i];
624 MCSymbolData &Data = *MSD.SymbolData;
Rafael Espindola10be0832014-03-25 23:44:25 +0000625 WriteSymbol(Writer, MSD, Layout);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000626 if (MCELF::GetBinding(Data) == ELF::STB_LOCAL)
Matt Fleming6c1ad482010-08-16 18:57:57 +0000627 LastLocalSymbolIndex++;
628 }
Rafael Espindola91fd2772015-04-29 21:09:32 +0000629
630 uint64_t SecEnd = OS.tell();
631 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
632
633 ArrayRef<uint32_t> ShndxIndexes = Writer.getShndxIndexes();
634 if (ShndxIndexes.empty())
635 return;
636
637 SecStart = OS.tell();
638 const MCSectionELF *SymtabShndxSection =
639 Ctx.getELFSection(".symtab_shndxr", ELF::SHT_SYMTAB_SHNDX, 0, 4, "");
640 Sections.push_back(SymtabShndxSection);
641 MCSectionData *SymtabShndxSD =
642 &Asm.getOrCreateSectionData(*SymtabShndxSection);
643 SymtabShndxSD->setAlignment(4);
644 for (uint32_t Index : ShndxIndexes)
645 write(Index);
646 SecEnd = OS.tell();
647 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
Matt Fleming6c1ad482010-08-16 18:57:57 +0000648}
649
Rafael Espindola5904e122014-03-29 06:26:49 +0000650// It is always valid to create a relocation with a symbol. It is preferable
651// to use a relocation with a section if that is possible. Using the section
652// allows us to omit some local symbols from the symbol table.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000653bool ELFObjectWriter::shouldRelocateWithSymbol(const MCAssembler &Asm,
654 const MCSymbolRefExpr *RefA,
Rafael Espindola5904e122014-03-29 06:26:49 +0000655 const MCSymbolData *SD,
656 uint64_t C,
657 unsigned Type) const {
658 // A PCRel relocation to an absolute value has no symbol (or section). We
659 // represent that with a relocation to a null section.
660 if (!RefA)
661 return false;
Rafael Espindola240028d2010-11-14 23:53:26 +0000662
Rafael Espindola5904e122014-03-29 06:26:49 +0000663 MCSymbolRefExpr::VariantKind Kind = RefA->getKind();
664 switch (Kind) {
665 default:
666 break;
667 // The .odp creation emits a relocation against the symbol ".TOC." which
668 // create a R_PPC64_TOC relocation. However the relocation symbol name
669 // in final object creation should be NULL, since the symbol does not
670 // really exist, it is just the reference to TOC base for the current
671 // object file. Since the symbol is undefined, returning false results
672 // in a relocation with a null section which is the desired result.
673 case MCSymbolRefExpr::VK_PPC_TOCBASE:
674 return false;
675
676 // These VariantKind cause the relocation to refer to something other than
677 // the symbol itself, like a linker generated table. Since the address of
678 // symbol is not relevant, we cannot replace the symbol with the
679 // section and patch the difference in the addend.
680 case MCSymbolRefExpr::VK_GOT:
681 case MCSymbolRefExpr::VK_PLT:
682 case MCSymbolRefExpr::VK_GOTPCREL:
683 case MCSymbolRefExpr::VK_Mips_GOT:
684 case MCSymbolRefExpr::VK_PPC_GOT_LO:
685 case MCSymbolRefExpr::VK_PPC_GOT_HI:
686 case MCSymbolRefExpr::VK_PPC_GOT_HA:
687 return true;
Rafael Espindola240028d2010-11-14 23:53:26 +0000688 }
Rafael Espindola240028d2010-11-14 23:53:26 +0000689
Rafael Espindola5904e122014-03-29 06:26:49 +0000690 // An undefined symbol is not in any section, so the relocation has to point
691 // to the symbol itself.
692 const MCSymbol &Sym = SD->getSymbol();
693 if (Sym.isUndefined())
694 return true;
695
696 unsigned Binding = MCELF::GetBinding(*SD);
697 switch(Binding) {
698 default:
699 llvm_unreachable("Invalid Binding");
700 case ELF::STB_LOCAL:
701 break;
702 case ELF::STB_WEAK:
703 // If the symbol is weak, it might be overridden by a symbol in another
704 // file. The relocation has to point to the symbol so that the linker
705 // can update it.
706 return true;
707 case ELF::STB_GLOBAL:
708 // Global ELF symbols can be preempted by the dynamic linker. The relocation
709 // has to point to the symbol for a reason analogous to the STB_WEAK case.
710 return true;
Rafael Espindola8c3039b2010-11-15 16:33:49 +0000711 }
Rafael Espindola75d65b92010-09-25 05:42:19 +0000712
Rafael Espindola5904e122014-03-29 06:26:49 +0000713 // If a relocation points to a mergeable section, we have to be careful.
714 // If the offset is zero, a relocation with the section will encode the
715 // same information. With a non-zero offset, the situation is different.
716 // For example, a relocation can point 42 bytes past the end of a string.
717 // If we change such a relocation to use the section, the linker would think
718 // that it pointed to another string and subtracting 42 at runtime will
719 // produce the wrong value.
720 auto &Sec = cast<MCSectionELF>(Sym.getSection());
721 unsigned Flags = Sec.getFlags();
722 if (Flags & ELF::SHF_MERGE) {
723 if (C != 0)
724 return true;
Rafael Espindolab1b49782014-04-02 12:15:20 +0000725
726 // It looks like gold has a bug (http://sourceware.org/PR16794) and can
727 // only handle section relocations to mergeable sections if using RELA.
728 if (!hasRelocationAddend())
729 return true;
Rafael Espindola9f75d5d2010-11-24 21:57:39 +0000730 }
731
Rafael Espindola5904e122014-03-29 06:26:49 +0000732 // Most TLS relocations use a got, so they need the symbol. Even those that
Rafael Espindola11527a12014-10-06 12:33:27 +0000733 // are just an offset (@tpoff), require a symbol in gold versions before
734 // 5efeedf61e4fe720fd3e9a08e6c91c10abb66d42 (2014-09-26) which fixed
735 // http://sourceware.org/PR16773.
Rafael Espindola5904e122014-03-29 06:26:49 +0000736 if (Flags & ELF::SHF_TLS)
737 return true;
Rafael Espindolad7565c32010-10-05 23:57:26 +0000738
Rafael Espindola9ef84412014-04-11 19:18:01 +0000739 // If the symbol is a thumb function the final relocation must set the lowest
740 // bit. With a symbol that is done by just having the symbol have that bit
741 // set, so we would lose the bit if we relocated with the section.
742 // FIXME: We could use the section but add the bit to the relocation value.
Rafael Espindolab60c8292014-04-29 12:46:50 +0000743 if (Asm.isThumbFunc(&Sym))
Rafael Espindola9ef84412014-04-11 19:18:01 +0000744 return true;
745
Ulrich Weigand46797c62014-07-20 23:15:06 +0000746 if (TargetObjectWriter->needsRelocateWithSymbol(*SD, Type))
Rafael Espindola5904e122014-03-29 06:26:49 +0000747 return true;
748 return false;
Rafael Espindola75d65b92010-09-25 05:42:19 +0000749}
750
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000751static const MCSymbol *getWeakRef(const MCSymbolRefExpr &Ref) {
752 const MCSymbol &Sym = Ref.getSymbol();
753
754 if (Ref.getKind() == MCSymbolRefExpr::VK_WEAKREF)
755 return &Sym;
756
757 if (!Sym.isVariable())
758 return nullptr;
759
760 const MCExpr *Expr = Sym.getVariableValue();
761 const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr);
762 if (!Inner)
763 return nullptr;
764
765 if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
766 return &Inner->getSymbol();
767 return nullptr;
768}
769
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000770// True if the assembler knows nothing about the final value of the symbol.
771// This doesn't cover the comdat issues, since in those cases the assembler
772// can at least know that all symbols in the section will move together.
Rafael Espindolac9e70682015-03-24 23:48:44 +0000773static bool isWeak(const MCSymbolData &D) {
Rafael Espindolaa635d832015-04-17 08:46:11 +0000774 if (MCELF::GetType(D) == ELF::STT_GNU_IFUNC)
775 return true;
776
777 switch (MCELF::GetBinding(D)) {
778 default:
779 llvm_unreachable("Unknown binding");
780 case ELF::STB_LOCAL:
781 return false;
782 case ELF::STB_GLOBAL:
Rafael Espindoladb8a5862015-04-17 20:05:17 +0000783 return false;
Rafael Espindolaa635d832015-04-17 08:46:11 +0000784 case ELF::STB_WEAK:
785 case ELF::STB_GNU_UNIQUE:
786 return true;
787 }
Rafael Espindolac9e70682015-03-24 23:48:44 +0000788}
789
Rafael Espindola26585542015-01-19 21:11:14 +0000790void ELFObjectWriter::RecordRelocation(MCAssembler &Asm,
Jason W Kim495c2bb2010-12-06 21:57:34 +0000791 const MCAsmLayout &Layout,
792 const MCFragment *Fragment,
Rafael Espindola26585542015-01-19 21:11:14 +0000793 const MCFixup &Fixup, MCValue Target,
794 bool &IsPCRel, uint64_t &FixedValue) {
Rafael Espindola34948e52015-04-30 00:45:46 +0000795 const MCSectionData *FixupSectionD = Fragment->getParent();
796 const MCSectionELF &FixupSection =
797 cast<MCSectionELF>(FixupSectionD->getSection());
Rafael Espindola5904e122014-03-29 06:26:49 +0000798 uint64_t C = Target.getConstant();
799 uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000800
Rafael Espindola5904e122014-03-29 06:26:49 +0000801 if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
802 assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
803 "Should not have constructed this");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000804
Rafael Espindola5904e122014-03-29 06:26:49 +0000805 // Let A, B and C being the components of Target and R be the location of
806 // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
807 // If it is pcrel, we want to compute (A - B + C - R).
Jason W Kim495c2bb2010-12-06 21:57:34 +0000808
Rafael Espindola5904e122014-03-29 06:26:49 +0000809 // In general, ELF has no relocations for -B. It can only represent (A + C)
810 // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
811 // replace B to implement it: (A - R - K + C)
812 if (IsPCRel)
813 Asm.getContext().FatalError(
814 Fixup.getLoc(),
815 "No relocation available to represent this relative expression");
David Majnemera45a1762014-01-06 07:39:46 +0000816
Rafael Espindola5904e122014-03-29 06:26:49 +0000817 const MCSymbol &SymB = RefB->getSymbol();
Jason W Kim495c2bb2010-12-06 21:57:34 +0000818
Rafael Espindola5904e122014-03-29 06:26:49 +0000819 if (SymB.isUndefined())
820 Asm.getContext().FatalError(
821 Fixup.getLoc(),
822 Twine("symbol '") + SymB.getName() +
823 "' can not be undefined in a subtraction expression");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000824
Rafael Espindola5904e122014-03-29 06:26:49 +0000825 assert(!SymB.isAbsolute() && "Should have been folded");
826 const MCSection &SecB = SymB.getSection();
Rafael Espindola34948e52015-04-30 00:45:46 +0000827 if (&SecB != &FixupSection)
Rafael Espindola5904e122014-03-29 06:26:49 +0000828 Asm.getContext().FatalError(
829 Fixup.getLoc(), "Cannot represent a difference across sections");
Jason W Kim495c2bb2010-12-06 21:57:34 +0000830
Rafael Espindola5904e122014-03-29 06:26:49 +0000831 const MCSymbolData &SymBD = Asm.getSymbolData(SymB);
Rafael Espindolaf275ad82015-03-25 13:16:53 +0000832 if (::isWeak(SymBD))
Rafael Espindolac9e70682015-03-24 23:48:44 +0000833 Asm.getContext().FatalError(
834 Fixup.getLoc(), "Cannot represent a subtraction with a weak symbol");
835
Rafael Espindola5904e122014-03-29 06:26:49 +0000836 uint64_t SymBOffset = Layout.getSymbolOffset(&SymBD);
837 uint64_t K = SymBOffset - FixupOffset;
838 IsPCRel = true;
839 C -= K;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000840 }
841
Rafael Espindola5904e122014-03-29 06:26:49 +0000842 // We either rejected the fixup or folded B into C at this point.
843 const MCSymbolRefExpr *RefA = Target.getSymA();
844 const MCSymbol *SymA = RefA ? &RefA->getSymbol() : nullptr;
845 const MCSymbolData *SymAD = SymA ? &Asm.getSymbolData(*SymA) : nullptr;
846
Rafael Espindolac03f44c2014-03-27 20:49:35 +0000847 unsigned Type = GetRelocType(Target, Fixup, IsPCRel);
Rafael Espindolab60c8292014-04-29 12:46:50 +0000848 bool RelocateWithSymbol = shouldRelocateWithSymbol(Asm, RefA, SymAD, C, Type);
Rafael Espindola5904e122014-03-29 06:26:49 +0000849 if (!RelocateWithSymbol && SymA && !SymA->isUndefined())
850 C += Layout.getSymbolOffset(SymAD);
851
852 uint64_t Addend = 0;
853 if (hasRelocationAddend()) {
854 Addend = C;
855 C = 0;
856 }
857
858 FixedValue = C;
859
860 // FIXME: What is this!?!?
861 MCSymbolRefExpr::VariantKind Modifier =
862 RefA ? RefA->getKind() : MCSymbolRefExpr::VK_None;
Rafael Espindola9e252bf2011-12-21 14:26:29 +0000863 if (RelocNeedsGOT(Modifier))
864 NeedsGOT = true;
Jan Sjödin30a52de2011-02-28 21:45:04 +0000865
Rafael Espindola5904e122014-03-29 06:26:49 +0000866 if (!RelocateWithSymbol) {
867 const MCSection *SecA =
868 (SymA && !SymA->isUndefined()) ? &SymA->getSection() : nullptr;
Rafael Espindolab6613022014-10-17 01:48:58 +0000869 auto *ELFSec = cast_or_null<MCSectionELF>(SecA);
870 MCSymbol *SectionSymbol =
871 ELFSec ? Asm.getContext().getOrCreateSectionSymbol(*ELFSec)
872 : nullptr;
873 ELFRelocationEntry Rec(FixupOffset, SectionSymbol, Type, Addend);
Rafael Espindola34948e52015-04-30 00:45:46 +0000874 Relocations[&FixupSection].push_back(Rec);
Rafael Espindola5904e122014-03-29 06:26:49 +0000875 return;
876 }
Roman Divackydfbecd12011-08-04 19:08:19 +0000877
Rafael Espindola5904e122014-03-29 06:26:49 +0000878 if (SymA) {
879 if (const MCSymbol *R = Renames.lookup(SymA))
880 SymA = R;
Rafael Espindolad7facaf2011-08-04 13:05:26 +0000881
Rafael Espindola3d082fa2014-05-03 19:57:04 +0000882 if (const MCSymbol *WeakRef = getWeakRef(*RefA))
883 WeakrefUsedInReloc.insert(WeakRef);
Rafael Espindola5904e122014-03-29 06:26:49 +0000884 else
885 UsedInReloc.insert(SymA);
886 }
887 ELFRelocationEntry Rec(FixupOffset, SymA, Type, Addend);
Rafael Espindola34948e52015-04-30 00:45:46 +0000888 Relocations[&FixupSection].push_back(Rec);
Rafael Espindola5904e122014-03-29 06:26:49 +0000889 return;
Jason W Kim495c2bb2010-12-06 21:57:34 +0000890}
891
892
Benjamin Kramer86511dc2010-08-23 21:19:37 +0000893uint64_t
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +0000894ELFObjectWriter::getSymbolIndexInSymbolTable(const MCAssembler &Asm,
895 const MCSymbol *S) {
David Blaikie908f4d42014-04-24 16:59:40 +0000896 const MCSymbolData &SD = Asm.getSymbolData(*S);
Rafael Espindola0e3decf2010-11-14 03:12:24 +0000897 return SD.getIndex();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000898}
899
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000900bool ELFObjectWriter::isInSymtab(const MCAsmLayout &Layout,
901 const MCSymbolData &Data, bool Used,
902 bool Renamed) {
Rafael Espindola7fadc0e2014-03-20 02:12:01 +0000903 const MCSymbol &Symbol = Data.getSymbol();
904 if (Symbol.isVariable()) {
905 const MCExpr *Expr = Symbol.getVariableValue();
906 if (const MCSymbolRefExpr *Ref = dyn_cast<MCSymbolRefExpr>(Expr)) {
907 if (Ref->getKind() == MCSymbolRefExpr::VK_WEAKREF)
908 return false;
909 }
910 }
Rafael Espindola16145972010-11-01 14:28:48 +0000911
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000912 if (Used)
913 return true;
914
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +0000915 if (Renamed)
916 return false;
917
Rafael Espindola45834a02010-10-29 23:09:31 +0000918 if (Symbol.getName() == "_GLOBAL_OFFSET_TABLE_")
919 return true;
920
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000921 if (Symbol.isVariable()) {
Rafael Espindola2aeac7a2014-05-01 13:24:25 +0000922 const MCSymbol *Base = Layout.getBaseSymbol(Symbol);
Rafael Espindola3b5ee552014-04-28 13:39:57 +0000923 if (Base && Base->isUndefined())
924 return false;
925 }
Rafael Espindola9e18e962011-02-23 20:22:07 +0000926
Jan Sjödin30a52de2011-02-28 21:45:04 +0000927 bool IsGlobal = MCELF::GetBinding(Data) == ELF::STB_GLOBAL;
Rafael Espindola9e18e962011-02-23 20:22:07 +0000928 if (!Symbol.isVariable() && Symbol.isUndefined() && !IsGlobal)
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +0000929 return false;
930
Rafael Espindolaee8d1512010-10-19 19:31:37 +0000931 if (Symbol.isTemporary())
Rafael Espindolab1d07892010-10-05 18:01:23 +0000932 return false;
933
934 return true;
935}
936
Rafael Espindola39f50422014-04-28 14:24:44 +0000937bool ELFObjectWriter::isLocal(const MCSymbolData &Data, bool isUsedInReloc) {
Rafael Espindolab1d07892010-10-05 18:01:23 +0000938 if (Data.isExternal())
939 return false;
940
941 const MCSymbol &Symbol = Data.getSymbol();
Rafael Espindola39f50422014-04-28 14:24:44 +0000942 if (Symbol.isDefined())
943 return true;
Rafael Espindola7d0ba342010-11-14 04:17:37 +0000944
Rafael Espindola39f50422014-04-28 14:24:44 +0000945 if (isUsedInReloc)
Rafael Espindolab1d07892010-10-05 18:01:23 +0000946 return false;
947
948 return true;
949}
950
Rafael Espindola8a90d872015-04-28 21:52:33 +0000951void ELFObjectWriter::maybeAddToGroup(MCAssembler &Asm,
Rafael Espindola89feff32015-04-28 22:59:58 +0000952 ArrayRef<const MCSectionELF *> Sections,
Rafael Espindola8a90d872015-04-28 21:52:33 +0000953 const RevGroupMapTy &RevGroupMap,
954 const MCSectionELF &Section,
955 unsigned Index) {
956 const MCSymbol *Sym = Section.getGroup();
957 if (!Sym)
958 return;
Rafael Espindola89feff32015-04-28 22:59:58 +0000959 const MCSectionELF *Group = Sections[RevGroupMap.lookup(Sym) - 1];
Rafael Espindola8a90d872015-04-28 21:52:33 +0000960 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
961 // FIXME: we could use the previous fragment
962 MCDataFragment *F = new MCDataFragment(&Data);
963 write(*F, Index);
964}
965
966void ELFObjectWriter::computeIndexMap(
967 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections,
968 SectionIndexMapTy &SectionIndexMap, const RevGroupMapTy &RevGroupMap) {
Rafael Espindolaad3cfaa2015-04-28 20:23:35 +0000969 for (const MCSectionData &SD : Asm) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000970 const MCSectionELF &Section =
Rafael Espindolaead85492015-02-17 20:31:13 +0000971 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindolacf6d5a92015-04-28 22:26:19 +0000972 if (Section.getType() == ELF::SHT_GROUP)
Rafael Espindolaa3e9a222010-11-11 18:13:52 +0000973 continue;
Rafael Espindola8a90d872015-04-28 21:52:33 +0000974 Sections.push_back(&Section);
975 unsigned Index = Sections.size();
976 SectionIndexMap[&Section] = Index;
Rafael Espindola89feff32015-04-28 22:59:58 +0000977 maybeAddToGroup(Asm, Sections, RevGroupMap, Section, Index);
Rafael Espindola34948e52015-04-30 00:45:46 +0000978 createRelocationSection(Asm, Section);
Rafael Espindola8a90d872015-04-28 21:52:33 +0000979 }
Rafael Espindolad6340032010-11-10 21:51:05 +0000980}
981
Rafael Espindolaea1b3942015-04-07 19:00:17 +0000982void ELFObjectWriter::computeSymbolTable(
983 MCAssembler &Asm, const MCAsmLayout &Layout,
984 const SectionIndexMapTy &SectionIndexMap,
985 const RevGroupMapTy &RevGroupMap) {
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000986 // FIXME: Is this the correct place to do this?
Rafael Espindola940a0ee2011-06-05 01:20:06 +0000987 // FIXME: Why is an undefined reference to _GLOBAL_OFFSET_TABLE_ needed?
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000988 if (NeedsGOT) {
Dmitri Gribenko226fea52013-01-13 16:01:15 +0000989 StringRef Name = "_GLOBAL_OFFSET_TABLE_";
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000990 MCSymbol *Sym = Asm.getContext().GetOrCreateSymbol(Name);
991 MCSymbolData &Data = Asm.getOrCreateSymbolData(*Sym);
992 Data.setExternal(true);
Jan Sjödin30a52de2011-02-28 21:45:04 +0000993 MCELF::SetBinding(Data, ELF::STB_GLOBAL);
Rafael Espindolad03e81d2010-10-05 15:48:37 +0000994 }
995
Rafael Espindolabee6e9f2010-10-14 16:34:44 +0000996 // Add the data for the symbols.
David Blaikie583a31c2014-04-18 18:24:25 +0000997 for (MCSymbolData &SD : Asm.symbols()) {
998 const MCSymbol &Symbol = SD.getSymbol();
Matt Fleming6c1ad482010-08-16 18:57:57 +0000999
Rafael Espindola16145972010-11-01 14:28:48 +00001000 bool Used = UsedInReloc.count(&Symbol);
1001 bool WeakrefUsed = WeakrefUsedInReloc.count(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001002 bool isSignature = RevGroupMap.count(&Symbol);
1003
Rafael Espindola3b5ee552014-04-28 13:39:57 +00001004 if (!isInSymtab(Layout, SD,
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001005 Used || WeakrefUsed || isSignature,
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001006 Renames.count(&Symbol)))
Matt Fleming6c1ad482010-08-16 18:57:57 +00001007 continue;
1008
Matt Fleming6c1ad482010-08-16 18:57:57 +00001009 ELFSymbolData MSD;
David Blaikie583a31c2014-04-18 18:24:25 +00001010 MSD.SymbolData = &SD;
Rafael Espindola2aeac7a2014-05-01 13:24:25 +00001011 const MCSymbol *BaseSymbol = Layout.getBaseSymbol(Symbol);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001012
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001013 // Undefined symbols are global, but this is the first place we
1014 // are able to set it.
Rafael Espindola39f50422014-04-28 14:24:44 +00001015 bool Local = isLocal(SD, Used);
David Blaikie583a31c2014-04-18 18:24:25 +00001016 if (!Local && MCELF::GetBinding(SD) == ELF::STB_LOCAL) {
Rafael Espindola022bb762014-03-24 03:43:21 +00001017 assert(BaseSymbol);
David Blaikie583a31c2014-04-18 18:24:25 +00001018 MCSymbolData &BaseData = Asm.getSymbolData(*BaseSymbol);
Jan Sjödin30a52de2011-02-28 21:45:04 +00001019 MCELF::SetBinding(SD, ELF::STB_GLOBAL);
David Blaikie583a31c2014-04-18 18:24:25 +00001020 MCELF::SetBinding(BaseData, ELF::STB_GLOBAL);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001021 }
1022
Rafael Espindola022bb762014-03-24 03:43:21 +00001023 if (!BaseSymbol) {
1024 MSD.SectionIndex = ELF::SHN_ABS;
David Blaikie583a31c2014-04-18 18:24:25 +00001025 } else if (SD.isCommon()) {
Rafael Espindolabee6e9f2010-10-14 16:34:44 +00001026 assert(!Local);
Rafael Espindolaf0591c12010-09-21 00:24:38 +00001027 MSD.SectionIndex = ELF::SHN_COMMON;
Rafael Espindola022bb762014-03-24 03:43:21 +00001028 } else if (BaseSymbol->isUndefined()) {
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001029 if (isSignature && !Used)
Rafael Espindola89feff32015-04-28 22:59:58 +00001030 MSD.SectionIndex = RevGroupMap.lookup(&Symbol);
Rafael Espindola7d0ba342010-11-14 04:17:37 +00001031 else
1032 MSD.SectionIndex = ELF::SHN_UNDEF;
Rafael Espindola022bb762014-03-24 03:43:21 +00001033 if (!Used && WeakrefUsed)
David Blaikie583a31c2014-04-18 18:24:25 +00001034 MCELF::SetBinding(SD, ELF::STB_WEAK);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001035 } else {
Rafael Espindolad6340032010-11-10 21:51:05 +00001036 const MCSectionELF &Section =
Rafael Espindola022bb762014-03-24 03:43:21 +00001037 static_cast<const MCSectionELF&>(BaseSymbol->getSection());
Rafael Espindolad6340032010-11-10 21:51:05 +00001038 MSD.SectionIndex = SectionIndexMap.lookup(&Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001039 assert(MSD.SectionIndex && "Invalid section index!");
Rafael Espindolafbcf0db2010-10-15 15:39:06 +00001040 }
1041
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001042 // The @@@ in symbol version is replaced with @ in undefined symbols and @@
1043 // in defined ones.
1044 //
1045 // FIXME: All name handling should be done before we get to the writer,
NAKAMURA Takumib01d86b2015-02-25 11:02:00 +00001046 // including dealing with GNU-style version suffixes. Fixing this isn't
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001047 // trivial.
1048 //
1049 // We thus have to be careful to not perform the symbol version replacement
1050 // blindly:
1051 //
1052 // The ELF format is used on Windows by the MCJIT engine. Thus, on
1053 // Windows, the ELFObjectWriter can encounter symbols mangled using the MS
1054 // Visual Studio C++ name mangling scheme. Symbols mangled using the MSVC
1055 // C++ name mangling can legally have "@@@" as a sub-string. In that case,
1056 // the EFLObjectWriter should not interpret the "@@@" sub-string as
1057 // specifying GNU-style symbol versioning. The ELFObjectWriter therefore
1058 // checks for the MSVC C++ name mangling prefix which is either "?", "@?",
1059 // "__imp_?" or "__imp_@?".
1060 //
1061 // It would have been interesting to perform the MS mangling prefix check
1062 // only when the target triple is of the form *-pc-windows-elf. But, it
1063 // seems that this information is not easily accessible from the
1064 // ELFObjectWriter.
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001065 StringRef Name = Symbol.getName();
Rafael Espindola5a67ed12015-01-22 14:20:45 +00001066 if (!Name.startswith("?") && !Name.startswith("@?") &&
1067 !Name.startswith("__imp_?") && !Name.startswith("__imp_@?")) {
1068 // This symbol isn't following the MSVC C++ name mangling convention. We
1069 // can thus safely interpret the @@@ in symbol names as specifying symbol
1070 // versioning.
1071 SmallString<32> Buf;
1072 size_t Pos = Name.find("@@@");
1073 if (Pos != StringRef::npos) {
1074 Buf += Name.substr(0, Pos);
1075 unsigned Skip = MSD.SectionIndex == ELF::SHN_UNDEF ? 2 : 1;
1076 Buf += Name.substr(Pos + Skip);
1077 Name = Buf;
1078 }
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001079 }
Rafael Espindolab6613022014-10-17 01:48:58 +00001080
1081 // Sections have their own string table
1082 if (MCELF::GetType(SD) != ELF::STT_SECTION)
1083 MSD.Name = StrTabBuilder.add(Name);
Rafael Espindolaeb0c2c12010-10-27 15:18:17 +00001084
Rafael Espindolaa5efd6a2010-10-27 14:44:52 +00001085 if (MSD.SectionIndex == ELF::SHN_UNDEF)
1086 UndefinedSymbolData.push_back(MSD);
1087 else if (Local)
1088 LocalSymbolData.push_back(MSD);
1089 else
1090 ExternalSymbolData.push_back(MSD);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001091 }
1092
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001093 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1094 StrTabBuilder.add(*i);
1095
Hans Wennborgf26bfc12014-09-29 22:43:20 +00001096 StrTabBuilder.finalize(StringTableBuilder::ELF);
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001097
1098 for (auto i = Asm.file_names_begin(), e = Asm.file_names_end(); i != e; ++i)
1099 FileSymbolData.push_back(StrTabBuilder.getOffset(*i));
1100
Rafael Espindolab6613022014-10-17 01:48:58 +00001101 for (ELFSymbolData &MSD : LocalSymbolData)
1102 MSD.StringIndex = MCELF::GetType(*MSD.SymbolData) == ELF::STT_SECTION
1103 ? 0
1104 : StrTabBuilder.getOffset(MSD.Name);
1105 for (ELFSymbolData &MSD : ExternalSymbolData)
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001106 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1107 for (ELFSymbolData& MSD : UndefinedSymbolData)
1108 MSD.StringIndex = StrTabBuilder.getOffset(MSD.Name);
1109
Matt Fleming6c1ad482010-08-16 18:57:57 +00001110 // Symbols are required to be in lexicographic order.
1111 array_pod_sort(LocalSymbolData.begin(), LocalSymbolData.end());
1112 array_pod_sort(ExternalSymbolData.begin(), ExternalSymbolData.end());
1113 array_pod_sort(UndefinedSymbolData.begin(), UndefinedSymbolData.end());
1114
1115 // Set the symbol indices. Local symbols must come before all other
1116 // symbols with non-local bindings.
Joerg Sonnenbergerfc184732013-10-29 01:06:17 +00001117 unsigned Index = FileSymbolData.size() + 1;
Matt Fleming6c1ad482010-08-16 18:57:57 +00001118 for (unsigned i = 0, e = LocalSymbolData.size(); i != e; ++i)
1119 LocalSymbolData[i].SymbolData->setIndex(Index++);
Rafael Espindola0e3decf2010-11-14 03:12:24 +00001120
Matt Fleming6c1ad482010-08-16 18:57:57 +00001121 for (unsigned i = 0, e = ExternalSymbolData.size(); i != e; ++i)
1122 ExternalSymbolData[i].SymbolData->setIndex(Index++);
1123 for (unsigned i = 0, e = UndefinedSymbolData.size(); i != e; ++i)
1124 UndefinedSymbolData[i].SymbolData->setIndex(Index++);
1125}
1126
Rafael Espindolacf6d5a92015-04-28 22:26:19 +00001127void ELFObjectWriter::createRelocationSection(MCAssembler &Asm,
Rafael Espindola34948e52015-04-30 00:45:46 +00001128 const MCSectionELF &Sec) {
1129 if (Relocations[&Sec].empty())
Rafael Espindolacf6d5a92015-04-28 22:26:19 +00001130 return;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001131
Rafael Espindolaead85492015-02-17 20:31:13 +00001132 MCContext &Ctx = Asm.getContext();
Rafael Espindola34948e52015-04-30 00:45:46 +00001133 const StringRef SectionName = Sec.getSectionName();
Rafael Espindolaead85492015-02-17 20:31:13 +00001134 std::string RelaSectionName = hasRelocationAddend() ? ".rela" : ".rel";
1135 RelaSectionName += SectionName;
Benjamin Kramerfd054152010-08-17 17:56:13 +00001136
Rafael Espindolaead85492015-02-17 20:31:13 +00001137 unsigned EntrySize;
1138 if (hasRelocationAddend())
1139 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rela) : sizeof(ELF::Elf32_Rela);
1140 else
1141 EntrySize = is64Bit() ? sizeof(ELF::Elf64_Rel) : sizeof(ELF::Elf32_Rel);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001142
Rafael Espindolaead85492015-02-17 20:31:13 +00001143 unsigned Flags = 0;
Rafael Espindola34948e52015-04-30 00:45:46 +00001144 if (Sec.getFlags() & ELF::SHF_GROUP)
Rafael Espindolaead85492015-02-17 20:31:13 +00001145 Flags = ELF::SHF_GROUP;
Rafael Espindolaead85492015-02-17 20:31:13 +00001146
Rafael Espindolac9d06922015-03-30 13:39:16 +00001147 const MCSectionELF *RelaSection = Ctx.createELFRelSection(
Rafael Espindolaead85492015-02-17 20:31:13 +00001148 RelaSectionName, hasRelocationAddend() ? ELF::SHT_RELA : ELF::SHT_REL,
Rafael Espindola34948e52015-04-30 00:45:46 +00001149 Flags, EntrySize, Sec.getGroup(), &Sec);
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001150 MCSectionData &RelSD = Asm.getOrCreateSectionData(*RelaSection);
1151 RelSD.setAlignment(is64Bit() ? 8 : 4);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001152}
Matt Fleming6c1ad482010-08-16 18:57:57 +00001153
David Blaikiee06e8012014-04-11 22:11:50 +00001154static SmallVector<char, 128>
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001155getUncompressedData(const MCAsmLayout &Layout,
David Blaikiee06e8012014-04-11 22:11:50 +00001156 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001157 SmallVector<char, 128> UncompressedData;
1158 for (const MCFragment &F : Fragments) {
1159 const SmallVectorImpl<char> *Contents;
1160 switch (F.getKind()) {
1161 case MCFragment::FT_Data:
1162 Contents = &cast<MCDataFragment>(F).getContents();
1163 break;
1164 case MCFragment::FT_Dwarf:
1165 Contents = &cast<MCDwarfLineAddrFragment>(F).getContents();
1166 break;
1167 case MCFragment::FT_DwarfFrame:
1168 Contents = &cast<MCDwarfCallFrameFragment>(F).getContents();
1169 break;
1170 default:
1171 llvm_unreachable(
1172 "Not expecting any other fragment types in a debug_* section");
1173 }
1174 UncompressedData.append(Contents->begin(), Contents->end());
1175 }
1176 return UncompressedData;
1177}
1178
1179// Include the debug info compression header:
1180// "ZLIB" followed by 8 bytes representing the uncompressed size of the section,
1181// useful for consumers to preallocate a buffer to decompress into.
David Blaikie76d3a3c2014-04-18 21:52:26 +00001182static bool
David Blaikiee06e8012014-04-11 22:11:50 +00001183prependCompressionHeader(uint64_t Size,
1184 SmallVectorImpl<char> &CompressedContents) {
Benjamin Kramer7149aab2015-03-01 18:09:56 +00001185 const StringRef Magic = "ZLIB";
David Blaikie76d3a3c2014-04-18 21:52:26 +00001186 if (Size <= Magic.size() + sizeof(Size) + CompressedContents.size())
1187 return false;
David Blaikie8019bf82014-04-10 21:53:53 +00001188 if (sys::IsLittleEndianHost)
Artyom Skrobov9aea8432014-06-14 13:18:07 +00001189 sys::swapByteOrder(Size);
David Blaikie8019bf82014-04-10 21:53:53 +00001190 CompressedContents.insert(CompressedContents.begin(),
1191 Magic.size() + sizeof(Size), 0);
1192 std::copy(Magic.begin(), Magic.end(), CompressedContents.begin());
1193 std::copy(reinterpret_cast<char *>(&Size),
1194 reinterpret_cast<char *>(&Size + 1),
1195 CompressedContents.begin() + Magic.size());
David Blaikie76d3a3c2014-04-18 21:52:26 +00001196 return true;
David Blaikie8019bf82014-04-10 21:53:53 +00001197}
1198
1199// Return a single fragment containing the compressed contents of the whole
1200// section. Null if the section was not compressed for any reason.
David Blaikiee06e8012014-04-11 22:11:50 +00001201static std::unique_ptr<MCDataFragment>
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001202getCompressedFragment(const MCAsmLayout &Layout,
David Blaikiee06e8012014-04-11 22:11:50 +00001203 MCSectionData::FragmentListType &Fragments) {
David Blaikie8019bf82014-04-10 21:53:53 +00001204 std::unique_ptr<MCDataFragment> CompressedFragment(new MCDataFragment());
1205
1206 // Gather the uncompressed data from all the fragments, recording the
1207 // alignment fragment, if seen, and any fixups.
1208 SmallVector<char, 128> UncompressedData =
1209 getUncompressedData(Layout, Fragments);
1210
1211 SmallVectorImpl<char> &CompressedContents = CompressedFragment->getContents();
1212
1213 zlib::Status Success = zlib::compress(
1214 StringRef(UncompressedData.data(), UncompressedData.size()),
1215 CompressedContents);
1216 if (Success != zlib::StatusOK)
1217 return nullptr;
1218
David Blaikie76d3a3c2014-04-18 21:52:26 +00001219 if (!prependCompressionHeader(UncompressedData.size(), CompressedContents))
1220 return nullptr;
David Blaikie8019bf82014-04-10 21:53:53 +00001221
1222 return CompressedFragment;
1223}
1224
David Blaikie39fa6a22014-04-25 00:48:01 +00001225typedef DenseMap<const MCSectionData *, std::vector<MCSymbolData *>>
1226DefiningSymbolMap;
1227
1228static void UpdateSymbols(const MCAsmLayout &Layout,
1229 const std::vector<MCSymbolData *> &Symbols,
1230 MCFragment &NewFragment) {
1231 for (MCSymbolData *Sym : Symbols) {
1232 Sym->setOffset(Sym->getOffset() +
1233 Layout.getFragmentOffset(Sym->getFragment()));
1234 Sym->setFragment(&NewFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001235 }
1236}
1237
David Blaikie8019bf82014-04-10 21:53:53 +00001238static void CompressDebugSection(MCAssembler &Asm, MCAsmLayout &Layout,
David Blaikie39fa6a22014-04-25 00:48:01 +00001239 const DefiningSymbolMap &DefiningSymbols,
David Blaikie8019bf82014-04-10 21:53:53 +00001240 const MCSectionELF &Section,
1241 MCSectionData &SD) {
1242 StringRef SectionName = Section.getSectionName();
1243 MCSectionData::FragmentListType &Fragments = SD.getFragmentList();
1244
1245 std::unique_ptr<MCDataFragment> CompressedFragment =
1246 getCompressedFragment(Layout, Fragments);
1247
1248 // Leave the section as-is if the fragments could not be compressed.
1249 if (!CompressedFragment)
1250 return;
1251
David Blaikiec029ab42014-04-18 21:24:12 +00001252 // Update the fragment+offsets of any symbols referring to fragments in this
1253 // section to refer to the new fragment.
David Blaikie39fa6a22014-04-25 00:48:01 +00001254 auto I = DefiningSymbols.find(&SD);
1255 if (I != DefiningSymbols.end())
1256 UpdateSymbols(Layout, I->second, *CompressedFragment);
David Blaikiec029ab42014-04-18 21:24:12 +00001257
David Blaikie8019bf82014-04-10 21:53:53 +00001258 // Invalidate the layout for the whole section since it will have new and
1259 // different fragments now.
1260 Layout.invalidateFragmentsFrom(&Fragments.front());
1261 Fragments.clear();
1262
1263 // Complete the initialization of the new fragment
1264 CompressedFragment->setParent(&SD);
1265 CompressedFragment->setLayoutOrder(0);
1266 Fragments.push_back(CompressedFragment.release());
1267
1268 // Rename from .debug_* to .zdebug_*
1269 Asm.getContext().renameELFSection(&Section,
1270 (".z" + SectionName.drop_front(1)).str());
1271}
1272
1273void ELFObjectWriter::CompressDebugSections(MCAssembler &Asm,
1274 MCAsmLayout &Layout) {
1275 if (!Asm.getContext().getAsmInfo()->compressDebugSections())
1276 return;
1277
David Blaikie39fa6a22014-04-25 00:48:01 +00001278 DefiningSymbolMap DefiningSymbols;
1279
1280 for (MCSymbolData &SD : Asm.symbols())
1281 if (MCFragment *F = SD.getFragment())
1282 DefiningSymbols[F->getParent()].push_back(&SD);
1283
David Blaikie8019bf82014-04-10 21:53:53 +00001284 for (MCSectionData &SD : Asm) {
David Blaikiee06e8012014-04-11 22:11:50 +00001285 const MCSectionELF &Section =
1286 static_cast<const MCSectionELF &>(SD.getSection());
David Blaikie8019bf82014-04-10 21:53:53 +00001287 StringRef SectionName = Section.getSectionName();
1288
1289 // Compressing debug_frame requires handling alignment fragments which is
1290 // more work (possibly generalizing MCAssembler.cpp:writeFragment to allow
1291 // for writing to arbitrary buffers) for little benefit.
1292 if (!SectionName.startswith(".debug_") || SectionName == ".debug_frame")
1293 continue;
1294
David Blaikie39fa6a22014-04-25 00:48:01 +00001295 CompressDebugSection(Asm, Layout, DefiningSymbols, Section, SD);
David Blaikie8019bf82014-04-10 21:53:53 +00001296 }
1297}
1298
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001299void ELFObjectWriter::WriteSecHdrEntry(uint32_t Name, uint32_t Type,
1300 uint64_t Flags, uint64_t Address,
1301 uint64_t Offset, uint64_t Size,
1302 uint32_t Link, uint32_t Info,
1303 uint64_t Alignment,
1304 uint64_t EntrySize) {
Matt Fleming6c1ad482010-08-16 18:57:57 +00001305 Write32(Name); // sh_name: index into string table
1306 Write32(Type); // sh_type
1307 WriteWord(Flags); // sh_flags
1308 WriteWord(Address); // sh_addr
1309 WriteWord(Offset); // sh_offset
1310 WriteWord(Size); // sh_size
1311 Write32(Link); // sh_link
1312 Write32(Info); // sh_info
1313 WriteWord(Alignment); // sh_addralign
1314 WriteWord(EntrySize); // sh_entsize
1315}
1316
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001317void ELFObjectWriter::writeRelocations(const MCAssembler &Asm,
Rafael Espindola34948e52015-04-30 00:45:46 +00001318 const MCSectionELF &Sec) {
1319 std::vector<ELFRelocationEntry> &Relocs = Relocations[&Sec];
Akira Hatanaka64ad2cf2012-03-23 23:06:45 +00001320
Petar Jovanovic0380d0b2015-04-14 13:23:34 +00001321 // Sort the relocation entries. Most targets just sort by Offset, but some
1322 // (e.g., MIPS) have additional constraints.
1323 TargetObjectWriter->sortRelocs(Asm, Relocs);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001324
1325 for (unsigned i = 0, e = Relocs.size(); i != e; ++i) {
Rafael Espindola5904e122014-03-29 06:26:49 +00001326 const ELFRelocationEntry &Entry = Relocs[e - i - 1];
Rafael Espindolab6613022014-10-17 01:48:58 +00001327 unsigned Index =
1328 Entry.Symbol ? getSymbolIndexInSymbolTable(Asm, Entry.Symbol) : 0;
Rafael Espindola5904e122014-03-29 06:26:49 +00001329
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001330 if (is64Bit()) {
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001331 write(Entry.Offset);
Jack Carter8ad0c272012-06-27 22:28:30 +00001332 if (TargetObjectWriter->isN64()) {
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001333 write(uint32_t(Index));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001334
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001335 write(TargetObjectWriter->getRSsym(Entry.Type));
1336 write(TargetObjectWriter->getRType3(Entry.Type));
1337 write(TargetObjectWriter->getRType2(Entry.Type));
1338 write(TargetObjectWriter->getRType(Entry.Type));
Rafael Espindola5904e122014-03-29 06:26:49 +00001339 } else {
Jack Carter8ad0c272012-06-27 22:28:30 +00001340 struct ELF::Elf64_Rela ERE64;
Rafael Espindola5904e122014-03-29 06:26:49 +00001341 ERE64.setSymbolAndType(Index, Entry.Type);
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001342 write(ERE64.r_info);
Jack Carter8ad0c272012-06-27 22:28:30 +00001343 }
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001344 if (hasRelocationAddend())
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001345 write(Entry.Addend);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001346 } else {
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001347 write(uint32_t(Entry.Offset));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001348
Rafael Espindolabce26a12010-10-05 15:11:03 +00001349 struct ELF::Elf32_Rela ERE32;
Rafael Espindola5904e122014-03-29 06:26:49 +00001350 ERE32.setSymbolAndType(Index, Entry.Type);
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001351 write(ERE32.r_info);
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001352
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001353 if (hasRelocationAddend())
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001354 write(uint32_t(Entry.Addend));
Benjamin Kramer6c3c3492010-09-09 18:01:29 +00001355 }
Matt Fleming6c1ad482010-08-16 18:57:57 +00001356 }
1357}
1358
Rafael Espindola88d1f632015-04-29 20:25:24 +00001359void ELFObjectWriter::createSectionHeaderStringTable(
1360 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections) {
1361 const MCSectionELF *ShstrtabSection = Sections[ShstrtabIndex - 1];
1362
1363 Asm.getOrCreateSectionData(*ShstrtabSection);
1364
1365 for (MCSectionData &SD : Asm) {
1366 const MCSectionELF &Section =
1367 static_cast<const MCSectionELF &>(SD.getSection());
1368 ShStrTabBuilder.add(Section.getSectionName());
1369 }
1370 ShStrTabBuilder.finalize(StringTableBuilder::ELF);
1371 OS << ShStrTabBuilder.data();
1372}
1373
Rafael Espindola88abc392015-04-29 20:34:31 +00001374void ELFObjectWriter::createStringTable(
1375 MCAssembler &Asm, std::vector<const MCSectionELF *> &Sections) {
1376 MCContext &Ctx = Asm.getContext();
1377 const MCSectionELF *StrtabSection =
1378 Ctx.getELFSection(".strtab", ELF::SHT_STRTAB, 0);
1379 Asm.getOrCreateSectionData(*StrtabSection);
1380 Sections.push_back(StrtabSection);
1381 StringTableIndex = Sections.size();
1382 OS << StrTabBuilder.data();
1383}
1384
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001385void ELFObjectWriter::createIndexedSections(
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001386 MCAssembler &Asm, const MCAsmLayout &Layout, RevGroupMapTy &RevGroupMap,
Rafael Espindola8a90d872015-04-28 21:52:33 +00001387 std::vector<const MCSectionELF *> &Sections,
Rafael Espindola55a3afb2015-04-28 21:07:28 +00001388 SectionIndexMapTy &SectionIndexMap) {
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001389 MCContext &Ctx = Asm.getContext();
Rafael Espindolab3eca9b2011-01-23 17:55:27 +00001390
Rafael Espindola88d1f632015-04-29 20:25:24 +00001391 const MCSectionELF *ShstrtabSection =
1392 Ctx.getELFSection(".shstrtab", ELF::SHT_STRTAB, 0);
1393 Sections.push_back(ShstrtabSection);
1394 ShstrtabIndex = Sections.size();
1395 assert(ShstrtabIndex == 1);
1396
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001397 // Build the groups
Rafael Espindolafac3fbc2015-04-28 21:58:05 +00001398 for (const MCSectionData &SD : Asm) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001399 const MCSectionELF &Section =
Rafael Espindolafac3fbc2015-04-28 21:58:05 +00001400 static_cast<const MCSectionELF &>(SD.getSection());
Rafael Espindola0e7e34e2011-01-23 04:43:11 +00001401 if (!(Section.getFlags() & ELF::SHF_GROUP))
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001402 continue;
1403
1404 const MCSymbol *SignatureSymbol = Section.getGroup();
1405 Asm.getOrCreateSymbolData(*SignatureSymbol);
Rafael Espindola89feff32015-04-28 22:59:58 +00001406 unsigned &GroupIdx = RevGroupMap[SignatureSymbol];
1407 if (!GroupIdx) {
1408 const MCSectionELF *Group = Ctx.createELFGroupSection(SignatureSymbol);
Rafael Espindola41920d02015-04-28 22:03:22 +00001409 Sections.push_back(Group);
Rafael Espindola89feff32015-04-28 22:59:58 +00001410 GroupIdx = Sections.size();
Rafael Espindola41920d02015-04-28 22:03:22 +00001411
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001412 MCSectionData &Data = Asm.getOrCreateSectionData(*Group);
1413 Data.setAlignment(4);
1414 MCDataFragment *F = new MCDataFragment(&Data);
Rafael Espindola0ce09712014-03-25 22:43:53 +00001415 write(*F, uint32_t(ELF::GRP_COMDAT));
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001416 }
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001417 }
1418
Rafael Espindola8a90d872015-04-28 21:52:33 +00001419 computeIndexMap(Asm, Sections, SectionIndexMap, RevGroupMap);
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001420}
1421
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001422void ELFObjectWriter::writeSection(MCAssembler &Asm,
Daniel Dunbarfe0c28f2010-11-13 07:33:40 +00001423 const SectionIndexMapTy &SectionIndexMap,
1424 uint32_t GroupSymbolIndex,
1425 uint64_t Offset, uint64_t Size,
1426 uint64_t Alignment,
1427 const MCSectionELF &Section) {
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001428 uint64_t sh_link = 0;
1429 uint64_t sh_info = 0;
1430
1431 switch(Section.getType()) {
Rafael Espindola86fe2fe2015-04-06 03:16:51 +00001432 default:
1433 // Nothing to do.
1434 break;
1435
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001436 case ELF::SHT_DYNAMIC:
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001437 sh_link = ShStrTabBuilder.getOffset(Section.getSectionName());
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001438 break;
1439
1440 case ELF::SHT_REL:
1441 case ELF::SHT_RELA: {
Rafael Espindola3a7c0eb2015-02-17 20:37:50 +00001442 sh_link = SymbolTableIndex;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001443 assert(sh_link && ".symtab not found");
Rafael Espindolab73b70e2015-04-06 03:09:30 +00001444 const MCSectionELF *InfoSection = Section.getAssociatedSection();
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001445 sh_info = SectionIndexMap.lookup(InfoSection);
1446 break;
1447 }
1448
1449 case ELF::SHT_SYMTAB:
1450 case ELF::SHT_DYNSYM:
1451 sh_link = StringTableIndex;
1452 sh_info = LastLocalSymbolIndex;
1453 break;
1454
1455 case ELF::SHT_SYMTAB_SHNDX:
1456 sh_link = SymbolTableIndex;
1457 break;
1458
Nick Lewyckyc6ac5f72011-10-07 23:28:32 +00001459 case ELF::SHT_GROUP:
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001460 sh_link = SymbolTableIndex;
1461 sh_info = GroupSymbolIndex;
1462 break;
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001463 }
1464
Logan Chien4b724422013-02-05 14:18:59 +00001465 if (TargetObjectWriter->getEMachine() == ELF::EM_ARM &&
Rafael Espindola61e8ce32015-04-06 04:25:18 +00001466 Section.getType() == ELF::SHT_ARM_EXIDX)
1467 sh_link = SectionIndexMap.lookup(Section.getAssociatedSection());
Logan Chien4b724422013-02-05 14:18:59 +00001468
Hans Wennborg83e6e1e2014-04-30 16:25:02 +00001469 WriteSecHdrEntry(ShStrTabBuilder.getOffset(Section.getSectionName()),
1470 Section.getType(),
Rafael Espindola5a8d7812010-11-10 23:36:59 +00001471 Section.getFlags(), 0, Offset, Size, sh_link, sh_info,
1472 Alignment, Section.getEntrySize());
1473}
1474
Jan Sjödin30a52de2011-02-28 21:45:04 +00001475bool ELFObjectWriter::IsELFMetaDataSection(const MCSectionData &SD) {
Rafael Espindolabaf2f3b2010-12-06 03:48:09 +00001476 return SD.getOrdinal() == ~UINT32_C(0) &&
Rafael Espindola60ebca92010-12-02 03:09:06 +00001477 !SD.getSection().isVirtualSection();
1478}
1479
Rafael Espindola642a2212015-04-14 22:54:16 +00001480void ELFObjectWriter::writeDataSectionData(MCAssembler &Asm,
Rafael Espindola1557fd62011-03-20 18:44:20 +00001481 const MCAsmLayout &Layout,
Rafael Espindola642a2212015-04-14 22:54:16 +00001482 const MCSectionData &SD) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001483 if (IsELFMetaDataSection(SD)) {
1484 for (MCSectionData::const_iterator i = SD.begin(), e = SD.end(); i != e;
1485 ++i) {
1486 const MCFragment &F = *i;
1487 assert(F.getKind() == MCFragment::FT_Data);
Eli Bendersky84b2a792012-12-07 22:06:56 +00001488 WriteBytes(cast<MCDataFragment>(F).getContents());
Rafael Espindola1557fd62011-03-20 18:44:20 +00001489 }
1490 } else {
Jim Grosbach18e2fe42011-12-06 00:03:48 +00001491 Asm.writeSectionData(&SD, Layout);
Rafael Espindola60ebca92010-12-02 03:09:06 +00001492 }
1493}
1494
Rafael Espindola7fe7e052015-02-17 20:40:59 +00001495void ELFObjectWriter::writeSectionHeader(
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001496 ArrayRef<const MCSectionELF *> Sections, MCAssembler &Asm,
Rafael Espindola55a3afb2015-04-28 21:07:28 +00001497 const MCAsmLayout &Layout, const SectionIndexMapTy &SectionIndexMap,
Rafael Espindolaa8201692015-04-28 15:26:21 +00001498 const SectionOffsetsTy &SectionOffsets) {
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001499 const unsigned NumSections = Asm.size();
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001500
Matt Fleming6c1ad482010-08-16 18:57:57 +00001501 // Null section first.
Rafael Espindola3fe87a12010-10-31 00:16:26 +00001502 uint64_t FirstSectionSize =
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001503 (NumSections + 1) >= ELF::SHN_LORESERVE ? NumSections + 1 : 0;
Rafael Espindola88d1f632015-04-29 20:25:24 +00001504 WriteSecHdrEntry(0, 0, 0, 0, 0, FirstSectionSize, 0, 0, 0, 0);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001505
Rafael Espindolabf0db6c2015-04-15 13:07:47 +00001506 for (unsigned i = 0; i < NumSections; ++i) {
Rafael Espindolaa3e9a222010-11-11 18:13:52 +00001507 const MCSectionELF &Section = *Sections[i];
1508 const MCSectionData &SD = Asm.getOrCreateSectionData(Section);
1509 uint32_t GroupSymbolIndex;
1510 if (Section.getType() != ELF::SHT_GROUP)
1511 GroupSymbolIndex = 0;
1512 else
Rafael Espindola55a3afb2015-04-28 21:07:28 +00001513 GroupSymbolIndex = getSymbolIndexInSymbolTable(Asm, Section.getGroup());
Matt Fleming6c1ad482010-08-16 18:57:57 +00001514
Rafael Espindolaa8201692015-04-28 15:26:21 +00001515 const std::pair<uint64_t, uint64_t> &Offsets = SectionOffsets[i];
Rafael Espindolab6417502015-04-28 15:04:09 +00001516 uint64_t Size = Section.getType() == ELF::SHT_NOBITS
1517 ? Layout.getSectionAddressSize(&SD)
1518 : Offsets.second - Offsets.first;
Rafael Espindola60ebca92010-12-02 03:09:06 +00001519
Rafael Espindolab6417502015-04-28 15:04:09 +00001520 writeSection(Asm, SectionIndexMap, GroupSymbolIndex, Offsets.first, Size,
1521 SD.getAlignment(), Section);
Matt Fleming6c1ad482010-08-16 18:57:57 +00001522 }
1523}
1524
Rafael Espindola1557fd62011-03-20 18:44:20 +00001525void ELFObjectWriter::WriteObject(MCAssembler &Asm,
1526 const MCAsmLayout &Layout) {
Rafael Espindola1557fd62011-03-20 18:44:20 +00001527 RevGroupMapTy RevGroupMap;
1528 SectionIndexMapTy SectionIndexMap;
1529
David Blaikiee06e8012014-04-11 22:11:50 +00001530 CompressDebugSections(Asm, const_cast<MCAsmLayout &>(Layout));
Rafael Espindola8a90d872015-04-28 21:52:33 +00001531 std::vector<const MCSectionELF *> Sections;
Rafael Espindolaae7e4992015-04-29 19:20:10 +00001532 createIndexedSections(Asm, Layout, RevGroupMap, Sections, SectionIndexMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001533
Rafael Espindola1557fd62011-03-20 18:44:20 +00001534 // Compute symbol table information.
Rafael Espindolaea1b3942015-04-07 19:00:17 +00001535 computeSymbolTable(Asm, Layout, SectionIndexMap, RevGroupMap);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001536
Rafael Espindolaa8201692015-04-28 15:26:21 +00001537 SectionOffsetsTy SectionOffsets;
Rafael Espindola1557fd62011-03-20 18:44:20 +00001538
Rafael Espindola1557fd62011-03-20 18:44:20 +00001539 // Write out the ELF header ...
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001540 writeHeader(Asm);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001541
Rafael Espindola7230f802015-04-08 11:41:24 +00001542 // ... then the sections ...
Rafael Espindola88d1f632015-04-29 20:25:24 +00001543 SectionOffsets.push_back(std::make_pair(0, 0));
1544 for (auto I = ++Sections.begin(), E = Sections.end(); I != E; ++I) {
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001545 const MCSectionELF &Sec = **I;
1546 const MCSectionData &SD = Asm.getOrCreateSectionData(Sec);
Rafael Espindola642a2212015-04-14 22:54:16 +00001547 uint64_t Padding = OffsetToAlignment(OS.tell(), SD.getAlignment());
1548 WriteZeros(Padding);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001549
Rafael Espindola642a2212015-04-14 22:54:16 +00001550 // Remember the offset into the file for this section.
Rafael Espindolab6417502015-04-28 15:04:09 +00001551 uint64_t SecStart = OS.tell();
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001552
1553 unsigned Type = Sec.getType();
Rafael Espindola34948e52015-04-30 00:45:46 +00001554 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001555 writeDataSectionData(Asm, Layout, SD);
Rafael Espindola34948e52015-04-30 00:45:46 +00001556 else
1557 writeRelocations(Asm, *Sec.getAssociatedSection());
Rafael Espindolab8cbb262015-04-30 00:30:40 +00001558
Rafael Espindolab6417502015-04-28 15:04:09 +00001559 uint64_t SecEnd = OS.tell();
Rafael Espindolaa8201692015-04-28 15:26:21 +00001560 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
Rafael Espindola642a2212015-04-14 22:54:16 +00001561 }
1562
Rafael Espindola91fd2772015-04-29 21:09:32 +00001563 WriteSymbolTable(Asm, Layout, Sections, SectionOffsets);
1564
Rafael Espindola88d1f632015-04-29 20:25:24 +00001565 {
1566 uint64_t SecStart = OS.tell();
Rafael Espindola88abc392015-04-29 20:34:31 +00001567 createStringTable(Asm, Sections);
1568 uint64_t SecEnd = OS.tell();
1569 SectionOffsets.push_back(std::make_pair(SecStart, SecEnd));
1570 }
1571
1572 {
1573 uint64_t SecStart = OS.tell();
Rafael Espindola88d1f632015-04-29 20:25:24 +00001574 createSectionHeaderStringTable(Asm, Sections);
1575 uint64_t SecEnd = OS.tell();
1576 SectionOffsets[0] = std::make_pair(SecStart, SecEnd);
1577 }
1578
Rafael Espindola642a2212015-04-14 22:54:16 +00001579 uint64_t NaturalAlignment = is64Bit() ? 8 : 4;
Benjamin Kramer084b9f42012-01-20 14:42:32 +00001580 uint64_t Padding = OffsetToAlignment(OS.tell(), NaturalAlignment);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001581 WriteZeros(Padding);
1582
Rafael Espindola642a2212015-04-14 22:54:16 +00001583 const unsigned SectionHeaderOffset = OS.tell();
1584
Rafael Espindola1557fd62011-03-20 18:44:20 +00001585 // ... then the section header table ...
Rafael Espindola55a3afb2015-04-28 21:07:28 +00001586 writeSectionHeader(Sections, Asm, Layout, SectionIndexMap, SectionOffsets);
Rafael Espindola642a2212015-04-14 22:54:16 +00001587
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001588 uint16_t NumSections = (Sections.size() + 1 >= ELF::SHN_LORESERVE)
Aaron Ballman9cab7322015-04-30 14:03:12 +00001589 ? (uint16_t)ELF::SHN_UNDEF
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001590 : Sections.size() + 1;
1591 if (sys::IsLittleEndianHost != IsLittleEndian)
1592 sys::swapByteOrder(NumSections);
1593 unsigned NumSectionsOffset;
1594
Rafael Espindola642a2212015-04-14 22:54:16 +00001595 if (is64Bit()) {
1596 uint64_t Val = SectionHeaderOffset;
1597 if (sys::IsLittleEndianHost != IsLittleEndian)
1598 sys::swapByteOrder(Val);
1599 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1600 offsetof(ELF::Elf64_Ehdr, e_shoff));
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001601 NumSectionsOffset = offsetof(ELF::Elf64_Ehdr, e_shnum);
Rafael Espindola642a2212015-04-14 22:54:16 +00001602 } else {
1603 uint32_t Val = SectionHeaderOffset;
1604 if (sys::IsLittleEndianHost != IsLittleEndian)
1605 sys::swapByteOrder(Val);
1606 OS.pwrite(reinterpret_cast<char *>(&Val), sizeof(Val),
1607 offsetof(ELF::Elf32_Ehdr, e_shoff));
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001608 NumSectionsOffset = offsetof(ELF::Elf32_Ehdr, e_shnum);
Rafael Espindola642a2212015-04-14 22:54:16 +00001609 }
Rafael Espindola8c7829b2015-04-29 20:39:37 +00001610 OS.pwrite(reinterpret_cast<char *>(&NumSections), sizeof(NumSections),
1611 NumSectionsOffset);
Rafael Espindola1557fd62011-03-20 18:44:20 +00001612}
1613
Rafael Espindola94a88d72015-04-06 15:27:57 +00001614bool ELFObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(
Rafael Espindola35d61892015-04-17 21:15:17 +00001615 const MCAssembler &Asm, const MCSymbolData &DataA, const MCFragment &FB,
1616 bool InSet, bool IsPCRel) const {
1617 if (IsPCRel) {
1618 assert(!InSet);
1619 if (::isWeak(DataA))
1620 return false;
1621 }
1622 return MCObjectWriter::IsSymbolRefDifferenceFullyResolvedImpl(Asm, DataA, FB,
1623 InSet, IsPCRel);
Eli Friedmand92d17b2011-03-03 07:24:36 +00001624}
1625
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001626bool ELFObjectWriter::isWeak(const MCSymbolData &SD) const {
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001627 if (::isWeak(SD))
1628 return true;
1629
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001630 // It is invalid to replace a reference to a global in a comdat
1631 // with a reference to a local since out of comdat references
1632 // to a local are forbidden.
1633 // We could try to return false for more cases, like the reference
1634 // being in the same comdat or Sym being an alias to another global,
1635 // but it is not clear if it is worth the effort.
Rafael Espindola29c82702015-04-20 12:44:06 +00001636 if (MCELF::GetBinding(SD) != ELF::STB_GLOBAL)
1637 return false;
Rafael Espindoladb8a5862015-04-17 20:05:17 +00001638
Rafael Espindola29c82702015-04-20 12:44:06 +00001639 const MCSymbol &Sym = SD.getSymbol();
1640 if (!Sym.isInSection())
1641 return false;
1642
1643 const auto &Sec = cast<MCSectionELF>(Sym.getSection());
1644 return Sec.getGroup();
Rafael Espindolaf275ad82015-03-25 13:16:53 +00001645}
1646
Rafael Espindola6b5e56c2010-12-17 17:45:22 +00001647MCObjectWriter *llvm::createELFObjectWriter(MCELFObjectTargetWriter *MOTW,
Rafael Espindola5560a4c2015-04-14 22:14:34 +00001648 raw_pwrite_stream &OS,
Rafael Espindolafdaae0d2010-12-18 03:27:34 +00001649 bool IsLittleEndian) {
Rafael Espindola34a68af2011-12-22 03:24:43 +00001650 return new ELFObjectWriter(MOTW, OS, IsLittleEndian);
Rafael Espindolab264d332011-12-21 17:30:17 +00001651}