blob: 35a8f2601ff1010dcb6c4aea35a7aad789f0455b [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"
Rafael Espindola5805c4f2015-09-21 21:38:08 +000012#include "OutputSections.h"
Rui Ueyamaafff74e22015-08-05 23:24:46 +000013#include "SymbolTable.h"
Rafael Espindola01205f72015-09-22 18:19:46 +000014#include "Target.h"
Rafael Espindola6b83b902015-08-12 00:00:24 +000015
Denis Protivensky8e3b38a2015-11-12 09:52:08 +000016#include "llvm/ADT/StringMap.h"
Hal Finkel3bae2d82015-10-12 20:51:48 +000017#include "llvm/ADT/StringSwitch.h"
Rui Ueyamaafff74e22015-08-05 23:24:46 +000018#include "llvm/Support/FileOutputBuffer.h"
Rui Ueyamad9189ce2015-10-15 17:11:03 +000019#include "llvm/Support/StringSaver.h"
Michael J. Spencer84487f12015-07-24 21:03:07 +000020
21using namespace llvm;
22using namespace llvm::ELF;
23using namespace llvm::object;
24
25using namespace lld;
26using namespace lld::elf2;
27
Rui Ueyamaafff74e22015-08-05 23:24:46 +000028namespace {
29// The writer writes a SymbolTable result to a file.
30template <class ELFT> class Writer {
31public:
Rafael Espindola18608a02015-09-08 21:57:31 +000032 typedef typename ELFFile<ELFT>::uintX_t uintX_t;
33 typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
34 typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
35 typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr;
36 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
Davide Italiano6d328d32015-09-16 20:45:57 +000037 typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
Rafael Espindola19e38892015-09-16 15:54:15 +000038 typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
Rui Ueyama3ce825e2015-10-09 21:07:25 +000039 Writer(SymbolTable<ELFT> &S) : Symtab(S) {}
Rui Ueyamaafff74e22015-08-05 23:24:46 +000040 void run();
41
42private:
Rui Ueyama5a9640b2015-10-08 23:49:30 +000043 void copyLocalSymbols();
Rui Ueyamaafff74e22015-08-05 23:24:46 +000044 void createSections();
Rafael Espindola67a5da62015-09-17 14:02:10 +000045 template <bool isRela>
Rafael Espindola0c6a4f12015-11-11 19:54:14 +000046 void scanRelocs(InputSectionBase<ELFT> &C,
Rafael Espindola67a5da62015-09-17 14:02:10 +000047 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels);
Rafael Espindolaa0fa8482015-11-11 15:29:50 +000048 void scanRelocs(InputSection<ELFT> &C);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +000049 void scanRelocs(InputSectionBase<ELFT> &S, const Elf_Shdr &RelSec);
George Rimare3336c02015-11-24 10:15:50 +000050 void updateRelro(Elf_Phdr *Cur, Elf_Phdr *GnuRelroPhdr,
51 OutputSectionBase<ELFT> *Sec, uintX_t VA);
Rui Ueyamaafff74e22015-08-05 23:24:46 +000052 void assignAddresses();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +000053 void buildSectionMap();
Rui Ueyamaafff74e22015-08-05 23:24:46 +000054 void openFile(StringRef OutputPath);
55 void writeHeader();
56 void writeSections();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +000057 bool isDiscarded(InputSectionBase<ELFT> *IS) const;
58 StringRef getOutputSectionName(StringRef S) const;
Rafael Espindola70107762015-09-11 18:49:42 +000059 bool needsInterpSection() const {
Rui Ueyama0d0bcf72015-10-07 21:25:39 +000060 return !Symtab.getSharedFiles().empty() && !Config->DynamicLinker.empty();
Rafael Espindola70107762015-09-11 18:49:42 +000061 }
Michael J. Spencerf32446f2015-10-06 20:39:09 +000062 bool isOutputDynamic() const {
Rui Ueyama0d0bcf72015-10-07 21:25:39 +000063 return !Symtab.getSharedFiles().empty() || Config->Shared;
Rafael Espindola4340aad2015-09-11 22:42:45 +000064 }
Rui Ueyamabcb2d0f2015-10-23 22:44:37 +000065 uintX_t getEntryAddr() const;
Rui Ueyama803195e2015-10-23 21:45:59 +000066 int getPhdrsNum() const;
Rui Ueyamaafff74e22015-08-05 23:24:46 +000067
Rafael Espindola443f50a2015-11-03 21:35:14 +000068 OutputSection<ELFT> *getBSS();
69 void addCommonSymbols(std::vector<DefinedCommon<ELFT> *> &Syms);
70 void addSharedCopySymbols(std::vector<SharedSymbol<ELFT> *> &Syms);
71
Rui Ueyamaafff74e22015-08-05 23:24:46 +000072 std::unique_ptr<llvm::FileOutputBuffer> Buffer;
Michael J. Spencer2f008242015-09-17 19:58:07 +000073
Rafael Espindola37f0b7d2015-10-15 12:33:04 +000074 SpecificBumpPtrAllocator<OutputSection<ELFT>> SecAlloc;
Rafael Espindolac159c962015-10-19 21:00:02 +000075 SpecificBumpPtrAllocator<MergeOutputSection<ELFT>> MSecAlloc;
Rafael Espindola0c6a4f12015-11-11 19:54:14 +000076 SpecificBumpPtrAllocator<EHOutputSection<ELFT>> EHSecAlloc;
Rui Ueyamad9189ce2015-10-15 17:11:03 +000077 BumpPtrAllocator Alloc;
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +000078 std::vector<OutputSectionBase<ELFT> *> OutputSections;
Rafael Espindola5f553872015-09-08 17:39:39 +000079 unsigned getNumSections() const { return OutputSections.size() + 1; }
Rui Ueyamaafff74e22015-08-05 23:24:46 +000080
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +000081 void addStartStopSymbols(OutputSectionBase<ELFT> *Sec);
Rui Ueyama536c9992015-10-11 19:45:58 +000082 void setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags, uintX_t FileOff,
Rui Ueyama803195e2015-10-23 21:45:59 +000083 uintX_t VA, uintX_t Size, uintX_t Align);
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +000084 void copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +000085
George Rimare3336c02015-11-24 10:15:50 +000086 bool HasRelro = false;
Rui Ueyama3ce825e2015-10-09 21:07:25 +000087 SymbolTable<ELFT> &Symtab;
Rui Ueyama953c2c42015-10-10 23:59:57 +000088 std::vector<Elf_Phdr> Phdrs;
Michael J. Spencer2f008242015-09-17 19:58:07 +000089
Rafael Espindola98f6bd02015-08-11 23:14:13 +000090 uintX_t FileSize;
Rui Ueyamaafff74e22015-08-05 23:24:46 +000091 uintX_t SectionHeaderOff;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +000092
93 llvm::StringMap<llvm::StringRef> InputToOutputSection;
Rui Ueyamaafff74e22015-08-05 23:24:46 +000094};
95} // anonymous namespace
96
Rui Ueyama3ce825e2015-10-09 21:07:25 +000097template <class ELFT> void lld::elf2::writeResult(SymbolTable<ELFT> *Symtab) {
Rui Ueyama15ef5e12015-10-07 19:18:16 +000098 // Initialize output sections that are handled by Writer specially.
99 // Don't reorder because the order of initialization matters.
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000100 InterpSection<ELFT> Interp;
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000101 Out<ELFT>::Interp = &Interp;
George Rimar0f5ac9f2015-10-20 17:21:35 +0000102 StringTableSection<ELFT> ShStrTab(".shstrtab", false);
103 Out<ELFT>::ShStrTab = &ShStrTab;
104 StringTableSection<ELFT> StrTab(".strtab", false);
George Rimar5dad7c12015-10-24 08:52:46 +0000105 if (!Config->StripAll)
106 Out<ELFT>::StrTab = &StrTab;
George Rimar0f5ac9f2015-10-20 17:21:35 +0000107 StringTableSection<ELFT> DynStrTab(".dynstr", true);
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000108 Out<ELFT>::DynStrTab = &DynStrTab;
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000109 GotSection<ELFT> Got;
110 Out<ELFT>::Got = &Got;
George Rimar648a2c32015-10-20 08:54:27 +0000111 GotPltSection<ELFT> GotPlt;
112 if (Target->supportsLazyRelocations())
113 Out<ELFT>::GotPlt = &GotPlt;
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000114 PltSection<ELFT> Plt;
115 Out<ELFT>::Plt = &Plt;
George Rimar5dad7c12015-10-24 08:52:46 +0000116 std::unique_ptr<SymbolTableSection<ELFT>> SymTab;
117 if (!Config->StripAll) {
118 SymTab.reset(new SymbolTableSection<ELFT>(*Symtab, *Out<ELFT>::StrTab));
119 Out<ELFT>::SymTab = SymTab.get();
120 }
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000121 SymbolTableSection<ELFT> DynSymTab(*Symtab, *Out<ELFT>::DynStrTab);
122 Out<ELFT>::DynSymTab = &DynSymTab;
123 HashTableSection<ELFT> HashTab;
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000124 if (Config->SysvHash)
125 Out<ELFT>::HashTab = &HashTab;
126 GnuHashTableSection<ELFT> GnuHashTab;
127 if (Config->GnuHash)
128 Out<ELFT>::GnuHashTab = &GnuHashTab;
George Rimar648a2c32015-10-20 08:54:27 +0000129 bool IsRela = Symtab->shouldUseRela();
130 RelocationSection<ELFT> RelaDyn(IsRela ? ".rela.dyn" : ".rel.dyn", IsRela);
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000131 Out<ELFT>::RelaDyn = &RelaDyn;
George Rimar648a2c32015-10-20 08:54:27 +0000132 RelocationSection<ELFT> RelaPlt(IsRela ? ".rela.plt" : ".rel.plt", IsRela);
133 if (Target->supportsLazyRelocations())
134 Out<ELFT>::RelaPlt = &RelaPlt;
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000135 DynamicSection<ELFT> Dynamic(*Symtab);
136 Out<ELFT>::Dynamic = &Dynamic;
137
Rui Ueyama0d0bcf72015-10-07 21:25:39 +0000138 Writer<ELFT>(*Symtab).run();
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000139}
140
Michael J. Spencer84487f12015-07-24 21:03:07 +0000141// The main function of the writer.
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000142template <class ELFT> void Writer<ELFT>::run() {
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000143 buildSectionMap();
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000144 if (!Config->DiscardAll)
145 copyLocalSymbols();
Michael J. Spencer84487f12015-07-24 21:03:07 +0000146 createSections();
147 assignAddresses();
Rui Ueyamacb8474ed2015-08-05 23:51:50 +0000148 openFile(Config->OutputFile);
Michael J. Spencer84487f12015-07-24 21:03:07 +0000149 writeHeader();
150 writeSections();
151 error(Buffer->commit());
152}
153
Rafael Espindolaa7471792015-08-13 17:04:50 +0000154namespace {
155template <bool Is64Bits> struct SectionKey {
156 typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
157 StringRef Name;
Rui Ueyama0fb1ee02015-10-02 21:13:19 +0000158 uint32_t Type;
159 uintX_t Flags;
Rafael Espindolac159c962015-10-19 21:00:02 +0000160 uintX_t EntSize;
Rafael Espindolaa7471792015-08-13 17:04:50 +0000161};
162}
163namespace llvm {
164template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
165 static SectionKey<Is64Bits> getEmptyKey() {
Rafael Espindolac159c962015-10-19 21:00:02 +0000166 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0,
167 0};
Rafael Espindolaa7471792015-08-13 17:04:50 +0000168 }
169 static SectionKey<Is64Bits> getTombstoneKey() {
170 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
Rafael Espindolac159c962015-10-19 21:00:02 +0000171 0, 0};
Rafael Espindolaa7471792015-08-13 17:04:50 +0000172 }
173 static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
Rafael Espindolac159c962015-10-19 21:00:02 +0000174 return hash_combine(Val.Name, Val.Type, Val.Flags, Val.EntSize);
Rafael Espindolaa7471792015-08-13 17:04:50 +0000175 }
176 static bool isEqual(const SectionKey<Is64Bits> &LHS,
177 const SectionKey<Is64Bits> &RHS) {
178 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
Rafael Espindolac159c962015-10-19 21:00:02 +0000179 LHS.Type == RHS.Type && LHS.Flags == RHS.Flags &&
180 LHS.EntSize == RHS.EntSize;
Rafael Espindolaa7471792015-08-13 17:04:50 +0000181 }
182};
183}
184
Rafael Espindola19e38892015-09-16 15:54:15 +0000185// The reason we have to do this early scan is as follows
186// * To mmap the output file, we need to know the size
187// * For that, we need to know how many dynamic relocs we will have.
188// It might be possible to avoid this by outputting the file with write:
189// * Write the allocated output sections, computing addresses.
190// * Apply relocations, recording which ones require a dynamic reloc.
191// * Write the dynamic relocations.
192// * Write the rest of the file.
193template <class ELFT>
Rafael Espindola67a5da62015-09-17 14:02:10 +0000194template <bool isRela>
195void Writer<ELFT>::scanRelocs(
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000196 InputSectionBase<ELFT> &C,
Rafael Espindola67a5da62015-09-17 14:02:10 +0000197 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) {
198 typedef Elf_Rel_Impl<ELFT, isRela> RelType;
199 const ObjectFile<ELFT> &File = *C.getFile();
Rafael Espindola67a5da62015-09-17 14:02:10 +0000200 for (const RelType &RI : Rels) {
Rui Ueyama64558522015-10-16 22:51:43 +0000201 uint32_t SymIndex = RI.getSymbol(Config->Mips64EL);
Rafael Espindola5c2310c2015-09-18 14:40:19 +0000202 SymbolBody *Body = File.getSymbolBody(SymIndex);
Rui Ueyama64558522015-10-16 22:51:43 +0000203 uint32_t Type = RI.getType(Config->Mips64EL);
Rui Ueyama35da9b62015-10-11 20:59:12 +0000204
Michael J. Spencerecd7f372015-11-13 00:32:58 +0000205 if (Target->isTlsLocalDynamicReloc(Type)) {
George Rimar6713cf82015-11-25 21:46:05 +0000206 if (Target->isTlsOptimized(Type, nullptr))
207 continue;
Michael J. Spencer1e225612015-11-11 01:00:24 +0000208 if (Out<ELFT>::LocalModuleTlsIndexOffset == uint32_t(-1)) {
209 Out<ELFT>::LocalModuleTlsIndexOffset =
210 Out<ELFT>::Got->addLocalModuleTlsIndex();
Michael J. Spencer627ae702015-11-13 00:28:34 +0000211 Out<ELFT>::RelaDyn->addReloc({&C, &RI});
Michael J. Spencer1e225612015-11-11 01:00:24 +0000212 }
213 continue;
214 }
215
Rui Ueyama35da9b62015-10-11 20:59:12 +0000216 // Set "used" bit for --as-needed.
217 if (Body && Body->isUndefined() && !Body->isWeak())
218 if (auto *S = dyn_cast<SharedSymbol<ELFT>>(Body->repl()))
219 S->File->IsUsed = true;
220
221 if (Body)
222 Body = Body->repl();
Michael J. Spencer627ae702015-11-13 00:28:34 +0000223
George Rimar687138c2015-11-13 16:28:53 +0000224 if (Body && Body->isTLS() && Target->isTlsGlobalDynamicReloc(Type)) {
George Rimar6713cf82015-11-25 21:46:05 +0000225 if (Target->isTlsOptimized(Type, Body))
226 continue;
Michael J. Spencer627ae702015-11-13 00:28:34 +0000227 if (Body->isInGot())
228 continue;
George Rimar687138c2015-11-13 16:28:53 +0000229 Out<ELFT>::Got->addDynTlsEntry(Body);
Michael J. Spencer627ae702015-11-13 00:28:34 +0000230 Out<ELFT>::RelaDyn->addReloc({&C, &RI});
231 Out<ELFT>::RelaDyn->addReloc({nullptr, nullptr});
232 Body->setUsedInDynamicReloc();
233 continue;
234 }
235
George Rimard23970f2015-11-25 20:41:53 +0000236 if ((Body && Body->isTLS()) && !Target->isTlsDynReloc(Type))
George Rimar687138c2015-11-13 16:28:53 +0000237 continue;
238
Rafael Espindolacc6ebb82015-10-14 18:42:16 +0000239 bool NeedsGot = false;
George Rimar648a2c32015-10-20 08:54:27 +0000240 bool NeedsPlt = false;
Rafael Espindolaae244002015-10-05 19:30:12 +0000241 if (Body) {
George Rimarbc590fe2015-10-28 16:48:58 +0000242 if (auto *E = dyn_cast<SharedSymbol<ELFT>>(Body)) {
Rafael Espindola9b896082015-11-03 14:34:11 +0000243 if (E->needsCopy())
George Rimarbc590fe2015-10-28 16:48:58 +0000244 continue;
Rafael Espindola9b896082015-11-03 14:34:11 +0000245 if (Target->relocNeedsCopy(Type, *Body))
246 E->OffsetInBSS = 0;
George Rimarbc590fe2015-10-28 16:48:58 +0000247 }
George Rimar648a2c32015-10-20 08:54:27 +0000248 NeedsPlt = Target->relocNeedsPlt(Type, *Body);
249 if (NeedsPlt) {
Rafael Espindolaae244002015-10-05 19:30:12 +0000250 if (Body->isInPlt())
251 continue;
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000252 Out<ELFT>::Plt->addEntry(Body);
Rui Ueyamac58656c2015-10-13 16:59:30 +0000253 }
Rafael Espindolacc6ebb82015-10-14 18:42:16 +0000254 NeedsGot = Target->relocNeedsGot(Type, *Body);
255 if (NeedsGot) {
George Rimar648a2c32015-10-20 08:54:27 +0000256 if (NeedsPlt && Target->supportsLazyRelocations()) {
257 Out<ELFT>::GotPlt->addEntry(Body);
258 } else {
259 if (Body->isInGot())
260 continue;
261 Out<ELFT>::Got->addEntry(Body);
262 }
Rafael Espindolaae244002015-10-05 19:30:12 +0000263 }
Rafael Espindolaeb792732015-09-21 15:11:29 +0000264 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000265
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000266 if (Config->EMachine == EM_MIPS && NeedsGot) {
267 // MIPS ABI has special rules to process GOT entries
268 // and doesn't require relocation entries for them.
269 // See "Global Offset Table" in Chapter 5 in the following document
270 // for detailed description:
271 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
272 Body->setUsedInDynamicReloc();
273 continue;
274 }
Rafael Espindolacc6ebb82015-10-14 18:42:16 +0000275 bool CBP = canBePreempted(Body, NeedsGot);
Rui Ueyama35da9b62015-10-11 20:59:12 +0000276 if (!CBP && (!Config->Shared || Target->isRelRelative(Type)))
277 continue;
278 if (CBP)
Rafael Espindolaa6627382015-10-06 23:56:53 +0000279 Body->setUsedInDynamicReloc();
George Rimar648a2c32015-10-20 08:54:27 +0000280 if (NeedsPlt && Target->supportsLazyRelocations())
Michael J. Spencer627ae702015-11-13 00:28:34 +0000281 Out<ELFT>::RelaPlt->addReloc({&C, &RI});
George Rimar648a2c32015-10-20 08:54:27 +0000282 else
Michael J. Spencer627ae702015-11-13 00:28:34 +0000283 Out<ELFT>::RelaDyn->addReloc({&C, &RI});
Rafael Espindola67a5da62015-09-17 14:02:10 +0000284 }
285}
286
Rafael Espindolaa0fa8482015-11-11 15:29:50 +0000287template <class ELFT> void Writer<ELFT>::scanRelocs(InputSection<ELFT> &C) {
Rafael Espindola19e38892015-09-16 15:54:15 +0000288 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
289 return;
290
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000291 for (const Elf_Shdr *RelSec : C.RelocSections)
292 scanRelocs(C, *RelSec);
293}
294
295template <class ELFT>
296void Writer<ELFT>::scanRelocs(InputSectionBase<ELFT> &S,
297 const Elf_Shdr &RelSec) {
298 ELFFile<ELFT> &EObj = S.getFile()->getObj();
299 if (RelSec.sh_type == SHT_RELA)
300 scanRelocs(S, EObj.relas(&RelSec));
301 else
302 scanRelocs(S, EObj.rels(&RelSec));
Rafael Espindola19e38892015-09-16 15:54:15 +0000303}
304
Rafael Espindola6173f842015-09-23 14:37:01 +0000305template <class ELFT>
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000306static void reportUndefined(const SymbolTable<ELFT> &S, const SymbolBody &Sym) {
Rafael Espindola6173f842015-09-23 14:37:01 +0000307 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
308 typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
309
George Rimar57e40de2015-10-01 20:14:45 +0000310 if (Config->Shared && !Config->NoUndefined)
George Rimaree058282015-10-01 17:24:24 +0000311 return;
312
Rafael Espindola6173f842015-09-23 14:37:01 +0000313 const Elf_Sym &SymE = cast<ELFSymbolBody<ELFT>>(Sym).Sym;
Rafael Espindolaaf707642015-10-12 01:55:32 +0000314 ELFFileBase<ELFT> *SymFile = nullptr;
Rafael Espindola6173f842015-09-23 14:37:01 +0000315
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000316 for (const std::unique_ptr<ObjectFile<ELFT>> &File : S.getObjectFiles()) {
317 Elf_Sym_Range Syms = File->getObj().symbols(File->getSymbolTable());
Rafael Espindola6173f842015-09-23 14:37:01 +0000318 if (&SymE > Syms.begin() && &SymE < Syms.end())
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000319 SymFile = File.get();
Rafael Espindola6173f842015-09-23 14:37:01 +0000320 }
Rafael Espindola551dfd82015-09-25 19:24:57 +0000321
322 std::string Message = "undefined symbol: " + Sym.getName().str();
Rafael Espindola6173f842015-09-23 14:37:01 +0000323 if (SymFile)
Rafael Espindola551dfd82015-09-25 19:24:57 +0000324 Message += " in " + SymFile->getName().str();
325 if (Config->NoInhibitExec)
326 warning(Message);
Rafael Espindola6173f842015-09-23 14:37:01 +0000327 else
Rafael Espindola551dfd82015-09-25 19:24:57 +0000328 error(Message);
Rafael Espindola6173f842015-09-23 14:37:01 +0000329}
330
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000331// Local symbols are not in the linker's symbol table. This function scans
332// each object file's symbol table to copy local symbols to the output.
333template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000334 for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
335 for (const Elf_Sym &Sym : F->getLocalSymbols()) {
336 ErrorOr<StringRef> SymNameOrErr = Sym.getName(F->getStringTable());
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000337 error(SymNameOrErr);
338 StringRef SymName = *SymNameOrErr;
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000339 if (!shouldKeepInSymtab<ELFT>(*F, SymName, Sym))
Rafael Espindola444576d2015-10-09 19:25:07 +0000340 continue;
George Rimar5dad7c12015-10-24 08:52:46 +0000341 if (Out<ELFT>::SymTab)
342 Out<ELFT>::SymTab->addLocalSymbol(SymName);
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000343 }
344 }
345}
346
Hal Finkel3bae2d82015-10-12 20:51:48 +0000347// PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
348// we would like to make sure appear is a specific order to maximize their
349// coverage by a single signed 16-bit offset from the TOC base pointer.
350// Conversely, the special .tocbss section should be first among all SHT_NOBITS
351// sections. This will put it next to the loaded special PPC64 sections (and,
352// thus, within reach of the TOC base pointer).
353static int getPPC64SectionRank(StringRef SectionName) {
354 return StringSwitch<int>(SectionName)
355 .Case(".tocbss", 0)
356 .Case(".branch_lt", 2)
357 .Case(".toc", 3)
358 .Case(".toc1", 4)
359 .Case(".opd", 5)
360 .Default(1);
361}
362
George Rimare3336c02015-11-24 10:15:50 +0000363template <class ELFT> static bool isRelroSection(OutputSectionBase<ELFT> *Sec) {
364 typename OutputSectionBase<ELFT>::uintX_t Flags = Sec->getFlags();
365 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
366 return false;
367 uint32_t Type = Sec->getType();
368 if ((Flags & SHF_TLS) || (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
369 Type == SHT_PREINIT_ARRAY))
370 return true;
371 if (Sec == Out<ELFT>::GotPlt)
372 return Config->ZNow;
373 if (Sec == Out<ELFT>::Dynamic || Sec == Out<ELFT>::Got)
374 return true;
375
376 StringRef Name = Sec->getName();
377 StringRef WhiteList[] = {".data.rel.ro", ".ctors", ".dtors", ".jcr",
378 ".eh_frame"};
379 return (std::find(std::begin(WhiteList), std::end(WhiteList), Name) !=
380 std::end(WhiteList));
381}
382
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000383// Output section ordering is determined by this function.
384template <class ELFT>
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000385static bool compareOutputSections(OutputSectionBase<ELFT> *A,
386 OutputSectionBase<ELFT> *B) {
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000387 typedef typename ELFFile<ELFT>::uintX_t uintX_t;
388
389 uintX_t AFlags = A->getFlags();
390 uintX_t BFlags = B->getFlags();
391
392 // Allocatable sections go first to reduce the total PT_LOAD size and
393 // so debug info doesn't change addresses in actual code.
394 bool AIsAlloc = AFlags & SHF_ALLOC;
395 bool BIsAlloc = BFlags & SHF_ALLOC;
396 if (AIsAlloc != BIsAlloc)
397 return AIsAlloc;
398
399 // We don't have any special requirements for the relative order of
400 // two non allocatable sections.
401 if (!AIsAlloc)
402 return false;
403
404 // We want the read only sections first so that they go in the PT_LOAD
405 // covering the program headers at the start of the file.
406 bool AIsWritable = AFlags & SHF_WRITE;
407 bool BIsWritable = BFlags & SHF_WRITE;
408 if (AIsWritable != BIsWritable)
409 return BIsWritable;
410
411 // For a corresponding reason, put non exec sections first (the program
412 // header PT_LOAD is not executable).
413 bool AIsExec = AFlags & SHF_EXECINSTR;
414 bool BIsExec = BFlags & SHF_EXECINSTR;
415 if (AIsExec != BIsExec)
416 return BIsExec;
417
Hal Finkel0d7e83b2015-10-13 17:57:46 +0000418 // 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 +0000419
420 // The TLS initialization block needs to be a single contiguous block in a R/W
421 // PT_LOAD, so stick TLS sections directly before R/W sections. The TLS NOBITS
422 // sections are placed here as they don't take up virtual address space in the
423 // PT_LOAD.
424 bool AIsTLS = AFlags & SHF_TLS;
425 bool BIsTLS = BFlags & SHF_TLS;
426 if (AIsTLS != BIsTLS)
427 return AIsTLS;
428
Hal Finkel08be6142015-10-13 18:55:01 +0000429 // The next requirement we have is to put nobits sections last. The
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000430 // reason is that the only thing the dynamic linker will see about
431 // them is a p_memsz that is larger than p_filesz. Seeing that it
432 // zeros the end of the PT_LOAD, so that has to correspond to the
433 // nobits sections.
Hal Finkel600ff142015-10-13 19:27:12 +0000434 bool AIsNoBits = A->getType() == SHT_NOBITS;
435 bool BIsNoBits = B->getType() == SHT_NOBITS;
436 if (AIsNoBits != BIsNoBits)
437 return BIsNoBits;
Hal Finkel3bae2d82015-10-12 20:51:48 +0000438
George Rimare3336c02015-11-24 10:15:50 +0000439 // We place RelRo section before plain r/w ones.
440 bool AIsRelRo = isRelroSection(A);
441 bool BIsRelRo = isRelroSection(B);
442 if (AIsRelRo != BIsRelRo)
443 return AIsRelRo;
444
Hal Finkel9abc2a52015-10-13 19:07:29 +0000445 // Some architectures have additional ordering restrictions for sections
446 // within the same PT_LOAD.
447 if (Config->EMachine == EM_PPC64)
448 return getPPC64SectionRank(A->getName()) <
449 getPPC64SectionRank(B->getName());
450
451 return false;
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000452}
453
Rafael Espindola443f50a2015-11-03 21:35:14 +0000454template <class ELFT> OutputSection<ELFT> *Writer<ELFT>::getBSS() {
455 if (!Out<ELFT>::Bss) {
456 Out<ELFT>::Bss = new (SecAlloc.Allocate())
457 OutputSection<ELFT>(".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE);
458 OutputSections.push_back(Out<ELFT>::Bss);
459 }
460 return Out<ELFT>::Bss;
461}
462
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000463// Until this function is called, common symbols do not belong to any section.
464// This function adds them to end of BSS section.
465template <class ELFT>
Rafael Espindola443f50a2015-11-03 21:35:14 +0000466void Writer<ELFT>::addCommonSymbols(std::vector<DefinedCommon<ELFT> *> &Syms) {
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000467 typedef typename ELFFile<ELFT>::uintX_t uintX_t;
468 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
469
Rafael Espindola443f50a2015-11-03 21:35:14 +0000470 if (Syms.empty())
471 return;
472
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000473 // Sort the common symbols by alignment as an heuristic to pack them better.
474 std::stable_sort(
475 Syms.begin(), Syms.end(),
476 [](const DefinedCommon<ELFT> *A, const DefinedCommon<ELFT> *B) {
477 return A->MaxAlignment > B->MaxAlignment;
478 });
479
Rafael Espindola443f50a2015-11-03 21:35:14 +0000480 uintX_t Off = getBSS()->getSize();
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000481 for (DefinedCommon<ELFT> *C : Syms) {
482 const Elf_Sym &Sym = C->Sym;
483 uintX_t Align = C->MaxAlignment;
484 Off = RoundUpToAlignment(Off, Align);
485 C->OffsetInBSS = Off;
486 Off += Sym.st_size;
487 }
488
489 Out<ELFT>::Bss->setSize(Off);
490}
491
George Rimarbc590fe2015-10-28 16:48:58 +0000492template <class ELFT>
Rafael Espindola443f50a2015-11-03 21:35:14 +0000493void Writer<ELFT>::addSharedCopySymbols(
494 std::vector<SharedSymbol<ELFT> *> &Syms) {
George Rimarbc590fe2015-10-28 16:48:58 +0000495 typedef typename ELFFile<ELFT>::uintX_t uintX_t;
496 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
Rafael Espindola115f0f32015-11-03 14:13:40 +0000497 typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
George Rimarbc590fe2015-10-28 16:48:58 +0000498
Rafael Espindola443f50a2015-11-03 21:35:14 +0000499 if (Syms.empty())
500 return;
501
502 uintX_t Off = getBSS()->getSize();
George Rimarbc590fe2015-10-28 16:48:58 +0000503 for (SharedSymbol<ELFT> *C : Syms) {
504 const Elf_Sym &Sym = C->Sym;
Rafael Espindola115f0f32015-11-03 14:13:40 +0000505 const Elf_Shdr *Sec = C->File->getSection(Sym);
506 uintX_t SecAlign = Sec->sh_addralign;
507 uintX_t Align = Sym.st_value % SecAlign;
508 if (Align == 0)
509 Align = SecAlign;
510 Out<ELFT>::Bss->updateAlign(Align);
511 Off = RoundUpToAlignment(Off, Align);
George Rimarbc590fe2015-10-28 16:48:58 +0000512 C->OffsetInBSS = Off;
513 Off += Sym.st_size;
514 }
515 Out<ELFT>::Bss->setSize(Off);
516}
517
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000518template <class ELFT>
519StringRef Writer<ELFT>::getOutputSectionName(StringRef S) const {
520 auto It = InputToOutputSection.find(S);
521 if (It != std::end(InputToOutputSection))
522 return It->second;
523
Rui Ueyama4fcadaf2015-10-14 19:21:25 +0000524 if (S.startswith(".text."))
525 return ".text";
526 if (S.startswith(".rodata."))
527 return ".rodata";
George Rimar51e37d92015-11-13 07:56:27 +0000528 if (S.startswith(".data.rel.ro"))
529 return ".data.rel.ro";
Rui Ueyama4fcadaf2015-10-14 19:21:25 +0000530 if (S.startswith(".data."))
531 return ".data";
532 if (S.startswith(".bss."))
533 return ".bss";
534 return S;
535}
536
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000537template <class ELFT>
538bool Writer<ELFT>::isDiscarded(InputSectionBase<ELFT> *IS) const {
539 if (!IS || !IS->isLive() || IS == &InputSection<ELFT>::Discarded)
540 return true;
541 return InputToOutputSection.lookup(IS->getSectionName()) == "/DISCARD/";
542}
543
544template <class ELFT>
545static bool compareSections(OutputSectionBase<ELFT> *A,
546 OutputSectionBase<ELFT> *B) {
547 auto ItA = Config->OutputSections.find(A->getName());
548 auto ItEnd = std::end(Config->OutputSections);
549 if (ItA == ItEnd)
550 return compareOutputSections(A, B);
551 auto ItB = Config->OutputSections.find(B->getName());
552 if (ItB == ItEnd)
553 return compareOutputSections(A, B);
554
555 return std::distance(ItA, ItB) > 0;
556}
557
Michael J. Spencer84487f12015-07-24 21:03:07 +0000558// Create output section objects and add them to OutputSections.
559template <class ELFT> void Writer<ELFT>::createSections() {
Rui Ueyama69960ba2015-10-10 23:25:39 +0000560 // .interp needs to be on the first page in the output file.
561 if (needsInterpSection())
562 OutputSections.push_back(Out<ELFT>::Interp);
563
Rafael Espindolac159c962015-10-19 21:00:02 +0000564 SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSectionBase<ELFT> *> Map;
Rafael Espindolac2d21192015-09-23 18:25:05 +0000565
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000566 std::vector<OutputSectionBase<ELFT> *> RegularSections;
Rui Ueyamad9189ce2015-10-15 17:11:03 +0000567
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000568 for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
Rafael Espindolac159c962015-10-19 21:00:02 +0000569 for (InputSectionBase<ELFT> *C : F->getSections()) {
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000570 if (isDiscarded(C))
Rafael Espindola19e38892015-09-16 15:54:15 +0000571 continue;
572 const Elf_Shdr *H = C->getSectionHdr();
Rafael Espindola444576d2015-10-09 19:25:07 +0000573 uintX_t OutFlags = H->sh_flags & ~SHF_GROUP;
Rafael Espindolac159c962015-10-19 21:00:02 +0000574 // For SHF_MERGE we create different output sections for each sh_entsize.
575 // This makes each output section simple and keeps a single level
576 // mapping from input to output.
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000577 typename InputSectionBase<ELFT>::Kind K = C->SectionKind;
578 uintX_t EntSize = K != InputSectionBase<ELFT>::Merge ? 0 : H->sh_entsize;
Rafael Espindolaa016b1e2015-11-11 17:33:22 +0000579 uint32_t OutType = H->sh_type;
580 if (OutType == SHT_PROGBITS && C->getSectionName() == ".eh_frame" &&
581 Config->EMachine == EM_X86_64)
582 OutType = SHT_X86_64_UNWIND;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000583 SectionKey<ELFT::Is64Bits> Key{getOutputSectionName(C->getSectionName()),
Rafael Espindolaa016b1e2015-11-11 17:33:22 +0000584 OutType, OutFlags, EntSize};
Rafael Espindolac159c962015-10-19 21:00:02 +0000585 OutputSectionBase<ELFT> *&Sec = Map[Key];
Rafael Espindolad13d9602015-09-25 15:08:44 +0000586 if (!Sec) {
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000587 switch (K) {
588 case InputSectionBase<ELFT>::Regular:
Rafael Espindolac159c962015-10-19 21:00:02 +0000589 Sec = new (SecAlloc.Allocate())
590 OutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000591 break;
592 case InputSectionBase<ELFT>::EHFrame:
593 Sec = new (EHSecAlloc.Allocate())
594 EHOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
595 break;
596 case InputSectionBase<ELFT>::Merge:
Rafael Espindolac159c962015-10-19 21:00:02 +0000597 Sec = new (MSecAlloc.Allocate())
598 MergeOutputSection<ELFT>(Key.Name, Key.Type, Key.Flags);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000599 break;
600 }
Rafael Espindolad13d9602015-09-25 15:08:44 +0000601 OutputSections.push_back(Sec);
Rui Ueyamad9189ce2015-10-15 17:11:03 +0000602 RegularSections.push_back(Sec);
Rafael Espindolad13d9602015-09-25 15:08:44 +0000603 }
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000604 switch (K) {
605 case InputSectionBase<ELFT>::Regular:
606 static_cast<OutputSection<ELFT> *>(Sec)
607 ->addSection(cast<InputSection<ELFT>>(C));
608 break;
609 case InputSectionBase<ELFT>::EHFrame:
610 static_cast<EHOutputSection<ELFT> *>(Sec)
611 ->addSection(cast<EHInputSection<ELFT>>(C));
612 break;
613 case InputSectionBase<ELFT>::Merge:
Rafael Espindolac159c962015-10-19 21:00:02 +0000614 static_cast<MergeOutputSection<ELFT> *>(Sec)
615 ->addSection(cast<MergeInputSection<ELFT>>(C));
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000616 break;
617 }
Rafael Espindola19e38892015-09-16 15:54:15 +0000618 }
619 }
620
Rafael Espindola443f50a2015-11-03 21:35:14 +0000621 Out<ELFT>::Bss = static_cast<OutputSection<ELFT> *>(
622 Map[{".bss", SHT_NOBITS, SHF_ALLOC | SHF_WRITE, 0}]);
623
Rafael Espindolac159c962015-10-19 21:00:02 +0000624 Out<ELFT>::Dynamic->PreInitArraySec = Map.lookup(
625 {".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0});
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000626 Out<ELFT>::Dynamic->InitArraySec =
Rafael Espindolac159c962015-10-19 21:00:02 +0000627 Map.lookup({".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC, 0});
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000628 Out<ELFT>::Dynamic->FiniArraySec =
Rafael Espindolac159c962015-10-19 21:00:02 +0000629 Map.lookup({".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC, 0});
Rafael Espindola77572242015-10-02 19:37:55 +0000630
Rui Ueyama0d0bcf72015-10-07 21:25:39 +0000631 auto AddStartEnd = [&](StringRef Start, StringRef End,
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000632 OutputSectionBase<ELFT> *OS) {
Michael J. Spencer95538ca2015-10-06 01:16:17 +0000633 if (OS) {
Rui Ueyama3ce825e2015-10-09 21:07:25 +0000634 Symtab.addSyntheticSym(Start, *OS, 0);
635 Symtab.addSyntheticSym(End, *OS, OS->getSize());
Rafael Espindola334c3e12015-10-19 15:21:42 +0000636 } else {
637 Symtab.addIgnoredSym(Start);
638 Symtab.addIgnoredSym(End);
Michael J. Spencer95538ca2015-10-06 01:16:17 +0000639 }
640 };
641
Michael J. Spencerfcacad22015-10-06 19:57:05 +0000642 AddStartEnd("__preinit_array_start", "__preinit_array_end",
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000643 Out<ELFT>::Dynamic->PreInitArraySec);
Michael J. Spencerfcacad22015-10-06 19:57:05 +0000644 AddStartEnd("__init_array_start", "__init_array_end",
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000645 Out<ELFT>::Dynamic->InitArraySec);
Michael J. Spencerfcacad22015-10-06 19:57:05 +0000646 AddStartEnd("__fini_array_start", "__fini_array_end",
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000647 Out<ELFT>::Dynamic->FiniArraySec);
Rafael Espindola0e604f92015-09-25 18:56:53 +0000648
Rafael Espindola334c3e12015-10-19 15:21:42 +0000649 for (OutputSectionBase<ELFT> *Sec : RegularSections)
650 addStartStopSymbols(Sec);
651
652 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
653 // static linking the linker is required to optimize away any references to
654 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
655 // to avoid the undefined symbol error.
656 if (!isOutputDynamic())
657 Symtab.addIgnoredSym("__tls_get_addr");
658
Igor Kudrinb044af52015-11-20 02:32:35 +0000659 // If the "_end" symbol is referenced, it is expected to point to the address
660 // right after the data segment. Usually, this symbol points to the end
661 // of .bss section or to the end of .data section if .bss section is absent.
662 // The order of the sections can be affected by linker script,
663 // so it is hard to predict which section will be the last one.
664 // So, if this symbol is referenced, we just add the placeholder here
665 // and update its value later.
666 if (Symtab.find("_end"))
667 Symtab.addAbsoluteSym("_end", DefinedAbsolute<ELFT>::End);
668
669 // If there is an undefined symbol "end", we should initialize it
670 // with the same value as "_end". In any other case it should stay intact,
671 // because it is an allowable name for a user symbol.
672 if (SymbolBody *B = Symtab.find("end"))
673 if (B->isUndefined())
674 Symtab.addAbsoluteSym("end", DefinedAbsolute<ELFT>::End);
675
Rafael Espindola334c3e12015-10-19 15:21:42 +0000676 // Scan relocations. This must be done after every symbol is declared so that
677 // we can correctly decide if a dynamic relocation is needed.
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000678 for (const std::unique_ptr<ObjectFile<ELFT>> &F : Symtab.getObjectFiles()) {
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000679 for (InputSectionBase<ELFT> *C : F->getSections()) {
680 if (isDiscarded(C))
681 continue;
682 if (auto *S = dyn_cast<InputSection<ELFT>>(C))
683 scanRelocs(*S);
684 else if (auto *S = dyn_cast<EHInputSection<ELFT>>(C))
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000685 if (S->RelocSection)
686 scanRelocs(*S, *S->RelocSection);
Rafael Espindola0c6a4f12015-11-11 19:54:14 +0000687 }
688 }
Rafael Espindola334c3e12015-10-19 15:21:42 +0000689
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000690 std::vector<DefinedCommon<ELFT> *> CommonSymbols;
George Rimarbc590fe2015-10-28 16:48:58 +0000691 std::vector<SharedSymbol<ELFT> *> SharedCopySymbols;
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000692 for (auto &P : Symtab.getSymbols()) {
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000693 SymbolBody *Body = P.second->Body;
Rui Ueyama96b19042015-10-15 20:55:20 +0000694 if (auto *U = dyn_cast<Undefined<ELFT>>(Body))
Denis Protivensky22220d52015-10-05 09:43:57 +0000695 if (!U->isWeak() && !U->canKeepUndefined())
696 reportUndefined<ELFT>(Symtab, *Body);
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000697
698 if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body))
699 CommonSymbols.push_back(C);
George Rimarbc590fe2015-10-28 16:48:58 +0000700 if (auto *SC = dyn_cast<SharedSymbol<ELFT>>(Body))
Rafael Espindola9b896082015-11-03 14:34:11 +0000701 if (SC->needsCopy())
George Rimarbc590fe2015-10-28 16:48:58 +0000702 SharedCopySymbols.push_back(SC);
703
Rafael Espindola4f674ed2015-10-05 15:24:04 +0000704 if (!includeInSymtab<ELFT>(*Body))
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000705 continue;
George Rimar5dad7c12015-10-24 08:52:46 +0000706 if (Out<ELFT>::SymTab)
707 Out<ELFT>::SymTab->addSymbol(Body);
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000708
Michael J. Spencer350e5b52015-10-12 23:39:23 +0000709 if (isOutputDynamic() && includeInDynamicSymtab(*Body))
Igor Kudrinab665fc2015-10-20 21:47:58 +0000710 Out<ELFT>::DynSymTab->addSymbol(Body);
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000711 }
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000712 addCommonSymbols(CommonSymbols);
George Rimarbc590fe2015-10-28 16:48:58 +0000713 addSharedCopySymbols(SharedCopySymbols);
Michael J. Spencer84487f12015-07-24 21:03:07 +0000714
Rui Ueyamac6ef3f22015-10-15 21:50:30 +0000715 // This order is not the same as the final output order
716 // because we sort the sections using their attributes below.
George Rimar5dad7c12015-10-24 08:52:46 +0000717 if (Out<ELFT>::SymTab)
718 OutputSections.push_back(Out<ELFT>::SymTab);
George Rimar0f5ac9f2015-10-20 17:21:35 +0000719 OutputSections.push_back(Out<ELFT>::ShStrTab);
George Rimar5dad7c12015-10-24 08:52:46 +0000720 if (Out<ELFT>::StrTab)
721 OutputSections.push_back(Out<ELFT>::StrTab);
Michael J. Spencer350e5b52015-10-12 23:39:23 +0000722 if (isOutputDynamic()) {
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000723 OutputSections.push_back(Out<ELFT>::DynSymTab);
Igor Kudrin1b0d7062015-10-22 08:21:35 +0000724 if (Out<ELFT>::GnuHashTab)
725 OutputSections.push_back(Out<ELFT>::GnuHashTab);
726 if (Out<ELFT>::HashTab)
727 OutputSections.push_back(Out<ELFT>::HashTab);
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000728 OutputSections.push_back(Out<ELFT>::Dynamic);
729 OutputSections.push_back(Out<ELFT>::DynStrTab);
730 if (Out<ELFT>::RelaDyn->hasRelocs())
731 OutputSections.push_back(Out<ELFT>::RelaDyn);
George Rimar648a2c32015-10-20 08:54:27 +0000732 if (Out<ELFT>::RelaPlt && Out<ELFT>::RelaPlt->hasRelocs())
733 OutputSections.push_back(Out<ELFT>::RelaPlt);
Igor Kudrin304860a2015-11-12 04:39:49 +0000734 // This is a MIPS specific section to hold a space within the data segment
735 // of executable file which is pointed to by the DT_MIPS_RLD_MAP entry.
736 // See "Dynamic section" in Chapter 5 in the following document:
737 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
738 if (Config->EMachine == EM_MIPS && !Config->Shared) {
739 Out<ELFT>::MipsRldMap = new (SecAlloc.Allocate())
740 OutputSection<ELFT>(".rld_map", SHT_PROGBITS, SHF_ALLOC | SHF_WRITE);
741 Out<ELFT>::MipsRldMap->setSize(ELFT::Is64Bits ? 8 : 4);
742 Out<ELFT>::MipsRldMap->updateAlign(ELFT::Is64Bits ? 8 : 4);
743 OutputSections.push_back(Out<ELFT>::MipsRldMap);
744 }
Rafael Espindola3f4228f2015-09-09 15:33:08 +0000745 }
Igor Kudrin304860a2015-11-12 04:39:49 +0000746
747 // We add the .got section to the result for dynamic MIPS target because
748 // its address and properties are mentioned in the .dynamic section.
749 if (!Out<ELFT>::Got->empty() ||
750 (isOutputDynamic() && Config->EMachine == EM_MIPS))
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000751 OutputSections.push_back(Out<ELFT>::Got);
George Rimar648a2c32015-10-20 08:54:27 +0000752 if (Out<ELFT>::GotPlt && !Out<ELFT>::GotPlt->empty())
753 OutputSections.push_back(Out<ELFT>::GotPlt);
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000754 if (!Out<ELFT>::Plt->empty())
755 OutputSections.push_back(Out<ELFT>::Plt);
Rafael Espindola740fafe2015-09-08 19:43:27 +0000756
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000757 std::stable_sort(OutputSections.begin(), OutputSections.end(),
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000758 compareSections<ELFT>);
Rui Ueyama3f4ec662015-09-25 03:48:25 +0000759
George Rimare3336c02015-11-24 10:15:50 +0000760 for (unsigned I = 0, N = OutputSections.size(); I < N; ++I) {
Rui Ueyama2317d0d2015-10-15 20:55:22 +0000761 OutputSections[I]->SectionIndex = I + 1;
George Rimare3336c02015-11-24 10:15:50 +0000762 HasRelro |= (Config->ZRelro && isRelroSection(OutputSections[I]));
763 }
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000764
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000765 for (OutputSectionBase<ELFT> *Sec : OutputSections)
George Rimar0f5ac9f2015-10-20 17:21:35 +0000766 Out<ELFT>::ShStrTab->add(Sec->getName());
Rui Ueyamac6ef3f22015-10-15 21:50:30 +0000767
Igor Kudrin2169b1b2015-11-02 10:46:14 +0000768 // Finalizers fix each section's size.
769 // .dynamic section's finalizer may add strings to .dynstr,
770 // so finalize that early.
771 // Likewise, .dynsym is finalized early since that may fill up .gnu.hash.
Rui Ueyama15ef5e12015-10-07 19:18:16 +0000772 Out<ELFT>::Dynamic->finalize();
Igor Kudrin2169b1b2015-11-02 10:46:14 +0000773 if (isOutputDynamic())
774 Out<ELFT>::DynSymTab->finalize();
Rui Ueyamaaf311c12015-10-09 16:03:53 +0000775
Rui Ueyamac6ef3f22015-10-15 21:50:30 +0000776 // Fill other section headers.
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000777 for (OutputSectionBase<ELFT> *Sec : OutputSections)
Rui Ueyamaaf311c12015-10-09 16:03:53 +0000778 Sec->finalize();
Hal Finkeldaedc122015-10-12 23:16:53 +0000779
780 // If we have a .opd section (used under PPC64 for function descriptors),
781 // store a pointer to it here so that we can use it later when processing
782 // relocations.
Rafael Espindolac159c962015-10-19 21:00:02 +0000783 Out<ELFT>::Opd = Map.lookup({".opd", SHT_PROGBITS, SHF_WRITE | SHF_ALLOC, 0});
Rafael Espindolaabad6182015-08-13 15:23:46 +0000784}
785
Rui Ueyamad9189ce2015-10-15 17:11:03 +0000786static bool isAlpha(char C) {
787 return ('a' <= C && C <= 'z') || ('A' <= C && C <= 'Z') || C == '_';
788}
789
790static bool isAlnum(char C) { return isAlpha(C) || ('0' <= C && C <= '9'); }
791
792// Returns true if S is valid as a C language identifier.
793static bool isValidCIdentifier(StringRef S) {
794 if (S.empty() || !isAlpha(S[0]))
795 return false;
796 return std::all_of(S.begin() + 1, S.end(), isAlnum);
797}
798
799// If a section name is valid as a C identifier (which is rare because of
800// the leading '.'), linkers are expected to define __start_<secname> and
801// __stop_<secname> symbols. They are at beginning and end of the section,
802// respectively. This is not requested by the ELF standard, but GNU ld and
803// gold provide the feature, and used by many programs.
804template <class ELFT>
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000805void Writer<ELFT>::addStartStopSymbols(OutputSectionBase<ELFT> *Sec) {
Rui Ueyamad9189ce2015-10-15 17:11:03 +0000806 StringRef S = Sec->getName();
807 if (!isValidCIdentifier(S))
808 return;
809 StringSaver Saver(Alloc);
810 StringRef Start = Saver.save("__start_" + S);
811 StringRef Stop = Saver.save("__stop_" + S);
812 if (Symtab.isUndefined(Start))
813 Symtab.addSyntheticSym(Start, *Sec, 0);
814 if (Symtab.isUndefined(Stop))
815 Symtab.addSyntheticSym(Stop, *Sec, Sec->getSize());
816}
817
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000818template <class ELFT> static bool needsPhdr(OutputSectionBase<ELFT> *Sec) {
Michael J. Spencer2f008242015-09-17 19:58:07 +0000819 return Sec->getFlags() & SHF_ALLOC;
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000820}
821
Rui Ueyama9eb7ed02015-10-24 18:22:59 +0000822static uint32_t toPhdrFlags(uint64_t Flags) {
823 uint32_t Ret = PF_R;
824 if (Flags & SHF_WRITE)
825 Ret |= PF_W;
826 if (Flags & SHF_EXECINSTR)
827 Ret |= PF_X;
828 return Ret;
829}
830
George Rimare3336c02015-11-24 10:15:50 +0000831template <class ELFT>
832void Writer<ELFT>::updateRelro(Elf_Phdr *Cur, Elf_Phdr *GnuRelroPhdr,
833 OutputSectionBase<ELFT> *Sec, uintX_t VA) {
834 if (!Config->ZRelro || !(Cur->p_flags & PF_W) || !isRelroSection(Sec))
835 return;
836 if (!GnuRelroPhdr->p_type)
837 setPhdr(GnuRelroPhdr, PT_GNU_RELRO, PF_R, Cur->p_offset, Cur->p_vaddr,
838 VA - Cur->p_vaddr, 1 /*p_align*/);
839 GnuRelroPhdr->p_filesz = VA - Cur->p_vaddr;
840 GnuRelroPhdr->p_memsz = VA - Cur->p_vaddr;
841}
842
Rui Ueyama803195e2015-10-23 21:45:59 +0000843// Visits all sections to create PHDRs and to assign incremental,
844// non-overlapping addresses to output sections.
Michael J. Spencer84487f12015-07-24 21:03:07 +0000845template <class ELFT> void Writer<ELFT>::assignAddresses() {
Igor Kudrinf6f45472015-11-10 08:39:27 +0000846 uintX_t VA = Target->getVAStart() + sizeof(Elf_Ehdr);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +0000847 uintX_t FileOff = sizeof(Elf_Ehdr);
Rafael Espindola60252d82015-09-09 22:53:55 +0000848
Rui Ueyama803195e2015-10-23 21:45:59 +0000849 // Calculate and reserve the space for the program header first so that
850 // the first section can start right after the program header.
851 Phdrs.resize(getPhdrsNum());
852 size_t PhdrSize = sizeof(Elf_Phdr) * Phdrs.size();
Rui Ueyama3486fe52015-10-11 17:44:22 +0000853
Rui Ueyama803195e2015-10-23 21:45:59 +0000854 // The first phdr entry is PT_PHDR which describes the program header itself.
855 setPhdr(&Phdrs[0], PT_PHDR, PF_R, FileOff, VA, PhdrSize, /*Align=*/8);
856 FileOff += PhdrSize;
857 VA += PhdrSize;
Rui Ueyama953c2c42015-10-10 23:59:57 +0000858
Rui Ueyama803195e2015-10-23 21:45:59 +0000859 // PT_INTERP must be the second entry if exists.
860 int PhdrIdx = 0;
Rui Ueyama953c2c42015-10-10 23:59:57 +0000861 Elf_Phdr *Interp = nullptr;
Rui Ueyama803195e2015-10-23 21:45:59 +0000862 if (needsInterpSection())
863 Interp = &Phdrs[++PhdrIdx];
Rafael Espindola70107762015-09-11 18:49:42 +0000864
Rui Ueyama803195e2015-10-23 21:45:59 +0000865 // Add the first PT_LOAD segment for regular output sections.
Igor Kudrinf6f45472015-11-10 08:39:27 +0000866 setPhdr(&Phdrs[++PhdrIdx], PT_LOAD, PF_R, 0, Target->getVAStart(), FileOff,
Rui Ueyama803195e2015-10-23 21:45:59 +0000867 Target->getPageSize());
Rafael Espindola0a2e2112015-09-10 15:41:34 +0000868
George Rimare3336c02015-11-24 10:15:50 +0000869 Elf_Phdr GnuRelroPhdr = {};
Michael J. Spencer2c6f2132015-11-03 22:43:11 +0000870 Elf_Phdr TlsPhdr{};
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000871 uintX_t ThreadBSSOffset = 0;
Rui Ueyama803195e2015-10-23 21:45:59 +0000872 // Create phdrs as we assign VAs and file offsets to all output sections.
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +0000873 for (OutputSectionBase<ELFT> *Sec : OutputSections) {
Rafael Espindola5fbe0082015-11-03 23:19:42 +0000874 if (needsPhdr<ELFT>(Sec)) {
875 uintX_t Flags = toPhdrFlags(Sec->getFlags());
876 if (Phdrs[PhdrIdx].p_flags != Flags) {
877 // Flags changed. Create a new PT_LOAD.
Rafael Espindola61362ce2015-11-03 22:08:08 +0000878 VA = RoundUpToAlignment(VA, Target->getPageSize());
879 FileOff = RoundUpToAlignment(FileOff, Target->getPageSize());
880 Elf_Phdr *PH = &Phdrs[++PhdrIdx];
881 setPhdr(PH, PT_LOAD, Flags, FileOff, VA, 0, Target->getPageSize());
Michael J. Spencer2f008242015-09-17 19:58:07 +0000882 }
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000883
Rafael Espindola5fbe0082015-11-03 23:19:42 +0000884 if (Sec->getFlags() & SHF_TLS) {
Rafael Espindolaea7a1e902015-11-06 22:14:44 +0000885 if (!TlsPhdr.p_vaddr)
Rafael Espindola5fbe0082015-11-03 23:19:42 +0000886 setPhdr(&TlsPhdr, PT_TLS, PF_R, FileOff, VA, 0, Sec->getAlign());
Rafael Espindola5fbe0082015-11-03 23:19:42 +0000887 if (Sec->getType() != SHT_NOBITS)
888 VA = RoundUpToAlignment(VA, Sec->getAlign());
889 uintX_t TVA = RoundUpToAlignment(VA + ThreadBSSOffset, Sec->getAlign());
890 Sec->setVA(TVA);
891 TlsPhdr.p_memsz += Sec->getSize();
892 if (Sec->getType() == SHT_NOBITS) {
893 ThreadBSSOffset = TVA - VA + Sec->getSize();
894 } else {
895 TlsPhdr.p_filesz += Sec->getSize();
896 VA += Sec->getSize();
897 }
898 TlsPhdr.p_align = std::max<uintX_t>(TlsPhdr.p_align, Sec->getAlign());
Rafael Espindola9eb3e572015-11-03 15:46:15 +0000899 } else {
Rafael Espindola5fbe0082015-11-03 23:19:42 +0000900 VA = RoundUpToAlignment(VA, Sec->getAlign());
901 Sec->setVA(VA);
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000902 VA += Sec->getSize();
George Rimare3336c02015-11-24 10:15:50 +0000903 updateRelro(&Phdrs[PhdrIdx], &GnuRelroPhdr, Sec, VA);
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000904 }
Rafael Espindolaef1ac012015-08-13 15:31:17 +0000905 }
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000906
Rui Ueyama803195e2015-10-23 21:45:59 +0000907 FileOff = RoundUpToAlignment(FileOff, Sec->getAlign());
Michael J. Spencer84487f12015-07-24 21:03:07 +0000908 Sec->setFileOffset(FileOff);
Rafael Espindola058f3432015-08-31 20:23:57 +0000909 if (Sec->getType() != SHT_NOBITS)
Rui Ueyama803195e2015-10-23 21:45:59 +0000910 FileOff += Sec->getSize();
Rafael Espindola5fbe0082015-11-03 23:19:42 +0000911 if (needsPhdr<ELFT>(Sec)) {
912 Elf_Phdr *Cur = &Phdrs[PhdrIdx];
913 Cur->p_filesz = FileOff - Cur->p_offset;
914 Cur->p_memsz = VA - Cur->p_vaddr;
915 }
Michael J. Spencer84487f12015-07-24 21:03:07 +0000916 }
Rafael Espindola6b83b902015-08-12 00:00:24 +0000917
Michael J. Spencer6c34eff2015-11-05 02:00:35 +0000918 if (TlsPhdr.p_vaddr) {
Rafael Espindolaea7a1e902015-11-06 22:14:44 +0000919 // The TLS pointer goes after PT_TLS. At least glibc will align it,
920 // so round up the size to make sure the offsets are correct.
921 TlsPhdr.p_memsz = RoundUpToAlignment(TlsPhdr.p_memsz, TlsPhdr.p_align);
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000922 Phdrs[++PhdrIdx] = TlsPhdr;
Rafael Espindolaea7a1e902015-11-06 22:14:44 +0000923 Out<ELFT>::TlsPhdr = &Phdrs[PhdrIdx];
Michael J. Spencer6c34eff2015-11-05 02:00:35 +0000924 }
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000925
Rui Ueyama803195e2015-10-23 21:45:59 +0000926 // Add an entry for .dynamic.
Michael J. Spencer350e5b52015-10-12 23:39:23 +0000927 if (isOutputDynamic()) {
Rui Ueyama803195e2015-10-23 21:45:59 +0000928 Elf_Phdr *PH = &Phdrs[++PhdrIdx];
Rui Ueyama953c2c42015-10-10 23:59:57 +0000929 PH->p_type = PT_DYNAMIC;
Rui Ueyama536c9992015-10-11 19:45:58 +0000930 copyPhdr(PH, Out<ELFT>::Dynamic);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +0000931 }
Rafael Espindola91009b32015-08-12 01:45:28 +0000932
George Rimare3336c02015-11-24 10:15:50 +0000933 if (HasRelro) {
934 Elf_Phdr *PH = &Phdrs[++PhdrIdx];
935 *PH = GnuRelroPhdr;
936 }
937
Rui Ueyamae79b09a2015-11-21 22:19:32 +0000938 // PT_GNU_STACK is a special section to tell the loader to make the
939 // pages for the stack non-executable.
Rui Ueyamaa46566f2015-11-24 23:42:33 +0000940 if (!Config->ZExecStack) {
941 Elf_Phdr *PH = &Phdrs[++PhdrIdx];
942 PH->p_type = PT_GNU_STACK;
Rui Ueyamae79b09a2015-11-21 22:19:32 +0000943 PH->p_flags = PF_R | PF_W;
Rui Ueyamaa46566f2015-11-24 23:42:33 +0000944 }
George Rimar03220302015-11-14 20:56:08 +0000945
Rui Ueyama803195e2015-10-23 21:45:59 +0000946 // Fix up PT_INTERP as we now know the address of .interp section.
947 if (Interp) {
948 Interp->p_type = PT_INTERP;
949 copyPhdr(Interp, Out<ELFT>::Interp);
Rui Ueyama69960ba2015-10-10 23:25:39 +0000950 }
951
Michael J. Spencer8039dae22015-07-29 00:30:10 +0000952 // Add space for section headers.
Rui Ueyama803195e2015-10-23 21:45:59 +0000953 SectionHeaderOff = RoundUpToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4);
954 FileSize = SectionHeaderOff + getNumSections() * sizeof(Elf_Shdr);
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000955
Igor Kudrinb044af52015-11-20 02:32:35 +0000956 // Update "_end" and "end" symbols so that they
957 // point to the end of the data segment.
958 DefinedAbsolute<ELFT>::End.st_value = VA;
959
Igor Kudrin15cd9ff2015-11-06 07:43:03 +0000960 // Update MIPS _gp absolute symbol so that it points to the static data.
961 if (Config->EMachine == EM_MIPS)
962 DefinedAbsolute<ELFT>::MipsGp.st_value = getMipsGpAddr<ELFT>();
Rui Ueyama803195e2015-10-23 21:45:59 +0000963}
964
965// Returns the number of PHDR entries.
966template <class ELFT> int Writer<ELFT>::getPhdrsNum() const {
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000967 bool Tls = false;
Rui Ueyamaa46566f2015-11-24 23:42:33 +0000968 int I = 2; // 2 for PT_PHDR and first PT_LOAD
Rui Ueyama803195e2015-10-23 21:45:59 +0000969 if (needsInterpSection())
970 ++I;
971 if (isOutputDynamic())
972 ++I;
Rui Ueyamaa46566f2015-11-24 23:42:33 +0000973 if (!Config->ZExecStack)
974 ++I;
Rui Ueyama803195e2015-10-23 21:45:59 +0000975 uintX_t Last = PF_R;
976 for (OutputSectionBase<ELFT> *Sec : OutputSections) {
Rafael Espindola61362ce2015-11-03 22:08:08 +0000977 if (!needsPhdr<ELFT>(Sec))
Rui Ueyama803195e2015-10-23 21:45:59 +0000978 continue;
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000979 if (Sec->getFlags() & SHF_TLS)
980 Tls = true;
Rui Ueyama803195e2015-10-23 21:45:59 +0000981 uintX_t Flags = toPhdrFlags(Sec->getFlags());
982 if (Last != Flags) {
983 Last = Flags;
984 ++I;
985 }
986 }
Michael J. Spencer78aa1de2015-11-03 00:34:39 +0000987 if (Tls)
988 ++I;
George Rimare3336c02015-11-24 10:15:50 +0000989 if (HasRelro)
990 ++I;
Rui Ueyama803195e2015-10-23 21:45:59 +0000991 return I;
Michael J. Spencer84487f12015-07-24 21:03:07 +0000992}
993
994template <class ELFT> void Writer<ELFT>::writeHeader() {
995 uint8_t *Buf = Buffer->getBufferStart();
Rui Ueyamae08cd672015-10-23 22:44:39 +0000996 memcpy(Buf, "\177ELF", 4);
997
Rui Ueyama6621d8e2015-10-24 17:57:40 +0000998 // Write the ELF header.
Rafael Espindola18608a02015-09-08 21:57:31 +0000999 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
Rafael Espindola4b7c2fc2015-08-05 15:08:40 +00001000 EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
1001 EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little
1002 ? ELFDATA2LSB
1003 : ELFDATA2MSB;
Michael J. Spencer84487f12015-07-24 21:03:07 +00001004 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
Davide Italianoaa7c5332015-09-25 01:59:13 +00001005
Rafael Espindolab9ca7bb2015-10-12 11:52:31 +00001006 auto &FirstObj = cast<ELFFileBase<ELFT>>(*Config->FirstElf);
Davide Italianoaa7c5332015-09-25 01:59:13 +00001007 EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI();
Michael J. Spencer84487f12015-07-24 21:03:07 +00001008
Rafael Espindola4340aad2015-09-11 22:42:45 +00001009 EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC;
Rafael Espindolaf98d6d82015-09-03 20:03:54 +00001010 EHdr->e_machine = FirstObj.getEMachine();
Michael J. Spencer84487f12015-07-24 21:03:07 +00001011 EHdr->e_version = EV_CURRENT;
Rui Ueyamabcb2d0f2015-10-23 22:44:37 +00001012 EHdr->e_entry = getEntryAddr();
Rui Ueyama5bfd7d42015-10-10 22:36:36 +00001013 EHdr->e_phoff = sizeof(Elf_Ehdr);
Michael J. Spencer8039dae22015-07-29 00:30:10 +00001014 EHdr->e_shoff = SectionHeaderOff;
Rafael Espindola18608a02015-09-08 21:57:31 +00001015 EHdr->e_ehsize = sizeof(Elf_Ehdr);
1016 EHdr->e_phentsize = sizeof(Elf_Phdr);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +00001017 EHdr->e_phnum = Phdrs.size();
Rafael Espindola18608a02015-09-08 21:57:31 +00001018 EHdr->e_shentsize = sizeof(Elf_Shdr);
Rafael Espindola5f553872015-09-08 17:39:39 +00001019 EHdr->e_shnum = getNumSections();
George Rimar0f5ac9f2015-10-20 17:21:35 +00001020 EHdr->e_shstrndx = Out<ELFT>::ShStrTab->SectionIndex;
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001021
1022 // Write the program header table.
Rui Ueyamabdca0b12015-10-11 00:10:36 +00001023 memcpy(Buf + EHdr->e_phoff, &Phdrs[0], Phdrs.size() * sizeof(Phdrs[0]));
Rafael Espindolae438e072015-09-08 22:55:28 +00001024
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001025 // Write the section header table. Note that the first table entry is null.
Rafael Espindola18608a02015-09-08 21:57:31 +00001026 auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
Rui Ueyama157c4332015-10-24 17:57:39 +00001027 for (OutputSectionBase<ELFT> *Sec : OutputSections)
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001028 Sec->writeHeaderTo(++SHdrs);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001029}
1030
1031template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) {
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001032 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
1033 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable);
1034 error(BufferOrErr, Twine("failed to open ") + Path);
1035 Buffer = std::move(*BufferOrErr);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001036}
1037
1038// Write section contents to a mmap'ed file.
1039template <class ELFT> void Writer<ELFT>::writeSections() {
1040 uint8_t *Buf = Buffer->getBufferStart();
Hal Finkeldaedc122015-10-12 23:16:53 +00001041
1042 // PPC64 needs to process relocations in the .opd section before processing
1043 // relocations in code-containing sections.
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001044 if (OutputSectionBase<ELFT> *Sec = Out<ELFT>::Opd) {
Rafael Espindola7a513052015-10-13 14:45:51 +00001045 Out<ELFT>::OpdBuf = Buf + Sec->getFileOff();
1046 Sec->writeTo(Buf + Sec->getFileOff());
1047 }
Hal Finkeldaedc122015-10-12 23:16:53 +00001048
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001049 for (OutputSectionBase<ELFT> *Sec : OutputSections)
Rafael Espindola7a513052015-10-13 14:45:51 +00001050 if (Sec != Out<ELFT>::Opd)
Hal Finkeldaedc122015-10-12 23:16:53 +00001051 Sec->writeTo(Buf + Sec->getFileOff());
Michael J. Spencer84487f12015-07-24 21:03:07 +00001052}
Rui Ueyama3ce825e2015-10-09 21:07:25 +00001053
Rui Ueyama2f1b79f2015-10-10 22:34:30 +00001054template <class ELFT>
Rui Ueyamabcb2d0f2015-10-23 22:44:37 +00001055typename ELFFile<ELFT>::uintX_t Writer<ELFT>::getEntryAddr() const {
1056 if (Config->EntrySym) {
1057 if (auto *E = dyn_cast<ELFSymbolBody<ELFT>>(Config->EntrySym->repl()))
1058 return getSymVA<ELFT>(*E);
1059 return 0;
1060 }
1061 if (Config->EntryAddr != uint64_t(-1))
1062 return Config->EntryAddr;
1063 return 0;
1064}
1065
1066template <class ELFT>
Rui Ueyama536c9992015-10-11 19:45:58 +00001067void Writer<ELFT>::setPhdr(Elf_Phdr *PH, uint32_t Type, uint32_t Flags,
Rui Ueyama803195e2015-10-23 21:45:59 +00001068 uintX_t FileOff, uintX_t VA, uintX_t Size,
1069 uintX_t Align) {
Rui Ueyama2f1b79f2015-10-10 22:34:30 +00001070 PH->p_type = Type;
1071 PH->p_flags = Flags;
1072 PH->p_offset = FileOff;
1073 PH->p_vaddr = VA;
1074 PH->p_paddr = VA;
Rui Ueyama803195e2015-10-23 21:45:59 +00001075 PH->p_filesz = Size;
1076 PH->p_memsz = Size;
Rui Ueyama2f1b79f2015-10-10 22:34:30 +00001077 PH->p_align = Align;
1078}
1079
1080template <class ELFT>
Rui Ueyamac7cc6ec2015-10-15 22:27:29 +00001081void Writer<ELFT>::copyPhdr(Elf_Phdr *PH, OutputSectionBase<ELFT> *From) {
Rui Ueyama2f1b79f2015-10-10 22:34:30 +00001082 PH->p_flags = toPhdrFlags(From->getFlags());
1083 PH->p_offset = From->getFileOff();
1084 PH->p_vaddr = From->getVA();
1085 PH->p_paddr = From->getVA();
1086 PH->p_filesz = From->getSize();
1087 PH->p_memsz = From->getSize();
1088 PH->p_align = From->getAlign();
1089}
1090
Denis Protivensky8e3b38a2015-11-12 09:52:08 +00001091template <class ELFT> void Writer<ELFT>::buildSectionMap() {
1092 for (const std::pair<StringRef, std::vector<StringRef>> &OutSec :
1093 Config->OutputSections)
1094 for (StringRef Name : OutSec.second)
1095 InputToOutputSection[Name] = OutSec.first;
1096}
1097
Rui Ueyama3ce825e2015-10-09 21:07:25 +00001098template void lld::elf2::writeResult<ELF32LE>(SymbolTable<ELF32LE> *Symtab);
1099template void lld::elf2::writeResult<ELF32BE>(SymbolTable<ELF32BE> *Symtab);
1100template void lld::elf2::writeResult<ELF64LE>(SymbolTable<ELF64LE> *Symtab);
1101template void lld::elf2::writeResult<ELF64BE>(SymbolTable<ELF64BE> *Symtab);