blob: 5244550456be926d2c54bde1b385f4e7142e637f [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
Rui Ueyamaafff74e22015-08-05 23:24:46 +000016#include "llvm/Support/FileOutputBuffer.h"
Michael J. Spencer84487f12015-07-24 21:03:07 +000017
18using namespace llvm;
19using namespace llvm::ELF;
20using namespace llvm::object;
21
22using namespace lld;
23using namespace lld::elf2;
24
25static const int PageSize = 4096;
26
Rafael Espindolad67bb262015-09-11 13:20:07 +000027// On freebsd x86_64 the first page cannot be mmaped.
28// On linux that is controled by vm.mmap_min_addr. At least on some x86_64
29// installs that is 65536, so the first 15 pages cannot be used.
30// Given that, the smallest value that can be used in here is 0x10000.
Rafael Espindola0a2e2112015-09-10 15:41:34 +000031// If using 2MB pages, the smallest page aligned address that works is
32// 0x200000, but it looks like every OS uses 4k pages for executables.
33// FIXME: This is architecture and OS dependent.
34static const int VAStart = 0x10000;
35
Rui Ueyamaafff74e22015-08-05 23:24:46 +000036namespace {
Rafael Espindola740fafe2015-09-08 19:43:27 +000037
Rui Ueyama04dae552015-10-02 21:23:17 +000038static uint32_t toPHDRFlags(uint64_t Flags) {
Michael J. Spencer2f008242015-09-17 19:58:07 +000039 uint32_t Ret = PF_R;
40 if (Flags & SHF_WRITE)
41 Ret |= PF_W;
Michael J. Spencer2f008242015-09-17 19:58:07 +000042 if (Flags & SHF_EXECINSTR)
43 Ret |= PF_X;
Michael J. Spencer2f008242015-09-17 19:58:07 +000044 return Ret;
45}
46
47template <bool Is64Bits>
48class ProgramHeader {
49public:
50 typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
51 typedef
52 typename std::conditional<Is64Bits, Elf64_Phdr, Elf32_Phdr>::type HeaderT;
53
Rui Ueyama04dae552015-10-02 21:23:17 +000054 ProgramHeader(uintX_t Type, uintX_t Flags, uintX_t FileOff, uintX_t VA) {
Michael J. Spencer2f008242015-09-17 19:58:07 +000055 std::memset(&Header, 0, sizeof(HeaderT));
Rui Ueyama0fb1ee02015-10-02 21:13:19 +000056 Header.p_type = Type;
57 Header.p_flags = Flags;
Michael J. Spencer2f008242015-09-17 19:58:07 +000058 Header.p_align = PageSize;
Rui Ueyama04dae552015-10-02 21:23:17 +000059 Header.p_offset = FileOff;
60 Header.p_vaddr = VA;
61 Header.p_paddr = VA;
Michael J. Spencer2f008242015-09-17 19:58:07 +000062 }
63
64 void setValuesFromSection(OutputSectionBase<Is64Bits> &Sec) {
Rui Ueyama04dae552015-10-02 21:23:17 +000065 Header.p_flags = toPHDRFlags(Sec.getFlags());
Michael J. Spencer2f008242015-09-17 19:58:07 +000066 Header.p_offset = Sec.getFileOff();
67 Header.p_vaddr = Sec.getVA();
68 Header.p_paddr = Header.p_vaddr;
69 Header.p_filesz = Sec.getSize();
70 Header.p_memsz = Header.p_filesz;
71 Header.p_align = Sec.getAlign();
72 }
73
74 template <endianness E>
75 void writeHeaderTo(typename ELFFile<ELFType<E, Is64Bits>>::Elf_Phdr *PHDR) {
76 PHDR->p_type = Header.p_type;
77 PHDR->p_flags = Header.p_flags;
78 PHDR->p_offset = Header.p_offset;
79 PHDR->p_vaddr = Header.p_vaddr;
80 PHDR->p_paddr = Header.p_paddr;
81 PHDR->p_filesz = Header.p_filesz;
82 PHDR->p_memsz = Header.p_memsz;
83 PHDR->p_align = Header.p_align;
84 }
85
86 HeaderT Header;
87 bool Closed = false;
88};
89
Rui Ueyamaafff74e22015-08-05 23:24:46 +000090// The writer writes a SymbolTable result to a file.
91template <class ELFT> class Writer {
92public:
Rafael Espindola18608a02015-09-08 21:57:31 +000093 typedef typename ELFFile<ELFT>::uintX_t uintX_t;
94 typedef typename ELFFile<ELFT>::Elf_Shdr Elf_Shdr;
95 typedef typename ELFFile<ELFT>::Elf_Ehdr Elf_Ehdr;
96 typedef typename ELFFile<ELFT>::Elf_Phdr Elf_Phdr;
97 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
Davide Italiano6d328d32015-09-16 20:45:57 +000098 typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
Rafael Espindola19e38892015-09-16 15:54:15 +000099 typedef typename ELFFile<ELFT>::Elf_Rela Elf_Rela;
Rafael Espindola3f4228f2015-09-09 15:33:08 +0000100 Writer(SymbolTable *T)
Rafael Espindolac2d21192015-09-23 18:25:05 +0000101 : SymTabSec(*T, StrTabSec, BssSec), DynSymSec(*T, DynStrSec, BssSec),
Rafael Espindolaeb792732015-09-21 15:11:29 +0000102 RelaDynSec(DynSymSec, GotSec, T->shouldUseRela()), PltSec(GotSec),
Rafael Espindolac2d21192015-09-23 18:25:05 +0000103 HashSec(DynSymSec), DynamicSec(*T, HashSec, RelaDynSec),
104 BssSec(PltSec, GotSec, BssSec, ".bss", SHT_NOBITS,
105 SHF_ALLOC | SHF_WRITE) {}
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000106 void run();
107
108private:
109 void createSections();
Rafael Espindola67a5da62015-09-17 14:02:10 +0000110 template <bool isRela>
Rafael Espindola53d5cea2015-09-21 17:47:00 +0000111 void scanRelocs(const InputSection<ELFT> &C,
Rafael Espindola67a5da62015-09-17 14:02:10 +0000112 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels);
Rafael Espindola53d5cea2015-09-21 17:47:00 +0000113 void scanRelocs(const InputSection<ELFT> &C);
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000114 void assignAddresses();
115 void openFile(StringRef OutputPath);
116 void writeHeader();
117 void writeSections();
Rafael Espindola70107762015-09-11 18:49:42 +0000118 bool needsInterpSection() const {
119 return !SymTabSec.getSymTable().getSharedFiles().empty() &&
120 !Config->DynamicLinker.empty();
121 }
Rafael Espindola4340aad2015-09-11 22:42:45 +0000122 bool needsDynamicSections() const {
123 return !SymTabSec.getSymTable().getSharedFiles().empty() || Config->Shared;
124 }
125 unsigned getVAStart() const { return Config->Shared ? 0 : VAStart; }
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000126
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000127 std::unique_ptr<llvm::FileOutputBuffer> Buffer;
Michael J. Spencer2f008242015-09-17 19:58:07 +0000128
Rafael Espindola83b0dc62015-08-13 22:21:37 +0000129 llvm::SpecificBumpPtrAllocator<OutputSection<ELFT>> CAlloc;
Rafael Espindolaebd21082015-08-13 22:14:37 +0000130 std::vector<OutputSectionBase<ELFT::Is64Bits> *> OutputSections;
Rafael Espindola5f553872015-09-08 17:39:39 +0000131 unsigned getNumSections() const { return OutputSections.size() + 1; }
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000132
Michael J. Spencer2f008242015-09-17 19:58:07 +0000133 llvm::BumpPtrAllocator PAlloc;
134 std::vector<ProgramHeader<ELFT::Is64Bits> *> PHDRs;
Rui Ueyama04dae552015-10-02 21:23:17 +0000135 ProgramHeader<ELFT::Is64Bits> FileHeaderPHDR{PT_LOAD, PF_R, 0, 0};
136 ProgramHeader<ELFT::Is64Bits> InterpPHDR{PT_INTERP, 0, 0, 0};
137 ProgramHeader<ELFT::Is64Bits> DynamicPHDR{PT_DYNAMIC, 0, 0, 0};
Michael J. Spencer2f008242015-09-17 19:58:07 +0000138
Rafael Espindola98f6bd02015-08-11 23:14:13 +0000139 uintX_t FileSize;
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000140 uintX_t ProgramHeaderOff;
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000141 uintX_t SectionHeaderOff;
Rafael Espindolaebd21082015-08-13 22:14:37 +0000142
Rui Ueyama9078f732015-09-14 20:32:41 +0000143 StringTableSection<ELFT::Is64Bits> StrTabSec = { /*dynamic=*/false };
144 StringTableSection<ELFT::Is64Bits> DynStrSec = { /*dynamic=*/true };
Rafael Espindolaebd21082015-08-13 22:14:37 +0000145
Rafael Espindola5805c4f2015-09-21 21:38:08 +0000146 lld::elf2::SymbolTableSection<ELFT> SymTabSec;
147 lld::elf2::SymbolTableSection<ELFT> DynSymSec;
Rafael Espindola740fafe2015-09-08 19:43:27 +0000148
Rafael Espindola19e38892015-09-16 15:54:15 +0000149 RelocationSection<ELFT> RelaDynSec;
150
Rafael Espindola5c2310c2015-09-18 14:40:19 +0000151 GotSection<ELFT> GotSec;
Rafael Espindolaeb792732015-09-21 15:11:29 +0000152 PltSection<ELFT> PltSec;
Rafael Espindola5c2310c2015-09-18 14:40:19 +0000153
Rafael Espindola601771e2015-09-14 20:20:34 +0000154 HashTableSection<ELFT> HashSec;
155
Rafael Espindola80faee82015-09-14 22:08:55 +0000156 DynamicSection<ELFT> DynamicSec;
157
Rafael Espindola70107762015-09-11 18:49:42 +0000158 InterpSection<ELFT::Is64Bits> InterpSec;
159
Rafael Espindolac2d21192015-09-23 18:25:05 +0000160 OutputSection<ELFT> BssSec;
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000161};
162} // anonymous namespace
163
164namespace lld {
165namespace elf2 {
166
Rafael Espindola2ffdd4d2015-08-04 14:29:01 +0000167template <class ELFT>
Rui Ueyamacb8474ed2015-08-05 23:51:50 +0000168void writeResult(SymbolTable *Symtab) { Writer<ELFT>(Symtab).run(); }
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000169
Rui Ueyamacb8474ed2015-08-05 23:51:50 +0000170template void writeResult<ELF32LE>(SymbolTable *);
171template void writeResult<ELF32BE>(SymbolTable *);
172template void writeResult<ELF64LE>(SymbolTable *);
173template void writeResult<ELF64BE>(SymbolTable *);
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000174
175} // namespace elf2
176} // namespace lld
Michael J. Spencer84487f12015-07-24 21:03:07 +0000177
178// The main function of the writer.
Rui Ueyamaafff74e22015-08-05 23:24:46 +0000179template <class ELFT> void Writer<ELFT>::run() {
Michael J. Spencer84487f12015-07-24 21:03:07 +0000180 createSections();
181 assignAddresses();
Rui Ueyamacb8474ed2015-08-05 23:51:50 +0000182 openFile(Config->OutputFile);
Michael J. Spencer84487f12015-07-24 21:03:07 +0000183 writeHeader();
184 writeSections();
185 error(Buffer->commit());
186}
187
Rafael Espindolaa7471792015-08-13 17:04:50 +0000188namespace {
189template <bool Is64Bits> struct SectionKey {
190 typedef typename std::conditional<Is64Bits, uint64_t, uint32_t>::type uintX_t;
191 StringRef Name;
Rui Ueyama0fb1ee02015-10-02 21:13:19 +0000192 uint32_t Type;
193 uintX_t Flags;
Rafael Espindolaa7471792015-08-13 17:04:50 +0000194};
195}
196namespace llvm {
197template <bool Is64Bits> struct DenseMapInfo<SectionKey<Is64Bits>> {
198 static SectionKey<Is64Bits> getEmptyKey() {
199 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getEmptyKey(), 0, 0};
200 }
201 static SectionKey<Is64Bits> getTombstoneKey() {
202 return SectionKey<Is64Bits>{DenseMapInfo<StringRef>::getTombstoneKey(), 0,
203 0};
204 }
205 static unsigned getHashValue(const SectionKey<Is64Bits> &Val) {
Rui Ueyama0fb1ee02015-10-02 21:13:19 +0000206 return hash_combine(Val.Name, Val.Type, Val.Flags);
Rafael Espindolaa7471792015-08-13 17:04:50 +0000207 }
208 static bool isEqual(const SectionKey<Is64Bits> &LHS,
209 const SectionKey<Is64Bits> &RHS) {
210 return DenseMapInfo<StringRef>::isEqual(LHS.Name, RHS.Name) &&
Rui Ueyama0fb1ee02015-10-02 21:13:19 +0000211 LHS.Type == RHS.Type && LHS.Flags == RHS.Flags;
Rafael Espindolaa7471792015-08-13 17:04:50 +0000212 }
213};
214}
215
Rafael Espindola19e38892015-09-16 15:54:15 +0000216// The reason we have to do this early scan is as follows
217// * To mmap the output file, we need to know the size
218// * For that, we need to know how many dynamic relocs we will have.
219// It might be possible to avoid this by outputting the file with write:
220// * Write the allocated output sections, computing addresses.
221// * Apply relocations, recording which ones require a dynamic reloc.
222// * Write the dynamic relocations.
223// * Write the rest of the file.
224template <class ELFT>
Rafael Espindola67a5da62015-09-17 14:02:10 +0000225template <bool isRela>
226void Writer<ELFT>::scanRelocs(
Rafael Espindola53d5cea2015-09-21 17:47:00 +0000227 const InputSection<ELFT> &C,
Rafael Espindola67a5da62015-09-17 14:02:10 +0000228 iterator_range<const Elf_Rel_Impl<ELFT, isRela> *> Rels) {
229 typedef Elf_Rel_Impl<ELFT, isRela> RelType;
230 const ObjectFile<ELFT> &File = *C.getFile();
Rafael Espindolae1901cc2015-09-24 15:11:50 +0000231 bool IsMips64EL = File.getObj().isMips64EL();
Rafael Espindola67a5da62015-09-17 14:02:10 +0000232 for (const RelType &RI : Rels) {
233 uint32_t SymIndex = RI.getSymbol(IsMips64EL);
Rafael Espindola5c2310c2015-09-18 14:40:19 +0000234 SymbolBody *Body = File.getSymbolBody(SymIndex);
Rafael Espindola67a5da62015-09-17 14:02:10 +0000235 if (!Body)
236 continue;
Rafael Espindolaeb792732015-09-21 15:11:29 +0000237 uint32_t Type = RI.getType(IsMips64EL);
Rafael Espindola3ef3a4c2015-09-29 23:22:16 +0000238 if (Target->relocNeedsPlt(Type, *Body)) {
Rafael Espindolaeb792732015-09-21 15:11:29 +0000239 if (Body->isInPlt())
240 continue;
241 PltSec.addEntry(Body);
242 }
Rafael Espindola3ef3a4c2015-09-29 23:22:16 +0000243 if (Target->relocNeedsGot(Type, *Body)) {
Rafael Espindola5c2310c2015-09-18 14:40:19 +0000244 if (Body->isInGot())
245 continue;
246 GotSec.addEntry(Body);
Rafael Espindola085a8f52015-09-28 20:18:40 +0000247 } else if (!isa<SharedSymbol<ELFT>>(Body))
248 continue;
Rafael Espindolacdfecff2015-09-23 20:08:25 +0000249 Body->setUsedInDynamicReloc();
Rafael Espindola67a5da62015-09-17 14:02:10 +0000250 RelaDynSec.addReloc({C, RI});
251 }
252}
253
254template <class ELFT>
Rafael Espindola53d5cea2015-09-21 17:47:00 +0000255void Writer<ELFT>::scanRelocs(const InputSection<ELFT> &C) {
Rafael Espindolae1901cc2015-09-24 15:11:50 +0000256 ObjectFile<ELFT> *File = C.getFile();
257 ELFFile<ELFT> &EObj = File->getObj();
Rafael Espindola19e38892015-09-16 15:54:15 +0000258
259 if (!(C.getSectionHdr()->sh_flags & SHF_ALLOC))
260 return;
261
262 for (const Elf_Shdr *RelSec : C.RelocSections) {
Rafael Espindola67a5da62015-09-17 14:02:10 +0000263 if (RelSec->sh_type == SHT_RELA)
Rafael Espindolae1901cc2015-09-24 15:11:50 +0000264 scanRelocs(C, EObj.relas(RelSec));
Rafael Espindola67a5da62015-09-17 14:02:10 +0000265 else
Rafael Espindolae1901cc2015-09-24 15:11:50 +0000266 scanRelocs(C, EObj.rels(RelSec));
Rafael Espindola19e38892015-09-16 15:54:15 +0000267 }
268}
269
Rafael Espindola6173f842015-09-23 14:37:01 +0000270template <class ELFT>
Rui Ueyama44f5d912015-10-01 14:46:54 +0000271static void reportUndefined(const SymbolTable &S, const SymbolBody &Sym) {
Rafael Espindola6173f842015-09-23 14:37:01 +0000272 typedef typename ELFFile<ELFT>::Elf_Sym Elf_Sym;
273 typedef typename ELFFile<ELFT>::Elf_Sym_Range Elf_Sym_Range;
274
George Rimar57e40de2015-10-01 20:14:45 +0000275 if (Config->Shared && !Config->NoUndefined)
George Rimaree058282015-10-01 17:24:24 +0000276 return;
277
Rafael Espindola6173f842015-09-23 14:37:01 +0000278 const Elf_Sym &SymE = cast<ELFSymbolBody<ELFT>>(Sym).Sym;
279 ELFFileBase *SymFile = nullptr;
280
281 for (const std::unique_ptr<ObjectFileBase> &F : S.getObjectFiles()) {
282 const auto &File = cast<ObjectFile<ELFT>>(*F);
Rafael Espindolae1901cc2015-09-24 15:11:50 +0000283 Elf_Sym_Range Syms = File.getObj().symbols(File.getSymbolTable());
Rafael Espindola6173f842015-09-23 14:37:01 +0000284 if (&SymE > Syms.begin() && &SymE < Syms.end())
285 SymFile = F.get();
286 }
Rafael Espindola551dfd82015-09-25 19:24:57 +0000287
288 std::string Message = "undefined symbol: " + Sym.getName().str();
Rafael Espindola6173f842015-09-23 14:37:01 +0000289 if (SymFile)
Rafael Espindola551dfd82015-09-25 19:24:57 +0000290 Message += " in " + SymFile->getName().str();
291 if (Config->NoInhibitExec)
292 warning(Message);
Rafael Espindola6173f842015-09-23 14:37:01 +0000293 else
Rafael Espindola551dfd82015-09-25 19:24:57 +0000294 error(Message);
Rafael Espindola6173f842015-09-23 14:37:01 +0000295}
296
Michael J. Spencer84487f12015-07-24 21:03:07 +0000297// Create output section objects and add them to OutputSections.
298template <class ELFT> void Writer<ELFT>::createSections() {
Rafael Espindola83b0dc62015-08-13 22:21:37 +0000299 SmallDenseMap<SectionKey<ELFT::Is64Bits>, OutputSection<ELFT> *> Map;
Rafael Espindolac2d21192015-09-23 18:25:05 +0000300
301 OutputSections.push_back(&BssSec);
302 Map[{BssSec.getName(), BssSec.getType(), BssSec.getFlags()}] = &BssSec;
303
Rafael Espindola0e604f92015-09-25 18:56:53 +0000304 SymbolTable &Symtab = SymTabSec.getSymTable();
Rafael Espindola19e38892015-09-16 15:54:15 +0000305 for (const std::unique_ptr<ObjectFileBase> &FileB : Symtab.getObjectFiles()) {
306 auto &File = cast<ObjectFile<ELFT>>(*FileB);
Davide Italiano6d328d32015-09-16 20:45:57 +0000307 if (!Config->DiscardAll) {
308 Elf_Sym_Range Syms = File.getLocalSymbols();
309 for (const Elf_Sym &Sym : Syms) {
310 ErrorOr<StringRef> SymName = Sym.getName(File.getStringTable());
Davide Italiano85121bb2015-09-25 03:56:11 +0000311 if (SymName && shouldKeepInSymtab(*SymName))
Davide Italiano6d328d32015-09-16 20:45:57 +0000312 SymTabSec.addSymbol(*SymName, true);
313 }
314 }
Rafael Espindola71675852015-09-22 00:16:19 +0000315 for (InputSection<ELFT> *C : File.getSections()) {
Rafael Espindola19e38892015-09-16 15:54:15 +0000316 if (!C)
317 continue;
318 const Elf_Shdr *H = C->getSectionHdr();
Rafael Espindolad13d9602015-09-25 15:08:44 +0000319 SectionKey<ELFT::Is64Bits> Key{C->getSectionName(), H->sh_type,
320 H->sh_flags};
321 OutputSection<ELFT> *&Sec = Map[Key];
322 if (!Sec) {
323 Sec = new (CAlloc.Allocate()) OutputSection<ELFT>(
Rui Ueyama0fb1ee02015-10-02 21:13:19 +0000324 PltSec, GotSec, BssSec, Key.Name, Key.Type, Key.Flags);
Rafael Espindolad13d9602015-09-25 15:08:44 +0000325 OutputSections.push_back(Sec);
326 }
Rafael Espindola71675852015-09-22 00:16:19 +0000327 Sec->addSection(C);
Rafael Espindola19e38892015-09-16 15:54:15 +0000328 scanRelocs(*C);
329 }
330 }
331
Rafael Espindola77572242015-10-02 19:37:55 +0000332 DynamicSec.PreInitArraySec =
333 Map.lookup({".preinit_array", SHT_PREINIT_ARRAY, SHF_WRITE | SHF_ALLOC});
334 DynamicSec.InitArraySec =
335 Map.lookup({".init_array", SHT_INIT_ARRAY, SHF_WRITE | SHF_ALLOC});
336 DynamicSec.FiniArraySec =
337 Map.lookup({".fini_array", SHT_FINI_ARRAY, SHF_WRITE | SHF_ALLOC});
338
339 if (OutputSection<ELFT> *OS = DynamicSec.InitArraySec) {
Rafael Espindola0e604f92015-09-25 18:56:53 +0000340 Symtab.addSyntheticSym<ELFT>("__init_array_start", *OS, 0);
341 Symtab.addSyntheticSym<ELFT>("__init_array_end", *OS, OS->getSize());
Rafael Espindola5d413262015-10-01 21:22:26 +0000342 } else {
343 Symtab.addIgnoredSym<ELFT>("__init_array_start");
344 Symtab.addIgnoredSym<ELFT>("__init_array_end");
Rafael Espindola0e604f92015-09-25 18:56:53 +0000345 }
346
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000347 // FIXME: Try to avoid the extra walk over all global symbols.
348 std::vector<DefinedCommon<ELFT> *> CommonSymbols;
349 for (auto &P : Symtab.getSymbols()) {
350 StringRef Name = P.first;
351 SymbolBody *Body = P.second->Body;
352 if (Body->isStrongUndefined())
Rui Ueyama44f5d912015-10-01 14:46:54 +0000353 reportUndefined<ELFT>(Symtab, *Body);
Rafael Espindola05a3dd22015-09-22 23:38:23 +0000354
355 if (auto *C = dyn_cast<DefinedCommon<ELFT>>(Body))
356 CommonSymbols.push_back(C);
357 if (!includeInSymtab(*Body))
358 continue;
359 SymTabSec.addSymbol(Name);
360
361 if (needsDynamicSections() && includeInDynamicSymtab(*Body))
362 HashSec.addSymbol(Body);
363 }
364
Rafael Espindolab56cb942015-09-01 00:16:38 +0000365 // Sort the common symbols by alignment as an heuristic to pack them better.
Rui Ueyama3f4ec662015-09-25 03:48:25 +0000366 std::stable_sort(
367 CommonSymbols.begin(), CommonSymbols.end(),
368 [](const DefinedCommon<ELFT> *A, const DefinedCommon<ELFT> *B) {
369 return A->MaxAlignment > B->MaxAlignment;
370 });
371
Rafael Espindolac2d21192015-09-23 18:25:05 +0000372 uintX_t Off = BssSec.getSize();
Rafael Espindolab56cb942015-09-01 00:16:38 +0000373 for (DefinedCommon<ELFT> *C : CommonSymbols) {
Rafael Espindola05185742015-08-31 22:07:18 +0000374 const Elf_Sym &Sym = C->Sym;
Rafael Espindolaf31f9612015-09-01 01:19:12 +0000375 uintX_t Align = C->MaxAlignment;
Rafael Espindola05185742015-08-31 22:07:18 +0000376 Off = RoundUpToAlignment(Off, Align);
Rafael Espindolace8c9c02015-08-31 22:55:21 +0000377 C->OffsetInBSS = Off;
Rafael Espindola05185742015-08-31 22:07:18 +0000378 Off += Sym.st_size;
379 }
Rafael Espindolab56cb942015-09-01 00:16:38 +0000380
Rafael Espindolac2d21192015-09-23 18:25:05 +0000381 BssSec.setSize(Off);
Michael J. Spencer84487f12015-07-24 21:03:07 +0000382
Rafael Espindolafb815282015-09-11 00:30:13 +0000383 OutputSections.push_back(&SymTabSec);
Rafael Espindolab01b5742015-09-08 18:08:57 +0000384
Rafael Espindola4340aad2015-09-11 22:42:45 +0000385 if (needsDynamicSections()) {
Rafael Espindola70107762015-09-11 18:49:42 +0000386 if (needsInterpSection())
387 OutputSections.push_back(&InterpSec);
Rafael Espindolafb815282015-09-11 00:30:13 +0000388 OutputSections.push_back(&DynSymSec);
Rafael Espindola601771e2015-09-14 20:20:34 +0000389 OutputSections.push_back(&HashSec);
Rafael Espindola740fafe2015-09-08 19:43:27 +0000390 OutputSections.push_back(&DynamicSec);
Rafael Espindola3f4228f2015-09-09 15:33:08 +0000391 OutputSections.push_back(&DynStrSec);
Denis Protivensky18add762015-09-17 09:54:29 +0000392 if (RelaDynSec.hasRelocs())
Rafael Espindola19e38892015-09-16 15:54:15 +0000393 OutputSections.push_back(&RelaDynSec);
Rafael Espindola3f4228f2015-09-09 15:33:08 +0000394 }
Rafael Espindolacdfecff2015-09-23 20:08:25 +0000395 if (!GotSec.empty())
396 OutputSections.push_back(&GotSec);
397 if (!PltSec.empty())
398 OutputSections.push_back(&PltSec);
Rafael Espindola740fafe2015-09-08 19:43:27 +0000399
Rui Ueyama3f4ec662015-09-25 03:48:25 +0000400 std::stable_sort(
401 OutputSections.begin(), OutputSections.end(),
402 [](OutputSectionBase<ELFT::Is64Bits> *A,
403 OutputSectionBase<ELFT::Is64Bits> *B) {
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000404 uintX_t AFlags = A->getFlags();
405 uintX_t BFlags = B->getFlags();
406
407 // Allocatable sections go first to reduce the total PT_LOAD size and
408 // so debug info doesn't change addresses in actual code.
409 bool AIsAlloc = AFlags & SHF_ALLOC;
410 bool BIsAlloc = BFlags & SHF_ALLOC;
411 if (AIsAlloc != BIsAlloc)
412 return AIsAlloc;
413
414 // We don't have any special requirements for the relative order of
415 // two non allocatable sections.
416 if (!AIsAlloc)
417 return false;
418
419 // We want the read only sections first so that they go in the PT_LOAD
420 // covering the program headers at the start of the file.
421 bool AIsWritable = AFlags & SHF_WRITE;
422 bool BIsWritable = BFlags & SHF_WRITE;
423 if (AIsWritable != BIsWritable)
424 return BIsWritable;
425
426 // For a corresponding reason, put non exec sections first (the program
427 // header PT_LOAD is not executable).
428 bool AIsExec = AFlags & SHF_EXECINSTR;
429 bool BIsExec = BFlags & SHF_EXECINSTR;
430 if (AIsExec != BIsExec)
431 return BIsExec;
432
433 // If we got here we know that both A and B and in the same PT_LOAD.
434 // The last requirement we have is to put nobits section last. The
435 // reason is that the only thing the dynamic linker will see about
436 // them is a p_memsz that is larger than p_filesz. Seeing that it
437 // zeros the end of the PT_LOAD, so that has to correspond to the
438 // nobits sections.
439 return A->getType() != SHT_NOBITS && B->getType() == SHT_NOBITS;
Rui Ueyama3f4ec662015-09-25 03:48:25 +0000440 });
441
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000442 // Always put StrTabSec last so that no section names are added to it after
443 // it's finalized.
444 OutputSections.push_back(&StrTabSec);
445
Rafael Espindolab01b5742015-09-08 18:08:57 +0000446 for (unsigned I = 0, N = OutputSections.size(); I < N; ++I)
447 OutputSections[I]->setSectionIndex(I + 1);
Michael J. Spencer52bf0eb2015-10-01 21:15:02 +0000448
449 // Fill the DynStrSec early.
450 DynamicSec.finalize();
Rafael Espindolaabad6182015-08-13 15:23:46 +0000451}
452
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000453template <class ELFT>
Rui Ueyama04dae552015-10-02 21:23:17 +0000454static bool needsPHDR(OutputSectionBase<ELFT::Is64Bits> *Sec) {
Michael J. Spencer2f008242015-09-17 19:58:07 +0000455 return Sec->getFlags() & SHF_ALLOC;
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000456}
457
Michael J. Spencer84487f12015-07-24 21:03:07 +0000458// Visits all sections to assign incremental, non-overlapping RVAs and
459// file offsets.
460template <class ELFT> void Writer<ELFT>::assignAddresses() {
Michael J. Spencer2f008242015-09-17 19:58:07 +0000461 assert(!OutputSections.empty() && "No output sections to layout!");
Rafael Espindola4340aad2015-09-11 22:42:45 +0000462 uintX_t VA = getVAStart();
Rafael Espindola0a2e2112015-09-10 15:41:34 +0000463 uintX_t FileOff = 0;
Rafael Espindola60252d82015-09-09 22:53:55 +0000464
Rafael Espindola0a2e2112015-09-10 15:41:34 +0000465 FileOff += sizeof(Elf_Ehdr);
466 VA += sizeof(Elf_Ehdr);
Rafael Espindolaabad6182015-08-13 15:23:46 +0000467
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000468 // Reserve space for PHDRs.
469 ProgramHeaderOff = FileOff;
470 FileOff = RoundUpToAlignment(FileOff, PageSize);
Rafael Espindola0a2e2112015-09-10 15:41:34 +0000471 VA = RoundUpToAlignment(VA, PageSize);
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000472
Rafael Espindola70107762015-09-11 18:49:42 +0000473 if (needsInterpSection())
Michael J. Spencer2f008242015-09-17 19:58:07 +0000474 PHDRs.push_back(&InterpPHDR);
Rafael Espindola70107762015-09-11 18:49:42 +0000475
Michael J. Spencer2f008242015-09-17 19:58:07 +0000476 // Create a PHDR for the file header.
477 PHDRs.push_back(&FileHeaderPHDR);
478 FileHeaderPHDR.Header.p_vaddr = getVAStart();
479 FileHeaderPHDR.Header.p_paddr = getVAStart();
480 FileHeaderPHDR.Header.p_align = PageSize;
Rafael Espindola0a2e2112015-09-10 15:41:34 +0000481
Rafael Espindolaebd21082015-08-13 22:14:37 +0000482 for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) {
Rafael Espindola3f4228f2015-09-09 15:33:08 +0000483 StrTabSec.add(Sec->getName());
Rafael Espindolaebd21082015-08-13 22:14:37 +0000484 Sec->finalize();
485
Michael J. Spencer2f008242015-09-17 19:58:07 +0000486 if (Sec->getSize()) {
Rui Ueyama04dae552015-10-02 21:23:17 +0000487 uintX_t Flags = toPHDRFlags(Sec->getFlags());
488 ProgramHeader<ELFT::Is64Bits> *Last = PHDRs.back();
489 if (Last->Header.p_flags != Flags || !needsPHDR<ELFT>(Sec)) {
Michael J. Spencer2f008242015-09-17 19:58:07 +0000490 // Flags changed. End current PHDR and potentially create a new one.
Rui Ueyama04dae552015-10-02 21:23:17 +0000491 if (!Last->Closed) {
492 Last->Header.p_filesz = FileOff - Last->Header.p_offset;
493 Last->Header.p_memsz = VA - Last->Header.p_vaddr;
494 Last->Closed = true;
Michael J. Spencer2f008242015-09-17 19:58:07 +0000495 }
496
Rui Ueyama04dae552015-10-02 21:23:17 +0000497 if (needsPHDR<ELFT>(Sec)) {
Michael J. Spencer2f008242015-09-17 19:58:07 +0000498 VA = RoundUpToAlignment(VA, PageSize);
499 FileOff = RoundUpToAlignment(FileOff, PageSize);
Rui Ueyama04dae552015-10-02 21:23:17 +0000500 PHDRs.push_back(new (PAlloc) ProgramHeader<ELFT::Is64Bits>(
501 PT_LOAD, Flags, FileOff, VA));
Michael J. Spencer2f008242015-09-17 19:58:07 +0000502 }
503 }
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000504 }
505
Rafael Espindola2db634d2015-08-13 20:24:18 +0000506 uintX_t Align = Sec->getAlign();
507 uintX_t Size = Sec->getSize();
Rafael Espindolaef1ac012015-08-13 15:31:17 +0000508 if (Sec->getFlags() & SHF_ALLOC) {
Rafael Espindolabfcdfb32015-09-14 19:00:35 +0000509 VA = RoundUpToAlignment(VA, Align);
Rafael Espindolaef1ac012015-08-13 15:31:17 +0000510 Sec->setVA(VA);
Rafael Espindolabfcdfb32015-09-14 19:00:35 +0000511 VA += Size;
Rafael Espindolaef1ac012015-08-13 15:31:17 +0000512 }
Rafael Espindolabfcdfb32015-09-14 19:00:35 +0000513 FileOff = RoundUpToAlignment(FileOff, Align);
Michael J. Spencer84487f12015-07-24 21:03:07 +0000514 Sec->setFileOffset(FileOff);
Rafael Espindola058f3432015-08-31 20:23:57 +0000515 if (Sec->getType() != SHT_NOBITS)
Rafael Espindolabfcdfb32015-09-14 19:00:35 +0000516 FileOff += Size;
Michael J. Spencer84487f12015-07-24 21:03:07 +0000517 }
Rafael Espindola6b83b902015-08-12 00:00:24 +0000518
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000519 // Add a PHDR for the dynamic table.
Rafael Espindola4340aad2015-09-11 22:42:45 +0000520 if (needsDynamicSections())
Michael J. Spencer2f008242015-09-17 19:58:07 +0000521 PHDRs.push_back(&DynamicPHDR);
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000522
Rafael Espindola91009b32015-08-12 01:45:28 +0000523 FileOff += OffsetToAlignment(FileOff, ELFT::Is64Bits ? 8 : 4);
524
Michael J. Spencer8039dae22015-07-29 00:30:10 +0000525 // Add space for section headers.
526 SectionHeaderOff = FileOff;
Rafael Espindola18608a02015-09-08 21:57:31 +0000527 FileOff += getNumSections() * sizeof(Elf_Shdr);
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000528 FileSize = FileOff;
Michael J. Spencer84487f12015-07-24 21:03:07 +0000529}
530
531template <class ELFT> void Writer<ELFT>::writeHeader() {
532 uint8_t *Buf = Buffer->getBufferStart();
Rafael Espindola18608a02015-09-08 21:57:31 +0000533 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
Michael J. Spencer84487f12015-07-24 21:03:07 +0000534 EHdr->e_ident[EI_MAG0] = 0x7F;
535 EHdr->e_ident[EI_MAG1] = 0x45;
536 EHdr->e_ident[EI_MAG2] = 0x4C;
537 EHdr->e_ident[EI_MAG3] = 0x46;
Rafael Espindola4b7c2fc2015-08-05 15:08:40 +0000538 EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
539 EHdr->e_ident[EI_DATA] = ELFT::TargetEndianness == llvm::support::little
540 ? ELFDATA2LSB
541 : ELFDATA2MSB;
Michael J. Spencer84487f12015-07-24 21:03:07 +0000542 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
Davide Italianoaa7c5332015-09-25 01:59:13 +0000543
544 const SymbolTable &Symtab = SymTabSec.getSymTable();
545 auto &FirstObj = cast<ObjectFile<ELFT>>(*Symtab.getFirstELF());
546 EHdr->e_ident[EI_OSABI] = FirstObj.getOSABI();
Michael J. Spencer84487f12015-07-24 21:03:07 +0000547
Rafael Espindolae438e072015-09-08 22:55:28 +0000548 // FIXME: Generalize the segment construction similar to how we create
549 // output sections.
Rafael Espindolae438e072015-09-08 22:55:28 +0000550
Rafael Espindola4340aad2015-09-11 22:42:45 +0000551 EHdr->e_type = Config->Shared ? ET_DYN : ET_EXEC;
Rafael Espindolaf98d6d82015-09-03 20:03:54 +0000552 EHdr->e_machine = FirstObj.getEMachine();
Michael J. Spencer84487f12015-07-24 21:03:07 +0000553 EHdr->e_version = EV_CURRENT;
Rafael Espindola4340aad2015-09-11 22:42:45 +0000554 SymbolBody *Entry = Symtab.getEntrySym();
Rafael Espindolacd076f02015-09-25 18:19:03 +0000555 EHdr->e_entry =
556 Entry ? getSymVA(cast<ELFSymbolBody<ELFT>>(*Entry), BssSec) : 0;
Michael J. Spencer1d299a82015-09-09 20:48:09 +0000557 EHdr->e_phoff = ProgramHeaderOff;
Michael J. Spencer8039dae22015-07-29 00:30:10 +0000558 EHdr->e_shoff = SectionHeaderOff;
Rafael Espindola18608a02015-09-08 21:57:31 +0000559 EHdr->e_ehsize = sizeof(Elf_Ehdr);
560 EHdr->e_phentsize = sizeof(Elf_Phdr);
Michael J. Spencer2f008242015-09-17 19:58:07 +0000561 EHdr->e_phnum = PHDRs.size();
Rafael Espindola18608a02015-09-08 21:57:31 +0000562 EHdr->e_shentsize = sizeof(Elf_Shdr);
Rafael Espindola5f553872015-09-08 17:39:39 +0000563 EHdr->e_shnum = getNumSections();
Rafael Espindola3f4228f2015-09-09 15:33:08 +0000564 EHdr->e_shstrndx = StrTabSec.getSectionIndex();
Michael J. Spencer84487f12015-07-24 21:03:07 +0000565
Michael J. Spencer2f008242015-09-17 19:58:07 +0000566 // If nothing was merged into the file header PT_LOAD, set the size correctly.
567 if (FileHeaderPHDR.Header.p_filesz == PageSize)
568 FileHeaderPHDR.Header.p_filesz = FileHeaderPHDR.Header.p_memsz =
569 sizeof(Elf_Ehdr) + sizeof(Elf_Phdr) * PHDRs.size();
570
571 if (needsInterpSection())
572 InterpPHDR.setValuesFromSection(InterpSec);
573 if (needsDynamicSections())
574 DynamicPHDR.setValuesFromSection(DynamicSec);
575
Rafael Espindola18608a02015-09-08 21:57:31 +0000576 auto PHdrs = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
Michael J. Spencer2f008242015-09-17 19:58:07 +0000577 for (ProgramHeader<ELFT::Is64Bits> *PHDR : PHDRs)
578 PHDR->template writeHeaderTo<ELFT::TargetEndianness>(PHdrs++);
Rafael Espindolae438e072015-09-08 22:55:28 +0000579
Rafael Espindola18608a02015-09-08 21:57:31 +0000580 auto SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
Michael J. Spencer8039dae22015-07-29 00:30:10 +0000581 // First entry is null.
582 ++SHdrs;
Rafael Espindolaebd21082015-08-13 22:14:37 +0000583 for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections) {
Rafael Espindola3f4228f2015-09-09 15:33:08 +0000584 Sec->setNameOffset(StrTabSec.getFileOff(Sec->getName()));
Rafael Espindolaa175eb62015-08-13 18:37:23 +0000585 Sec->template writeHeaderTo<ELFT::TargetEndianness>(SHdrs++);
Rafael Espindola6b83b902015-08-12 00:00:24 +0000586 }
Michael J. Spencer84487f12015-07-24 21:03:07 +0000587}
588
589template <class ELFT> void Writer<ELFT>::openFile(StringRef Path) {
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +0000590 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
591 FileOutputBuffer::create(Path, FileSize, FileOutputBuffer::F_executable);
592 error(BufferOrErr, Twine("failed to open ") + Path);
593 Buffer = std::move(*BufferOrErr);
Michael J. Spencer84487f12015-07-24 21:03:07 +0000594}
595
596// Write section contents to a mmap'ed file.
597template <class ELFT> void Writer<ELFT>::writeSections() {
598 uint8_t *Buf = Buffer->getBufferStart();
Rafael Espindolaebd21082015-08-13 22:14:37 +0000599 for (OutputSectionBase<ELFT::Is64Bits> *Sec : OutputSections)
Rui Ueyama8050d322015-08-14 05:17:30 +0000600 Sec->writeTo(Buf + Sec->getFileOff());
Michael J. Spencer84487f12015-07-24 21:03:07 +0000601}