blob: 153c645c8f1328392c8f9d3f06a77fa3add82114 [file] [log] [blame]
Michael J. Spencer84487f12015-07-24 21:03:07 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Michael J. Spencerf8325412015-09-04 22:48:30 +000010#include "Writer.h"
Rui Ueyamacb8474ed2015-08-05 23:51:50 +000011#include "Config.h"
Rui Ueyama717677a2016-02-11 21:17:59 +000012#include "LinkerScript.h"
Rafael Espindola5805c4f2015-09-21 21:38:08 +000013#include "OutputSections.h"
Rui Ueyamaafff74e22015-08-05 23:24:46 +000014#include "SymbolTable.h"
Rafael Espindola01205f72015-09-22 18:19:46 +000015#include "Target.h"
Rafael Espindola6b83b902015-08-12 00:00:24 +000016
Rafael Espindola4fc60442016-02-10 22:43:13 +000017#include "llvm/ADT/SmallPtrSet.h"
Denis Protivensky8e3b38a2015-11-12 09:52:08 +000018#include "llvm/ADT/StringMap.h"
Hal Finkel3bae2d82015-10-12 20:51:48 +000019#include "llvm/ADT/StringSwitch.h"
Rafael Espindola22ef9562016-04-13 01:40:19 +000020#include "llvm/Support/Endian.h"
Rui Ueyamaafff74e22015-08-05 23:24:46 +000021#include "llvm/Support/FileOutputBuffer.h"
Rui Ueyamad9189ce2015-10-15 17:11:03 +000022#include "llvm/Support/StringSaver.h"
Rafael Espindolad0078b22016-02-06 00:06:26 +000023#include "llvm/Support/raw_ostream.h"
Michael J. Spencer84487f12015-07-24 21:03:07 +000024
25using namespace llvm;
26using namespace llvm::ELF;
27using namespace llvm::object;
Rafael Espindola22ef9562016-04-13 01:40:19 +000028using namespace llvm::support::endian;
Michael J. Spencer84487f12015-07-24 21:03:07 +000029
30using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000031using namespace lld::elf;
Michael J. Spencer84487f12015-07-24 21:03:07 +000032
Rui Ueyamaafff74e22015-08-05 23:24:46 +000033namespace {
34// The writer writes a SymbolTable result to a file.
35template <class ELFT> class Writer {
36public:
Rui Ueyama9328b2c2016-03-14 23:16:09 +000037 typedef typename ELFT::uint uintX_t;
38 typedef typename ELFT::Shdr Elf_Shdr;
39 typedef typename ELFT::Ehdr Elf_Ehdr;
40 typedef typename ELFT::Phdr Elf_Phdr;
41 typedef typename ELFT::Sym Elf_Sym;
42 typedef typename ELFT::SymRange Elf_Sym_Range;
43 typedef typename ELFT::Rela Elf_Rela;
Rui Ueyama3ce825e2015-10-09 21:07:25 +000044 Writer(SymbolTable<ELFT> &S) : Symtab(S) {}
Rui Ueyamaafff74e22015-08-05 23:24:46 +000045 void run();
46
47private:
Rafael Espindola4fc60442016-02-10 22:43:13 +000048 // This describes a program header entry.
49 // Each contains type, access flags and range of output sections that will be
50 // placed in it.
51 struct Phdr {
52 Phdr(unsigned Type, unsigned Flags) {
53 H.p_type = Type;
54 H.p_flags = Flags;
55 }
56 Elf_Phdr H = {};
57 OutputSectionBase<ELFT> *First = nullptr;
58 OutputSectionBase<ELFT> *Last = nullptr;
59 };
60
Rui Ueyama5a9640b2015-10-08 23:49:30 +000061 void copyLocalSymbols();
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +000062 void addReservedSymbols();
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +000063 void createSections();
Rui Ueyama84417f82015-12-26 07:50:41 +000064 void addPredefinedSections();
Rui Ueyama30951482016-02-25 19:34:37 +000065 bool needsGot();
Rui Ueyama2df0fd82015-12-25 07:38:58 +000066
Rui Ueyamafc467e72016-03-13 05:06:50 +000067 template <class RelTy>
Rafael Espindola0f7ccc32016-04-05 14:47:28 +000068 void scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels);
Rui Ueyama2df0fd82015-12-25 07:38:58 +000069
Rafael Espindolaa0fa8482015-11-11 15:29:50 +000070 void scanRelocs(InputSection<ELFT> &C);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +000071 void scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec);
Rafael Espindolaa85efd92016-04-30 01:15:17 +000072 RelExpr adjustExpr(SymbolBody &S, bool IsWrite, RelExpr Expr, uint32_t Type);
Rafael Espindola4fc60442016-02-10 22:43:13 +000073 void createPhdrs();
Rui Ueyamaafff74e22015-08-05 23:24:46 +000074 void assignAddresses();
Rui Ueyamae044e9c2016-04-01 17:07:17 +000075 void assignFileOffsets();
76 void setPhdrs();
George Rimar7ca06272016-04-06 07:20:45 +000077 void fixHeaders();
Rui Ueyama47091902016-03-30 19:41:51 +000078 void fixSectionAlignments();
Rui Ueyama1a311f12015-12-26 10:52:26 +000079 void fixAbsoluteSymbols();
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +000080 void openFile();
Rui Ueyamaafff74e22015-08-05 23:24:46 +000081 void writeHeader();
82 void writeSections();
Rui Ueyama634ddf02016-03-11 20:51:53 +000083 void writeBuildId();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +000084 bool isDiscarded(InputSectionBase<ELFT> *IS) const;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000085 StringRef getOutputSectionName(InputSectionBase<ELFT> *S) const;
Rafael Espindola70107762015-09-11 18:49:42 +000086 bool needsInterpSection() const {
Rui Ueyama0d0bcf72015-10-07 21:25:39 +000087 return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty();
Rafael Espindola70107762015-09-11 18:49:42 +000088 }
Michael J. Spencerf32446f2015-10-06 20:39:09 +000089 bool isOutputDynamic() const {
George Rimar786e8662016-03-17 05:57:33 +000090 return !Symtab.getSharedFiles().empty() || Config->Pic;
Rafael Espindola4340aad2015-09-11 22:42:45 +000091 }
Simon Atanasyan13f6da12016-03-31 21:26:23 +000092 template <class RelTy>
93 void scanRelocsForThunks(const elf::ObjectFile<ELFT> &File,
Rafael Espindola0f7ccc32016-04-05 14:47:28 +000094 ArrayRef<RelTy> Rels);
Rui Ueyamaafff74e22015-08-05 23:24:46 +000095
Rui Ueyamab30f73562016-03-13 04:11:53 +000096 void ensureBss();
Rafael Espindola11191912015-12-24 16:23:37 +000097 void addCommonSymbols(std::vector<DefinedCommon *> &Syms);
Peter Collingbourne4cdade62016-04-04 22:29:24 +000098 void addCopyRelSymbol(SharedSymbol<ELFT> *Sym);
Rafael Espindola443f50a2015-11-03 21:35:14 +000099
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000100 std::unique_ptr<llvm::FileOutputBuffer> Buffer;
Michael J. Spencer2f008242015-09-17 19:58:07 +0000101
Rui Ueyamad9189ce2015-10-15 17:11:03 +0000102 BumpPtrAllocator Alloc;
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000103 std::vector<OutputSectionBase<ELFT> *> OutputSections;
Rui Ueyamad4ea7dd2015-12-26 07:01:26 +0000104 std::vector<std::unique_ptr<OutputSectionBase<ELFT>>> OwningSections;
Rafael Espindola4fc60442016-02-10 22:43:13 +0000105
Rui Ueyama01687222015-12-26 09:47:57 +0000106 void addRelIpltSymbols();
Rui Ueyamaa5d79d12015-12-26 09:48:00 +0000107 void addStartEndSymbols();
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000108 void addStartStopSymbols(OutputSectionBase<ELFT> *Sec);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +0000109
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000110 SymbolTable<ELFT> &Symtab;
Rafael Espindola4fc60442016-02-10 22:43:13 +0000111 std::vector<Phdr> Phdrs;
Michael J. Spencer2f008242015-09-17 19:58:07 +0000112
Rafael Espindola98f6bd02015-08-11 23:14:13 +0000113 uintX_t FileSize;
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000114 uintX_t SectionHeaderOff;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000115
Sean Silvaf1c5a0f2016-01-23 01:49:37 +0000116 // Flag to force GOT to be in output if we have relocations
117 // that relies on its address.
118 bool HasGotOffRel = false;
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000119};
120} // anonymous namespace
121
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000122template <class ELFT> void elf::writeResult(SymbolTable<ELFT> *Symtab) {
Rui Ueyama9328b2c2016-03-14 23:16:09 +0000123 typedef typename ELFT::uint uintX_t;
George Rimar687788c2016-04-01 17:30:52 +0000124 typedef typename ELFT::Ehdr Elf_Ehdr;
Rafael Espindola4fc60442016-02-10 22:43:13 +0000125
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000126 // Create singleton output sections.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000127 DynamicSection<ELFT> Dynamic(*Symtab);
George Rimarf6bc65a2016-01-15 13:34:52 +0000128 EhFrameHeader<ELFT> EhFrameHdr;
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000129 GotSection<ELFT> Got;
130 InterpSection<ELFT> Interp;
131 PltSection<ELFT> Plt;
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000132 RelocationSection<ELFT> RelaDyn(Config->Rela ? ".rela.dyn" : ".rel.dyn");
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000133 StringTableSection<ELFT> DynStrTab(".dynstr", true);
134 StringTableSection<ELFT> ShStrTab(".shstrtab", false);
135 SymbolTableSection<ELFT> DynSymTab(*Symtab, DynStrTab);
Peter Collingbourne21a12fc2016-04-27 20:22:31 +0000136 VersionTableSection<ELFT> VerSym;
137 VersionNeedSection<ELFT> VerNeed;
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000138
Rafael Espindola4fc60442016-02-10 22:43:13 +0000139 OutputSectionBase<ELFT> ElfHeader("", 0, SHF_ALLOC);
George Rimar687788c2016-04-01 17:30:52 +0000140 ElfHeader.setSize(sizeof(Elf_Ehdr));
Rafael Espindola4fc60442016-02-10 22:43:13 +0000141 OutputSectionBase<ELFT> ProgramHeaders("", 0, SHF_ALLOC);
142 ProgramHeaders.updateAlign(sizeof(uintX_t));
143
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000144 // Instantiate optional output sections if they are needed.
Rui Ueyama634ddf02016-03-11 20:51:53 +0000145 std::unique_ptr<BuildIdSection<ELFT>> BuildId;
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000146 std::unique_ptr<GnuHashTableSection<ELFT>> GnuHashTab;
147 std::unique_ptr<GotPltSection<ELFT>> GotPlt;
148 std::unique_ptr<HashTableSection<ELFT>> HashTab;
149 std::unique_ptr<RelocationSection<ELFT>> RelaPlt;
150 std::unique_ptr<StringTableSection<ELFT>> StrTab;
151 std::unique_ptr<SymbolTableSection<ELFT>> SymTabSec;
Rui Ueyamaa354c5c2016-02-25 23:54:49 +0000152 std::unique_ptr<OutputSection<ELFT>> MipsRldMap;
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000153
Rui Ueyama3a41be22016-04-07 22:49:21 +0000154 if (Config->BuildId == BuildIdKind::Fnv1)
155 BuildId.reset(new BuildIdFnv1<ELFT>);
156 else if (Config->BuildId == BuildIdKind::Md5)
157 BuildId.reset(new BuildIdMd5<ELFT>);
Rui Ueyamad86ec302016-04-07 23:51:56 +0000158 else if (Config->BuildId == BuildIdKind::Sha1)
159 BuildId.reset(new BuildIdSha1<ELFT>);
Rui Ueyama3a41be22016-04-07 22:49:21 +0000160
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000161 if (Config->GnuHash)
162 GnuHashTab.reset(new GnuHashTableSection<ELFT>);
163 if (Config->SysvHash)
164 HashTab.reset(new HashTableSection<ELFT>);
165 if (Target->UseLazyBinding) {
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000166 StringRef S = Config->Rela ? ".rela.plt" : ".rel.plt";
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000167 GotPlt.reset(new GotPltSection<ELFT>);
Rui Ueyama6c5638b2016-03-13 20:10:20 +0000168 RelaPlt.reset(new RelocationSection<ELFT>(S));
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000169 }
170 if (!Config->StripAll) {
171 StrTab.reset(new StringTableSection<ELFT>(".strtab", false));
172 SymTabSec.reset(new SymbolTableSection<ELFT>(*Symtab, *StrTab));
173 }
Rui Ueyamaa354c5c2016-02-25 23:54:49 +0000174 if (Config->EMachine == EM_MIPS && !Config->Shared) {
175 // This is a MIPS specific section to hold a space within the data segment
176 // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
177 // See "Dynamic section" in Chapter 5 in the following document:
178 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
179 MipsRldMap.reset(new OutputSection<ELFT>(".rld_map", SHT_PROGBITS,
180 SHF_ALLOC | SHF_WRITE));
181 MipsRldMap->setSize(sizeof(uintX_t));
182 MipsRldMap->updateAlign(sizeof(uintX_t));
183 }
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000184
Rui Ueyama634ddf02016-03-11 20:51:53 +0000185 Out<ELFT>::BuildId = BuildId.get();
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000186 Out<ELFT>::DynStrTab = &DynStrTab;
187 Out<ELFT>::DynSymTab = &DynSymTab;
188 Out<ELFT>::Dynamic = &Dynamic;
George Rimarf6bc65a2016-01-15 13:34:52 +0000189 Out<ELFT>::EhFrameHdr = &EhFrameHdr;
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000190 Out<ELFT>::GnuHashTab = GnuHashTab.get();
191 Out<ELFT>::Got = &Got;
192 Out<ELFT>::GotPlt = GotPlt.get();
193 Out<ELFT>::HashTab = HashTab.get();
194 Out<ELFT>::Interp = &Interp;
195 Out<ELFT>::Plt = &Plt;
196 Out<ELFT>::RelaDyn = &RelaDyn;
197 Out<ELFT>::RelaPlt = RelaPlt.get();
198 Out<ELFT>::ShStrTab = &ShStrTab;
199 Out<ELFT>::StrTab = StrTab.get();
200 Out<ELFT>::SymTab = SymTabSec.get();
Peter Collingbourne21a12fc2016-04-27 20:22:31 +0000201 Out<ELFT>::VerSym = &VerSym;
202 Out<ELFT>::VerNeed = &VerNeed;
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000203 Out<ELFT>::Bss = nullptr;
Rui Ueyamaa354c5c2016-02-25 23:54:49 +0000204 Out<ELFT>::MipsRldMap = MipsRldMap.get();
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000205 Out<ELFT>::Opd = nullptr;
206 Out<ELFT>::OpdBuf = nullptr;
207 Out<ELFT>::TlsPhdr = nullptr;
Rafael Espindola4fc60442016-02-10 22:43:13 +0000208 Out<ELFT>::ElfHeader = &ElfHeader;
209 Out<ELFT>::ProgramHeaders = &ProgramHeaders;
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000210
Rui Ueyama0d0bcf72015-10-07 21:25:39 +0000211 Writer<ELFT>(*Symtab).run();
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000212}
213
Michael J. Spencer84487f12015-07-24 21:03:07 +0000214// The main function of the writer.
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000215template <class ELFT> void Writer<ELFT>::run() {
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000216 if (!Config->DiscardAll)
217 copyLocalSymbols();
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +0000218 addReservedSymbols();
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +0000219 createSections();
220 if (HasError)
Rui Ueyamac2a0d7e2016-01-28 22:56:29 +0000221 return;
Rui Ueyamae044e9c2016-04-01 17:07:17 +0000222
223 if (Config->Relocatable) {
224 assignFileOffsets();
225 } else {
George Rimar58941ee2016-02-25 08:23:37 +0000226 createPhdrs();
George Rimar7ca06272016-04-06 07:20:45 +0000227 fixHeaders();
Rui Ueyama07320e42016-04-20 20:13:41 +0000228 if (ScriptConfig->DoLayout) {
229 Script<ELFT>::X->assignAddresses(OutputSections);
George Rimar652852c2016-04-16 10:10:32 +0000230 } else {
231 fixSectionAlignments();
232 assignAddresses();
233 }
Rui Ueyamae044e9c2016-04-01 17:07:17 +0000234 assignFileOffsets();
235 setPhdrs();
Rui Ueyamaa63baf12016-04-01 17:11:42 +0000236 fixAbsoluteSymbols();
George Rimar58941ee2016-02-25 08:23:37 +0000237 }
Rui Ueyamae044e9c2016-04-01 17:07:17 +0000238
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +0000239 openFile();
240 if (HasError)
Rui Ueyamacbe39262016-02-02 22:48:04 +0000241 return;
Michael J. Spencer84487f12015-07-24 21:03:07 +0000242 writeHeader();
243 writeSections();
Rui Ueyama634ddf02016-03-11 20:51:53 +0000244 writeBuildId();
Rui Ueyama21923992016-02-01 23:28:21 +0000245 if (HasError)
246 return;
Rafael Espindola75714f62016-03-03 22:24:39 +0000247 check(Buffer->commit());
Michael J. Spencer84487f12015-07-24 21:03:07 +0000248}
249
Rafael Espindolaa7471792015-08-13 17:04:50 +0000250namespace {
251template <bool Is64Bits> struct SectionKey {
252 typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
253 StringRef Name;
Rui Ueyama0fb1ee02015-10-02 21:13:19 +0000254 uint32_t Type;
255 uintX_t Flags;
Rafael Espindola7efa5be2016-02-19 14:17:40 +0000256 uintX_t Alignment;
Rafael Espindolaa7471792015-08-13 17:04:50 +0000257};
258}
259namespace llvm {
260template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
261 static SectionKey<Is64Bits> getEmptyKey() {
Rafael Espindolac159c962015-10-19 21:00:02 +0000262 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0,
263 0};
Rafael Espindolaa7471792015-08-13 17:04:50 +0000264 }
265 static SectionKey<Is64Bits> getTombstoneKey() {
266 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
Rafael Espindolac159c962015-10-19 21:00:02 +0000267 0, 0};
Rafael Espindolaa7471792015-08-13 17:04:50 +0000268 }
269 static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
Rafael Espindola7efa5be2016-02-19 14:17:40 +0000270 return hash_combine(Val.Name, Val.Type, Val.Flags, Val.Alignment);
Rafael Espindolaa7471792015-08-13 17:04:50 +0000271 }
272 static bool isEqual(const SectionKey<Is64Bits> &LHS,
273 const SectionKey<Is64Bits> &RHS) {
274 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
Rafael Espindolac159c962015-10-19 21:00:02 +0000275 LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
Rafael Espindola7efa5be2016-02-19 14:17:40 +0000276 LHS.Alignment == RHS.Alignment;
Rafael Espindolaa7471792015-08-13 17:04:50 +0000277 }
278};
279}
280
Rafael Espindola26d239c2016-03-22 13:24:29 +0000281// Returns the number of relocations processed.
Rafael Espindola22ef9562016-04-13 01:40:19 +0000282template <class ELFT>
Rafael Espindola26d239c2016-03-22 13:24:29 +0000283static unsigned handleTlsRelocation(uint32_t Type, SymbolBody &Body,
Rafael Espindola22ef9562016-04-13 01:40:19 +0000284 InputSectionBase<ELFT> &C,
285 typename ELFT::uint Offset,
286 typename ELFT::uint Addend, RelExpr Expr) {
287 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
288 return 0;
289
Rafael Espindolaf54413c2016-04-20 14:52:18 +0000290 if (!Body.isTls())
291 return 0;
292
Rafael Espindola74031ba2016-04-07 15:20:56 +0000293 typedef typename ELFT::uint uintX_t;
Rafael Espindola99c22472016-04-18 01:34:20 +0000294 if (Expr == R_TLSLD_PC || Expr == R_TLSLD) {
Rafael Espindola2081dbc2016-04-20 15:01:42 +0000295 // Local-Dynamic relocs can be relaxed to Local-Exec.
296 if (!Config->Shared) {
Rafael Espindola22ef9562016-04-13 01:40:19 +0000297 C.Relocations.push_back(
298 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
Rafael Espindola059f3fb2016-04-02 00:19:22 +0000299 return 2;
Rafael Espindola22ef9562016-04-13 01:40:19 +0000300 }
Rui Ueyama0e53c7d2016-02-05 00:10:02 +0000301 if (Out<ELFT>::Got->addTlsIndex())
Rafael Espindola74031ba2016-04-07 15:20:56 +0000302 Out<ELFT>::RelaDyn->addReloc({Target->TlsModuleIndexRel, Out<ELFT>::Got,
303 Out<ELFT>::Got->getTlsIndexOff(), false,
304 nullptr, 0});
Rafael Espindola22ef9562016-04-13 01:40:19 +0000305 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rafael Espindola26d239c2016-03-22 13:24:29 +0000306 return 1;
George Rimarbfd29a12016-01-21 09:14:22 +0000307 }
308
Rafael Espindola2081dbc2016-04-20 15:01:42 +0000309 // Local-Dynamic relocs can be relaxed to Local-Exec.
310 if (Target->isTlsLocalDynamicRel(Type) && !Config->Shared) {
Rafael Espindola22ef9562016-04-13 01:40:19 +0000311 C.Relocations.push_back(
312 {R_RELAX_TLS_LD_TO_LE, Type, Offset, Addend, &Body});
313 return 1;
314 }
315
Rui Ueyamac516ae12016-01-29 02:33:45 +0000316 if (Target->isTlsGlobalDynamicRel(Type)) {
Rafael Espindola2081dbc2016-04-20 15:01:42 +0000317 if (Config->Shared) {
Rafael Espindola56da3132016-02-22 19:57:55 +0000318 if (Out<ELFT>::Got->addDynTlsEntry(Body)) {
Rafael Espindola74031ba2016-04-07 15:20:56 +0000319 uintX_t Off = Out<ELFT>::Got->getGlobalDynOffset(Body);
Rafael Espindola56da3132016-02-22 19:57:55 +0000320 Out<ELFT>::RelaDyn->addReloc(
Rafael Espindola74031ba2016-04-07 15:20:56 +0000321 {Target->TlsModuleIndexRel, Out<ELFT>::Got, Off, false, &Body, 0});
322 Out<ELFT>::RelaDyn->addReloc({Target->TlsOffsetRel, Out<ELFT>::Got,
323 Off + (uintX_t)sizeof(uintX_t), false,
324 &Body, 0});
Rafael Espindola56da3132016-02-22 19:57:55 +0000325 }
Rafael Espindola22ef9562016-04-13 01:40:19 +0000326 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rafael Espindola26d239c2016-03-22 13:24:29 +0000327 return 1;
George Rimarbfd29a12016-01-21 09:14:22 +0000328 }
Rafael Espindola22ef9562016-04-13 01:40:19 +0000329
Rafael Espindola2081dbc2016-04-20 15:01:42 +0000330 // Global-Dynamic relocs can be relaxed to Initial-Exec or Local-Exec
331 // depending on the symbol being locally defined or not.
Rafael Espindola22ef9562016-04-13 01:40:19 +0000332 if (Body.isPreemptible()) {
Rafael Espindoladf172772016-04-18 01:29:15 +0000333 Expr =
334 Expr == R_TLSGD_PC ? R_RELAX_TLS_GD_TO_IE_PC : R_RELAX_TLS_GD_TO_IE;
Rafael Espindola22ef9562016-04-13 01:40:19 +0000335 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
336 if (!Body.isInGot()) {
337 Out<ELFT>::Got->addEntry(Body);
338 Out<ELFT>::RelaDyn->addReloc({Target->TlsGotRel, Out<ELFT>::Got,
339 Body.getGotOffset<ELFT>(), false, &Body,
340 0});
341 }
Rafael Espindolacf3b04d2016-04-01 23:36:56 +0000342 return 2;
Rafael Espindolab97f4be2016-04-01 12:54:27 +0000343 }
Rafael Espindola22ef9562016-04-13 01:40:19 +0000344 C.Relocations.push_back(
345 {R_RELAX_TLS_GD_TO_LE, Type, Offset, Addend, &Body});
346 return Target->TlsGdToLeSkip;
347 }
Rafael Espindola2081dbc2016-04-20 15:01:42 +0000348
349 // Initial-Exec relocs can be relaxed to Local-Exec if the symbol is locally
350 // defined.
351 if (Target->isTlsInitialExecRel(Type) && !Config->Shared &&
352 !Body.isPreemptible()) {
Rafael Espindola22ef9562016-04-13 01:40:19 +0000353 C.Relocations.push_back(
354 {R_RELAX_TLS_IE_TO_LE, Type, Offset, Addend, &Body});
355 return 1;
George Rimarbfd29a12016-01-21 09:14:22 +0000356 }
Rafael Espindola26d239c2016-03-22 13:24:29 +0000357 return 0;
George Rimarbfd29a12016-01-21 09:14:22 +0000358}
359
Simon Atanasyan13f6da12016-03-31 21:26:23 +0000360// Some targets might require creation of thunks for relocations. Now we
361// support only MIPS which requires LA25 thunk to call PIC code from non-PIC
362// one. Scan relocations to find each one requires thunk.
363template <class ELFT>
364template <class RelTy>
365void Writer<ELFT>::scanRelocsForThunks(const elf::ObjectFile<ELFT> &File,
Rafael Espindola0f7ccc32016-04-05 14:47:28 +0000366 ArrayRef<RelTy> Rels) {
Simon Atanasyan13f6da12016-03-31 21:26:23 +0000367 for (const RelTy &RI : Rels) {
368 uint32_t Type = RI.getType(Config->Mips64EL);
Peter Collingbourne676c7cd2016-04-26 23:52:44 +0000369 SymbolBody &Body = File.getRelocTargetSym(RI);
Simon Atanasyan13f6da12016-03-31 21:26:23 +0000370 if (Body.hasThunk() || !Target->needsThunk(Type, File, Body))
371 continue;
372 auto *D = cast<DefinedRegular<ELFT>>(&Body);
373 auto *S = cast<InputSection<ELFT>>(D->Section);
374 S->addThunk(Body);
375 }
376}
377
Rafael Espindola22ef9562016-04-13 01:40:19 +0000378template <endianness E> static int16_t readSignedLo16(const uint8_t *Loc) {
379 return read32<E>(Loc) & 0xffff;
380}
381
382template <class RelTy>
383static uint32_t getMipsPairType(const RelTy *Rel, const SymbolBody &Sym) {
384 switch (Rel->getType(Config->Mips64EL)) {
385 case R_MIPS_HI16:
386 return R_MIPS_LO16;
387 case R_MIPS_GOT16:
388 return Sym.isLocal() ? R_MIPS_LO16 : R_MIPS_NONE;
389 case R_MIPS_PCHI16:
390 return R_MIPS_PCLO16;
391 case R_MICROMIPS_HI16:
392 return R_MICROMIPS_LO16;
393 default:
394 return R_MIPS_NONE;
395 }
396}
397
398template <class ELFT, class RelTy>
399static int32_t findMipsPairedAddend(const uint8_t *Buf, const uint8_t *BufLoc,
400 SymbolBody &Sym, const RelTy *Rel,
401 const RelTy *End) {
402 uint32_t SymIndex = Rel->getSymbol(Config->Mips64EL);
403 uint32_t Type = getMipsPairType(Rel, Sym);
404
405 // Some MIPS relocations use addend calculated from addend of the relocation
406 // itself and addend of paired relocation. ABI requires to compute such
407 // combined addend in case of REL relocation record format only.
408 // See p. 4-17 at ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
409 if (RelTy::IsRela || Type == R_MIPS_NONE)
410 return 0;
411
412 for (const RelTy *RI = Rel; RI != End; ++RI) {
413 if (RI->getType(Config->Mips64EL) != Type)
414 continue;
415 if (RI->getSymbol(Config->Mips64EL) != SymIndex)
416 continue;
417 const endianness E = ELFT::TargetEndianness;
418 return ((read32<E>(BufLoc) & 0xffff) << 16) +
419 readSignedLo16<E>(Buf + RI->r_offset);
420 }
421 unsigned OldType = Rel->getType(Config->Mips64EL);
422 StringRef OldName = getELFRelocationTypeName(Config->EMachine, OldType);
423 StringRef NewName = getELFRelocationTypeName(Config->EMachine, Type);
424 warning("can't find matching " + NewName + " relocation for " + OldName);
425 return 0;
426}
427
Rafael Espindolaf8f6ad72016-04-15 12:22:22 +0000428// True if non-preemptable symbol always has the same value regardless of where
429// the DSO is loaded.
430template <class ELFT> static bool isAbsolute(const SymbolBody &Body) {
Peter Collingbourne4f952702016-05-01 04:55:03 +0000431 if (Body.isUndefined())
432 return !Body.isLocal() && Body.symbol()->isWeak();
Rafael Espindolaf8f6ad72016-04-15 12:22:22 +0000433 if (const auto *DR = dyn_cast<DefinedRegular<ELFT>>(&Body))
434 return DR->Section == nullptr; // Absolute symbol.
435 return false;
436}
437
Rafael Espindolab312a742016-04-21 17:30:24 +0000438static bool needsPlt(RelExpr Expr) {
439 return Expr == R_PLT_PC || Expr == R_PPC_PLT_OPD || Expr == R_PLT;
440}
441
Rafael Espindola7ac96282016-04-27 12:47:30 +0000442template <class ELFT>
Rafael Espindola3fa5bbd2016-05-04 21:28:56 +0000443static bool isStaticLinkTimeConstant(RelExpr E, uint32_t Type,
444 const SymbolBody &Body) {
Rafael Espindolade17d282016-05-04 21:40:07 +0000445 // These expressions always compute a constant
446 if (E == R_SIZE || E == R_GOT_FROM_END || E == R_GOT_OFF || E == R_MIPS_GOT ||
447 E == R_MIPS_GOT_LOCAL || E == R_GOT_PAGE_PC || E == R_GOT_PC ||
448 E == R_PLT_PC || E == R_TLSGD_PC || E == R_TLSGD || E == R_PPC_PLT_OPD)
Rafael Espindola7ac96282016-04-27 12:47:30 +0000449 return true;
450
Rafael Espindolade17d282016-05-04 21:40:07 +0000451 // These never do, except if the entire file is position dependent or if
452 // only the low bits are used.
453 if (E == R_GOT || E == R_PLT)
454 return Target->usesOnlyLowPageBits(Type) || !Config->Pic;
Rafael Espindola7ac96282016-04-27 12:47:30 +0000455
Rafael Espindolade17d282016-05-04 21:40:07 +0000456 if (Body.isPreemptible())
457 return false;
458
459 if (!Config->Pic)
460 return true;
461
462 bool AbsVal = isAbsolute<ELFT>(Body) || Body.isTls();
463 bool RelE = E == R_PC || E == R_GOTREL || E == R_PAGE_PC;
Rafael Espindola7ac96282016-04-27 12:47:30 +0000464 if (AbsVal && !RelE)
465 return true;
466 if (!AbsVal && RelE)
467 return true;
468
Peter Collingbourne6a422592016-05-03 01:21:08 +0000469 // Relative relocation to an absolute value. This is normally unrepresentable,
470 // but if the relocation refers to a weak undefined symbol, we allow it to
471 // resolve to the image base. This is a little strange, but it allows us to
472 // link function calls to such symbols. Normally such a call will be guarded
473 // with a comparison, which will load a zero from the GOT.
474 if (AbsVal && RelE) {
475 if (Body.isUndefined() && !Body.isLocal() && Body.symbol()->isWeak())
476 return true;
477 StringRef S = getELFRelocationTypeName(Config->EMachine, Type);
478 error("relocation " + S + " cannot refer to absolute symbol " +
479 Body.getName());
480 return true;
481 }
482
Rafael Espindolab8ff59a2016-04-28 14:34:39 +0000483 return Target->usesOnlyLowPageBits(Type);
Rafael Espindola7ac96282016-04-27 12:47:30 +0000484}
485
Rafael Espindolaa85efd92016-04-30 01:15:17 +0000486static RelExpr toPlt(RelExpr Expr) {
487 if (Expr == R_PPC_OPD)
488 return R_PPC_PLT_OPD;
489 if (Expr == R_PC)
490 return R_PLT_PC;
491 if (Expr == R_ABS)
492 return R_PLT;
493 return Expr;
494}
495
496static RelExpr fromPlt(RelExpr Expr) {
497 // We decided not to use a plt. Optimize a reference to the plt to a
498 // reference to the symbol itself.
499 if (Expr == R_PLT_PC)
500 return R_PC;
501 if (Expr == R_PPC_PLT_OPD)
502 return R_PPC_OPD;
503 if (Expr == R_PLT)
504 return R_ABS;
505 return Expr;
506}
507
508template <class ELFT>
509RelExpr Writer<ELFT>::adjustExpr(SymbolBody &Body, bool IsWrite, RelExpr Expr,
510 uint32_t Type) {
Rafael Espindolaa85efd92016-04-30 01:15:17 +0000511 bool Preemptible = Body.isPreemptible();
Rafael Espindolade17d282016-05-04 21:40:07 +0000512 if (Body.isGnuIFunc())
513 Expr = toPlt(Expr);
514 else if (needsPlt(Expr) && !Preemptible)
515 Expr = fromPlt(Expr);
Rafael Espindolaa85efd92016-04-30 01:15:17 +0000516
Rafael Espindolade17d282016-05-04 21:40:07 +0000517 if (IsWrite || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body))
Rafael Espindola946ca272016-05-04 21:09:24 +0000518 return Expr;
519
520 // This relocation would require the dynamic linker to write a value to read
521 // only memory. We can hack around it if we are producing an executable and
522 // the refered symbol can be preemepted to refer to the executable.
523 if (Config->Shared) {
524 StringRef S = getELFRelocationTypeName(Config->EMachine, Type);
525 error("relocation " + S + " cannot be used when making a shared "
526 "object; recompile with -fPIC.");
527 return Expr;
Rafael Espindolaa85efd92016-04-30 01:15:17 +0000528 }
Rafael Espindola946ca272016-05-04 21:09:24 +0000529 if (Body.getVisibility() != STV_DEFAULT) {
530 error("Cannot preempt symbol");
531 return Expr;
532 }
533 if (Body.isObject()) {
534 // Produce a copy relocation.
535 auto *B = cast<SharedSymbol<ELFT>>(&Body);
536 if (!B->needsCopy())
537 addCopyRelSymbol(B);
538 return Expr;
539 }
540 if (Body.isFunc()) {
541 // This handles a non PIC program call to function in a shared library. In
542 // an ideal world, we could just report an error saying the relocation can
543 // overflow at runtime. In the real world with glibc, crt1.o has a
544 // R_X86_64_PC32 pointing to libc.so.
545 //
546 // The general idea on how to handle such cases is to create a PLT entry and
547 // use that as the function value.
548 //
549 // For the static linking part, we just return a plt expr and everything
550 // else will use the the PLT entry as the address.
551 //
552 // The remaining problem is making sure pointer equality still works. We
553 // need the help of the dynamic linker for that. We let it know that we have
554 // a direct reference to a so symbol by creating an undefined symbol with a
555 // non zero st_value. Seeing that, the dynamic linker resolves the symbol to
556 // the value of the symbol we created. This is true even for got entries, so
557 // pointer equality is maintained. To avoid an infinite loop, the only entry
558 // that points to the real function is a dedicated got entry used by the
559 // plt. That is identified by special relocation types (R_X86_64_JUMP_SLOT,
560 // R_386_JMP_SLOT, etc).
561 Body.NeedsCopyOrPltAddr = true;
562 return toPlt(Expr);
563 }
564 error("Symbol is missing type");
565
Rafael Espindolaa85efd92016-04-30 01:15:17 +0000566 return Expr;
567}
568
Rafael Espindola19e38892015-09-16 15:54:15 +0000569// The reason we have to do this early scan is as follows
570// * To mmap the output file, we need to know the size
571// * For that, we need to know how many dynamic relocs we will have.
572// It might be possible to avoid this by outputting the file with write:
573// * Write the allocated output sections, computing addresses.
574// * Apply relocations, recording which ones require a dynamic reloc.
575// * Write the dynamic relocations.
576// * Write the rest of the file.
Rafael Espindola0df1b0b2016-02-02 15:45:37 +0000577// This would have some drawbacks. For example, we would only know if .rela.dyn
578// is needed after applying relocations. If it is, it will go after rw and rx
579// sections. Given that it is ro, we will need an extra PT_LOAD. This
580// complicates things for the dynamic linker and means we would have to reserve
581// space for the extra PT_LOAD even if we end up not using it.
Rafael Espindola19e38892015-09-16 15:54:15 +0000582template <class ELFT>
Rui Ueyamafc467e72016-03-13 05:06:50 +0000583template <class RelTy>
Rafael Espindola0f7ccc32016-04-05 14:47:28 +0000584void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &C, ArrayRef<RelTy> Rels) {
Peter Collingbourne0a68cf52016-04-14 01:48:11 +0000585 uintX_t Flags = C.getSectionHdr()->sh_flags;
Peter Collingbourne0a68cf52016-04-14 01:48:11 +0000586 bool IsWrite = Flags & SHF_WRITE;
Rafael Espindola22ef9562016-04-13 01:40:19 +0000587
588 auto AddDyn = [=](const DynamicReloc<ELFT> &Reloc) {
Rui Ueyama2b6fb802016-04-28 18:42:04 +0000589 Out<ELFT>::RelaDyn->addReloc(Reloc);
Rafael Espindola22ef9562016-04-13 01:40:19 +0000590 };
591
Rui Ueyama6b074f52016-03-11 18:56:05 +0000592 const elf::ObjectFile<ELFT> &File = *C.getFile();
Rafael Espindola22ef9562016-04-13 01:40:19 +0000593 ArrayRef<uint8_t> SectionData = C.getSectionData();
594 const uint8_t *Buf = SectionData.begin();
Rafael Espindola26d239c2016-03-22 13:24:29 +0000595 for (auto I = Rels.begin(), E = Rels.end(); I != E; ++I) {
596 const RelTy &RI = *I;
Peter Collingbourne676c7cd2016-04-26 23:52:44 +0000597 SymbolBody &Body = File.getRelocTargetSym(RI);
Rui Ueyama64558522015-10-16 22:51:43 +0000598 uint32_t Type = RI.getType(Config->Mips64EL);
Rui Ueyama35da9b62015-10-11 20:59:12 +0000599
Rafael Espindolaebb04b92016-05-04 14:44:22 +0000600 RelExpr Expr = Target->getRelExpr(Type, Body);
Simon Atanasyan682aeea2016-01-14 20:42:09 +0000601 // Ignore "hint" relocation because it is for optional code optimization.
Rafael Espindolaebb04b92016-05-04 14:44:22 +0000602 if (Expr == R_HINT)
Simon Atanasyan682aeea2016-01-14 20:42:09 +0000603 continue;
604
Rafael Espindola56004c52016-04-07 14:22:09 +0000605 uintX_t Offset = C.getOffset(RI.r_offset);
606 if (Offset == (uintX_t)-1)
607 continue;
608
Rafael Espindolaa85efd92016-04-30 01:15:17 +0000609 Expr = adjustExpr(Body, IsWrite, Expr, Type);
610 if (HasError)
611 continue;
612 bool Preemptible = Body.isPreemptible();
613 if (auto *B = dyn_cast<SharedSymbol<ELFT>>(&Body))
614 if (B->needsCopy())
615 Preemptible = false;
616
Rafael Espindola5bf59722016-04-18 12:31:37 +0000617 // This relocation does not require got entry, but it is relative to got and
618 // needs it to be created. Here we request for that.
Rafael Espindola520ed3a2016-04-27 12:21:27 +0000619 if (Expr == R_GOTONLY_PC || Expr == R_GOTREL || Expr == R_PPC_TOC)
Rafael Espindola5bf59722016-04-18 12:31:37 +0000620 HasGotOffRel = true;
621
Rafael Espindola22ef9562016-04-13 01:40:19 +0000622 uintX_t Addend = getAddend<ELFT>(RI);
623 const uint8_t *BufLoc = Buf + RI.r_offset;
624 if (!RelTy::IsRela)
625 Addend += Target->getImplicitAddend(BufLoc, Type);
Simon Atanasyan1ca263c2016-04-14 21:10:05 +0000626 if (Config->EMachine == EM_MIPS) {
Rafael Espindola22ef9562016-04-13 01:40:19 +0000627 Addend += findMipsPairedAddend<ELFT>(Buf, BufLoc, Body, &RI, E);
Simon Atanasyan1ca263c2016-04-14 21:10:05 +0000628 if (Type == R_MIPS_LO16 && Expr == R_PC)
629 // R_MIPS_LO16 expression has R_PC type iif the target is _gp_disp
630 // symbol. In that case we should use the following formula for
Simon Atanasyan63dcba02016-05-02 09:49:03 +0000631 // calculation "AHL + GP - P + 4". Let's add 4 right here.
Simon Atanasyan1ca263c2016-04-14 21:10:05 +0000632 // For details see p. 4-19 at
633 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
634 Addend += 4;
635 }
Rafael Espindola22ef9562016-04-13 01:40:19 +0000636
Rafael Espindola22ef9562016-04-13 01:40:19 +0000637 if (unsigned Processed =
638 handleTlsRelocation<ELFT>(Type, Body, C, Offset, Addend, Expr)) {
Rafael Espindola26d239c2016-03-22 13:24:29 +0000639 I += (Processed - 1);
George Rimar687138c2015-11-13 16:28:53 +0000640 continue;
Rafael Espindola26d239c2016-03-22 13:24:29 +0000641 }
George Rimar687138c2015-11-13 16:28:53 +0000642
Rafael Espindola3fa5bbd2016-05-04 21:28:56 +0000643 if (Expr == R_GOT && !isStaticLinkTimeConstant<ELFT>(Expr, Type, Body) &&
Rafael Espindola7ac96282016-04-27 12:47:30 +0000644 Config->Shared)
Rafael Espindola22ef9562016-04-13 01:40:19 +0000645 AddDyn({Target->RelativeRel, C.OutSec, Offset, true, &Body,
646 getAddend<ELFT>(RI)});
George Rimar6f17e092015-12-17 09:32:21 +0000647
Rui Ueyama554f2732016-02-02 07:07:34 +0000648 // If a relocation needs PLT, we create a PLT and a GOT slot
649 // for the symbol.
Rafael Espindolaa85efd92016-04-30 01:15:17 +0000650 if (needsPlt(Expr)) {
651 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rafael Espindola22ef9562016-04-13 01:40:19 +0000652
Rafael Espindola67d72c02016-03-11 12:06:30 +0000653 if (Body.isInPlt())
Rui Ueyama554f2732016-02-02 07:07:34 +0000654 continue;
655 Out<ELFT>::Plt->addEntry(Body);
656
Rafael Espindola31d2ada2016-04-01 14:14:48 +0000657 uint32_t Rel;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000658 if (Body.isGnuIFunc())
Rafael Espindola31d2ada2016-04-01 14:14:48 +0000659 Rel = Preemptible ? Target->PltRel : Target->IRelativeRel;
660 else
661 Rel = Target->UseLazyBinding ? Target->PltRel : Target->GotRel;
662
Rui Ueyama554f2732016-02-02 07:07:34 +0000663 if (Target->UseLazyBinding) {
664 Out<ELFT>::GotPlt->addEntry(Body);
Rui Ueyama2b6fb802016-04-28 18:42:04 +0000665 Out<ELFT>::RelaPlt->addReloc({Rel, Out<ELFT>::GotPlt,
666 Body.getGotPltOffset<ELFT>(),
667 !Preemptible, &Body, 0});
Rui Ueyama554f2732016-02-02 07:07:34 +0000668 } else {
Rafael Espindola67d72c02016-03-11 12:06:30 +0000669 if (Body.isInGot())
Rui Ueyama554f2732016-02-02 07:07:34 +0000670 continue;
671 Out<ELFT>::Got->addEntry(Body);
Rafael Espindola22ef9562016-04-13 01:40:19 +0000672 AddDyn({Rel, Out<ELFT>::Got, Body.getGotOffset<ELFT>(), !Preemptible,
673 &Body, 0});
Rui Ueyama554f2732016-02-02 07:07:34 +0000674 }
Rui Ueyama554f2732016-02-02 07:07:34 +0000675 continue;
676 }
677
Rafael Espindola22ef9562016-04-13 01:40:19 +0000678 if (Target->needsThunk(Type, File, Body)) {
679 C.Relocations.push_back({R_THUNK, Type, Offset, Addend, &Body});
680 continue;
681 }
682
Rui Ueyamaf263c4b2016-02-02 07:07:35 +0000683 // If a relocation needs GOT, we create a GOT slot for the symbol.
Rafael Espindolac6b17bd2016-04-20 17:30:22 +0000684 if (refersToGotEntry(Expr)) {
Rafael Espindola58cd5db2016-04-19 22:46:03 +0000685 if (Config->EMachine == EM_MIPS && Expr == R_GOT_OFF)
686 Addend -= MipsGPOffset;
Rafael Espindola38bd2172016-05-04 15:51:23 +0000687 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rafael Espindola67d72c02016-03-11 12:06:30 +0000688 if (Body.isInGot())
Rui Ueyamaf263c4b2016-02-02 07:07:35 +0000689 continue;
690 Out<ELFT>::Got->addEntry(Body);
Rui Ueyama1ac13382016-02-02 05:55:28 +0000691
Simon Atanasyanf3ec3be2016-03-22 08:36:48 +0000692 if (Config->EMachine == EM_MIPS)
Rui Ueyamaf263c4b2016-02-02 07:07:35 +0000693 // MIPS ABI has special rules to process GOT entries
694 // and doesn't require relocation entries for them.
695 // See "Global Offset Table" in Chapter 5 in the following document
696 // for detailed description:
697 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
698 continue;
699
Rafael Espindola69a38062016-04-15 12:44:43 +0000700 if (Preemptible || (Config->Pic && !isAbsolute<ELFT>(Body))) {
Rafael Espindolade9857e2016-02-04 21:33:05 +0000701 uint32_t DynType;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000702 if (Body.isTls())
Rafael Espindola22304832016-03-11 18:33:48 +0000703 DynType = Target->TlsGotRel;
Rui Ueyamac4466602016-03-13 19:48:18 +0000704 else if (Preemptible)
Rafael Espindola22304832016-03-11 18:33:48 +0000705 DynType = Target->GotRel;
Rafael Espindolade9857e2016-02-04 21:33:05 +0000706 else
707 DynType = Target->RelativeRel;
Rafael Espindola22ef9562016-04-13 01:40:19 +0000708 AddDyn({DynType, Out<ELFT>::Got, Body.getGotOffset<ELFT>(),
709 !Preemptible, &Body, 0});
Rafael Espindolade9857e2016-02-04 21:33:05 +0000710 }
Rui Ueyamaf263c4b2016-02-02 07:07:35 +0000711 continue;
Rafael Espindolaeb792732015-09-21 15:11:29 +0000712 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000713
Rui Ueyamac4466602016-03-13 19:48:18 +0000714 if (Preemptible) {
Rafael Espindolade9857e2016-02-04 21:33:05 +0000715 // We don't know anything about the finaly symbol. Just ask the dynamic
716 // linker to handle the relocation for us.
Rafael Espindola22ef9562016-04-13 01:40:19 +0000717 AddDyn({Target->getDynRel(Type), C.OutSec, Offset, false, &Body, Addend});
Simon Atanasyanca58a8f2016-04-20 21:40:33 +0000718 // MIPS ABI turns using of GOT and dynamic relocations inside out.
719 // While regular ABI uses dynamic relocations to fill up GOT entries
720 // MIPS ABI requires dynamic linker to fills up GOT entries using
721 // specially sorted dynamic symbol table. This affects even dynamic
722 // relocations against symbols which do not require GOT entries
723 // creation explicitly, i.e. do not have any GOT-relocations. So if
724 // a preemptible symbol has a dynamic relocation we anyway have
725 // to create a GOT entry for it.
726 // If a non-preemptible symbol has a dynamic relocation against it,
727 // dynamic linker takes it st_value, adds offset and writes down
728 // result of the dynamic relocation. In case of preemptible symbol
729 // dynamic linker performs symbol resolution, writes the symbol value
730 // to the GOT entry and reads the GOT entry when it needs to perform
731 // a dynamic relocation.
732 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf p.4-19
733 if (Config->EMachine == EM_MIPS && !Body.isInGot())
734 Out<ELFT>::Got->addEntry(Body);
Rafael Espindola22ef9562016-04-13 01:40:19 +0000735 continue;
736 }
737
Rafael Espindolade9857e2016-02-04 21:33:05 +0000738 // We know that this is the final symbol. If the program being produced
739 // is position independent, the final value is still not known.
740 // If the relocation depends on the symbol value (not the size or distances
741 // in the output), we still need some help from the dynamic linker.
742 // We can however do better than just copying the incoming relocation. We
743 // can process some of it and and just ask the dynamic linker to add the
744 // load address.
Rafael Espindola3fa5bbd2016-05-04 21:28:56 +0000745 if (!Config->Pic || isStaticLinkTimeConstant<ELFT>(Expr, Type, Body)) {
Rafael Espindola22ef9562016-04-13 01:40:19 +0000746 if (Config->EMachine == EM_MIPS && Body.isLocal() &&
Rafael Espindola1763dc42016-04-26 22:00:04 +0000747 (Type == R_MIPS_GPREL16 || Type == R_MIPS_GPREL32))
Rafael Espindola475dbf42016-04-20 17:20:49 +0000748 Addend += File.getMipsGp0();
Rafael Espindola22ef9562016-04-13 01:40:19 +0000749 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
750 continue;
751 }
752
Rafael Espindola365e5f62016-04-27 11:54:07 +0000753 if (Config->EMachine == EM_PPC64 && Type == R_PPC64_TOC)
754 Addend += getPPC64TocBase();
Rafael Espindola22ef9562016-04-13 01:40:19 +0000755 AddDyn({Target->RelativeRel, C.OutSec, Offset, true, &Body, Addend});
Rafael Espindola365e5f62016-04-27 11:54:07 +0000756 C.Relocations.push_back({Expr, Type, Offset, Addend, &Body});
Rafael Espindola67a5da62015-09-17 14:02:10 +0000757 }
Simon Atanasyan13f6da12016-03-31 21:26:23 +0000758
759 // Scan relocations for necessary thunks.
760 if (Config->EMachine == EM_MIPS)
761 scanRelocsForThunks(File, Rels);
Rafael Espindola67a5da62015-09-17 14:02:10 +0000762}
763
Rafael Espindolaa0fa8482015-11-11 15:29:50 +0000764template <class ELFT> void Writer<ELFT>::scanRelocs(InputSection<ELFT> &C) {
Rui Ueyamae5c1ec42016-04-28 03:04:15 +0000765 // Scan all relocations. Each relocation goes through a series
766 // of tests to determine if it needs special treatment, such as
767 // creating GOT, PLT, copy relocations, etc.
Rui Ueyama2b6fb802016-04-28 18:42:04 +0000768 // Note that relocations for non-alloc sections are directly
769 // processed by InputSection::relocateNative.
770 if (C.getSectionHdr()->sh_flags & SHF_ALLOC)
771 for (const Elf_Shdr *RelSec : C.RelocSections)
772 scanRelocs(C, *RelSec);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000773}
774
775template <class ELFT>
776void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &S,
777 const Elf_Shdr &RelSec) {
778 ELFFile<ELFT> &EObj = S.getFile()->getObj();
779 if (RelSec.sh_type == SHT_RELA)
780 scanRelocs(S, EObj.relas(&RelSec));
781 else
782 scanRelocs(S, EObj.rels(&RelSec));
Rafael Espindola19e38892015-09-16 15:54:15 +0000783}
784
Rafael Espindola6173f842015-09-23 14:37:01 +0000785template <class ELFT>
Rui Ueyama2a65a492016-01-05 20:01:29 +0000786static void reportUndefined(SymbolTable<ELFT> &Symtab, SymbolBody *Sym) {
Peter Collingbourne6d01a352016-04-24 02:31:04 +0000787 if (!Config->NoUndefined) {
788 if (Config->Relocatable)
789 return;
790 if (Config->Shared)
Peter Collingbourne4f952702016-05-01 04:55:03 +0000791 if (Sym->symbol()->Visibility == STV_DEFAULT)
Peter Collingbourne6d01a352016-04-24 02:31:04 +0000792 return;
793 }
George Rimaree058282015-10-01 17:24:24 +0000794
George Rimar57610422016-03-11 14:43:02 +0000795 std::string Msg = "undefined symbol: " + Sym->getName().str();
Peter Collingbournec3572782016-05-03 01:48:25 +0000796 if (InputFile *File = Sym->getSourceFile<ELFT>())
Rui Ueyama2a65a492016-01-05 20:01:29 +0000797 Msg += " in " + File->getName().str();
Rui Ueyama3f9f0922016-03-08 04:06:29 +0000798 if (Config->NoinhibitExec)
Rui Ueyama2a65a492016-01-05 20:01:29 +0000799 warning(Msg);
Rafael Espindola6173f842015-09-23 14:37:01 +0000800 else
Rui Ueyamac2a0d7e2016-01-28 22:56:29 +0000801 error(Msg);
Rafael Espindola6173f842015-09-23 14:37:01 +0000802}
803
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000804template <class ELFT>
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000805static bool shouldKeepInSymtab(InputSectionBase<ELFT> *Sec, StringRef SymName,
806 const SymbolBody &B) {
807 if (B.isFile())
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000808 return false;
809
George Rimar4cfe5722016-03-03 07:49:35 +0000810 // We keep sections in symtab for relocatable output.
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000811 if (B.isSection())
George Rimar4cfe5722016-03-03 07:49:35 +0000812 return Config->Relocatable;
813
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000814 // If sym references a section in a discarded group, don't keep it.
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000815 if (Sec == &InputSection<ELFT>::Discarded)
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000816 return false;
817
818 if (Config->DiscardNone)
819 return true;
820
821 // In ELF assembly .L symbols are normally discarded by the assembler.
822 // If the assembler fails to do so, the linker discards them if
823 // * --discard-locals is used.
824 // * The symbol is in a SHF_MERGE section, which is normally the reason for
825 // the assembler keeping the .L symbol.
826 if (!SymName.startswith(".L") && !SymName.empty())
827 return true;
828
829 if (Config->DiscardLocals)
830 return false;
831
832 return !(Sec->getSectionHdr()->sh_flags & SHF_MERGE);
833}
834
Rafael Espindola474eb012016-05-05 16:40:28 +0000835template <class ELFT> static bool includeInSymtab(const SymbolBody &B) {
836 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
837 return false;
838
839 if (auto *D = dyn_cast<DefinedRegular<ELFT>>(&B)) {
840 // Always include absolute symbols.
841 if (!D->Section)
842 return true;
843 // Exclude symbols pointing to garbage-collected sections.
844 if (!D->Section->Live)
845 return false;
846 if (auto *S = dyn_cast<MergeInputSection<ELFT>>(D->Section))
847 if (S->getRangeAndSize(D->Value).first->second ==
848 MergeInputSection<ELFT>::PieceDead)
849 return false;
850 }
851 return true;
852}
Rafael Espindola462220d2016-05-05 16:38:46 +0000853
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000854// Local symbols are not in the linker's symbol table. This function scans
855// each object file's symbol table to copy local symbols to the output.
856template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
Rui Ueyama90f76fb2016-01-21 03:07:38 +0000857 if (!Out<ELFT>::SymTab)
858 return;
Rafael Espindola78620972016-03-11 16:41:23 +0000859 for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
860 Symtab.getObjectFiles()) {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000861 const char *StrTab = F->getStringTable().data();
Rafael Espindola67d72c02016-03-11 12:06:30 +0000862 for (SymbolBody *B : F->getLocalSymbols()) {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000863 auto *DR = dyn_cast<DefinedRegular<ELFT>>(B);
864 // No reason to keep local undefined symbol in symtab.
865 if (!DR)
Rafael Espindola444576d2015-10-09 19:25:07 +0000866 continue;
Rafael Espindola462220d2016-05-05 16:38:46 +0000867 if (!includeInSymtab<ELFT>(*B))
868 continue;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000869 StringRef SymName(StrTab + B->getNameOffset());
870 InputSectionBase<ELFT> *Sec = DR->Section;
871 if (!shouldKeepInSymtab<ELFT>(Sec, SymName, *B))
872 continue;
Rafael Espindolae2c24612016-01-29 01:24:25 +0000873 ++Out<ELFT>::SymTab->NumLocals;
George Rimar4cfe5722016-03-03 07:49:35 +0000874 if (Config->Relocatable)
Rui Ueyama98a4b8b2016-03-13 20:18:12 +0000875 B->DynsymIndex = Out<ELFT>::SymTab->NumLocals;
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000876 F->KeptLocalSyms.push_back(
877 std::make_pair(DR, Out<ELFT>::SymTab->StrTabSec.addString(SymName)));
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000878 }
879 }
880}
881
Hal Finkel3bae2d82015-10-12 20:51:48 +0000882// PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
883// we would like to make sure appear is a specific order to maximize their
884// coverage by a single signed 16-bit offset from the TOC base pointer.
885// Conversely, the special .tocbss section should be first among all SHT_NOBITS
886// sections. This will put it next to the loaded special PPC64 sections (and,
887// thus, within reach of the TOC base pointer).
888static int getPPC64SectionRank(StringRef SectionName) {
889 return StringSwitch<int>(SectionName)
George Rimaree741cf2016-04-14 13:23:02 +0000890 .Case(".tocbss", 0)
891 .Case(".branch_lt", 2)
892 .Case(".toc", 3)
893 .Case(".toc1", 4)
894 .Case(".opd", 5)
895 .Default(1);
Hal Finkel3bae2d82015-10-12 20:51:48 +0000896}
897
George Rimare3336c02015-11-24 10:15:50 +0000898template <class ELFT> static bool isRelroSection(OutputSectionBase<ELFT> *Sec) {
Rafael Espindola4fc60442016-02-10 22:43:13 +0000899 if (!Config->ZRelro)
900 return false;
Rui Ueyama389aa8e2016-04-27 03:04:56 +0000901 typename ELFT::uint Flags = Sec->getFlags();
George Rimare3336c02015-11-24 10:15:50 +0000902 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
903 return false;
Rui Ueyamaccfc3262015-12-10 19:13:08 +0000904 if (Flags & SHF_TLS)
905 return true;
George Rimare3336c02015-11-24 10:15:50 +0000906 uint32_t Type = Sec->getType();
Rui Ueyamaccfc3262015-12-10 19:13:08 +0000907 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
908 Type == SHT_PREINIT_ARRAY)
George Rimare3336c02015-11-24 10:15:50 +0000909 return true;
910 if (Sec == Out<ELFT>::GotPlt)
911 return Config->ZNow;
912 if (Sec == Out<ELFT>::Dynamic || Sec == Out<ELFT>::Got)
913 return true;
Rui Ueyama01faef02015-12-10 19:19:04 +0000914 StringRef S = Sec->getName();
915 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
916 S == ".eh_frame";
George Rimare3336c02015-11-24 10:15:50 +0000917}
918
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000919// Output section ordering is determined by this function.
920template <class ELFT>
Rui Ueyama717677a2016-02-11 21:17:59 +0000921static bool compareSections(OutputSectionBase<ELFT> *A,
922 OutputSectionBase<ELFT> *B) {
Rui Ueyama9328b2c2016-03-14 23:16:09 +0000923 typedef typename ELFT::uint uintX_t;
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000924
Rui Ueyama07320e42016-04-20 20:13:41 +0000925 int Comp = Script<ELFT>::X->compareSections(A->getName(), B->getName());
Rui Ueyama717677a2016-02-11 21:17:59 +0000926 if (Comp != 0)
927 return Comp < 0;
928
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000929 uintX_t AFlags = A->getFlags();
930 uintX_t BFlags = B->getFlags();
931
932 // Allocatable sections go first to reduce the total PT_LOAD size and
933 // so debug info doesn't change addresses in actual code.
934 bool AIsAlloc = AFlags & SHF_ALLOC;
935 bool BIsAlloc = BFlags & SHF_ALLOC;
936 if (AIsAlloc != BIsAlloc)
937 return AIsAlloc;
938
939 // We don't have any special requirements for the relative order of
940 // two non allocatable sections.
941 if (!AIsAlloc)
942 return false;
943
944 // We want the read only sections first so that they go in the PT_LOAD
945 // covering the program headers at the start of the file.
946 bool AIsWritable = AFlags & SHF_WRITE;
947 bool BIsWritable = BFlags & SHF_WRITE;
948 if (AIsWritable != BIsWritable)
949 return BIsWritable;
950
951 // For a corresponding reason, put non exec sections first (the program
952 // header PT_LOAD is not executable).
953 bool AIsExec = AFlags & SHF_EXECINSTR;
954 bool BIsExec = BFlags & SHF_EXECINSTR;
955 if (AIsExec != BIsExec)
956 return BIsExec;
957
Hal Finkel0d7e83b2015-10-13 17:57:46 +0000958 // If we got here we know that both A and B are in the same PT_LOAD.
Michael J. Spencer1bf73002015-10-16 23:11:07 +0000959
960 // The TLS initialization block needs to be a single contiguous block in a R/W
961 // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS
962 // sections are placed here as they don't take up virtual address space in the
963 // PT_LOAD.
Rui Ueyama61805ec2015-12-17 00:12:03 +0000964 bool AIsTls = AFlags & SHF_TLS;
965 bool BIsTls = BFlags & SHF_TLS;
966 if (AIsTls != BIsTls)
967 return AIsTls;
Michael J. Spencer1bf73002015-10-16 23:11:07 +0000968
Hal Finkel08be6142015-10-13 18:55:01 +0000969 // The next requirement we have is to put nobits sections last. The
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000970 // reason is that the only thing the dynamic linker will see about
971 // them is a p_memsz that is larger than p_filesz. Seeing that it
972 // zeros the end of the PT_LOAD, so that has to correspond to the
973 // nobits sections.
Hal Finkel600ff142015-10-13 19:27:12 +0000974 bool AIsNoBits = A->getType() == SHT_NOBITS;
975 bool BIsNoBits = B->getType() == SHT_NOBITS;
976 if (AIsNoBits != BIsNoBits)
977 return BIsNoBits;
Hal Finkel3bae2d82015-10-12 20:51:48 +0000978
George Rimare3336c02015-11-24 10:15:50 +0000979 // We place RelRo section before plain r/w ones.
980 bool AIsRelRo = isRelroSection(A);
981 bool BIsRelRo = isRelroSection(B);
982 if (AIsRelRo != BIsRelRo)
983 return AIsRelRo;
984
Hal Finkel9abc2a52015-10-13 19:07:29 +0000985 // Some architectures have additional ordering restrictions for sections
986 // within the same PT_LOAD.
987 if (Config->EMachine == EM_PPC64)
988 return getPPC64SectionRank(A->getName()) <
989 getPPC64SectionRank(B->getName());
990
991 return false;
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000992}
993
Rui Ueyamab30f73562016-03-13 04:11:53 +0000994// The .bss section does not exist if no input file has a .bss section.
995// This function creates one if that's the case.
996template <class ELFT> void Writer<ELFT>::ensureBss() {
997 if (Out<ELFT>::Bss)
998 return;
999 Out<ELFT>::Bss =
1000 new OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
1001 OwningSections.emplace_back(Out<ELFT>::Bss);
1002 OutputSections.push_back(Out<ELFT>::Bss);
Rafael Espindola443f50a2015-11-03 21:35:14 +00001003}
1004
Rui Ueyama5a9640b2015-10-08 23:49:30 +00001005// Until this function is called, common symbols do not belong to any section.
1006// This function adds them to end of BSS section.
1007template <class ELFT>
Rafael Espindola11191912015-12-24 16:23:37 +00001008void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon *> &Syms) {
Rafael Espindola443f50a2015-11-03 21:35:14 +00001009 if (Syms.empty())
1010 return;
1011
Rui Ueyama5a9640b2015-10-08 23:49:30 +00001012 // Sort the common symbols by alignment as an heuristic to pack them better.
Rafael Espindola11191912015-12-24 16:23:37 +00001013 std::stable_sort(Syms.begin(), Syms.end(),
1014 [](const DefinedCommon *A, const DefinedCommon *B) {
Rui Ueyama17d69832016-03-10 18:58:53 +00001015 return A->Alignment > B->Alignment;
Rafael Espindola11191912015-12-24 16:23:37 +00001016 });
Rui Ueyama5a9640b2015-10-08 23:49:30 +00001017
Rui Ueyamab30f73562016-03-13 04:11:53 +00001018 ensureBss();
1019 uintX_t Off = Out<ELFT>::Bss->getSize();
Rafael Espindola11191912015-12-24 16:23:37 +00001020 for (DefinedCommon *C : Syms) {
Rui Ueyama17d69832016-03-10 18:58:53 +00001021 Off = alignTo(Off, C->Alignment);
1022 Out<ELFT>::Bss->updateAlign(C->Alignment);
Rui Ueyamae57c4872016-01-05 16:35:43 +00001023 C->OffsetInBss = Off;
Rafael Espindola11191912015-12-24 16:23:37 +00001024 Off += C->Size;
Rui Ueyama5a9640b2015-10-08 23:49:30 +00001025 }
1026
1027 Out<ELFT>::Bss->setSize(Off);
1028}
1029
Rui Ueyamaf50e1d82016-03-14 22:41:08 +00001030template <class ELFT> static uint32_t getAlignment(SharedSymbol<ELFT> *SS) {
1031 typedef typename ELFFile<ELFT>::uintX_t uintX_t;
1032
1033 uintX_t SecAlign = SS->File->getSection(SS->Sym)->sh_addralign;
1034 uintX_t SymValue = SS->Sym.st_value;
George Rimaree741cf2016-04-14 13:23:02 +00001035 int TrailingZeros =
1036 std::min(countTrailingZeros(SecAlign), countTrailingZeros(SymValue));
Rui Ueyamaa9692182016-03-13 04:05:42 +00001037 return 1 << TrailingZeros;
1038}
1039
Peter Collingbourne4cdade62016-04-04 22:29:24 +00001040// Reserve space in .bss for copy relocation.
George Rimarbc590fe2015-10-28 16:48:58 +00001041template <class ELFT>
Peter Collingbourne4cdade62016-04-04 22:29:24 +00001042void Writer<ELFT>::addCopyRelSymbol(SharedSymbol<ELFT> *SS) {
Rui Ueyamab30f73562016-03-13 04:11:53 +00001043 ensureBss();
Peter Collingbourne4cdade62016-04-04 22:29:24 +00001044 uintX_t Align = getAlignment(SS);
George Rimar21221682016-04-14 13:56:28 +00001045 uintX_t Off = alignTo(Out<ELFT>::Bss->getSize(), Align);
Peter Collingbourne4cdade62016-04-04 22:29:24 +00001046 Out<ELFT>::Bss->setSize(Off + SS->template getSize<ELFT>());
1047 Out<ELFT>::Bss->updateAlign(Align);
Peter Collingbourne4cdade62016-04-04 22:29:24 +00001048 uintX_t Shndx = SS->Sym.st_shndx;
1049 uintX_t Value = SS->Sym.st_value;
Peter Collingbourne4f952702016-05-01 04:55:03 +00001050 // Look through the DSO's dynamic symbol table for aliases and create a
1051 // dynamic symbol for each one. This causes the copy relocation to correctly
1052 // interpose any aliases.
1053 for (const Elf_Sym &S : SS->File->getElfSymbols(true)) {
1054 if (S.st_shndx != Shndx || S.st_value != Value)
Peter Collingbourne4cdade62016-04-04 22:29:24 +00001055 continue;
Peter Collingbourne4f952702016-05-01 04:55:03 +00001056 auto *Alias = dyn_cast_or_null<SharedSymbol<ELFT>>(
1057 Symtab.find(check(S.getName(SS->File->getStringTable()))));
1058 if (!Alias)
1059 continue;
1060 Alias->OffsetInBss = Off;
1061 Alias->NeedsCopyOrPltAddr = true;
1062 Alias->symbol()->IsUsedInRegularObj = true;
George Rimarbc590fe2015-10-28 16:48:58 +00001063 }
Rafael Espindolac012db32016-04-07 14:34:15 +00001064 Out<ELFT>::RelaDyn->addReloc(
1065 {Target->CopyRel, Out<ELFT>::Bss, SS->OffsetInBss, false, SS, 0});
George Rimarbc590fe2015-10-28 16:48:58 +00001066}
1067
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001068template <class ELFT>
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001069StringRef Writer<ELFT>::getOutputSectionName(InputSectionBase<ELFT> *S) const {
Rui Ueyama07320e42016-04-20 20:13:41 +00001070 StringRef Dest = Script<ELFT>::X->getOutputSection(S);
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001071 if (!Dest.empty())
1072 return Dest;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001073
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001074 StringRef Name = S->getSectionName();
Rafael Espindola14928202016-02-16 16:05:27 +00001075 for (StringRef V : {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.",
1076 ".init_array.", ".fini_array.", ".ctors.", ".dtors.",
Rafael Espindola8ae12902016-02-16 16:12:06 +00001077 ".tbss.", ".gcc_except_table.", ".tdata."})
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001078 if (Name.startswith(V))
Rui Ueyamac2dca5d2016-02-11 01:07:18 +00001079 return V.drop_back();
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001080 return Name;
Rui Ueyama4fcadaf2015-10-14 19:21:25 +00001081}
1082
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001083template <class ELFT>
George Rimara5fbebc2015-12-10 09:12:18 +00001084void reportDiscarded(InputSectionBase<ELFT> *IS,
Rafael Espindola36a73d22016-03-11 16:32:46 +00001085 const std::unique_ptr<elf::ObjectFile<ELFT>> &File) {
Rui Ueyama8fc070d2016-02-24 00:23:15 +00001086 if (!Config->PrintGcSections || !IS || IS->Live)
George Rimara5fbebc2015-12-10 09:12:18 +00001087 return;
1088 llvm::errs() << "removing unused section from '" << IS->getSectionName()
1089 << "' in file '" << File->getName() << "'\n";
1090}
1091
1092template <class ELFT>
Rui Ueyama717677a2016-02-11 21:17:59 +00001093bool Writer<ELFT>::isDiscarded(InputSectionBase<ELFT> *S) const {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001094 return !S || S == &InputSection<ELFT>::Discarded || !S->Live ||
Rui Ueyama07320e42016-04-20 20:13:41 +00001095 Script<ELFT>::X->isDiscarded(S);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001096}
1097
Rafael Espindola6f92e142016-04-12 13:26:51 +00001098template <class ELFT>
Peter Collingbourne4f952702016-05-01 04:55:03 +00001099static Symbol *addOptionalSynthetic(SymbolTable<ELFT> &Table, StringRef Name,
Peter Collingbourne6a422592016-05-03 01:21:08 +00001100 OutputSectionBase<ELFT> *Sec,
Peter Collingbourne4f952702016-05-01 04:55:03 +00001101 typename ELFT::uint Val) {
Rafael Espindola6f92e142016-04-12 13:26:51 +00001102 if (!Table.find(Name))
1103 return nullptr;
Peter Collingbournef6e9b4e2016-04-13 16:57:28 +00001104 return Table.addSynthetic(Name, Sec, Val);
Rafael Espindola6f92e142016-04-12 13:26:51 +00001105}
1106
Rui Ueyama01687222015-12-26 09:47:57 +00001107// The beginning and the ending of .rel[a].plt section are marked
1108// with __rel[a]_iplt_{start,end} symbols if it is a statically linked
1109// executable. The runtime needs these symbols in order to resolve
1110// all IRELATIVE relocs on startup. For dynamic executables, we don't
1111// need these symbols, since IRELATIVE relocs are resolved through GOT
1112// and PLT. For details, see http://www.airs.com/blog/archives/403.
George Rimaree741cf2016-04-14 13:23:02 +00001113template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
Rui Ueyama01687222015-12-26 09:47:57 +00001114 if (isOutputDynamic() || !Out<ELFT>::RelaPlt)
George Rimara07ff662015-12-21 10:12:06 +00001115 return;
Rui Ueyama6c5638b2016-03-13 20:10:20 +00001116 StringRef S = Config->Rela ? "__rela_iplt_start" : "__rel_iplt_start";
Peter Collingbourne6a422592016-05-03 01:21:08 +00001117 addOptionalSynthetic(Symtab, S, Out<ELFT>::RelaPlt, 0);
Rui Ueyama01687222015-12-26 09:47:57 +00001118
Rui Ueyama6c5638b2016-03-13 20:10:20 +00001119 S = Config->Rela ? "__rela_iplt_end" : "__rel_iplt_end";
Peter Collingbourne6a422592016-05-03 01:21:08 +00001120 addOptionalSynthetic(Symtab, S, Out<ELFT>::RelaPlt,
Peter Collingbourne4f952702016-05-01 04:55:03 +00001121 DefinedSynthetic<ELFT>::SectionEnd);
George Rimara07ff662015-12-21 10:12:06 +00001122}
1123
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001124// This class knows how to create an output section for a given
1125// input section. Output section type is determined by various
1126// factors, including input section's sh_flags, sh_type and
1127// linker scripts.
1128namespace {
1129template <class ELFT> class OutputSectionFactory {
Rui Ueyama9328b2c2016-03-14 23:16:09 +00001130 typedef typename ELFT::Shdr Elf_Shdr;
1131 typedef typename ELFT::uint uintX_t;
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001132
1133public:
1134 std::pair<OutputSectionBase<ELFT> *, bool> create(InputSectionBase<ELFT> *C,
1135 StringRef OutsecName);
1136
George Rimard502f472016-04-14 14:07:54 +00001137 OutputSectionBase<ELFT> *lookup(StringRef Name, uint32_t Type,
1138 uintX_t Flags) {
George Rimar4c2ae3a2016-04-14 14:24:23 +00001139 return Map.lookup({Name, Type, Flags, 0});
George Rimard502f472016-04-14 14:07:54 +00001140 }
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001141
1142private:
1143 SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
1144 StringRef OutsecName);
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001145
1146 SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map;
1147};
1148}
1149
1150template <class ELFT>
1151std::pair<OutputSectionBase<ELFT> *, bool>
1152OutputSectionFactory<ELFT>::create(InputSectionBase<ELFT> *C,
1153 StringRef OutsecName) {
1154 SectionKey<ELFT::Is64Bits> Key = createKey(C, OutsecName);
1155 OutputSectionBase<ELFT> *&Sec = Map[Key];
1156 if (Sec)
1157 return {Sec, false};
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001158
Rui Ueyama2df0fd82015-12-25 07:38:58 +00001159 switch (C->SectionKind) {
1160 case InputSectionBase<ELFT>::Regular:
Rui Ueyamaf949f7f2016-01-11 23:50:55 +00001161 Sec = new OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
1162 break;
Rui Ueyama2df0fd82015-12-25 07:38:58 +00001163 case InputSectionBase<ELFT>::EHFrame:
Rui Ueyamaf949f7f2016-01-11 23:50:55 +00001164 Sec = new EHOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
1165 break;
Rui Ueyama2df0fd82015-12-25 07:38:58 +00001166 case InputSectionBase<ELFT>::Merge:
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001167 Sec = new MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags,
1168 Key.Alignment);
Rui Ueyamaf949f7f2016-01-11 23:50:55 +00001169 break;
Rui Ueyama2df0fd82015-12-25 07:38:58 +00001170 case InputSectionBase<ELFT>::MipsReginfo:
Rui Ueyamaf949f7f2016-01-11 23:50:55 +00001171 Sec = new MipsReginfoOutputSection<ELFT>();
1172 break;
Simon Atanasyanadd74f32016-05-04 10:07:38 +00001173 case InputSectionBase<ELFT>::MipsOptions:
1174 Sec = new MipsOptionsOutputSection<ELFT>();
1175 break;
Rui Ueyama2df0fd82015-12-25 07:38:58 +00001176 }
Rui Ueyamaf949f7f2016-01-11 23:50:55 +00001177 return {Sec, true};
Rui Ueyama2df0fd82015-12-25 07:38:58 +00001178}
1179
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001180template <class ELFT>
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001181SectionKey<ELFT::Is64Bits>
1182OutputSectionFactory<ELFT>::createKey(InputSectionBase<ELFT> *C,
1183 StringRef OutsecName) {
1184 const Elf_Shdr *H = C->getSectionHdr();
Rui Ueyama63de9172015-12-26 07:13:38 +00001185 uintX_t Flags = H->sh_flags & ~SHF_GROUP;
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001186
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001187 // For SHF_MERGE we create different output sections for each alignment.
1188 // This makes each output section simple and keeps a single level mapping from
1189 // input to output.
1190 uintX_t Alignment = 0;
George Rimar4e8cf852016-04-14 13:00:03 +00001191 if (isa<MergeInputSection<ELFT>>(C))
1192 Alignment = std::max(H->sh_addralign, H->sh_entsize);
Rui Ueyama63de9172015-12-26 07:13:38 +00001193
George Rimar959d1802016-04-28 13:38:10 +00001194 // GNU as can give .eh_frame section type SHT_PROGBITS or SHT_X86_64_UNWIND
Rui Ueyama63de9172015-12-26 07:13:38 +00001195 // depending on the construct. We want to canonicalize it so that
1196 // there is only one .eh_frame in the end.
1197 uint32_t Type = H->sh_type;
1198 if (Type == SHT_PROGBITS && Config->EMachine == EM_X86_64 &&
1199 isa<EHInputSection<ELFT>>(C))
1200 Type = SHT_X86_64_UNWIND;
1201
Rafael Espindola7efa5be2016-02-19 14:17:40 +00001202 return SectionKey<ELFT::Is64Bits>{OutsecName, Type, Flags, Alignment};
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001203}
1204
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +00001205// The linker is expected to define some symbols depending on
1206// the linking result. This function defines such symbols.
1207template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001208 if (Config->EMachine == EM_MIPS) {
Rafael Espindola9b3f99e2016-04-12 02:24:43 +00001209 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
1210 // so that it points to an absolute address which is relative to GOT.
1211 // See "Global Data Symbols" in Chapter 6 in the following document:
1212 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Peter Collingbourne6a422592016-05-03 01:21:08 +00001213 Symtab.addSynthetic("_gp", Out<ELFT>::Got, MipsGPOffset);
Rafael Espindola9b3f99e2016-04-12 02:24:43 +00001214
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001215 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
1216 // start of function and 'gp' pointer into GOT.
Peter Collingbourne6f535b72016-05-03 18:03:45 +00001217 Symbol *Sym =
1218 addOptionalSynthetic(Symtab, "_gp_disp", Out<ELFT>::Got, MipsGPOffset);
1219 if (Sym)
1220 ElfSym<ELFT>::MipsGpDisp = Sym->body();
1221
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001222 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
1223 // pointer. This symbol is used in the code generated by .cpload pseudo-op
1224 // in case of using -mno-shared option.
1225 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
Peter Collingbourne6a422592016-05-03 01:21:08 +00001226 addOptionalSynthetic(Symtab, "__gnu_local_gp", Out<ELFT>::Got,
Peter Collingbourne4f952702016-05-01 04:55:03 +00001227 MipsGPOffset);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001228 }
1229
1230 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
1231 // is magical and is used to produce a R_386_GOTPC relocation.
1232 // The R_386_GOTPC relocation value doesn't actually depend on the
1233 // symbol value, so it could use an index of STN_UNDEF which, according
1234 // to the spec, means the symbol value is 0.
1235 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
1236 // the object file.
1237 // The situation is even stranger on x86_64 where the assembly doesn't
1238 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
1239 // an undefined symbol in the .o files.
1240 // Given that the symbol is effectively unused, we just create a dummy
1241 // hidden one to avoid the undefined symbol error.
1242 if (!Config->Relocatable)
1243 Symtab.addIgnored("_GLOBAL_OFFSET_TABLE_");
1244
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +00001245 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
1246 // static linking the linker is required to optimize away any references to
1247 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
1248 // to avoid the undefined symbol error.
1249 if (!isOutputDynamic())
1250 Symtab.addIgnored("__tls_get_addr");
1251
Rui Ueyama467dbdd2016-04-21 20:50:15 +00001252 auto Define = [this](StringRef S, DefinedRegular<ELFT> *&Sym1,
1253 DefinedRegular<ELFT> *&Sym2) {
1254 Sym1 = Symtab.addIgnored(S, STV_DEFAULT);
Rui Ueyama4d169bd2016-02-26 16:38:39 +00001255
1256 // The name without the underscore is not a reserved name,
1257 // so it is defined only when there is a reference against it.
Rui Ueyama68e15552016-02-26 16:49:54 +00001258 assert(S.startswith("_"));
Rui Ueyama4d169bd2016-02-26 16:38:39 +00001259 S = S.substr(1);
1260 if (SymbolBody *B = Symtab.find(S))
George Rimar9e859392016-02-26 14:36:36 +00001261 if (B->isUndefined())
Rui Ueyama467dbdd2016-04-21 20:50:15 +00001262 Sym2 = Symtab.addAbsolute(S, STV_DEFAULT);
George Rimar9e859392016-02-26 14:36:36 +00001263 };
1264
Rui Ueyama467dbdd2016-04-21 20:50:15 +00001265 Define("_end", ElfSym<ELFT>::End, ElfSym<ELFT>::End2);
1266 Define("_etext", ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2);
1267 Define("_edata", ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2);
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +00001268}
1269
Rui Ueyamac4185702016-02-10 23:20:42 +00001270// Sort input sections by section name suffixes for
1271// __attribute__((init_priority(N))).
Rui Ueyama5af83682016-02-11 23:41:38 +00001272template <class ELFT> static void sortInitFini(OutputSectionBase<ELFT> *S) {
Rui Ueyamac4185702016-02-10 23:20:42 +00001273 if (S)
Rui Ueyama5af83682016-02-11 23:41:38 +00001274 reinterpret_cast<OutputSection<ELFT> *>(S)->sortInitFini();
1275}
1276
1277// Sort input sections by the special rule for .ctors and .dtors.
1278template <class ELFT> static void sortCtorsDtors(OutputSectionBase<ELFT> *S) {
1279 if (S)
1280 reinterpret_cast<OutputSection<ELFT> *>(S)->sortCtorsDtors();
Rui Ueyamac4185702016-02-10 23:20:42 +00001281}
1282
Michael J. Spencer84487f12015-07-24 21:03:07 +00001283// Create output section objects and add them to OutputSections.
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +00001284template <class ELFT> void Writer<ELFT>::createSections() {
Rui Ueyama1b2a8bf2015-12-26 10:22:16 +00001285 // Add .interp first because some loaders want to see that section
1286 // on the first page of the executable file when loaded into memory.
Rui Ueyama69960ba2015-10-10 23:25:39 +00001287 if (needsInterpSection())
1288 OutputSections.push_back(Out<ELFT>::Interp);
1289
Rui Ueyama28286cd2016-03-13 01:54:48 +00001290 // A core file does not usually contain unmodified segments except
1291 // the first page of the executable. Add the build ID section now
1292 // so that the section is included in the first page.
1293 if (Out<ELFT>::BuildId)
1294 OutputSections.push_back(Out<ELFT>::BuildId);
1295
Rui Ueyama1b2a8bf2015-12-26 10:22:16 +00001296 // Create output sections for input object file sections.
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001297 std::vector<OutputSectionBase<ELFT> *> RegularSections;
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001298 OutputSectionFactory<ELFT> Factory;
Rafael Espindola78620972016-03-11 16:41:23 +00001299 for (const std::unique_ptr<elf::ObjectFile<ELFT>> &F :
1300 Symtab.getObjectFiles()) {
Rafael Espindolac159c962015-10-19 21:00:02 +00001301 for (InputSectionBase<ELFT> *C : F->getSections()) {
George Rimara5fbebc2015-12-10 09:12:18 +00001302 if (isDiscarded(C)) {
1303 reportDiscarded(C, F);
Rafael Espindola19e38892015-09-16 15:54:15 +00001304 continue;
George Rimara5fbebc2015-12-10 09:12:18 +00001305 }
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001306 OutputSectionBase<ELFT> *Sec;
1307 bool IsNew;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001308 std::tie(Sec, IsNew) = Factory.create(C, getOutputSectionName(C));
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001309 if (IsNew) {
Rui Ueyamad4ea7dd2015-12-26 07:01:26 +00001310 OwningSections.emplace_back(Sec);
Rafael Espindolad13d9602015-09-25 15:08:44 +00001311 OutputSections.push_back(Sec);
Rui Ueyamad9189ce2015-10-15 17:11:03 +00001312 RegularSections.push_back(Sec);
Rafael Espindolad13d9602015-09-25 15:08:44 +00001313 }
Rui Ueyama40845e62015-12-26 05:51:07 +00001314 Sec->addSection(C);
Rafael Espindola19e38892015-09-16 15:54:15 +00001315 }
1316 }
1317
Rafael Espindola443f50a2015-11-03 21:35:14 +00001318 Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>(
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001319 Factory.lookup(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE));
Rafael Espindola443f50a2015-11-03 21:35:14 +00001320
Rui Ueyama84417f82015-12-26 07:50:41 +00001321 // If we have a .opd section (used under PPC64 for function descriptors),
1322 // store a pointer to it here so that we can use it later when processing
1323 // relocations.
1324 Out<ELFT>::Opd = Factory.lookup(".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC);
1325
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001326 Out<ELFT>::Dynamic->PreInitArraySec = Factory.lookup(
1327 ".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC);
Rui Ueyama15ef5e12015-10-07 19:18:16 +00001328 Out<ELFT>::Dynamic->InitArraySec =
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001329 Factory.lookup(".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC);
Rui Ueyama15ef5e12015-10-07 19:18:16 +00001330 Out<ELFT>::Dynamic->FiniArraySec =
Rui Ueyama3a1f0362015-12-26 07:01:28 +00001331 Factory.lookup(".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC);
Rafael Espindola77572242015-10-02 19:37:55 +00001332
Rui Ueyamac4185702016-02-10 23:20:42 +00001333 // Sort section contents for __attribute__((init_priority(N)).
Rui Ueyama5af83682016-02-11 23:41:38 +00001334 sortInitFini(Out<ELFT>::Dynamic->InitArraySec);
1335 sortInitFini(Out<ELFT>::Dynamic->FiniArraySec);
1336 sortCtorsDtors(Factory.lookup(".ctors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
1337 sortCtorsDtors(Factory.lookup(".dtors", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC));
Rui Ueyamac4185702016-02-10 23:20:42 +00001338
Rui Ueyamaa5d79d12015-12-26 09:48:00 +00001339 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1340 // symbols for sections, so that the runtime can get the start and end
1341 // addresses of each section by section name. Add such symbols.
George Rimarc1034a82016-03-01 19:12:35 +00001342 if (!Config->Relocatable) {
1343 addStartEndSymbols();
1344 for (OutputSectionBase<ELFT> *Sec : RegularSections)
1345 addStartStopSymbols(Sec);
1346 }
Rui Ueyamad4530c62016-03-04 18:34:14 +00001347
1348 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1349 // It should be okay as no one seems to care about the type.
1350 // Even the author of gold doesn't remember why gold behaves that way.
1351 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
George Rimaraa4dc202016-03-01 16:23:13 +00001352 if (isOutputDynamic())
Peter Collingbourne6a422592016-05-03 01:21:08 +00001353 Symtab.addSynthetic("_DYNAMIC", Out<ELFT>::Dynamic, 0);
Rafael Espindola334c3e12015-10-19 15:21:42 +00001354
Rafael Espindolade9857e2016-02-04 21:33:05 +00001355 // Define __rel[a]_iplt_{start,end} symbols if needed.
1356 addRelIpltSymbols();
1357
Rafael Espindola56004c52016-04-07 14:22:09 +00001358 if (Out<ELFT>::EhFrameHdr->Sec)
1359 Out<ELFT>::EhFrameHdr->Sec->finalize();
1360
Rafael Espindola334c3e12015-10-19 15:21:42 +00001361 // Scan relocations. This must be done after every symbol is declared so that
1362 // we can correctly decide if a dynamic relocation is needed.
Rafael Espindola3828b882016-04-07 15:50:23 +00001363 // Check size() each time to guard against .bss being created.
1364 for (unsigned I = 0; I < OutputSections.size(); ++I) {
1365 OutputSectionBase<ELFT> *Sec = OutputSections[I];
Rafael Espindola56004c52016-04-07 14:22:09 +00001366 Sec->forEachInputSection([&](InputSectionBase<ELFT> *S) {
1367 if (auto *IS = dyn_cast<InputSection<ELFT>>(S)) {
1368 // Set OutSecOff so that scanRelocs can use it.
1369 uintX_t Off = alignTo(Sec->getSize(), S->Align);
1370 IS->OutSecOff = Off;
Rafael Espindola334c3e12015-10-19 15:21:42 +00001371
Rafael Espindola56004c52016-04-07 14:22:09 +00001372 scanRelocs(*IS);
1373
1374 // Now that scan relocs possibly changed the size, update the offset.
1375 Sec->setSize(Off + S->getSize());
1376 } else if (auto *EH = dyn_cast<EHInputSection<ELFT>>(S)) {
1377 if (EH->RelocSection)
1378 scanRelocs(*EH, *EH->RelocSection);
1379 }
1380 });
1381 }
Simon Atanasyan13f6da12016-03-31 21:26:23 +00001382
Rui Ueyama1b2a8bf2015-12-26 10:22:16 +00001383 // Now that we have defined all possible symbols including linker-
1384 // synthesized ones. Visit all symbols to give the finishing touches.
Rafael Espindola11191912015-12-24 16:23:37 +00001385 std::vector<DefinedCommon *> CommonSymbols;
Rafael Espindola7f0b7272016-04-14 20:42:43 +00001386 for (Symbol *S : Symtab.getSymbols()) {
Peter Collingbourne4f952702016-05-01 04:55:03 +00001387 SymbolBody *Body = S->body();
Rafael Espindola0baa73f2016-04-26 13:56:26 +00001388
1389 // Set "used" bit for --as-needed.
1390 if (S->IsUsedInRegularObj && !S->isWeak())
1391 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
1392 SS->File->IsUsed = true;
1393
Peter Collingbourne892d49802016-04-27 00:05:03 +00001394 if (Body->isUndefined() && !S->isWeak())
1395 reportUndefined<ELFT>(Symtab, Body);
Rafael Espindola05a3dd22015-09-22 23:38:23 +00001396
Rafael Espindola11191912015-12-24 16:23:37 +00001397 if (auto *C = dyn_cast<DefinedCommon>(Body))
Rafael Espindola05a3dd22015-09-22 23:38:23 +00001398 CommonSymbols.push_back(C);
George Rimarbc590fe2015-10-28 16:48:58 +00001399
Rafael Espindola4f674ed2015-10-05 15:24:04 +00001400 if (!includeInSymtab<ELFT>(*Body))
Rafael Espindola05a3dd22015-09-22 23:38:23 +00001401 continue;
George Rimar5dad7c12015-10-24 08:52:46 +00001402 if (Out<ELFT>::SymTab)
1403 Out<ELFT>::SymTab->addSymbol(Body);
Rafael Espindola05a3dd22015-09-22 23:38:23 +00001404
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001405 if (isOutputDynamic() && S->includeInDynsym()) {
Igor Kudrinab665fc2015-10-20 21:47:58 +00001406 Out<ELFT>::DynSymTab->addSymbol(Body);
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001407 if (auto *SS = dyn_cast<SharedSymbol<ELFT>>(Body))
1408 Out<ELFT>::VerNeed->addSymbol(SS);
1409 }
Rafael Espindola05a3dd22015-09-22 23:38:23 +00001410 }
Rui Ueyamac2a0d7e2016-01-28 22:56:29 +00001411
1412 // Do not proceed if there was an undefined symbol.
1413 if (HasError)
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +00001414 return;
Rui Ueyamac2a0d7e2016-01-28 22:56:29 +00001415
Rui Ueyama5a9640b2015-10-08 23:49:30 +00001416 addCommonSymbols(CommonSymbols);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001417
Rui Ueyama84417f82015-12-26 07:50:41 +00001418 // So far we have added sections from input object files.
1419 // This function adds linker-created Out<ELFT>::* sections.
1420 addPredefinedSections();
1421
1422 std::stable_sort(OutputSections.begin(), OutputSections.end(),
1423 compareSections<ELFT>);
1424
George Rimar7ca06272016-04-06 07:20:45 +00001425 unsigned I = 1;
1426 for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1427 Sec->SectionIndex = I++;
Rafael Espindolae2c24612016-01-29 01:24:25 +00001428 Sec->setSHName(Out<ELFT>::ShStrTab->addString(Sec->getName()));
George Rimar7ca06272016-04-06 07:20:45 +00001429 }
Rui Ueyama84417f82015-12-26 07:50:41 +00001430
1431 // Finalizers fix each section's size.
Rafael Espindolade069362016-01-25 21:32:04 +00001432 // .dynsym is finalized early since that may fill up .gnu.hash.
Rui Ueyama84417f82015-12-26 07:50:41 +00001433 if (isOutputDynamic())
1434 Out<ELFT>::DynSymTab->finalize();
1435
Simon Atanasyan40d25f32016-02-02 09:07:47 +00001436 // Fill other section headers. The dynamic table is finalized
1437 // at the end because some tags like RELSZ depend on result
1438 // of finalizing other sections. The dynamic string table is
1439 // finalized once the .dynamic finalizer has added a few last
1440 // strings. See DynamicSection::finalize()
Rui Ueyama84417f82015-12-26 07:50:41 +00001441 for (OutputSectionBase<ELFT> *Sec : OutputSections)
Simon Atanasyan40d25f32016-02-02 09:07:47 +00001442 if (Sec != Out<ELFT>::DynStrTab && Sec != Out<ELFT>::Dynamic)
Rafael Espindolade069362016-01-25 21:32:04 +00001443 Sec->finalize();
Simon Atanasyan40d25f32016-02-02 09:07:47 +00001444
1445 if (isOutputDynamic())
1446 Out<ELFT>::Dynamic->finalize();
Rui Ueyama84417f82015-12-26 07:50:41 +00001447}
1448
Rui Ueyama30951482016-02-25 19:34:37 +00001449template <class ELFT> bool Writer<ELFT>::needsGot() {
1450 if (!Out<ELFT>::Got->empty())
1451 return true;
1452
1453 // We add the .got section to the result for dynamic MIPS target because
1454 // its address and properties are mentioned in the .dynamic section.
Rafael Espindolaa22b0822016-04-12 13:21:13 +00001455 if (Config->EMachine == EM_MIPS)
Rui Ueyama30951482016-02-25 19:34:37 +00001456 return true;
1457
1458 // If we have a relocation that is relative to GOT (such as GOTOFFREL),
1459 // we need to emit a GOT even if it's empty.
1460 return HasGotOffRel;
1461}
1462
Rui Ueyama84417f82015-12-26 07:50:41 +00001463// This function add Out<ELFT>::* sections to OutputSections.
1464template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001465 auto Add = [&](OutputSectionBase<ELFT> *C) {
1466 if (C)
1467 OutputSections.push_back(C);
1468 };
1469
Rui Ueyamac6ef3f22015-10-15 21:50:30 +00001470 // This order is not the same as the final output order
1471 // because we sort the sections using their attributes below.
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001472 Add(Out<ELFT>::SymTab);
1473 Add(Out<ELFT>::ShStrTab);
1474 Add(Out<ELFT>::StrTab);
Michael J. Spencer350e5b52015-10-12 23:39:23 +00001475 if (isOutputDynamic()) {
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001476 Add(Out<ELFT>::DynSymTab);
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001477 if (Out<ELFT>::VerNeed->getNeedNum() != 0) {
1478 Add(Out<ELFT>::VerSym);
1479 Add(Out<ELFT>::VerNeed);
1480 }
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001481 Add(Out<ELFT>::GnuHashTab);
1482 Add(Out<ELFT>::HashTab);
1483 Add(Out<ELFT>::Dynamic);
1484 Add(Out<ELFT>::DynStrTab);
Rui Ueyama15ef5e12015-10-07 19:18:16 +00001485 if (Out<ELFT>::RelaDyn->hasRelocs())
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001486 Add(Out<ELFT>::RelaDyn);
Rui Ueyamaa354c5c2016-02-25 23:54:49 +00001487 Add(Out<ELFT>::MipsRldMap);
Rafael Espindola3f4228f2015-09-09 15:33:08 +00001488 }
Igor Kudrin304860a2015-11-12 04:39:49 +00001489
George Rimara07ff662015-12-21 10:12:06 +00001490 // We always need to add rel[a].plt to output if it has entries.
1491 // Even during static linking it can contain R_[*]_IRELATIVE relocations.
1492 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs()) {
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001493 Add(Out<ELFT>::RelaPlt);
George Rimara07ff662015-12-21 10:12:06 +00001494 Out<ELFT>::RelaPlt->Static = !isOutputDynamic();
1495 }
1496
Rui Ueyama30951482016-02-25 19:34:37 +00001497 if (needsGot())
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001498 Add(Out<ELFT>::Got);
George Rimar648a2c32015-10-20 08:54:27 +00001499 if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty())
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001500 Add(Out<ELFT>::GotPlt);
Rui Ueyama15ef5e12015-10-07 19:18:16 +00001501 if (!Out<ELFT>::Plt->empty())
Rui Ueyama5a4ae1f2015-12-26 10:34:33 +00001502 Add(Out<ELFT>::Plt);
George Rimarf6bc65a2016-01-15 13:34:52 +00001503 if (Out<ELFT>::EhFrameHdr->Live)
1504 Add(Out<ELFT>::EhFrameHdr);
Rafael Espindolaabad6182015-08-13 15:23:46 +00001505}
1506
Rui Ueyamaa5d79d12015-12-26 09:48:00 +00001507// The linker is expected to define SECNAME_start and SECNAME_end
1508// symbols for a few sections. This function defines them.
1509template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1510 auto Define = [&](StringRef Start, StringRef End,
1511 OutputSectionBase<ELFT> *OS) {
1512 if (OS) {
Peter Collingbourne6a422592016-05-03 01:21:08 +00001513 this->Symtab.addSynthetic(Start, OS, 0);
1514 this->Symtab.addSynthetic(End, OS, DefinedSynthetic<ELFT>::SectionEnd);
Rui Ueyamaa5d79d12015-12-26 09:48:00 +00001515 } else {
Peter Collingbourne6a422592016-05-03 01:21:08 +00001516 addOptionalSynthetic(this->Symtab, Start,
1517 (OutputSectionBase<ELFT> *)nullptr, 0);
1518 addOptionalSynthetic(this->Symtab, End,
1519 (OutputSectionBase<ELFT> *)nullptr, 0);
Rui Ueyamaa5d79d12015-12-26 09:48:00 +00001520 }
1521 };
1522
1523 Define("__preinit_array_start", "__preinit_array_end",
1524 Out<ELFT>::Dynamic->PreInitArraySec);
1525 Define("__init_array_start", "__init_array_end",
1526 Out<ELFT>::Dynamic->InitArraySec);
1527 Define("__fini_array_start", "__fini_array_end",
1528 Out<ELFT>::Dynamic->FiniArraySec);
1529}
1530
Rui Ueyamad9189ce2015-10-15 17:11:03 +00001531// If a section name is valid as a C identifier (which is rare because of
1532// the leading '.'), linkers are expected to define __start_<secname> and
1533// __stop_<secname> symbols. They are at beginning and end of the section,
1534// respectively. This is not requested by the ELF standard, but GNU ld and
1535// gold provide the feature, and used by many programs.
1536template <class ELFT>
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001537void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) {
Rui Ueyamad9189ce2015-10-15 17:11:03 +00001538 StringRef S = Sec->getName();
1539 if (!isValidCIdentifier(S))
1540 return;
1541 StringSaver Saver(Alloc);
1542 StringRef Start = Saver.save("__start_" + S);
1543 StringRef Stop = Saver.save("__stop_" + S);
Rui Ueyama2ef58a12016-01-05 20:35:16 +00001544 if (SymbolBody *B = Symtab.find(Start))
1545 if (B->isUndefined())
Peter Collingbourne6a422592016-05-03 01:21:08 +00001546 Symtab.addSynthetic(Start, Sec, 0);
Rui Ueyama2ef58a12016-01-05 20:35:16 +00001547 if (SymbolBody *B = Symtab.find(Stop))
1548 if (B->isUndefined())
Peter Collingbourne6a422592016-05-03 01:21:08 +00001549 Symtab.addSynthetic(Stop, Sec, DefinedSynthetic<ELFT>::SectionEnd);
Rui Ueyamad9189ce2015-10-15 17:11:03 +00001550}
1551
Rafael Espindolaef762f22016-02-10 23:29:38 +00001552template <class ELFT> static bool needsPtLoad(OutputSectionBase<ELFT> *Sec) {
1553 if (!(Sec->getFlags() & SHF_ALLOC))
1554 return false;
1555
1556 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1557 // responsible for allocating space for them, not the PT_LOAD that
1558 // contains the TLS initialization image.
1559 if (Sec->getFlags() & SHF_TLS && Sec->getType() == SHT_NOBITS)
1560 return false;
1561 return true;
Michael J. Spencer1d299a82015-09-09 20:48:09 +00001562}
1563
Rui Ueyama9eb7ed02015-10-24 18:22:59 +00001564static uint32_t toPhdrFlags(uint64_t Flags) {
1565 uint32_t Ret = PF_R;
1566 if (Flags & SHF_WRITE)
1567 Ret |= PF_W;
1568 if (Flags & SHF_EXECINSTR)
1569 Ret |= PF_X;
1570 return Ret;
1571}
1572
Rafael Espindola4fc60442016-02-10 22:43:13 +00001573// Decide which program headers to create and which sections to include in each
1574// one.
1575template <class ELFT> void Writer<ELFT>::createPhdrs() {
1576 auto AddHdr = [this](unsigned Type, unsigned Flags) {
1577 return &*Phdrs.emplace(Phdrs.end(), Type, Flags);
1578 };
George Rimare3336c02015-11-24 10:15:50 +00001579
Rafael Espindola4fc60442016-02-10 22:43:13 +00001580 auto AddSec = [](Phdr &Hdr, OutputSectionBase<ELFT> *Sec) {
1581 Hdr.Last = Sec;
1582 if (!Hdr.First)
1583 Hdr.First = Sec;
1584 Hdr.H.p_align = std::max<uintX_t>(Hdr.H.p_align, Sec->getAlign());
1585 };
Rui Ueyama3486fe52015-10-11 17:44:22 +00001586
Rui Ueyama803195e2015-10-23 21:45:59 +00001587 // The first phdr entry is PT_PHDR which describes the program header itself.
Rafael Espindola4fc60442016-02-10 22:43:13 +00001588 Phdr &Hdr = *AddHdr(PT_PHDR, PF_R);
1589 AddSec(Hdr, Out<ELFT>::ProgramHeaders);
Rui Ueyama953c2c42015-10-10 23:59:57 +00001590
Rui Ueyama803195e2015-10-23 21:45:59 +00001591 // PT_INTERP must be the second entry if exists.
Rafael Espindola4fc60442016-02-10 22:43:13 +00001592 if (needsInterpSection()) {
1593 Phdr &Hdr = *AddHdr(PT_INTERP, toPhdrFlags(Out<ELFT>::Interp->getFlags()));
1594 AddSec(Hdr, Out<ELFT>::Interp);
1595 }
Rafael Espindola70107762015-09-11 18:49:42 +00001596
Rui Ueyama803195e2015-10-23 21:45:59 +00001597 // Add the first PT_LOAD segment for regular output sections.
Rafael Espindola4fc60442016-02-10 22:43:13 +00001598 uintX_t Flags = PF_R;
1599 Phdr *Load = AddHdr(PT_LOAD, Flags);
1600 AddSec(*Load, Out<ELFT>::ElfHeader);
George Rimar7ca06272016-04-06 07:20:45 +00001601 AddSec(*Load, Out<ELFT>::ProgramHeaders);
Rafael Espindola0a2e2112015-09-10 15:41:34 +00001602
Rafael Espindola4fc60442016-02-10 22:43:13 +00001603 Phdr TlsHdr(PT_TLS, PF_R);
1604 Phdr RelRo(PT_GNU_RELRO, PF_R);
Rafael Espindola9907eb02016-03-01 13:23:29 +00001605 Phdr Note(PT_NOTE, PF_R);
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001606 for (OutputSectionBase<ELFT> *Sec : OutputSections) {
Rafael Espindolaef762f22016-02-10 23:29:38 +00001607 if (!(Sec->getFlags() & SHF_ALLOC))
Rafael Espindola4fc60442016-02-10 22:43:13 +00001608 break;
Rafael Espindola97cbe3e32015-12-23 15:20:38 +00001609
Rafael Espindolaef762f22016-02-10 23:29:38 +00001610 // If we meet TLS section then we create TLS header
1611 // and put all TLS sections inside for futher use when
1612 // assign addresses.
1613 if (Sec->getFlags() & SHF_TLS)
1614 AddSec(TlsHdr, Sec);
1615
1616 if (!needsPtLoad<ELFT>(Sec))
1617 continue;
1618
Rafael Espindola4fc60442016-02-10 22:43:13 +00001619 // If flags changed then we want new load segment.
1620 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
1621 if (Flags != NewFlags) {
Rafael Espindolae090fb22016-03-09 21:37:22 +00001622 Load = AddHdr(PT_LOAD, NewFlags);
Rafael Espindola4fc60442016-02-10 22:43:13 +00001623 Flags = NewFlags;
1624 }
Michael J. Spencer78aa1de2015-11-03 00:34:39 +00001625
Rafael Espindola4fc60442016-02-10 22:43:13 +00001626 AddSec(*Load, Sec);
1627
1628 if (isRelroSection(Sec))
1629 AddSec(RelRo, Sec);
Rafael Espindola9907eb02016-03-01 13:23:29 +00001630 if (Sec->getType() == SHT_NOTE)
1631 AddSec(Note, Sec);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001632 }
Rafael Espindola6b83b902015-08-12 00:00:24 +00001633
Rafael Espindola4fc60442016-02-10 22:43:13 +00001634 // Add the TLS segment unless it's empty.
1635 if (TlsHdr.First)
1636 Phdrs.push_back(std::move(TlsHdr));
Michael J. Spencer78aa1de2015-11-03 00:34:39 +00001637
Rui Ueyama803195e2015-10-23 21:45:59 +00001638 // Add an entry for .dynamic.
Michael J. Spencer350e5b52015-10-12 23:39:23 +00001639 if (isOutputDynamic()) {
Rafael Espindola4fc60442016-02-10 22:43:13 +00001640 Phdr &H = *AddHdr(PT_DYNAMIC, toPhdrFlags(Out<ELFT>::Dynamic->getFlags()));
1641 AddSec(H, Out<ELFT>::Dynamic);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +00001642 }
Rafael Espindola91009b32015-08-12 01:45:28 +00001643
Rafael Espindola4fc60442016-02-10 22:43:13 +00001644 // PT_GNU_RELRO includes all sections that should be marked as
1645 // read-only by dynamic linker after proccessing relocations.
1646 if (RelRo.First)
1647 Phdrs.push_back(std::move(RelRo));
George Rimare3336c02015-11-24 10:15:50 +00001648
Rafael Espindola4fc60442016-02-10 22:43:13 +00001649 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
George Rimarf6bc65a2016-01-15 13:34:52 +00001650 if (Out<ELFT>::EhFrameHdr->Live) {
Rafael Espindola4fc60442016-02-10 22:43:13 +00001651 Phdr &Hdr = *AddHdr(PT_GNU_EH_FRAME,
1652 toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags()));
1653 AddSec(Hdr, Out<ELFT>::EhFrameHdr);
George Rimarf6bc65a2016-01-15 13:34:52 +00001654 }
1655
Rui Ueyamae79b09a2015-11-21 22:19:32 +00001656 // PT_GNU_STACK is a special section to tell the loader to make the
1657 // pages for the stack non-executable.
Rafael Espindola4fc60442016-02-10 22:43:13 +00001658 if (!Config->ZExecStack)
1659 AddHdr(PT_GNU_STACK, PF_R | PF_W);
Rafael Espindola9907eb02016-03-01 13:23:29 +00001660
1661 if (Note.First)
1662 Phdrs.push_back(std::move(Note));
George Rimar687788c2016-04-01 17:30:52 +00001663
1664 Out<ELFT>::ProgramHeaders->setSize(sizeof(Elf_Phdr) * Phdrs.size());
Rafael Espindola4fc60442016-02-10 22:43:13 +00001665}
1666
Rui Ueyama47091902016-03-30 19:41:51 +00001667// The first section of each PT_LOAD and the first section after PT_GNU_RELRO
1668// have to be page aligned so that the dynamic linker can set the permissions.
1669template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
1670 for (const Phdr &P : Phdrs)
1671 if (P.H.p_type == PT_LOAD)
1672 P.First->PageAlign = true;
1673
1674 for (const Phdr &P : Phdrs) {
1675 if (P.H.p_type != PT_GNU_RELRO)
1676 continue;
1677 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1678 // have to align it to a page.
1679 auto End = OutputSections.end();
1680 auto I = std::find(OutputSections.begin(), End, P.Last);
1681 if (I == End || (I + 1) == End)
1682 continue;
1683 OutputSectionBase<ELFT> *Sec = *(I + 1);
1684 if (needsPtLoad(Sec))
1685 Sec->PageAlign = true;
1686 }
1687}
1688
George Rimar7ca06272016-04-06 07:20:45 +00001689// We should set file offsets and VAs for elf header and program headers
1690// sections. These are special, we do not include them into output sections
1691// list, but have them to simplify the code.
1692template <class ELFT> void Writer<ELFT>::fixHeaders() {
Rui Ueyama07320e42016-04-20 20:13:41 +00001693 uintX_t BaseVA = ScriptConfig->DoLayout ? 0 : Target->getVAStart();
George Rimar652852c2016-04-16 10:10:32 +00001694 Out<ELFT>::ElfHeader->setVA(BaseVA);
George Rimar7ca06272016-04-06 07:20:45 +00001695 Out<ELFT>::ElfHeader->setFileOffset(0);
1696 uintX_t Off = Out<ELFT>::ElfHeader->getSize();
George Rimar652852c2016-04-16 10:10:32 +00001697 Out<ELFT>::ProgramHeaders->setVA(Off + BaseVA);
George Rimar7ca06272016-04-06 07:20:45 +00001698 Out<ELFT>::ProgramHeaders->setFileOffset(Off);
1699}
1700
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001701// Assign VAs (addresses at run-time) to output sections.
Rafael Espindola4fc60442016-02-10 22:43:13 +00001702template <class ELFT> void Writer<ELFT>::assignAddresses() {
George Rimar7ca06272016-04-06 07:20:45 +00001703 uintX_t VA = Target->getVAStart() + Out<ELFT>::ElfHeader->getSize() +
1704 Out<ELFT>::ProgramHeaders->getSize();
Rafael Espindola4fc60442016-02-10 22:43:13 +00001705
George Rimar7ca06272016-04-06 07:20:45 +00001706 uintX_t ThreadBssOffset = 0;
Rafael Espindola4fc60442016-02-10 22:43:13 +00001707 for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1708 uintX_t Align = Sec->getAlign();
Rui Ueyama47091902016-03-30 19:41:51 +00001709 if (Sec->PageAlign)
Rafael Espindola4fc60442016-02-10 22:43:13 +00001710 Align = std::max<uintX_t>(Align, Target->PageSize);
Rafael Espindola4fc60442016-02-10 22:43:13 +00001711
1712 // We only assign VAs to allocated sections.
Rafael Espindolaef762f22016-02-10 23:29:38 +00001713 if (needsPtLoad<ELFT>(Sec)) {
1714 VA = alignTo(VA, Align);
1715 Sec->setVA(VA);
1716 VA += Sec->getSize();
1717 } else if (Sec->getFlags() & SHF_TLS && Sec->getType() == SHT_NOBITS) {
1718 uintX_t TVA = VA + ThreadBssOffset;
1719 TVA = alignTo(TVA, Align);
1720 Sec->setVA(TVA);
1721 ThreadBssOffset = TVA - VA + Sec->getSize();
Rafael Espindola4fc60442016-02-10 22:43:13 +00001722 }
Rui Ueyama69960ba2015-10-10 23:25:39 +00001723 }
George Rimar900a2602016-04-01 10:49:14 +00001724}
1725
George Rimar5f857322016-04-27 09:16:28 +00001726// Adjusts the file alignment for a given output section and returns
1727// its new file offset. The file offset must be the same with its
1728// virtual address (modulo the page size) so that the loader can load
1729// executables without any address adjustment.
1730template <class ELFT, class uintX_t>
1731static uintX_t getFileAlignment(uintX_t Off, OutputSectionBase<ELFT> *Sec) {
1732 uintX_t Align = Sec->getAlign();
1733 if (Sec->PageAlign)
1734 Align = std::max<uintX_t>(Align, Target->PageSize);
1735 Off = alignTo(Off, Align);
1736
1737 // Relocatable output does not have program headers
1738 // and does not need any other offset adjusting.
1739 if (Config->Relocatable || !(Sec->getFlags() & SHF_ALLOC))
1740 return Off;
1741 return alignTo(Off, Target->PageSize, Sec->getVA());
1742}
1743
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001744// Assign file offsets to output sections.
1745template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
George Rimar7ca06272016-04-06 07:20:45 +00001746 uintX_t Off =
1747 Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
1748
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001749 for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1750 if (Sec->getType() == SHT_NOBITS) {
1751 Sec->setFileOffset(Off);
1752 continue;
1753 }
George Rimar5f857322016-04-27 09:16:28 +00001754
1755 Off = getFileAlignment<ELFT>(Off, Sec);
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001756 Sec->setFileOffset(Off);
1757 Off += Sec->getSize();
1758 }
1759 SectionHeaderOff = alignTo(Off, sizeof(uintX_t));
George Rimar7ca06272016-04-06 07:20:45 +00001760 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001761}
1762
1763// Finalize the program headers. We call this function after we assign
1764// file offsets and VAs to all sections.
1765template <class ELFT> void Writer<ELFT>::setPhdrs() {
Rui Ueyamae8a45e42016-04-01 22:42:04 +00001766 for (Phdr &P : Phdrs) {
1767 Elf_Phdr &H = P.H;
1768 OutputSectionBase<ELFT> *First = P.First;
1769 OutputSectionBase<ELFT> *Last = P.Last;
1770 if (First) {
1771 H.p_filesz = Last->getFileOff() - First->getFileOff();
Rafael Espindola4fc60442016-02-10 22:43:13 +00001772 if (Last->getType() != SHT_NOBITS)
1773 H.p_filesz += Last->getSize();
Rui Ueyamae8a45e42016-04-01 22:42:04 +00001774 H.p_memsz = Last->getVA() + Last->getSize() - First->getVA();
1775 H.p_offset = First->getFileOff();
1776 H.p_vaddr = First->getVA();
Rafael Espindola4fc60442016-02-10 22:43:13 +00001777 }
George Rimar6de3f632016-03-01 08:46:03 +00001778 if (H.p_type == PT_LOAD)
Rafael Espindola4fc60442016-02-10 22:43:13 +00001779 H.p_align = Target->PageSize;
George Rimar6de3f632016-03-01 08:46:03 +00001780 else if (H.p_type == PT_GNU_RELRO)
Rafael Espindola4fc60442016-02-10 22:43:13 +00001781 H.p_align = 1;
1782 H.p_paddr = H.p_vaddr;
1783
1784 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1785 // so round up the size to make sure the offsets are correct.
George Rimar6de3f632016-03-01 08:46:03 +00001786 if (H.p_type == PT_TLS) {
Rafael Espindola4fc60442016-02-10 22:43:13 +00001787 Out<ELFT>::TlsPhdr = &H;
1788 H.p_memsz = alignTo(H.p_memsz, H.p_align);
Rui Ueyama803195e2015-10-23 21:45:59 +00001789 }
1790 }
Michael J. Spencer84487f12015-07-24 21:03:07 +00001791}
1792
Simon Atanasyanae77ab72016-04-29 10:39:17 +00001793static uint32_t getMipsEFlags(bool Is64Bits) {
Simon Atanasyan034c4cd2015-12-19 05:51:49 +00001794 // FIXME: In fact ELF flags depends on ELF flags of input object files
Simon Atanasyandb147eb2016-01-12 06:24:02 +00001795 // and selected emulation. For now just use hard coded values.
Simon Atanasyanae77ab72016-04-29 10:39:17 +00001796 if (Is64Bits)
1797 return EF_MIPS_CPIC | EF_MIPS_PIC | EF_MIPS_ARCH_64R2;
1798
1799 uint32_t V = EF_MIPS_CPIC | EF_MIPS_ABI_O32 | EF_MIPS_ARCH_32R2;
Simon Atanasyan034c4cd2015-12-19 05:51:49 +00001800 if (Config->Shared)
1801 V |= EF_MIPS_PIC;
1802 return V;
1803}
1804
Rui Ueyama9328b2c2016-03-14 23:16:09 +00001805template <class ELFT> static typename ELFT::uint getEntryAddr() {
Rafael Espindola38c67a22016-04-15 14:41:56 +00001806 if (Symbol *S = Config->EntrySym)
Peter Collingbourne4f952702016-05-01 04:55:03 +00001807 return S->body()->getVA<ELFT>();
Rui Ueyama3bfaba92015-12-24 08:37:34 +00001808 if (Config->EntryAddr != uint64_t(-1))
1809 return Config->EntryAddr;
1810 return 0;
1811}
1812
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001813template <class ELFT> static uint8_t getELFEncoding() {
1814 if (ELFT::TargetEndianness == llvm::support::little)
1815 return ELFDATA2LSB;
1816 return ELFDATA2MSB;
1817}
1818
1819static uint16_t getELFType() {
George Rimar786e8662016-03-17 05:57:33 +00001820 if (Config->Pic)
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001821 return ET_DYN;
1822 if (Config->Relocatable)
1823 return ET_REL;
1824 return ET_EXEC;
1825}
1826
Rui Ueyama1a311f12015-12-26 10:52:26 +00001827// This function is called after we have assigned address and size
1828// to each section. This function fixes some predefined absolute
1829// symbol values that depend on section address and size.
1830template <class ELFT> void Writer<ELFT>::fixAbsoluteSymbols() {
Rui Ueyama467dbdd2016-04-21 20:50:15 +00001831 auto Set = [](DefinedRegular<ELFT> *&S1, DefinedRegular<ELFT> *&S2,
1832 uintX_t V) {
1833 if (S1)
1834 S1->Value = V;
1835 if (S2)
1836 S2->Value = V;
1837 };
1838
George Rimar2abc5872016-03-01 19:18:07 +00001839 // _etext is the first location after the last read-only loadable segment.
1840 // _edata is the first location after the last read-write loadable segment.
George Rimarefded312016-04-01 10:23:32 +00001841 // _end is the first location after the uninitialized data region.
Rui Ueyamae8a45e42016-04-01 22:42:04 +00001842 for (Phdr &P : Phdrs) {
1843 Elf_Phdr &H = P.H;
1844 if (H.p_type != PT_LOAD)
George Rimar9e859392016-02-26 14:36:36 +00001845 continue;
Rui Ueyama467dbdd2016-04-21 20:50:15 +00001846 Set(ElfSym<ELFT>::End, ElfSym<ELFT>::End2, H.p_vaddr + H.p_memsz);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +00001847
George Rimar8bbff7e2016-04-14 14:37:59 +00001848 uintX_t Val = H.p_vaddr + H.p_filesz;
1849 if (H.p_flags & PF_W)
Rui Ueyama467dbdd2016-04-21 20:50:15 +00001850 Set(ElfSym<ELFT>::Edata, ElfSym<ELFT>::Edata2, Val);
George Rimar8bbff7e2016-04-14 14:37:59 +00001851 else
Rui Ueyama467dbdd2016-04-21 20:50:15 +00001852 Set(ElfSym<ELFT>::Etext, ElfSym<ELFT>::Etext2, Val);
George Rimar9e859392016-02-26 14:36:36 +00001853 }
Rui Ueyama1a311f12015-12-26 10:52:26 +00001854}
1855
Michael J. Spencer84487f12015-07-24 21:03:07 +00001856template <class ELFT> void Writer<ELFT>::writeHeader() {
1857 uint8_t *Buf = Buffer->getBufferStart();
Rui Ueyamae08cd672015-10-23 22:44:39 +00001858 memcpy(Buf, "\177ELF", 4);
1859
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001860 auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf);
1861
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001862 // Write the ELF header.
Rafael Espindola18608a02015-09-08 21:57:31 +00001863 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
Rafael Espindola4b7c2fc2015-08-05 15:08:40 +00001864 EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001865 EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
Michael J. Spencer84487f12015-07-24 21:03:07 +00001866 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
Davide Italianoaa7c5332015-09-25 01:59:13 +00001867 EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI();
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001868 EHdr->e_type = getELFType();
Rafael Espindolaf98d6d82015-09-03 20:03:54 +00001869 EHdr->e_machine = FirstObj.getEMachine();
Michael J. Spencer84487f12015-07-24 21:03:07 +00001870 EHdr->e_version = EV_CURRENT;
Rui Ueyama3bfaba92015-12-24 08:37:34 +00001871 EHdr->e_entry = getEntryAddr<ELFT>();
Michael J. Spencer8039dae22015-07-29 00:30:10 +00001872 EHdr->e_shoff = SectionHeaderOff;
Rafael Espindola18608a02015-09-08 21:57:31 +00001873 EHdr->e_ehsize = sizeof(Elf_Ehdr);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +00001874 EHdr->e_phnum = Phdrs.size();
Rafael Espindola18608a02015-09-08 21:57:31 +00001875 EHdr->e_shentsize = sizeof(Elf_Shdr);
George Rimar7ca06272016-04-06 07:20:45 +00001876 EHdr->e_shnum = OutputSections.size() + 1;
George Rimar0f5ac9f2015-10-20 17:21:35 +00001877 EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex;
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001878
Rui Ueyama22b5d1f2016-03-13 19:29:17 +00001879 if (Config->EMachine == EM_MIPS)
Simon Atanasyanae77ab72016-04-29 10:39:17 +00001880 EHdr->e_flags = getMipsEFlags(ELFT::Is64Bits);
Rui Ueyama22b5d1f2016-03-13 19:29:17 +00001881
George Rimar58941ee2016-02-25 08:23:37 +00001882 if (!Config->Relocatable) {
1883 EHdr->e_phoff = sizeof(Elf_Ehdr);
1884 EHdr->e_phentsize = sizeof(Elf_Phdr);
1885 }
1886
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001887 // Write the program header table.
Rafael Espindola4fc60442016-02-10 22:43:13 +00001888 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
1889 for (Phdr &P : Phdrs)
1890 *HBuf++ = P.H;
Rafael Espindolae438e072015-09-08 22:55:28 +00001891
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001892 // Write the section header table. Note that the first table entry is null.
Rui Ueyamaad59b652016-02-25 23:58:21 +00001893 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
George Rimar7ca06272016-04-06 07:20:45 +00001894 for (OutputSectionBase<ELFT> *Sec : OutputSections)
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001895 Sec->writeHeaderTo(++SHdrs);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001896}
1897
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +00001898template <class ELFT> void Writer<ELFT>::openFile() {
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001899 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Rui Ueyamacbe39262016-02-02 22:48:04 +00001900 FileOutputBuffer::create(Config->OutputFile, FileSize,
1901 FileOutputBuffer::F_executable);
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +00001902 if (BufferOrErr)
1903 Buffer = std::move(*BufferOrErr);
1904 else
Rui Ueyama6eafa7f2016-03-13 04:25:41 +00001905 error(BufferOrErr, "failed to open " + Config->OutputFile);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001906}
1907
1908// Write section contents to a mmap'ed file.
1909template <class ELFT> void Writer<ELFT>::writeSections() {
1910 uint8_t *Buf = Buffer->getBufferStart();
Hal Finkeldaedc122015-10-12 23:16:53 +00001911
1912 // PPC64 needs to process relocations in the .opd section before processing
1913 // relocations in code-containing sections.
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001914 if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) {
Rafael Espindola7a513052015-10-13 14:45:51 +00001915 Out<ELFT>::OpdBuf = Buf + Sec->getFileOff();
1916 Sec->writeTo(Buf + Sec->getFileOff());
1917 }
Hal Finkeldaedc122015-10-12 23:16:53 +00001918
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001919 for (OutputSectionBase<ELFT> *Sec : OutputSections)
Rafael Espindola4d91f7f2016-02-01 21:52:00 +00001920 if (Sec != Out<ELFT>::Opd)
Hal Finkeldaedc122015-10-12 23:16:53 +00001921 Sec->writeTo(Buf + Sec->getFileOff());
Michael J. Spencer84487f12015-07-24 21:03:07 +00001922}
Rui Ueyama3ce825e2015-10-09 21:07:25 +00001923
Rui Ueyama634ddf02016-03-11 20:51:53 +00001924template <class ELFT> void Writer<ELFT>::writeBuildId() {
1925 BuildIdSection<ELFT> *S = Out<ELFT>::BuildId;
1926 if (!S)
1927 return;
1928
1929 // Compute a hash of all sections except .debug_* sections.
1930 // We skip debug sections because they tend to be very large
1931 // and their contents are very likely to be the same as long as
1932 // other sections are the same.
1933 uint8_t *Start = Buffer->getBufferStart();
1934 uint8_t *Last = Start;
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001935 std::vector<ArrayRef<uint8_t>> Regions;
Rui Ueyama634ddf02016-03-11 20:51:53 +00001936 for (OutputSectionBase<ELFT> *Sec : OutputSections) {
1937 uint8_t *End = Start + Sec->getFileOff();
1938 if (!Sec->getName().startswith(".debug_"))
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001939 Regions.push_back({Last, End});
Rui Ueyama634ddf02016-03-11 20:51:53 +00001940 Last = End;
1941 }
Rui Ueyamadd368fc2016-05-02 23:35:59 +00001942 Regions.push_back({Last, Start + FileSize});
1943 S->writeBuildId(Regions);
Rui Ueyama634ddf02016-03-11 20:51:53 +00001944}
1945
Rafael Espindolae0df00b2016-02-28 00:25:54 +00001946template void elf::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab);
1947template void elf::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab);
1948template void elf::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab);
1949template void elf::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab);