blob: 03dc358a3676b7a7375cd55a8f8def6ad7a94080 [file] [log] [blame]
Michael J. Spencer84487f12015-07-24 21:03:07 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Michael J. Spencerf8325412015-09-04 22:48:30 +000010#include "Writer.h"
Rui Ueyamacb8474ed2015-08-05 23:51:50 +000011#include "Config.h"
Rui Ueyama9b55e922017-03-24 00:15:16 +000012#include "Filesystem.h"
Rui Ueyama717677a2016-02-11 21:17:59 +000013#include "LinkerScript.h"
Rafael Espindola1ebfc592017-01-13 21:05:46 +000014#include "MapFile.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000015#include "Memory.h"
Rafael Espindola5805c4f2015-09-21 21:38:08 +000016#include "OutputSections.h"
Rui Ueyama0fcdc732016-05-24 20:24:43 +000017#include "Relocations.h"
Rui Ueyamafbbde542016-06-29 09:08:02 +000018#include "Strings.h"
Rui Ueyamaafff74e22015-08-05 23:24:46 +000019#include "SymbolTable.h"
Rui Ueyama6dc7fcb2016-11-01 20:28:21 +000020#include "SyntheticSections.h"
Rafael Espindola01205f72015-09-22 18:19:46 +000021#include "Target.h"
Denis Protivensky8e3b38a2015-11-12 09:52:08 +000022#include "llvm/ADT/StringMap.h"
Hal Finkel3bae2d82015-10-12 20:51:48 +000023#include "llvm/ADT/StringSwitch.h"
Rui Ueyamaafff74e22015-08-05 23:24:46 +000024#include "llvm/Support/FileOutputBuffer.h"
Rafael Espindolad0078b22016-02-06 00:06:26 +000025#include "llvm/Support/raw_ostream.h"
Rui Ueyamae8b2df42016-09-29 01:45:22 +000026#include <climits>
Michael J. Spencer84487f12015-07-24 21:03:07 +000027
28using namespace llvm;
29using namespace llvm::ELF;
30using namespace llvm::object;
Peter Smith0a259f32016-10-10 09:39:26 +000031using namespace llvm::support;
32using namespace llvm::support::endian;
Michael J. Spencer84487f12015-07-24 21:03:07 +000033
34using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000035using namespace lld::elf;
Michael J. Spencer84487f12015-07-24 21:03:07 +000036
Rui Ueyamaafff74e22015-08-05 23:24:46 +000037namespace {
38// The writer writes a SymbolTable result to a file.
39template <class ELFT> class Writer {
40public:
Rui Ueyama9328b2c2016-03-14 23:16:09 +000041 typedef typename ELFT::uint uintX_t;
42 typedef typename ELFT::Shdr Elf_Shdr;
43 typedef typename ELFT::Ehdr Elf_Ehdr;
44 typedef typename ELFT::Phdr Elf_Phdr;
45 typedef typename ELFT::Sym Elf_Sym;
46 typedef typename ELFT::SymRange Elf_Sym_Range;
47 typedef typename ELFT::Rela Elf_Rela;
Rui Ueyamaafff74e22015-08-05 23:24:46 +000048 void run();
49
50private:
Rui Ueyamaf83aca42016-11-01 23:17:45 +000051 void createSyntheticSections();
Rui Ueyama5a9640b2015-10-08 23:49:30 +000052 void copyLocalSymbols();
Rafael Espindola08d6a3f2017-02-11 01:40:49 +000053 void addSectionSymbols();
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +000054 void addReservedSymbols();
George Rimar9e694502016-07-29 16:18:47 +000055 void createSections();
Rafael Espindolab4c9b812017-02-23 02:28:28 +000056 void forEachRelSec(std::function<void(InputSectionBase &)> Fn);
Rafael Espindola24c073d2016-09-21 22:36:19 +000057 void sortSections();
Eugene Leviante63d81b2016-07-20 14:43:20 +000058 void finalizeSections();
Rui Ueyama84417f82015-12-26 07:50:41 +000059 void addPredefinedSections();
Rui Ueyama2df0fd82015-12-25 07:38:58 +000060
Rafael Espindola17cb7c02016-12-19 17:01:01 +000061 std::vector<PhdrEntry> createPhdrs();
Rafael Espindola074ba932016-12-06 13:43:34 +000062 void removeEmptyPTLoad();
Rafael Espindola17cb7c02016-12-19 17:01:01 +000063 void addPtArmExid(std::vector<PhdrEntry> &Phdrs);
Rui Ueyamaafff74e22015-08-05 23:24:46 +000064 void assignAddresses();
Rui Ueyamae044e9c2016-04-01 17:07:17 +000065 void assignFileOffsets();
George Rimar86ce2672016-08-25 09:05:47 +000066 void assignFileOffsetsBinary();
Rui Ueyamae044e9c2016-04-01 17:07:17 +000067 void setPhdrs();
George Rimar7ca06272016-04-06 07:20:45 +000068 void fixHeaders();
Rui Ueyama47091902016-03-30 19:41:51 +000069 void fixSectionAlignments();
Rafael Espindola78493a22017-01-28 17:48:21 +000070 void fixPredefinedSymbols();
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +000071 void openFile();
Rui Ueyamaafff74e22015-08-05 23:24:46 +000072 void writeHeader();
73 void writeSections();
George Rimar86ce2672016-08-25 09:05:47 +000074 void writeSectionsBinary();
Rui Ueyama634ddf02016-03-11 20:51:53 +000075 void writeBuildId();
Rui Ueyamaafff74e22015-08-05 23:24:46 +000076
Rui Ueyama818bb2f2016-07-16 18:55:47 +000077 std::unique_ptr<FileOutputBuffer> Buffer;
Michael J. Spencer2f008242015-09-17 19:58:07 +000078
Rafael Espindola24e6f362017-02-24 15:07:30 +000079 std::vector<OutputSection *> OutputSections;
Rui Ueyama02a036f2017-02-27 02:31:48 +000080 OutputSectionFactory Factory{OutputSections};
Rafael Espindola4fc60442016-02-10 22:43:13 +000081
Rui Ueyama01687222015-12-26 09:47:57 +000082 void addRelIpltSymbols();
Rui Ueyamaa5d79d12015-12-26 09:48:00 +000083 void addStartEndSymbols();
Rafael Espindola24e6f362017-02-24 15:07:30 +000084 void addStartStopSymbols(OutputSection *Sec);
Rui Ueyama2eda6d12016-11-23 22:41:00 +000085 uintX_t getEntryAddr();
Rafael Espindola24e6f362017-02-24 15:07:30 +000086 OutputSection *findSection(StringRef Name);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +000087
Rafael Espindola17cb7c02016-12-19 17:01:01 +000088 std::vector<PhdrEntry> 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;
Rafael Espindola5967c972016-12-19 21:21:07 +000092 bool AllocateHeader = true;
Rui Ueyamaafff74e22015-08-05 23:24:46 +000093};
94} // anonymous namespace
95
Rui Ueyama55518e72016-10-28 20:57:25 +000096StringRef elf::getOutputSectionName(StringRef Name) {
Eugene Levianta8d12ef2016-10-05 10:10:45 +000097 if (Config->Relocatable)
98 return Name;
99
Rui Ueyama5acac352017-02-17 00:40:44 +0000100 // If -emit-relocs is given (which is rare), we need to copy
101 // relocation sections to the output. If input section .foo is
102 // output as .bar, we want to rename .rel.foo .rel.bar as well.
Rafael Espindolaee61d352017-02-17 00:28:17 +0000103 if (Config->EmitRelocs) {
104 for (StringRef V : {".rel.", ".rela."}) {
105 if (Name.startswith(V)) {
106 StringRef Inner = getOutputSectionName(Name.substr(V.size() - 1));
107 return Saver.save(Twine(V.drop_back()) + Inner);
108 }
109 }
110 }
111
Rafael Espindola7d382732016-09-19 19:59:21 +0000112 for (StringRef V :
George Rimar1ab9cf42017-03-17 10:14:53 +0000113 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
114 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
Rafael Espindola7d382732016-09-19 19:59:21 +0000115 ".gcc_except_table.", ".tdata.", ".ARM.exidx."}) {
116 StringRef Prefix = V.drop_back();
117 if (Name.startswith(V) || Name == Prefix)
118 return Prefix;
119 }
Rui Ueyama05384082016-10-12 22:36:31 +0000120
Rui Ueyamae8a61022016-11-05 23:05:47 +0000121 // CommonSection is identified as "COMMON" in linker scripts.
122 // By default, it should go to .bss section.
123 if (Name == "COMMON")
124 return ".bss";
125
Rui Ueyama05384082016-10-12 22:36:31 +0000126 // ".zdebug_" is a prefix for ZLIB-compressed sections.
127 // Because we decompressed input sections, we want to remove 'z'.
128 if (Name.startswith(".zdebug_"))
Rui Ueyama55518e72016-10-28 20:57:25 +0000129 return Saver.save(Twine(".") + Name.substr(2));
George Rimar5d53d1f2016-07-12 08:50:42 +0000130 return Name;
131}
132
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000133template <class ELFT> static bool needsInterpSection() {
134 return !Symtab<ELFT>::X->getSharedFiles().empty() &&
George Rimara8dba482017-03-20 10:09:58 +0000135 !Config->DynamicLinker.empty() && !Script->ignoreInterpSection();
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000136}
137
George Rimard8b27762016-11-14 10:14:18 +0000138template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
Rafael Espindola4fc60442016-02-10 22:43:13 +0000139
Rafael Espindola074ba932016-12-06 13:43:34 +0000140template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000141 auto I = std::remove_if(Phdrs.begin(), Phdrs.end(), [&](const PhdrEntry &P) {
142 if (P.p_type != PT_LOAD)
Rafael Espindola074ba932016-12-06 13:43:34 +0000143 return false;
Rafael Espindola41217612016-12-08 03:17:05 +0000144 if (!P.First)
145 return true;
Rafael Espindola074ba932016-12-06 13:43:34 +0000146 uintX_t Size = P.Last->Addr + P.Last->Size - P.First->Addr;
147 return Size == 0;
148 });
149 Phdrs.erase(I, Phdrs.end());
150}
151
Rafael Espindola9e9754b2017-02-03 13:06:18 +0000152template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000153static typename ELFT::uint getOutFlags(InputSectionBase *S) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +0000154 return S->Flags & ~(typename ELFT::uint)(SHF_GROUP | SHF_COMPRESSED);
155}
156
157// This function scans over the input sections and creates mergeable
158// synthetic sections. It removes MergeInputSections from array and
159// adds new synthetic ones. Each synthetic section is added to the
160// location of the first input section it replaces.
161template <class ELFT> static void combineMergableSections() {
162 typedef typename ELFT::uint uintX_t;
163
Rafael Espindola6119b862017-03-06 20:23:56 +0000164 std::vector<MergeSyntheticSection *> MergeSections;
Rui Ueyama536a2672017-02-27 02:32:08 +0000165 for (InputSectionBase *&S : InputSections) {
Rafael Espindola6119b862017-03-06 20:23:56 +0000166 MergeInputSection *MS = dyn_cast<MergeInputSection>(S);
Rafael Espindola9e9754b2017-02-03 13:06:18 +0000167 if (!MS)
168 continue;
169
170 // We do not want to handle sections that are not alive, so just remove
171 // them instead of trying to merge.
172 if (!MS->Live)
173 continue;
174
175 StringRef OutsecName = getOutputSectionName(MS->Name);
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000176 uintX_t Flags = getOutFlags<ELFT>(MS);
Rafael Espindolafcd208f2017-03-08 19:35:29 +0000177 uint32_t Alignment = std::max<uintX_t>(MS->Alignment, MS->Entsize);
Rafael Espindola9e9754b2017-02-03 13:06:18 +0000178
179 auto I =
Rafael Espindola6119b862017-03-06 20:23:56 +0000180 llvm::find_if(MergeSections, [=](MergeSyntheticSection *Sec) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +0000181 return Sec->Name == OutsecName && Sec->Flags == Flags &&
182 Sec->Alignment == Alignment;
183 });
184 if (I == MergeSections.end()) {
Rafael Espindola6119b862017-03-06 20:23:56 +0000185 MergeSyntheticSection *Syn =
186 make<MergeSyntheticSection>(OutsecName, MS->Type, Flags, Alignment);
Rafael Espindola9e9754b2017-02-03 13:06:18 +0000187 MergeSections.push_back(Syn);
188 I = std::prev(MergeSections.end());
189 S = Syn;
190 } else {
191 S = nullptr;
192 }
193 (*I)->addSection(MS);
194 }
195
Rui Ueyama536a2672017-02-27 02:32:08 +0000196 std::vector<InputSectionBase *> &V = InputSections;
Rafael Espindola9e9754b2017-02-03 13:06:18 +0000197 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
198}
199
Petr Hosek7b793212017-03-10 20:00:42 +0000200template <class ELFT> static void combineEhFrameSections() {
201 for (InputSectionBase *&S : InputSections) {
202 EhInputSection *ES = dyn_cast<EhInputSection>(S);
Rafael Espindolaa1565552017-03-15 12:31:54 +0000203 if (!ES || !ES->Live)
Petr Hosek7b793212017-03-10 20:00:42 +0000204 continue;
205
206 In<ELFT>::EhFrame->addSection(ES);
207 S = nullptr;
208 }
209
210 std::vector<InputSectionBase *> &V = InputSections;
211 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
212}
213
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000214// The main function of the writer.
215template <class ELFT> void Writer<ELFT>::run() {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000216 // Create linker-synthesized sections such as .got or .plt.
217 // Such sections are of type input section.
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000218 createSyntheticSections();
Rafael Espindola9e9754b2017-02-03 13:06:18 +0000219 combineMergableSections<ELFT>();
George Rimar7beff422016-11-15 08:19:02 +0000220
Petr Hosek7b793212017-03-10 20:00:42 +0000221 if (!Config->Relocatable)
222 combineEhFrameSections<ELFT>();
223
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000224 // We need to create some reserved symbols such as _end. Create them.
George Rimar7beff422016-11-15 08:19:02 +0000225 if (!Config->Relocatable)
226 addReservedSymbols();
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000227
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000228 // Create output sections.
George Rimara8dba482017-03-20 10:09:58 +0000229 Script->OutputSections = &OutputSections;
Rui Ueyamaa34da932017-03-21 23:03:09 +0000230 if (Script->Opt.HasSections) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000231 // If linker script contains SECTIONS commands, let it create sections.
George Rimara8dba482017-03-20 10:09:58 +0000232 Script->processCommands(Factory);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000233
234 // Linker scripts may have left some input sections unassigned.
235 // Assign such sections using the default rule.
George Rimara8dba482017-03-20 10:09:58 +0000236 Script->addOrphanSections(Factory);
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000237 } else {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000238 // If linker script does not contain SECTIONS commands, create
239 // output sections by default rules. We still need to give the
240 // linker script a chance to run, because it might contain
241 // non-SECTIONS commands such as ASSERT.
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000242 createSections();
George Rimara8dba482017-03-20 10:09:58 +0000243 Script->processCommands(Factory);
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000244 }
245
246 if (Config->Discard != DiscardPolicy::All)
247 copyLocalSymbols();
248
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000249 if (Config->CopyRelocs)
Rafael Espindola08d6a3f2017-02-11 01:40:49 +0000250 addSectionSymbols();
251
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000252 // Now that we have a complete set of output sections. This function
253 // completes section contents. For example, we need to add strings
254 // to the string table, and add entries to .got and .plt.
255 // finalizeSections does that.
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000256 finalizeSections();
Rui Ueyamaf373dd72016-11-24 01:43:21 +0000257 if (ErrorCount)
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000258 return;
259
260 if (Config->Relocatable) {
261 assignFileOffsets();
262 } else {
Rui Ueyamaa34da932017-03-21 23:03:09 +0000263 if (Script->Opt.HasSections) {
George Rimara8dba482017-03-20 10:09:58 +0000264 Script->assignAddresses(Phdrs);
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000265 } else {
266 fixSectionAlignments();
267 assignAddresses();
George Rimara8dba482017-03-20 10:09:58 +0000268 Script->processNonSectionCommands();
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000269 }
270
Rafael Espindola074ba932016-12-06 13:43:34 +0000271 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
272 // 0 sized region. This has to be done late since only after assignAddresses
273 // we know the size of the sections.
274 removeEmptyPTLoad();
275
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000276 if (!Config->OFormatBinary)
277 assignFileOffsets();
278 else
279 assignFileOffsetsBinary();
280
281 setPhdrs();
Rafael Espindola78493a22017-01-28 17:48:21 +0000282 fixPredefinedSymbols();
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000283 }
284
George Rimar2ddab6d2017-01-17 13:50:34 +0000285 // It does not make sense try to open the file if we have error already.
286 if (ErrorCount)
287 return;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000288 // Write the result down to a file.
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000289 openFile();
Rui Ueyamaf373dd72016-11-24 01:43:21 +0000290 if (ErrorCount)
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000291 return;
292 if (!Config->OFormatBinary) {
293 writeHeader();
294 writeSections();
295 } else {
296 writeSectionsBinary();
297 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000298
299 // Backfill .note.gnu.build-id section content. This is done at last
300 // because the content is usually a hash value of the entire output file.
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000301 writeBuildId();
Rui Ueyamaf373dd72016-11-24 01:43:21 +0000302 if (ErrorCount)
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000303 return;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000304
Rui Ueyama40eaa992017-01-18 03:34:38 +0000305 // Handle -Map option.
Rafael Espindola1ebfc592017-01-13 21:05:46 +0000306 writeMapFile<ELFT>(OutputSections);
Rui Ueyama40eaa992017-01-18 03:34:38 +0000307 if (ErrorCount)
308 return;
309
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000310 if (auto EC = Buffer->commit())
Rui Ueyamac8d3a832017-01-12 22:18:04 +0000311 error("failed to write to the output file: " + EC.message());
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000312
313 // Flush the output streams and exit immediately. A full shutdown
314 // is a good test that we are keeping track of all allocated memory,
315 // but actually freeing it is a waste of time in a regular linker run.
316 if (Config->ExitEarly)
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000317 exitLld(0);
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000318}
319
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000320// Initialize Out members.
Rui Ueyamaf83aca42016-11-01 23:17:45 +0000321template <class ELFT> void Writer<ELFT>::createSyntheticSections() {
322 // Initialize all pointers with NULL. This is needed because
323 // you can call lld::elf::main more than once as a library.
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000324 memset(&Out::First, 0, sizeof(Out));
Rui Ueyamacfadbd92016-11-01 23:12:51 +0000325
Rui Ueyama536a2672017-02-27 02:32:08 +0000326 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000327
George Rimar49648002017-03-15 09:32:36 +0000328 In<ELFT>::DynStrTab = make<StringTableSection>(".dynstr", true);
Eugene Leviant6380ce22016-11-15 12:26:55 +0000329 In<ELFT>::Dynamic = make<DynamicSection<ELFT>>();
Eugene Levianta96d9022016-11-16 10:02:27 +0000330 In<ELFT>::RelaDyn = make<RelocationSection<ELFT>>(
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000331 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
George Rimar49648002017-03-15 09:32:36 +0000332 In<ELFT>::ShStrTab = make<StringTableSection>(".shstrtab", false);
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000333
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000334 Out::ElfHeader = make<OutputSection>("", 0, SHF_ALLOC);
335 Out::ElfHeader->Size = sizeof(Elf_Ehdr);
336 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
337 Out::ProgramHeaders->updateAlignment(sizeof(uintX_t));
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000338
Rui Ueyamae8a61022016-11-05 23:05:47 +0000339 if (needsInterpSection<ELFT>()) {
Rui Ueyama3255a522017-02-27 02:32:49 +0000340 In<ELFT>::Interp = createInterpSection();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000341 Add(In<ELFT>::Interp);
Rui Ueyamae8a61022016-11-05 23:05:47 +0000342 } else {
343 In<ELFT>::Interp = nullptr;
344 }
Rui Ueyama3a41be22016-04-07 22:49:21 +0000345
George Rimar3fb5a6d2016-11-29 16:05:27 +0000346 if (!Config->Relocatable)
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000347 Add(createCommentSection<ELFT>());
Rui Ueyama3b31e672016-05-23 16:24:16 +0000348
George Rimarf21aade2016-08-31 08:38:11 +0000349 if (Config->Strip != StripPolicy::All) {
George Rimar49648002017-03-15 09:32:36 +0000350 In<ELFT>::StrTab = make<StringTableSection>(".strtab", false);
Eugene Leviant9230db92016-11-17 09:16:34 +0000351 In<ELFT>::SymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::StrTab);
Rui Ueyama4197a6a2016-02-05 18:41:40 +0000352 }
Rui Ueyamacfadbd92016-11-01 23:12:51 +0000353
Rui Ueyamac4030a12016-11-22 00:54:15 +0000354 if (Config->BuildId != BuildIdKind::None) {
George Rimar6c2949d2017-03-20 16:40:21 +0000355 In<ELFT>::BuildId = make<BuildIdSection>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000356 Add(In<ELFT>::BuildId);
Rui Ueyamac4030a12016-11-22 00:54:15 +0000357 }
Rui Ueyamae8a61022016-11-05 23:05:47 +0000358
George Rimar176d6062017-03-17 13:31:07 +0000359 In<ELFT>::Common = createCommonSection<ELFT>();
360 if (In<ELFT>::Common)
361 Add(InX::Common);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000362
George Rimar1ab9cf42017-03-17 10:14:53 +0000363 In<ELFT>::Bss = make<BssSection>(".bss");
364 Add(In<ELFT>::Bss);
365 In<ELFT>::BssRelRo = make<BssSection>(".bss.rel.ro");
366 Add(In<ELFT>::BssRelRo);
367
Rui Ueyama1d75de02016-11-22 04:28:39 +0000368 // Add MIPS-specific sections.
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000369 bool HasDynSymTab = !Symtab<ELFT>::X->getSharedFiles().empty() ||
370 Config->Pic || Config->ExportDynamic;
Simon Atanasyance02cf02016-11-09 21:36:56 +0000371 if (Config->EMachine == EM_MIPS) {
George Rimar11992c862016-11-25 08:05:41 +0000372 if (!Config->Shared && HasDynSymTab) {
George Rimar42886c42017-03-15 12:02:31 +0000373 In<ELFT>::MipsRldMap = make<MipsRldMapSection>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000374 Add(In<ELFT>::MipsRldMap);
Eugene Leviant17b7a572016-11-22 17:49:14 +0000375 }
Rui Ueyama1d75de02016-11-22 04:28:39 +0000376 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000377 Add(Sec);
Rui Ueyama1d75de02016-11-22 04:28:39 +0000378 if (auto *Sec = MipsOptionsSection<ELFT>::create())
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000379 Add(Sec);
Rui Ueyama1d75de02016-11-22 04:28:39 +0000380 if (auto *Sec = MipsReginfoSection<ELFT>::create())
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000381 Add(Sec);
Simon Atanasyance02cf02016-11-09 21:36:56 +0000382 }
Eugene Leviant41ca3272016-11-10 09:48:29 +0000383
George Rimar11992c862016-11-25 08:05:41 +0000384 if (HasDynSymTab) {
385 In<ELFT>::DynSymTab = make<SymbolTableSection<ELFT>>(*In<ELFT>::DynStrTab);
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000386 Add(In<ELFT>::DynSymTab);
George Rimar11992c862016-11-25 08:05:41 +0000387
388 In<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000389 Add(In<ELFT>::VerSym);
George Rimar11992c862016-11-25 08:05:41 +0000390
391 if (!Config->VersionDefinitions.empty()) {
392 In<ELFT>::VerDef = make<VersionDefinitionSection<ELFT>>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000393 Add(In<ELFT>::VerDef);
George Rimar11992c862016-11-25 08:05:41 +0000394 }
395
396 In<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000397 Add(In<ELFT>::VerNeed);
George Rimar11992c862016-11-25 08:05:41 +0000398
399 if (Config->GnuHash) {
400 In<ELFT>::GnuHashTab = make<GnuHashTableSection<ELFT>>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000401 Add(In<ELFT>::GnuHashTab);
George Rimar11992c862016-11-25 08:05:41 +0000402 }
403
404 if (Config->SysvHash) {
405 In<ELFT>::HashTab = make<HashTableSection<ELFT>>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000406 Add(In<ELFT>::HashTab);
George Rimar11992c862016-11-25 08:05:41 +0000407 }
408
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000409 Add(In<ELFT>::Dynamic);
410 Add(In<ELFT>::DynStrTab);
411 Add(In<ELFT>::RelaDyn);
George Rimar11992c862016-11-25 08:05:41 +0000412 }
413
Rui Ueyama1d75de02016-11-22 04:28:39 +0000414 // Add .got. MIPS' .got is so different from the other archs,
415 // it has its own class.
George Rimar11992c862016-11-25 08:05:41 +0000416 if (Config->EMachine == EM_MIPS) {
George Rimar14534eb2017-03-20 16:44:28 +0000417 In<ELFT>::MipsGot = make<MipsGotSection>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000418 Add(In<ELFT>::MipsGot);
George Rimar11992c862016-11-25 08:05:41 +0000419 } else {
Simon Atanasyan725dc142016-11-16 21:01:02 +0000420 In<ELFT>::Got = make<GotSection<ELFT>>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000421 Add(In<ELFT>::Got);
George Rimar11992c862016-11-25 08:05:41 +0000422 }
Simon Atanasyan725dc142016-11-16 21:01:02 +0000423
George Rimar10f74fc2017-03-15 09:12:56 +0000424 In<ELFT>::GotPlt = make<GotPltSection>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000425 Add(In<ELFT>::GotPlt);
George Rimar10f74fc2017-03-15 09:12:56 +0000426 In<ELFT>::IgotPlt = make<IgotPltSection>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000427 Add(In<ELFT>::IgotPlt);
George Rimar3fb5a6d2016-11-29 16:05:27 +0000428
429 if (Config->GdbIndex) {
George Rimar35e846e2017-03-21 08:19:34 +0000430 In<ELFT>::GdbIndex = make<GdbIndexSection>();
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000431 Add(In<ELFT>::GdbIndex);
George Rimar3fb5a6d2016-11-29 16:05:27 +0000432 }
433
434 // We always need to add rel[a].plt to output if it has entries.
435 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
436 In<ELFT>::RelaPlt = make<RelocationSection<ELFT>>(
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000437 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000438 Add(In<ELFT>::RelaPlt);
George Rimar3fb5a6d2016-11-29 16:05:27 +0000439
Peter Smithbaffdb82016-12-08 12:58:55 +0000440 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
441 // that the IRelative relocations are processed last by the dynamic loader
442 In<ELFT>::RelaIplt = make<RelocationSection<ELFT>>(
443 (Config->EMachine == EM_ARM) ? ".rel.dyn" : In<ELFT>::RelaPlt->Name,
444 false /*Sort*/);
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000445 Add(In<ELFT>::RelaIplt);
Peter Smithbaffdb82016-12-08 12:58:55 +0000446
George Rimardfc020e2017-03-17 11:01:57 +0000447 In<ELFT>::Plt = make<PltSection>(Target->PltHeaderSize);
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000448 Add(In<ELFT>::Plt);
George Rimardfc020e2017-03-17 11:01:57 +0000449 In<ELFT>::Iplt = make<PltSection>(0);
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000450 Add(In<ELFT>::Iplt);
George Rimar3fb5a6d2016-11-29 16:05:27 +0000451
Rafael Espindola66b4e212017-02-23 22:06:28 +0000452 if (!Config->Relocatable) {
George Rimar1c74c2f2017-03-09 08:45:25 +0000453 if (Config->EhFrameHdr) {
454 In<ELFT>::EhFrameHdr = make<EhFrameHeader<ELFT>>();
455 Add(In<ELFT>::EhFrameHdr);
456 }
Rafael Espindola66b4e212017-02-23 22:06:28 +0000457 In<ELFT>::EhFrame = make<EhFrameSection<ELFT>>();
458 Add(In<ELFT>::EhFrame);
459 }
460
George Rimar1e799942017-01-13 16:18:15 +0000461 if (In<ELFT>::SymTab)
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000462 Add(In<ELFT>::SymTab);
463 Add(In<ELFT>::ShStrTab);
George Rimar1e799942017-01-13 16:18:15 +0000464 if (In<ELFT>::StrTab)
Rui Ueyama7ddd7a82017-02-05 05:18:58 +0000465 Add(In<ELFT>::StrTab);
Michael J. Spencer84487f12015-07-24 21:03:07 +0000466}
467
Rafael Espindola5616adf2017-03-08 22:36:28 +0000468static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000469 const SymbolBody &B) {
Rafael Espindola08d6a3f2017-02-11 01:40:49 +0000470 if (B.isFile() || B.isSection())
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000471 return false;
472
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000473 // If sym references a section in a discarded group, don't keep it.
Rafael Espindola774ea7d2017-02-23 16:49:07 +0000474 if (Sec == &InputSection::Discarded)
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000475 return false;
476
George Rimar9503f6d2016-08-31 08:46:30 +0000477 if (Config->Discard == DiscardPolicy::None)
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000478 return true;
479
480 // In ELF assembly .L symbols are normally discarded by the assembler.
481 // If the assembler fails to do so, the linker discards them if
482 // * --discard-locals is used.
483 // * The symbol is in a SHF_MERGE section, which is normally the reason for
484 // the assembler keeping the .L symbol.
485 if (!SymName.startswith(".L") && !SymName.empty())
486 return true;
487
George Rimar9503f6d2016-08-31 08:46:30 +0000488 if (Config->Discard == DiscardPolicy::Locals)
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000489 return false;
490
Rafael Espindola1854a8e2016-10-26 12:36:56 +0000491 return !Sec || !(Sec->Flags & SHF_MERGE);
Rafael Espindola10d71ff2016-01-27 18:04:26 +0000492}
493
George Rimar7702bc22017-03-16 11:20:02 +0000494static bool includeInSymtab(const SymbolBody &B) {
Rafael Espindola474eb012016-05-05 16:40:28 +0000495 if (!B.isLocal() && !B.symbol()->IsUsedInRegularObj)
496 return false;
497
Rui Ueyama80474a22017-02-28 19:29:55 +0000498 if (auto *D = dyn_cast<DefinedRegular>(&B)) {
Rafael Espindola474eb012016-05-05 16:40:28 +0000499 // Always include absolute symbols.
Rafael Espindola5616adf2017-03-08 22:36:28 +0000500 SectionBase *Sec = D->Section;
501 if (!Sec)
Rafael Espindola474eb012016-05-05 16:40:28 +0000502 return true;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000503 if (auto *IS = dyn_cast<InputSectionBase>(Sec)) {
504 Sec = IS->Repl;
505 IS = cast<InputSectionBase>(Sec);
506 // Exclude symbols pointing to garbage-collected sections.
507 if (!IS->Live)
508 return false;
509 }
510 if (auto *S = dyn_cast<MergeInputSection>(Sec))
Rui Ueyama90fa3722016-05-22 00:41:38 +0000511 if (!S->getSectionPiece(D->Value)->Live)
Rafael Espindola474eb012016-05-05 16:40:28 +0000512 return false;
513 }
514 return true;
515}
Rafael Espindola462220d2016-05-05 16:38:46 +0000516
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000517// Local symbols are not in the linker's symbol table. This function scans
518// each object file's symbol table to copy local symbols to the output.
519template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
Eugene Leviant9230db92016-11-17 09:16:34 +0000520 if (!In<ELFT>::SymTab)
Rui Ueyama90f76fb2016-01-21 03:07:38 +0000521 return;
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000522 for (elf::ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
Rafael Espindola67d72c02016-03-11 12:06:30 +0000523 for (SymbolBody *B : F->getLocalSymbols()) {
George Rimar78fe56e2016-10-11 09:07:14 +0000524 if (!B->IsLocal)
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000525 fatal(toString(F) +
George Rimar78fe56e2016-10-11 09:07:14 +0000526 ": broken object: getLocalSymbols returns a non-local symbol");
Rui Ueyama80474a22017-02-28 19:29:55 +0000527 auto *DR = dyn_cast<DefinedRegular>(B);
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000528
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000529 // No reason to keep local undefined symbol in symtab.
530 if (!DR)
Rafael Espindola444576d2015-10-09 19:25:07 +0000531 continue;
George Rimar7702bc22017-03-16 11:20:02 +0000532 if (!includeInSymtab(*B))
Rafael Espindola462220d2016-05-05 16:38:46 +0000533 continue;
Rui Ueyama3fc0f7e2016-11-23 18:07:33 +0000534
Rafael Espindola5616adf2017-03-08 22:36:28 +0000535 SectionBase *Sec = DR->Section;
George Rimar7702bc22017-03-16 11:20:02 +0000536 if (!shouldKeepInSymtab(Sec, B->getName(), *B))
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000537 continue;
Rui Ueyamab8dcdb52017-02-28 04:20:16 +0000538 In<ELFT>::SymTab->addSymbol(B);
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000539 }
540 }
541}
542
Rafael Espindola08d6a3f2017-02-11 01:40:49 +0000543template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
544 // Create one STT_SECTION symbol for each output section we might
545 // have a relocation with.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000546 for (OutputSection *Sec : OutputSections) {
Rui Ueyama73d29ab2017-02-28 19:43:54 +0000547 if (Sec->Sections.empty())
548 continue;
549
550 InputSection *IS = Sec->Sections[0];
551 if (isa<SyntheticSection>(IS) || IS->Type == SHT_REL ||
Rafael Espindola08d6a3f2017-02-11 01:40:49 +0000552 IS->Type == SHT_RELA)
553 continue;
Rafael Espindola08d6a3f2017-02-11 01:40:49 +0000554
Rui Ueyama175e81c2017-02-28 19:36:30 +0000555 auto *Sym =
556 make<DefinedRegular>("", /*IsLocal=*/true, /*StOther=*/0, STT_SECTION,
557 /*Value=*/0, /*Size=*/0, IS, nullptr);
558 In<ELFT>::SymTab->addSymbol(Sym);
Rafael Espindola08d6a3f2017-02-11 01:40:49 +0000559 }
560}
561
Hal Finkel3bae2d82015-10-12 20:51:48 +0000562// PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections that
563// we would like to make sure appear is a specific order to maximize their
564// coverage by a single signed 16-bit offset from the TOC base pointer.
565// Conversely, the special .tocbss section should be first among all SHT_NOBITS
566// sections. This will put it next to the loaded special PPC64 sections (and,
567// thus, within reach of the TOC base pointer).
568static int getPPC64SectionRank(StringRef SectionName) {
569 return StringSwitch<int>(SectionName)
George Rimaree741cf2016-04-14 13:23:02 +0000570 .Case(".tocbss", 0)
571 .Case(".branch_lt", 2)
572 .Case(".toc", 3)
573 .Case(".toc1", 4)
574 .Case(".opd", 5)
575 .Default(1);
Hal Finkel3bae2d82015-10-12 20:51:48 +0000576}
577
Simon Atanasyan2bd98af2017-01-16 21:17:23 +0000578// All sections with SHF_MIPS_GPREL flag should be grouped together
579// because data in these sections is addressable with a gp relative address.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000580static int getMipsSectionRank(const OutputSection *S) {
Simon Atanasyan2bd98af2017-01-16 21:17:23 +0000581 if ((S->Flags & SHF_MIPS_GPREL) == 0)
582 return 0;
Rafael Espindola40849412017-02-24 14:28:00 +0000583 if (S->Name == ".got")
Simon Atanasyan2bd98af2017-01-16 21:17:23 +0000584 return 1;
585 return 2;
586}
587
Rui Ueyama26ad0572017-02-16 04:51:46 +0000588// Today's loaders have a feature to make segments read-only after
589// processing dynamic relocations to enhance security. PT_GNU_RELRO
590// is defined for that.
591//
592// This function returns true if a section needs to be put into a
593// PT_GNU_RELRO segment.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000594template <class ELFT> bool elf::isRelroSection(const OutputSection *Sec) {
Rafael Espindola4fc60442016-02-10 22:43:13 +0000595 if (!Config->ZRelro)
596 return false;
Rui Ueyama26ad0572017-02-16 04:51:46 +0000597
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000598 uint64_t Flags = Sec->Flags;
George Rimare3336c02015-11-24 10:15:50 +0000599 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
600 return false;
Rui Ueyamaccfc3262015-12-10 19:13:08 +0000601 if (Flags & SHF_TLS)
602 return true;
Rui Ueyama26ad0572017-02-16 04:51:46 +0000603
Rafael Espindola04a2e342016-11-09 01:42:41 +0000604 uint32_t Type = Sec->Type;
Rui Ueyamaccfc3262015-12-10 19:13:08 +0000605 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
606 Type == SHT_PREINIT_ARRAY)
George Rimare3336c02015-11-24 10:15:50 +0000607 return true;
Rui Ueyama26ad0572017-02-16 04:51:46 +0000608
Eugene Leviant41ca3272016-11-10 09:48:29 +0000609 if (Sec == In<ELFT>::GotPlt->OutSec)
George Rimare3336c02015-11-24 10:15:50 +0000610 return Config->ZNow;
Simon Atanasyan725dc142016-11-16 21:01:02 +0000611 if (Sec == In<ELFT>::Dynamic->OutSec)
612 return true;
613 if (In<ELFT>::Got && Sec == In<ELFT>::Got->OutSec)
614 return true;
George Rimar1ab9cf42017-03-17 10:14:53 +0000615 if (Sec == In<ELFT>::BssRelRo->OutSec)
Peter Collingbournefeb66292017-01-10 01:21:50 +0000616 return true;
Rui Ueyama26ad0572017-02-16 04:51:46 +0000617
Rafael Espindola40849412017-02-24 14:28:00 +0000618 StringRef S = Sec->Name;
Rui Ueyama01faef02015-12-10 19:19:04 +0000619 return S == ".data.rel.ro" || S == ".ctors" || S == ".dtors" || S == ".jcr" ||
George Rimard003c7f2016-12-20 11:28:54 +0000620 S == ".eh_frame" || S == ".openbsd.randomdata";
George Rimare3336c02015-11-24 10:15:50 +0000621}
622
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000623template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +0000624static bool compareSectionsNonScript(const OutputSection *A,
625 const OutputSection *B) {
Rui Ueyamae288eef2016-11-02 18:58:44 +0000626 // Put .interp first because some loaders want to see that section
627 // on the first page of the executable file when loaded into memory.
Rafael Espindola40849412017-02-24 14:28:00 +0000628 bool AIsInterp = A->Name == ".interp";
629 bool BIsInterp = B->Name == ".interp";
Rui Ueyamae288eef2016-11-02 18:58:44 +0000630 if (AIsInterp != BIsInterp)
631 return AIsInterp;
632
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000633 // Allocatable sections go first to reduce the total PT_LOAD size and
634 // so debug info doesn't change addresses in actual code.
Rafael Espindola04a2e342016-11-09 01:42:41 +0000635 bool AIsAlloc = A->Flags & SHF_ALLOC;
636 bool BIsAlloc = B->Flags & SHF_ALLOC;
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000637 if (AIsAlloc != BIsAlloc)
638 return AIsAlloc;
639
Rafael Espindolab6b8f6c2016-09-20 22:43:15 +0000640 // We don't have any special requirements for the relative order of two non
641 // allocatable sections.
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000642 if (!AIsAlloc)
Rafael Espindola24c073d2016-09-21 22:36:19 +0000643 return false;
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000644
Rafael Espindola5967c972016-12-19 21:21:07 +0000645 // We want to put section specified by -T option first, so we
646 // can start assigning VA starting from them later.
Rafael Espindola40849412017-02-24 14:28:00 +0000647 auto AAddrSetI = Config->SectionStartMap.find(A->Name);
648 auto BAddrSetI = Config->SectionStartMap.find(B->Name);
Rafael Espindola5967c972016-12-19 21:21:07 +0000649 bool AHasAddrSet = AAddrSetI != Config->SectionStartMap.end();
650 bool BHasAddrSet = BAddrSetI != Config->SectionStartMap.end();
651 if (AHasAddrSet != BHasAddrSet)
652 return AHasAddrSet;
653 if (AHasAddrSet)
654 return AAddrSetI->second < BAddrSetI->second;
655
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000656 // We want the read only sections first so that they go in the PT_LOAD
657 // covering the program headers at the start of the file.
Rafael Espindola04a2e342016-11-09 01:42:41 +0000658 bool AIsWritable = A->Flags & SHF_WRITE;
659 bool BIsWritable = B->Flags & SHF_WRITE;
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000660 if (AIsWritable != BIsWritable)
661 return BIsWritable;
662
George Rimar1642c5d2016-11-28 10:26:21 +0000663 if (!Config->SingleRoRx) {
Rafael Espindolae979fd12016-09-29 22:48:55 +0000664 // For a corresponding reason, put non exec sections first (the program
665 // header PT_LOAD is not executable).
666 // We only do that if we are not using linker scripts, since with linker
667 // scripts ro and rx sections are in the same PT_LOAD, so their relative
George Rimar1642c5d2016-11-28 10:26:21 +0000668 // order is not important. The same applies for -no-rosegment.
Rafael Espindola04a2e342016-11-09 01:42:41 +0000669 bool AIsExec = A->Flags & SHF_EXECINSTR;
670 bool BIsExec = B->Flags & SHF_EXECINSTR;
Rafael Espindolae979fd12016-09-29 22:48:55 +0000671 if (AIsExec != BIsExec)
672 return BIsExec;
673 }
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000674
Hal Finkel0d7e83b2015-10-13 17:57:46 +0000675 // 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 +0000676
Rafael Espindola04a2e342016-11-09 01:42:41 +0000677 bool AIsTls = A->Flags & SHF_TLS;
678 bool BIsTls = B->Flags & SHF_TLS;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000679 bool AIsNoBits = A->Type == SHT_NOBITS;
680 bool BIsNoBits = B->Type == SHT_NOBITS;
Hal Finkel3bae2d82015-10-12 20:51:48 +0000681
Peter Collingbourne628ec9f2017-01-10 01:21:30 +0000682 // The first requirement we have is to put (non-TLS) nobits sections last. The
683 // reason is that the only thing the dynamic linker will see about them is a
684 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
685 // PT_LOAD, so that has to correspond to the nobits sections.
686 bool AIsNonTlsNoBits = AIsNoBits && !AIsTls;
687 bool BIsNonTlsNoBits = BIsNoBits && !BIsTls;
688 if (AIsNonTlsNoBits != BIsNonTlsNoBits)
689 return BIsNonTlsNoBits;
690
691 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
692 // sections after r/w ones, so that the RelRo sections are contiguous.
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000693 bool AIsRelRo = isRelroSection<ELFT>(A);
694 bool BIsRelRo = isRelroSection<ELFT>(B);
George Rimare3336c02015-11-24 10:15:50 +0000695 if (AIsRelRo != BIsRelRo)
Peter Collingbourne628ec9f2017-01-10 01:21:30 +0000696 return AIsNonTlsNoBits ? AIsRelRo : BIsRelRo;
697
698 // The TLS initialization block needs to be a single contiguous block in a R/W
699 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
700 // sections. The TLS NOBITS sections are placed here as they don't take up
701 // virtual address space in the PT_LOAD.
702 if (AIsTls != BIsTls)
703 return AIsTls;
704
705 // Within the TLS initialization block, the non-nobits sections need to appear
706 // first.
707 if (AIsNoBits != BIsNoBits)
708 return BIsNoBits;
George Rimare3336c02015-11-24 10:15:50 +0000709
Hal Finkel9abc2a52015-10-13 19:07:29 +0000710 // Some architectures have additional ordering restrictions for sections
711 // within the same PT_LOAD.
712 if (Config->EMachine == EM_PPC64)
Rafael Espindola40849412017-02-24 14:28:00 +0000713 return getPPC64SectionRank(A->Name) < getPPC64SectionRank(B->Name);
Simon Atanasyan2bd98af2017-01-16 21:17:23 +0000714 if (Config->EMachine == EM_MIPS)
715 return getMipsSectionRank(A) < getMipsSectionRank(B);
Hal Finkel9abc2a52015-10-13 19:07:29 +0000716
Rafael Espindola24c073d2016-09-21 22:36:19 +0000717 return false;
718}
719
720// Output section ordering is determined by this function.
721template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +0000722static bool compareSections(const OutputSection *A, const OutputSection *B) {
Rafael Espindola24c073d2016-09-21 22:36:19 +0000723 // For now, put sections mentioned in a linker script first.
George Rimara8dba482017-03-20 10:09:58 +0000724 int AIndex = Script->getSectionIndex(A->Name);
725 int BIndex = Script->getSectionIndex(B->Name);
Rafael Espindola24c073d2016-09-21 22:36:19 +0000726 bool AInScript = AIndex != INT_MAX;
727 bool BInScript = BIndex != INT_MAX;
728 if (AInScript != BInScript)
729 return AInScript;
730 // If both are in the script, use that order.
731 if (AInScript)
732 return AIndex < BIndex;
733
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000734 return compareSectionsNonScript<ELFT>(A, B);
Rui Ueyama5a9640b2015-10-08 23:49:30 +0000735}
736
Eugene Leviantbbe38602016-07-19 09:25:43 +0000737// Program header entry
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000738PhdrEntry::PhdrEntry(unsigned Type, unsigned Flags) {
739 p_type = Type;
740 p_flags = Flags;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000741}
742
Rafael Espindola24e6f362017-02-24 15:07:30 +0000743void PhdrEntry::add(OutputSection *Sec) {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000744 Last = Sec;
745 if (!First)
746 First = Sec;
Rafael Espindola37707632017-03-07 14:55:52 +0000747 p_align = std::max(p_align, Sec->Alignment);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000748 if (p_type == PT_LOAD)
Eugene Leviant3d9abec2016-09-29 09:20:33 +0000749 Sec->FirstInPtLoad = First;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000750}
751
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000752template <class ELFT>
Rafael Espindola5616adf2017-03-08 22:36:28 +0000753static Symbol *addRegular(StringRef Name, SectionBase *Sec, uint64_t Value,
754 uint8_t StOther = STV_HIDDEN,
755 uint8_t Binding = STB_WEAK) {
Rafael Espindoladab02d42016-11-17 21:20:16 +0000756 // The linker generated symbols are added as STB_WEAK to allow user defined
757 // ones to override them.
Rafael Espindola5616adf2017-03-08 22:36:28 +0000758 return Symtab<ELFT>::X->addRegular(Name, StOther, STT_NOTYPE, Value,
759 /*Size=*/0, Binding, Sec,
Rui Ueyama0cbf7492016-11-23 06:59:47 +0000760 /*File=*/nullptr);
Eugene Leviantad4439e2016-11-11 11:33:32 +0000761}
762
763template <class ELFT>
Rafael Espindola5616adf2017-03-08 22:36:28 +0000764static DefinedRegular *
765addOptionalRegular(StringRef Name, SectionBase *Sec, uint64_t Val,
766 uint8_t StOther = STV_HIDDEN, uint8_t Binding = STB_GLOBAL) {
Eugene Leviantad4439e2016-11-11 11:33:32 +0000767 SymbolBody *S = Symtab<ELFT>::X->find(Name);
768 if (!S)
769 return nullptr;
Rafael Espindola1d6d1b42017-01-17 16:08:06 +0000770 if (S->isInCurrentDSO())
Rafael Espindola5616adf2017-03-08 22:36:28 +0000771 return nullptr;
772 return cast<DefinedRegular>(
773 addRegular<ELFT>(Name, Sec, Val, StOther, Binding)->body());
Eugene Leviantad4439e2016-11-11 11:33:32 +0000774}
775
Rui Ueyama01687222015-12-26 09:47:57 +0000776// The beginning and the ending of .rel[a].plt section are marked
777// with __rel[a]_iplt_{start,end} symbols if it is a statically linked
778// executable. The runtime needs these symbols in order to resolve
779// all IRELATIVE relocs on startup. For dynamic executables, we don't
780// need these symbols, since IRELATIVE relocs are resolved through GOT
781// and PLT. For details, see http://www.airs.com/blog/archives/403.
George Rimaree741cf2016-04-14 13:23:02 +0000782template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
Eugene Leviant9230db92016-11-17 09:16:34 +0000783 if (In<ELFT>::DynSymTab)
George Rimara07ff662015-12-21 10:12:06 +0000784 return;
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000785 StringRef S = Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start";
Rafael Espindola5616adf2017-03-08 22:36:28 +0000786 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, 0, STV_HIDDEN, STB_WEAK);
Rui Ueyama01687222015-12-26 09:47:57 +0000787
Rui Ueyamad57e74b72017-03-17 23:29:01 +0000788 S = Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end";
Rafael Espindola5616adf2017-03-08 22:36:28 +0000789 addOptionalRegular<ELFT>(S, In<ELFT>::RelaIplt, -1, STV_HIDDEN, STB_WEAK);
George Rimara07ff662015-12-21 10:12:06 +0000790}
791
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +0000792// The linker is expected to define some symbols depending on
793// the linking result. This function defines such symbols.
794template <class ELFT> void Writer<ELFT>::addReservedSymbols() {
George Rimar7beff422016-11-15 08:19:02 +0000795 if (Config->EMachine == EM_MIPS) {
Rafael Espindola9b3f99e2016-04-12 02:24:43 +0000796 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000797 // so that it points to an absolute address which by default is relative
798 // to GOT. Default offset is 0x7ff0.
Rafael Espindola9b3f99e2016-04-12 02:24:43 +0000799 // See "Global Data Symbols" in Chapter 6 in the following document:
800 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
Rui Ueyama80474a22017-02-28 19:29:55 +0000801 ElfSym::MipsGp = Symtab<ELFT>::X->addAbsolute("_gp", STV_HIDDEN, STB_LOCAL);
Rafael Espindola9b3f99e2016-04-12 02:24:43 +0000802
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000803 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
Simon Atanasyand34a3632017-03-20 21:03:43 +0000804 // start of function and 'gp' pointer into GOT.
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000805 if (Symtab<ELFT>::X->find("_gp_disp"))
Rui Ueyama80474a22017-02-28 19:29:55 +0000806 ElfSym::MipsGpDisp =
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000807 Symtab<ELFT>::X->addAbsolute("_gp_disp", STV_HIDDEN, STB_LOCAL);
Peter Collingbourne6f535b72016-05-03 18:03:45 +0000808
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000809 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
810 // pointer. This symbol is used in the code generated by .cpload pseudo-op
811 // in case of using -mno-shared option.
812 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000813 if (Symtab<ELFT>::X->find("__gnu_local_gp"))
Rui Ueyama80474a22017-02-28 19:29:55 +0000814 ElfSym::MipsLocalGp =
Simon Atanasyan6a4eb752016-12-08 06:19:47 +0000815 Symtab<ELFT>::X->addAbsolute("__gnu_local_gp", STV_HIDDEN, STB_LOCAL);
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000816 }
817
818 // In the assembly for 32 bit x86 the _GLOBAL_OFFSET_TABLE_ symbol
819 // is magical and is used to produce a R_386_GOTPC relocation.
820 // The R_386_GOTPC relocation value doesn't actually depend on the
821 // symbol value, so it could use an index of STN_UNDEF which, according
822 // to the spec, means the symbol value is 0.
823 // Unfortunately both gas and MC keep the _GLOBAL_OFFSET_TABLE_ symbol in
824 // the object file.
825 // The situation is even stranger on x86_64 where the assembly doesn't
826 // need the magical symbol, but gas still puts _GLOBAL_OFFSET_TABLE_ as
827 // an undefined symbol in the .o files.
828 // Given that the symbol is effectively unused, we just create a dummy
829 // hidden one to avoid the undefined symbol error.
George Rimar7beff422016-11-15 08:19:02 +0000830 Symtab<ELFT>::X->addIgnored("_GLOBAL_OFFSET_TABLE_");
Rafael Espindolaccfe3cb2016-04-04 14:04:16 +0000831
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +0000832 // __tls_get_addr is defined by the dynamic linker for dynamic ELFs. For
833 // static linking the linker is required to optimize away any references to
834 // __tls_get_addr, so it's not defined anywhere. Create a hidden definition
Peter Smith17cd3752016-10-27 10:28:53 +0000835 // to avoid the undefined symbol error. As usual special cases are ARM and
836 // MIPS - the libc for these targets defines __tls_get_addr itself because
837 // there are no TLS optimizations for these targets.
Eugene Leviant9230db92016-11-17 09:16:34 +0000838 if (!In<ELFT>::DynSymTab &&
Peter Smith17cd3752016-10-27 10:28:53 +0000839 (Config->EMachine != EM_MIPS && Config->EMachine != EM_ARM))
Rui Ueyama84907c52016-08-09 03:38:23 +0000840 Symtab<ELFT>::X->addIgnored("__tls_get_addr");
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +0000841
George Rimar28ac19c2016-08-08 08:42:48 +0000842 // If linker script do layout we do not need to create any standart symbols.
Rui Ueyamaa34da932017-03-21 23:03:09 +0000843 if (Script->Opt.HasSections)
George Rimar28ac19c2016-08-08 08:42:48 +0000844 return;
845
Petr Hosekf087e312017-02-24 04:11:02 +0000846 // __ehdr_start is the location of ELF file headers.
Rafael Espindola5616adf2017-03-08 22:36:28 +0000847 addOptionalRegular<ELFT>("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
Petr Hosek4f7a5c32016-08-22 18:44:04 +0000848
Rafael Espindola5616adf2017-03-08 22:36:28 +0000849 auto Define = [](StringRef S, DefinedRegular *&Sym1, DefinedRegular *&Sym2) {
850 Sym1 = addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
Rui Ueyama68e15552016-02-26 16:49:54 +0000851 assert(S.startswith("_"));
Rui Ueyama4d169bd2016-02-26 16:38:39 +0000852 S = S.substr(1);
Rafael Espindola5616adf2017-03-08 22:36:28 +0000853 Sym2 = addOptionalRegular<ELFT>(S, Out::ElfHeader, 0, STV_DEFAULT);
George Rimar9e859392016-02-26 14:36:36 +0000854 };
855
Rui Ueyama80474a22017-02-28 19:29:55 +0000856 Define("_end", ElfSym::End, ElfSym::End2);
857 Define("_etext", ElfSym::Etext, ElfSym::Etext2);
858 Define("_edata", ElfSym::Edata, ElfSym::Edata2);
Rui Ueyamaf18fe7b2015-12-26 07:50:39 +0000859}
860
Rui Ueyamac4185702016-02-10 23:20:42 +0000861// Sort input sections by section name suffixes for
862// __attribute__((init_priority(N))).
Rafael Espindola24e6f362017-02-24 15:07:30 +0000863template <class ELFT> static void sortInitFini(OutputSection *S) {
Rui Ueyamac4185702016-02-10 23:20:42 +0000864 if (S)
Rafael Espindola24e6f362017-02-24 15:07:30 +0000865 reinterpret_cast<OutputSection *>(S)->sortInitFini();
Rui Ueyama5af83682016-02-11 23:41:38 +0000866}
867
868// Sort input sections by the special rule for .ctors and .dtors.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000869template <class ELFT> static void sortCtorsDtors(OutputSection *S) {
Rui Ueyama5af83682016-02-11 23:41:38 +0000870 if (S)
Rafael Espindola24e6f362017-02-24 15:07:30 +0000871 reinterpret_cast<OutputSection *>(S)->sortCtorsDtors();
Rui Ueyamac4185702016-02-10 23:20:42 +0000872}
873
George Rimar1a33c0f2016-11-10 09:05:20 +0000874// Sort input sections using the list provided by --symbol-ordering-file.
875template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +0000876static void sortBySymbolsOrder(ArrayRef<OutputSection *> OutputSections) {
George Rimar1a33c0f2016-11-10 09:05:20 +0000877 if (Config->SymbolOrderingFile.empty())
878 return;
879
Rui Ueyama31270312016-12-20 01:51:08 +0000880 // Build a map from symbols to their priorities. Symbols that didn't
881 // appear in the symbol ordering file have the lowest priority 0.
882 // All explicitly mentioned symbols have negative (higher) priorities.
883 DenseMap<StringRef, int> SymbolOrder;
884 int Priority = -Config->SymbolOrderingFile.size();
885 for (StringRef S : Config->SymbolOrderingFile)
886 SymbolOrder.insert({S, Priority++});
887
888 // Build a map from sections to their priorities.
Rafael Espindola5616adf2017-03-08 22:36:28 +0000889 DenseMap<SectionBase *, int> SectionOrder;
George Rimar1a33c0f2016-11-10 09:05:20 +0000890 for (elf::ObjectFile<ELFT> *File : Symtab<ELFT>::X->getObjectFiles()) {
891 for (SymbolBody *Body : File->getSymbols()) {
Rui Ueyama80474a22017-02-28 19:29:55 +0000892 auto *D = dyn_cast<DefinedRegular>(Body);
George Rimar1a33c0f2016-11-10 09:05:20 +0000893 if (!D || !D->Section)
894 continue;
Rui Ueyama31270312016-12-20 01:51:08 +0000895 int &Priority = SectionOrder[D->Section];
896 Priority = std::min(Priority, SymbolOrder.lookup(D->getName()));
George Rimar1a33c0f2016-11-10 09:05:20 +0000897 }
898 }
899
Rui Ueyama31270312016-12-20 01:51:08 +0000900 // Sort sections by priority.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000901 for (OutputSection *Base : OutputSections)
902 if (auto *Sec = dyn_cast<OutputSection>(Base))
Rafael Espindolac404d502017-02-23 02:32:18 +0000903 Sec->sort([&](InputSectionBase *S) { return SectionOrder.lookup(S); });
George Rimar1a33c0f2016-11-10 09:05:20 +0000904}
905
Eugene Leviante63d81b2016-07-20 14:43:20 +0000906template <class ELFT>
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000907void Writer<ELFT>::forEachRelSec(std::function<void(InputSectionBase &)> Fn) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000908 for (InputSectionBase *IS : InputSections) {
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000909 if (!IS->Live)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000910 continue;
911 // Scan all relocations. Each relocation goes through a series
912 // of tests to determine if it needs special treatment, such as
913 // creating GOT, PLT, copy relocations, etc.
914 // Note that relocations for non-alloc sections are directly
915 // processed by InputSection::relocateNonAlloc.
916 if (!(IS->Flags & SHF_ALLOC))
917 continue;
Rafael Espindola5c02b742017-03-06 21:17:18 +0000918 if (isa<InputSection>(IS) || isa<EhInputSection>(IS))
Rafael Espindola9f0c4bb2016-11-10 14:53:24 +0000919 Fn(*IS);
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000920 }
Petr Hosek7b793212017-03-10 20:00:42 +0000921
922 if (!Config->Relocatable) {
923 for (EhInputSection *ES : In<ELFT>::EhFrame->Sections)
924 Fn(*ES);
925 }
Rafael Espindola0f7ceda2016-07-20 17:58:07 +0000926}
927
Eugene Leviant282251a2016-11-01 09:49:24 +0000928template <class ELFT> void Writer<ELFT>::createSections() {
Rui Ueyama536a2672017-02-27 02:32:08 +0000929 for (InputSectionBase *IS : InputSections)
Rafael Espindola82902742017-02-16 17:32:26 +0000930 if (IS)
George Rimare21c3af2017-03-14 09:30:25 +0000931 Factory.addInputSec(IS, getOutputSectionName(IS->Name));
Eugene Leviantceabe802016-08-11 07:56:43 +0000932
George Rimar1a33c0f2016-11-10 09:05:20 +0000933 sortBySymbolsOrder<ELFT>(OutputSections);
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000934 sortInitFini<ELFT>(findSection(".init_array"));
935 sortInitFini<ELFT>(findSection(".fini_array"));
936 sortCtorsDtors<ELFT>(findSection(".ctors"));
937 sortCtorsDtors<ELFT>(findSection(".dtors"));
Eugene Leviantceabe802016-08-11 07:56:43 +0000938
Rafael Espindola24e6f362017-02-24 15:07:30 +0000939 for (OutputSection *Sec : OutputSections)
George Rimarf98c5c12017-03-16 10:24:54 +0000940 Sec->assignOffsets();
Eugene Leviante63d81b2016-07-20 14:43:20 +0000941}
942
Rafael Espindola24e6f362017-02-24 15:07:30 +0000943static bool canSharePtLoad(const OutputSection &S1, const OutputSection &S2) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000944 if (!(S1.Flags & SHF_ALLOC) || !(S2.Flags & SHF_ALLOC))
Eugene Leviantbae1c652016-11-08 10:44:48 +0000945 return false;
946
Rafael Espindola04a2e342016-11-09 01:42:41 +0000947 bool S1IsWrite = S1.Flags & SHF_WRITE;
948 bool S2IsWrite = S2.Flags & SHF_WRITE;
Eugene Leviantbae1c652016-11-08 10:44:48 +0000949 if (S1IsWrite != S2IsWrite)
950 return false;
951
952 if (!S1IsWrite)
953 return true; // RO and RX share a PT_LOAD with linker scripts.
Rafael Espindola04a2e342016-11-09 01:42:41 +0000954 return (S1.Flags & SHF_EXECINSTR) == (S2.Flags & SHF_EXECINSTR);
Eugene Leviantbae1c652016-11-08 10:44:48 +0000955}
956
Rafael Espindola24c073d2016-09-21 22:36:19 +0000957template <class ELFT> void Writer<ELFT>::sortSections() {
Rafael Espindola1960bcd2016-11-11 22:43:27 +0000958 // Don't sort if using -r. It is not necessary and we want to preserve the
959 // relative order for SHF_LINK_ORDER sections.
960 if (Config->Relocatable)
961 return;
Rui Ueyamaa34da932017-03-21 23:03:09 +0000962 if (!Script->Opt.HasSections) {
Rafael Espindola24c073d2016-09-21 22:36:19 +0000963 std::stable_sort(OutputSections.begin(), OutputSections.end(),
964 compareSectionsNonScript<ELFT>);
965 return;
966 }
George Rimara8dba482017-03-20 10:09:58 +0000967 Script->adjustSectionsBeforeSorting();
Rafael Espindola24c073d2016-09-21 22:36:19 +0000968
969 // The order of the sections in the script is arbitrary and may not agree with
970 // compareSectionsNonScript. This means that we cannot easily define a
971 // strict weak ordering. To see why, consider a comparison of a section in the
972 // script and one not in the script. We have a two simple options:
973 // * Make them equivalent (a is not less than b, and b is not less than a).
974 // The problem is then that equivalence has to be transitive and we can
975 // have sections a, b and c with only b in a script and a less than c
976 // which breaks this property.
977 // * Use compareSectionsNonScript. Given that the script order doesn't have
978 // to match, we can end up with sections a, b, c, d where b and c are in the
979 // script and c is compareSectionsNonScript less than b. In which case d
980 // can be equivalent to c, a to b and d < a. As a concrete example:
981 // .a (rx) # not in script
982 // .b (rx) # in script
983 // .c (ro) # in script
984 // .d (ro) # not in script
985 //
986 // The way we define an order then is:
987 // * First put script sections at the start and sort the script and
988 // non-script sections independently.
Eugene Leviantbae1c652016-11-08 10:44:48 +0000989 // * Move each non-script section to its preferred position. We try
990 // to put each section in the last position where it it can share
991 // a PT_LOAD.
Rafael Espindola24c073d2016-09-21 22:36:19 +0000992
993 std::stable_sort(OutputSections.begin(), OutputSections.end(),
994 compareSections<ELFT>);
995
996 auto I = OutputSections.begin();
997 auto E = OutputSections.end();
Eugene Leviantbae1c652016-11-08 10:44:48 +0000998 auto NonScriptI =
Rafael Espindola24e6f362017-02-24 15:07:30 +0000999 std::find_if(OutputSections.begin(), E, [](OutputSection *S) {
George Rimara8dba482017-03-20 10:09:58 +00001000 return Script->getSectionIndex(S->Name) == INT_MAX;
Eugene Leviantbae1c652016-11-08 10:44:48 +00001001 });
Rafael Espindola24c073d2016-09-21 22:36:19 +00001002 while (NonScriptI != E) {
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001003 auto BestPos = std::max_element(
Rafael Espindola24e6f362017-02-24 15:07:30 +00001004 I, NonScriptI, [&](OutputSection *&A, OutputSection *&B) {
George Rimar7702bc22017-03-16 11:20:02 +00001005 bool ACanSharePtLoad = canSharePtLoad(**NonScriptI, *A);
1006 bool BCanSharePtLoad = canSharePtLoad(**NonScriptI, *B);
Eugene Leviantbae1c652016-11-08 10:44:48 +00001007 if (ACanSharePtLoad != BCanSharePtLoad)
1008 return BCanSharePtLoad;
1009
1010 bool ACmp = compareSectionsNonScript<ELFT>(*NonScriptI, A);
1011 bool BCmp = compareSectionsNonScript<ELFT>(*NonScriptI, B);
1012 if (ACmp != BCmp)
1013 return BCmp; // FIXME: missing test
1014
1015 size_t PosA = &A - &OutputSections[0];
1016 size_t PosB = &B - &OutputSections[0];
1017 return ACmp ? PosA > PosB : PosA < PosB;
Rafael Espindola24c073d2016-09-21 22:36:19 +00001018 });
Eugene Leviantbae1c652016-11-08 10:44:48 +00001019
1020 // max_element only returns NonScriptI if the range is empty. If the range
1021 // is not empty we should consider moving the the element forward one
1022 // position.
1023 if (BestPos != NonScriptI &&
1024 !compareSectionsNonScript<ELFT>(*NonScriptI, *BestPos))
1025 ++BestPos;
1026 std::rotate(BestPos, NonScriptI, NonScriptI + 1);
Rafael Espindola24c073d2016-09-21 22:36:19 +00001027 ++NonScriptI;
Rafael Espindola24c073d2016-09-21 22:36:19 +00001028 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +00001029
George Rimara8dba482017-03-20 10:09:58 +00001030 Script->adjustSectionsAfterSorting();
Rafael Espindola24c073d2016-09-21 22:36:19 +00001031}
1032
Peter Smith1ec42d92017-03-08 14:06:24 +00001033static void applySynthetic(const std::vector<SyntheticSection *> &Sections,
1034 std::function<void(SyntheticSection *)> Fn) {
Rui Ueyama9320cb02017-02-27 02:56:02 +00001035 for (SyntheticSection *SS : Sections)
George Rimar3fb5a6d2016-11-29 16:05:27 +00001036 if (SS && SS->OutSec && !SS->empty()) {
Peter Smith1ec42d92017-03-08 14:06:24 +00001037 Fn(SS);
George Rimarf98c5c12017-03-16 10:24:54 +00001038 SS->OutSec->assignOffsets();
Eugene Leviant6380ce22016-11-15 12:26:55 +00001039 }
1040}
1041
George Rimar11992c862016-11-25 08:05:41 +00001042// We need to add input synthetic sections early in createSyntheticSections()
Rui Ueyamac38860b2016-12-05 21:39:35 +00001043// to make them visible from linkescript side. But not all sections are always
1044// required to be in output. For example we don't need dynamic section content
1045// sometimes. This function filters out such unused sections from output.
Rafael Espindola24e6f362017-02-24 15:07:30 +00001046static void removeUnusedSyntheticSections(std::vector<OutputSection *> &V) {
Rafael Espindola9e9754b2017-02-03 13:06:18 +00001047 // All input synthetic sections that can be empty are placed after
1048 // all regular ones. We iterate over them all and exit at first
1049 // non-synthetic.
Rui Ueyama536a2672017-02-27 02:32:08 +00001050 for (InputSectionBase *S : llvm::reverse(InputSections)) {
Rui Ueyama9320cb02017-02-27 02:56:02 +00001051 SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
Rui Ueyamac38860b2016-12-05 21:39:35 +00001052 if (!SS)
George Rimar11992c862016-11-25 08:05:41 +00001053 return;
Rui Ueyamac38860b2016-12-05 21:39:35 +00001054 if (!SS->empty() || !SS->OutSec)
George Rimar11992c862016-11-25 08:05:41 +00001055 continue;
1056
Rafael Espindola24e6f362017-02-24 15:07:30 +00001057 OutputSection *OutSec = cast<OutputSection>(SS->OutSec);
Rui Ueyamac38860b2016-12-05 21:39:35 +00001058 OutSec->Sections.erase(
1059 std::find(OutSec->Sections.begin(), OutSec->Sections.end(), SS));
1060 // If there is no other sections in output section, remove it from output.
1061 if (OutSec->Sections.empty())
1062 V.erase(std::find(V.begin(), V.end(), OutSec));
George Rimar11992c862016-11-25 08:05:41 +00001063 }
1064}
1065
Eugene Leviante63d81b2016-07-20 14:43:20 +00001066// Create output section objects and add them to OutputSections.
1067template <class ELFT> void Writer<ELFT>::finalizeSections() {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001068 Out::DebugInfo = findSection(".debug_info");
1069 Out::PreinitArray = findSection(".preinit_array");
1070 Out::InitArray = findSection(".init_array");
1071 Out::FiniArray = findSection(".fini_array");
Rafael Espindola77572242015-10-02 19:37:55 +00001072
Rui Ueyamaa5d79d12015-12-26 09:48:00 +00001073 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1074 // symbols for sections, so that the runtime can get the start and end
1075 // addresses of each section by section name. Add such symbols.
George Rimarc1034a82016-03-01 19:12:35 +00001076 if (!Config->Relocatable) {
1077 addStartEndSymbols();
Rafael Espindola24e6f362017-02-24 15:07:30 +00001078 for (OutputSection *Sec : OutputSections)
George Rimarc1034a82016-03-01 19:12:35 +00001079 addStartStopSymbols(Sec);
1080 }
Rui Ueyamad4530c62016-03-04 18:34:14 +00001081
1082 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1083 // It should be okay as no one seems to care about the type.
1084 // Even the author of gold doesn't remember why gold behaves that way.
1085 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
Eugene Leviant9230db92016-11-17 09:16:34 +00001086 if (In<ELFT>::DynSymTab)
Rafael Espindolab4c9b812017-02-23 02:28:28 +00001087 addRegular<ELFT>("_DYNAMIC", In<ELFT>::Dynamic, 0);
Rafael Espindola334c3e12015-10-19 15:21:42 +00001088
Rafael Espindolade9857e2016-02-04 21:33:05 +00001089 // Define __rel[a]_iplt_{start,end} symbols if needed.
1090 addRelIpltSymbols();
1091
Rafael Espindola66b4e212017-02-23 22:06:28 +00001092 // This responsible for splitting up .eh_frame section into
Peter Smith1ec42d92017-03-08 14:06:24 +00001093 // pieces. The relocation scan uses those pieces, so this has to be
Rafael Espindola66b4e212017-02-23 22:06:28 +00001094 // earlier.
George Rimar49a47f22017-03-16 10:29:44 +00001095 applySynthetic({In<ELFT>::EhFrame},
1096 [](SyntheticSection *SS) { SS->finalizeContents(); });
Rafael Espindola56004c52016-04-07 14:22:09 +00001097
Rafael Espindola0f7ceda2016-07-20 17:58:07 +00001098 // Scan relocations. This must be done after every symbol is declared so that
1099 // we can correctly decide if a dynamic relocation is needed.
1100 forEachRelSec(scanRelocations<ELFT>);
1101
Peter Smith96943762017-01-25 10:31:16 +00001102 if (In<ELFT>::Plt && !In<ELFT>::Plt->empty())
1103 In<ELFT>::Plt->addSymbols();
1104 if (In<ELFT>::Iplt && !In<ELFT>::Iplt->empty())
1105 In<ELFT>::Iplt->addSymbols();
1106
Peter Smith55865432017-02-20 11:12:33 +00001107 // Now that we have defined all possible global symbols including linker-
Rui Ueyama1b2a8bf2015-12-26 10:22:16 +00001108 // synthesized ones. Visit all symbols to give the finishing touches.
Rui Ueyama84907c52016-08-09 03:38:23 +00001109 for (Symbol *S : Symtab<ELFT>::X->getSymbols()) {
Peter Collingbourne4f952702016-05-01 04:55:03 +00001110 SymbolBody *Body = S->body();
Rafael Espindola0baa73f2016-04-26 13:56:26 +00001111
George Rimar7702bc22017-03-16 11:20:02 +00001112 if (!includeInSymtab(*Body))
Rafael Espindola05a3dd22015-09-22 23:38:23 +00001113 continue;
Eugene Leviant9230db92016-11-17 09:16:34 +00001114 if (In<ELFT>::SymTab)
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001115 In<ELFT>::SymTab->addSymbol(Body);
Rafael Espindola05a3dd22015-09-22 23:38:23 +00001116
Eugene Leviant9230db92016-11-17 09:16:34 +00001117 if (In<ELFT>::DynSymTab && S->includeInDynsym()) {
Rui Ueyamab8dcdb52017-02-28 04:20:16 +00001118 In<ELFT>::DynSymTab->addSymbol(Body);
Rui Ueyama4076fa12017-02-26 23:35:34 +00001119 if (auto *SS = dyn_cast<SharedSymbol>(Body))
1120 if (cast<SharedFile<ELFT>>(SS->File)->isNeeded())
Eugene Leviante9bab5d2016-11-21 16:59:33 +00001121 In<ELFT>::VerNeed->addSymbol(SS);
Peter Collingbourne21a12fc2016-04-27 20:22:31 +00001122 }
Rafael Espindola05a3dd22015-09-22 23:38:23 +00001123 }
Rui Ueyamac2a0d7e2016-01-28 22:56:29 +00001124
1125 // Do not proceed if there was an undefined symbol.
Rui Ueyamaf373dd72016-11-24 01:43:21 +00001126 if (ErrorCount)
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +00001127 return;
Rui Ueyamac2a0d7e2016-01-28 22:56:29 +00001128
Rui Ueyama84417f82015-12-26 07:50:41 +00001129 // So far we have added sections from input object files.
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001130 // This function adds linker-created Out::* sections.
Rui Ueyama84417f82015-12-26 07:50:41 +00001131 addPredefinedSections();
George Rimar7702bc22017-03-16 11:20:02 +00001132 removeUnusedSyntheticSections(OutputSections);
Rui Ueyama84417f82015-12-26 07:50:41 +00001133
Rafael Espindola24c073d2016-09-21 22:36:19 +00001134 sortSections();
Rui Ueyama84417f82015-12-26 07:50:41 +00001135
Rafael Espindola78493a22017-01-28 17:48:21 +00001136 // This is a bit of a hack. A value of 0 means undef, so we set it
1137 // to 1 t make __ehdr_start defined. The section number is not
1138 // particularly relevant.
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001139 Out::ElfHeader->SectionIndex = 1;
Rafael Espindola78493a22017-01-28 17:48:21 +00001140
George Rimar7ca06272016-04-06 07:20:45 +00001141 unsigned I = 1;
Rafael Espindola24e6f362017-02-24 15:07:30 +00001142 for (OutputSection *Sec : OutputSections) {
George Rimar7ca06272016-04-06 07:20:45 +00001143 Sec->SectionIndex = I++;
Rafael Espindola40849412017-02-24 14:28:00 +00001144 Sec->ShName = In<ELFT>::ShStrTab->addString(Sec->Name);
George Rimar7ca06272016-04-06 07:20:45 +00001145 }
Rui Ueyama84417f82015-12-26 07:50:41 +00001146
Rafael Espindola5967c972016-12-19 21:21:07 +00001147 // Binary and relocatable output does not have PHDRS.
1148 // The headers have to be created before finalize as that can influence the
1149 // image base and the dynamic section on mips includes the image base.
1150 if (!Config->Relocatable && !Config->OFormatBinary) {
George Rimara8dba482017-03-20 10:09:58 +00001151 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
Rafael Espindola5967c972016-12-19 21:21:07 +00001152 addPtArmExid(Phdrs);
1153 fixHeaders();
1154 }
1155
Eugene Leviantbe809a72016-11-18 06:44:18 +00001156 // Dynamic section must be the last one in this list and dynamic
1157 // symbol table section (DynSymTab) must be the first one.
George Rimar1ab9cf42017-03-17 10:14:53 +00001158 applySynthetic({In<ELFT>::DynSymTab, In<ELFT>::Bss, In<ELFT>::BssRelRo,
1159 In<ELFT>::GnuHashTab, In<ELFT>::HashTab, In<ELFT>::SymTab,
1160 In<ELFT>::ShStrTab, In<ELFT>::StrTab, In<ELFT>::VerDef,
1161 In<ELFT>::DynStrTab, In<ELFT>::GdbIndex, In<ELFT>::Got,
1162 In<ELFT>::MipsGot, In<ELFT>::IgotPlt, In<ELFT>::GotPlt,
1163 In<ELFT>::RelaDyn, In<ELFT>::RelaIplt, In<ELFT>::RelaPlt,
1164 In<ELFT>::Plt, In<ELFT>::Iplt, In<ELFT>::Plt,
1165 In<ELFT>::EhFrameHdr, In<ELFT>::VerSym, In<ELFT>::VerNeed,
1166 In<ELFT>::Dynamic},
George Rimar49a47f22017-03-16 10:29:44 +00001167 [](SyntheticSection *SS) { SS->finalizeContents(); });
Peter Smith1ec42d92017-03-08 14:06:24 +00001168
1169 // Some architectures use small displacements for jump instructions.
1170 // It is linker's responsibility to create thunks containing long
1171 // jump instructions if jump targets are too far. Create thunks.
1172 if (Target->NeedsThunks) {
1173 // FIXME: only ARM Interworking and Mips LA25 Thunks are implemented,
1174 // these
1175 // do not require address information. To support range extension Thunks
1176 // we need to assign addresses so that we can tell if jump instructions
1177 // are out of range. This will need to turn into a loop that converges
1178 // when no more Thunks are added
1179 if (createThunks<ELFT>(OutputSections))
George Rimar49a47f22017-03-16 10:29:44 +00001180 applySynthetic({In<ELFT>::MipsGot},
1181 [](SyntheticSection *SS) { SS->updateAllocSize(); });
Peter Smith1ec42d92017-03-08 14:06:24 +00001182 }
1183 // Fill other section headers. The dynamic table is finalized
1184 // at the end because some tags like RELSZ depend on result
1185 // of finalizing other sections.
1186 for (OutputSection *Sec : OutputSections)
1187 Sec->finalize<ELFT>();
1188
1189 // createThunks may have added local symbols to the static symbol table
George Rimar49a47f22017-03-16 10:29:44 +00001190 applySynthetic({In<ELFT>::SymTab, In<ELFT>::ShStrTab, In<ELFT>::StrTab},
1191 [](SyntheticSection *SS) { SS->postThunkContents(); });
Rui Ueyama84417f82015-12-26 07:50:41 +00001192}
1193
Rui Ueyama84417f82015-12-26 07:50:41 +00001194template <class ELFT> void Writer<ELFT>::addPredefinedSections() {
Rui Ueyamadec4ab02017-02-16 04:19:03 +00001195 // ARM ABI requires .ARM.exidx to be terminated by some piece of data.
1196 // We have the terminater synthetic section class. Add that at the end.
Rafael Espindola24e6f362017-02-24 15:07:30 +00001197 auto *OS = dyn_cast_or_null<OutputSection>(findSection(".ARM.exidx"));
Peter Smith719eb8e2016-11-24 11:43:55 +00001198 if (OS && !OS->Sections.empty() && !Config->Relocatable)
George Rimar90a528b2017-03-21 09:01:39 +00001199 OS->addSection(make<ARMExidxSentinelSection>());
Rafael Espindolaabad6182015-08-13 15:23:46 +00001200}
1201
Rui Ueyamaa5d79d12015-12-26 09:48:00 +00001202// The linker is expected to define SECNAME_start and SECNAME_end
1203// symbols for a few sections. This function defines them.
1204template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
Rafael Espindola24e6f362017-02-24 15:07:30 +00001205 auto Define = [&](StringRef Start, StringRef End, OutputSection *OS) {
Peter Collingbourne0fab40b2016-10-24 20:46:21 +00001206 // These symbols resolve to the image base if the section does not exist.
Rui Ueyama4f2f50d2016-12-21 08:40:09 +00001207 // A special value -1 indicates end of the section.
Peter Collingbournef8435a92017-03-13 16:40:20 +00001208 if (OS) {
1209 addOptionalRegular<ELFT>(Start, OS, 0);
1210 addOptionalRegular<ELFT>(End, OS, -1);
1211 } else {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001212 if (Config->Pic)
Peter Collingbournef8435a92017-03-13 16:40:20 +00001213 OS = Out::ElfHeader;
1214 addOptionalRegular<ELFT>(Start, OS, 0);
1215 addOptionalRegular<ELFT>(End, OS, 0);
1216 }
Rui Ueyamaa5d79d12015-12-26 09:48:00 +00001217 };
1218
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001219 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1220 Define("__init_array_start", "__init_array_end", Out::InitArray);
1221 Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
Peter Smith17cd3752016-10-27 10:28:53 +00001222
Rafael Espindola24e6f362017-02-24 15:07:30 +00001223 if (OutputSection *Sec = findSection(".ARM.exidx"))
Peter Smith17cd3752016-10-27 10:28:53 +00001224 Define("__exidx_start", "__exidx_end", Sec);
Rui Ueyamaa5d79d12015-12-26 09:48:00 +00001225}
1226
Rui Ueyamad9189ce2015-10-15 17:11:03 +00001227// If a section name is valid as a C identifier (which is rare because of
1228// the leading '.'), linkers are expected to define __start_<secname> and
1229// __stop_<secname> symbols. They are at beginning and end of the section,
1230// respectively. This is not requested by the ELF standard, but GNU ld and
1231// gold provide the feature, and used by many programs.
1232template <class ELFT>
Rafael Espindola24e6f362017-02-24 15:07:30 +00001233void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
Rafael Espindola40849412017-02-24 14:28:00 +00001234 StringRef S = Sec->Name;
Rui Ueyamad9189ce2015-10-15 17:11:03 +00001235 if (!isValidCIdentifier(S))
1236 return;
Rafael Espindola5616adf2017-03-08 22:36:28 +00001237 addOptionalRegular<ELFT>(Saver.save("__start_" + S), Sec, 0, STV_DEFAULT);
1238 addOptionalRegular<ELFT>(Saver.save("__stop_" + S), Sec, -1, STV_DEFAULT);
Rui Ueyamad9189ce2015-10-15 17:11:03 +00001239}
1240
Rafael Espindola24e6f362017-02-24 15:07:30 +00001241template <class ELFT> OutputSection *Writer<ELFT>::findSection(StringRef Name) {
1242 for (OutputSection *Sec : OutputSections)
Rafael Espindola40849412017-02-24 14:28:00 +00001243 if (Sec->Name == Name)
Rui Ueyama30634d92016-08-09 01:35:38 +00001244 return Sec;
1245 return nullptr;
1246}
1247
George Rimar7702bc22017-03-16 11:20:02 +00001248static bool needsPtLoad(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001249 if (!(Sec->Flags & SHF_ALLOC))
Rafael Espindolaef762f22016-02-10 23:29:38 +00001250 return false;
1251
1252 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1253 // responsible for allocating space for them, not the PT_LOAD that
1254 // contains the TLS initialization image.
Rafael Espindola04a2e342016-11-09 01:42:41 +00001255 if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS)
Rafael Espindolaef762f22016-02-10 23:29:38 +00001256 return false;
1257 return true;
Michael J. Spencer1d299a82015-09-09 20:48:09 +00001258}
1259
Rafael Espindolab45fd702016-09-20 15:22:27 +00001260// Linker scripts are responsible for aligning addresses. Unfortunately, most
1261// linker scripts are designed for creating two PT_LOADs only, one RX and one
1262// RW. This means that there is no alignment in the RO to RX transition and we
1263// cannot create a PT_LOAD there.
1264template <class ELFT>
1265static typename ELFT::uint computeFlags(typename ELFT::uint F) {
Rui Ueyamaa37ace8d2017-02-25 01:52:03 +00001266 if (Config->Omagic)
George Rimar595a7632016-11-29 09:43:51 +00001267 return PF_R | PF_W | PF_X;
George Rimar63bf0112016-11-28 10:05:20 +00001268 if (Config->SingleRoRx && !(F & PF_W))
Rafael Espindolab45fd702016-09-20 15:22:27 +00001269 return F | PF_X;
1270 return F;
1271}
1272
Rafael Espindola4fc60442016-02-10 22:43:13 +00001273// Decide which program headers to create and which sections to include in each
1274// one.
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001275template <class ELFT> std::vector<PhdrEntry> Writer<ELFT>::createPhdrs() {
1276 std::vector<PhdrEntry> Ret;
1277 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
Rui Ueyama703296a2016-07-20 19:36:39 +00001278 Ret.emplace_back(Type, Flags);
1279 return &Ret.back();
Rafael Espindola4fc60442016-02-10 22:43:13 +00001280 };
George Rimare3336c02015-11-24 10:15:50 +00001281
Rui Ueyama803195e2015-10-23 21:45:59 +00001282 // The first phdr entry is PT_PHDR which describes the program header itself.
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001283 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
Rui Ueyama953c2c42015-10-10 23:59:57 +00001284
Rui Ueyama803195e2015-10-23 21:45:59 +00001285 // PT_INTERP must be the second entry if exists.
Rafael Espindola24e6f362017-02-24 15:07:30 +00001286 if (OutputSection *Sec = findSection(".interp"))
Rui Ueyamadb00b612017-02-01 22:42:17 +00001287 AddHdr(PT_INTERP, Sec->getPhdrFlags())->add(Sec);
Rafael Espindola70107762015-09-11 18:49:42 +00001288
Rui Ueyama803195e2015-10-23 21:45:59 +00001289 // Add the first PT_LOAD segment for regular output sections.
Rafael Espindolab45fd702016-09-20 15:22:27 +00001290 uintX_t Flags = computeFlags<ELFT>(PF_R);
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001291 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
Rafael Espindola24e6f362017-02-24 15:07:30 +00001292 for (OutputSection *Sec : OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001293 if (!(Sec->Flags & SHF_ALLOC))
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +00001294 break;
George Rimar7702bc22017-03-16 11:20:02 +00001295 if (!needsPtLoad(Sec))
Rafael Espindolaef762f22016-02-10 23:29:38 +00001296 continue;
1297
George Rimar8ceadb32016-08-17 07:44:19 +00001298 // Segments are contiguous memory regions that has the same attributes
1299 // (e.g. executable or writable). There is one phdr for each segment.
1300 // Therefore, we need to create a new phdr when the next section has
1301 // different flags or is loaded at a discontiguous address using AT linker
1302 // script command.
Rafael Espindolab45fd702016-09-20 15:22:27 +00001303 uintX_t NewFlags = computeFlags<ELFT>(Sec->getPhdrFlags());
George Rimara8dba482017-03-20 10:09:58 +00001304 if (Script->hasLMA(Sec->Name) || Flags != NewFlags) {
Rafael Espindolae090fb22016-03-09 21:37:22 +00001305 Load = AddHdr(PT_LOAD, NewFlags);
Rafael Espindola4fc60442016-02-10 22:43:13 +00001306 Flags = NewFlags;
1307 }
Michael J. Spencer78aa1de2015-11-03 00:34:39 +00001308
Rui Ueyama18f084f2016-07-20 19:36:41 +00001309 Load->add(Sec);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001310 }
Rafael Espindola6b83b902015-08-12 00:00:24 +00001311
Rui Ueyamadb00b612017-02-01 22:42:17 +00001312 // Add a TLS segment if any.
1313 PhdrEntry TlsHdr(PT_TLS, PF_R);
Rafael Espindola24e6f362017-02-24 15:07:30 +00001314 for (OutputSection *Sec : OutputSections)
Rui Ueyamadb00b612017-02-01 22:42:17 +00001315 if (Sec->Flags & SHF_TLS)
1316 TlsHdr.add(Sec);
Rafael Espindola4fc60442016-02-10 22:43:13 +00001317 if (TlsHdr.First)
Rui Ueyama703296a2016-07-20 19:36:39 +00001318 Ret.push_back(std::move(TlsHdr));
Michael J. Spencer78aa1de2015-11-03 00:34:39 +00001319
Rui Ueyama803195e2015-10-23 21:45:59 +00001320 // Add an entry for .dynamic.
Rui Ueyamadb00b612017-02-01 22:42:17 +00001321 if (In<ELFT>::DynSymTab)
1322 AddHdr(PT_DYNAMIC, In<ELFT>::Dynamic->OutSec->getPhdrFlags())
1323 ->add(In<ELFT>::Dynamic->OutSec);
Rafael Espindola91009b32015-08-12 01:45:28 +00001324
Rafael Espindola4fc60442016-02-10 22:43:13 +00001325 // PT_GNU_RELRO includes all sections that should be marked as
1326 // read-only by dynamic linker after proccessing relocations.
Rui Ueyamadb00b612017-02-01 22:42:17 +00001327 PhdrEntry RelRo(PT_GNU_RELRO, PF_R);
Rafael Espindola24e6f362017-02-24 15:07:30 +00001328 for (OutputSection *Sec : OutputSections)
George Rimar7702bc22017-03-16 11:20:02 +00001329 if (needsPtLoad(Sec) && isRelroSection<ELFT>(Sec))
Rui Ueyamadb00b612017-02-01 22:42:17 +00001330 RelRo.add(Sec);
Rafael Espindola4fc60442016-02-10 22:43:13 +00001331 if (RelRo.First)
Rui Ueyama703296a2016-07-20 19:36:39 +00001332 Ret.push_back(std::move(RelRo));
George Rimare3336c02015-11-24 10:15:50 +00001333
Rafael Espindola4fc60442016-02-10 22:43:13 +00001334 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
Eugene Leviant30c1b432017-03-14 08:49:09 +00001335 if (!In<ELFT>::EhFrame->empty() && In<ELFT>::EhFrameHdr &&
1336 In<ELFT>::EhFrame->OutSec && In<ELFT>::EhFrameHdr->OutSec)
Rui Ueyamadb00b612017-02-01 22:42:17 +00001337 AddHdr(PT_GNU_EH_FRAME, In<ELFT>::EhFrameHdr->OutSec->getPhdrFlags())
1338 ->add(In<ELFT>::EhFrameHdr->OutSec);
George Rimarf6bc65a2016-01-15 13:34:52 +00001339
George Rimar270173f2016-10-14 13:02:22 +00001340 // PT_OPENBSD_RANDOMIZE specifies the location and size of a part of the
1341 // memory image of the program that must be filled with random data before any
1342 // code in the object is executed.
Rafael Espindola24e6f362017-02-24 15:07:30 +00001343 if (OutputSection *Sec = findSection(".openbsd.randomdata"))
Rui Ueyamadb00b612017-02-01 22:42:17 +00001344 AddHdr(PT_OPENBSD_RANDOMIZE, Sec->getPhdrFlags())->add(Sec);
George Rimar270173f2016-10-14 13:02:22 +00001345
Rui Ueyamae79b09a2015-11-21 22:19:32 +00001346 // PT_GNU_STACK is a special section to tell the loader to make the
Rui Ueyamaa7e87252017-02-23 08:09:51 +00001347 // pages for the stack non-executable. If you really want an executable
1348 // stack, you can pass -z execstack, but that's not recommended for
1349 // security reasons.
1350 unsigned Perm;
1351 if (Config->ZExecstack)
1352 Perm = PF_R | PF_W | PF_X;
1353 else
1354 Perm = PF_R | PF_W;
1355 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
Rafael Espindola9907eb02016-03-01 13:23:29 +00001356
George Rimarcc6e5672016-10-14 10:34:36 +00001357 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
1358 // is expected to perform W^X violations, such as calling mprotect(2) or
1359 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
1360 // OpenBSD.
1361 if (Config->ZWxneeded)
1362 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
1363
Petr Hosek4d65ef3b2017-02-01 20:58:41 +00001364 // Create one PT_NOTE per a group of contiguous .note sections.
1365 PhdrEntry *Note = nullptr;
Rafael Espindola24e6f362017-02-24 15:07:30 +00001366 for (OutputSection *Sec : OutputSections) {
Petr Hosek4d65ef3b2017-02-01 20:58:41 +00001367 if (Sec->Type == SHT_NOTE) {
George Rimara8dba482017-03-20 10:09:58 +00001368 if (!Note || Script->hasLMA(Sec->Name))
Petr Hosek4d65ef3b2017-02-01 20:58:41 +00001369 Note = AddHdr(PT_NOTE, PF_R);
1370 Note->add(Sec);
1371 } else {
1372 Note = nullptr;
1373 }
1374 }
Rui Ueyama703296a2016-07-20 19:36:39 +00001375 return Ret;
Rafael Espindola4fc60442016-02-10 22:43:13 +00001376}
1377
Rafael Espindola8e670002016-11-28 00:40:21 +00001378template <class ELFT>
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001379void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry> &Phdrs) {
Rafael Espindola8e670002016-11-28 00:40:21 +00001380 if (Config->EMachine != EM_ARM)
1381 return;
1382 auto I = std::find_if(
1383 OutputSections.begin(), OutputSections.end(),
Rafael Espindola24e6f362017-02-24 15:07:30 +00001384 [](OutputSection *Sec) { return Sec->Type == SHT_ARM_EXIDX; });
Rafael Espindola8e670002016-11-28 00:40:21 +00001385 if (I == OutputSections.end())
1386 return;
1387
1388 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001389 PhdrEntry ARMExidx(PT_ARM_EXIDX, PF_R);
Rafael Espindola8e670002016-11-28 00:40:21 +00001390 ARMExidx.add(*I);
1391 Phdrs.push_back(ARMExidx);
1392}
1393
Peter Collingbourne628ec9f2017-01-10 01:21:30 +00001394// The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
1395// first section after PT_GNU_RELRO have to be page aligned so that the dynamic
1396// linker can set the permissions.
Rui Ueyama47091902016-03-30 19:41:51 +00001397template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001398 for (const PhdrEntry &P : Phdrs)
Rafael Espindola5967c972016-12-19 21:21:07 +00001399 if (P.p_type == PT_LOAD && P.First)
Rui Ueyama47091902016-03-30 19:41:51 +00001400 P.First->PageAlign = true;
1401
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001402 for (const PhdrEntry &P : Phdrs) {
1403 if (P.p_type != PT_GNU_RELRO)
Rui Ueyama47091902016-03-30 19:41:51 +00001404 continue;
Peter Collingbourne628ec9f2017-01-10 01:21:30 +00001405 if (P.First)
1406 P.First->PageAlign = true;
Rui Ueyama47091902016-03-30 19:41:51 +00001407 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
1408 // have to align it to a page.
1409 auto End = OutputSections.end();
1410 auto I = std::find(OutputSections.begin(), End, P.Last);
1411 if (I == End || (I + 1) == End)
1412 continue;
Rafael Espindola24e6f362017-02-24 15:07:30 +00001413 OutputSection *Sec = *(I + 1);
George Rimar7702bc22017-03-16 11:20:02 +00001414 if (needsPtLoad(Sec))
Rui Ueyama47091902016-03-30 19:41:51 +00001415 Sec->PageAlign = true;
1416 }
1417}
1418
Rafael Espindola0347c0b2017-01-20 20:46:15 +00001419bool elf::allocateHeaders(std::vector<PhdrEntry> &Phdrs,
Rafael Espindola24e6f362017-02-24 15:07:30 +00001420 ArrayRef<OutputSection *> OutputSections,
Rafael Espindola8c495e22017-01-20 20:41:18 +00001421 uint64_t Min) {
Rafael Espindola5967c972016-12-19 21:21:07 +00001422 auto FirstPTLoad =
1423 std::find_if(Phdrs.begin(), Phdrs.end(),
1424 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
1425 if (FirstPTLoad == Phdrs.end())
Rafael Espindola8c495e22017-01-20 20:41:18 +00001426 return false;
1427
George Rimar78aa2702017-03-13 14:40:58 +00001428 uint64_t HeaderSize = getHeaderSize();
Rafael Espindola0347c0b2017-01-20 20:46:15 +00001429 if (HeaderSize > Min) {
1430 auto PhdrI =
1431 std::find_if(Phdrs.begin(), Phdrs.end(),
1432 [](const PhdrEntry &E) { return E.p_type == PT_PHDR; });
1433 if (PhdrI != Phdrs.end())
1434 Phdrs.erase(PhdrI);
Rafael Espindola8c495e22017-01-20 20:41:18 +00001435 return false;
Rafael Espindola0347c0b2017-01-20 20:46:15 +00001436 }
Rafael Espindola8c495e22017-01-20 20:41:18 +00001437 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
1438
Rui Ueyamaa34da932017-03-21 23:03:09 +00001439 if (!Script->Opt.HasSections)
Rafael Espindola8c495e22017-01-20 20:41:18 +00001440 Config->ImageBase = Min = std::min(Min, Config->ImageBase);
1441
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001442 Out::ElfHeader->Addr = Min;
1443 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
Rafael Espindola8c495e22017-01-20 20:41:18 +00001444
George Rimara8dba482017-03-20 10:09:58 +00001445 if (Script->hasPhdrsCommands())
Rafael Espindola8c495e22017-01-20 20:41:18 +00001446 return true;
1447
Rafael Espindola5967c972016-12-19 21:21:07 +00001448 if (FirstPTLoad->First)
Rafael Espindola24e6f362017-02-24 15:07:30 +00001449 for (OutputSection *Sec : OutputSections)
Rafael Espindola5967c972016-12-19 21:21:07 +00001450 if (Sec->FirstInPtLoad == FirstPTLoad->First)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001451 Sec->FirstInPtLoad = Out::ElfHeader;
1452 FirstPTLoad->First = Out::ElfHeader;
Rafael Espindola5967c972016-12-19 21:21:07 +00001453 if (!FirstPTLoad->Last)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001454 FirstPTLoad->Last = Out::ProgramHeaders;
Rafael Espindola8c495e22017-01-20 20:41:18 +00001455 return true;
Rafael Espindola5967c972016-12-19 21:21:07 +00001456}
1457
George Rimar7ca06272016-04-06 07:20:45 +00001458// We should set file offsets and VAs for elf header and program headers
1459// sections. These are special, we do not include them into output sections
1460// list, but have them to simplify the code.
1461template <class ELFT> void Writer<ELFT>::fixHeaders() {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001462 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
Rafael Espindola1c570072016-11-21 19:59:33 +00001463 // If the script has SECTIONS, assignAddresses will compute the values.
Rui Ueyamaa34da932017-03-21 23:03:09 +00001464 if (Script->Opt.HasSections)
Rafael Espindola1c570072016-11-21 19:59:33 +00001465 return;
Rafael Espindola5967c972016-12-19 21:21:07 +00001466
Rafael Espindola5967c972016-12-19 21:21:07 +00001467 // When -T<section> option is specified, lower the base to make room for those
1468 // sections.
Rafael Espindola8c495e22017-01-20 20:41:18 +00001469 uint64_t Min = -1;
1470 if (!Config->SectionStartMap.empty())
Rafael Espindola5967c972016-12-19 21:21:07 +00001471 for (const auto &P : Config->SectionStartMap)
1472 Min = std::min(Min, P.second);
Rafael Espindola5967c972016-12-19 21:21:07 +00001473
George Rimar2d262102017-03-14 09:03:53 +00001474 AllocateHeader = allocateHeaders(Phdrs, OutputSections, Min);
George Rimar7ca06272016-04-06 07:20:45 +00001475}
1476
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001477// Assign VAs (addresses at run-time) to output sections.
Rafael Espindola4fc60442016-02-10 22:43:13 +00001478template <class ELFT> void Writer<ELFT>::assignAddresses() {
Rafael Espindola5967c972016-12-19 21:21:07 +00001479 uintX_t VA = Config->ImageBase;
1480 if (AllocateHeader)
George Rimar78aa2702017-03-13 14:40:58 +00001481 VA += getHeaderSize();
George Rimar7ca06272016-04-06 07:20:45 +00001482 uintX_t ThreadBssOffset = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +00001483 for (OutputSection *Sec : OutputSections) {
Rafael Espindolafcd208f2017-03-08 19:35:29 +00001484 uint32_t Alignment = Sec->Alignment;
Rui Ueyama47091902016-03-30 19:41:51 +00001485 if (Sec->PageAlign)
Petr Hosek997f8832016-09-28 15:20:47 +00001486 Alignment = std::max<uintX_t>(Alignment, Config->MaxPageSize);
Rafael Espindola4fc60442016-02-10 22:43:13 +00001487
Rafael Espindola40849412017-02-24 14:28:00 +00001488 auto I = Config->SectionStartMap.find(Sec->Name);
George Rimard73ef172016-09-14 13:07:13 +00001489 if (I != Config->SectionStartMap.end())
1490 VA = I->second;
1491
Rafael Espindola4fc60442016-02-10 22:43:13 +00001492 // We only assign VAs to allocated sections.
George Rimar7702bc22017-03-16 11:20:02 +00001493 if (needsPtLoad(Sec)) {
Rui Ueyama424b4082016-06-17 01:18:46 +00001494 VA = alignTo(VA, Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +00001495 Sec->Addr = VA;
1496 VA += Sec->Size;
1497 } else if (Sec->Flags & SHF_TLS && Sec->Type == SHT_NOBITS) {
Rafael Espindolaef762f22016-02-10 23:29:38 +00001498 uintX_t TVA = VA + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +00001499 TVA = alignTo(TVA, Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +00001500 Sec->Addr = TVA;
1501 ThreadBssOffset = TVA - VA + Sec->Size;
Rafael Espindola4fc60442016-02-10 22:43:13 +00001502 }
Rui Ueyama69960ba2015-10-10 23:25:39 +00001503 }
George Rimar900a2602016-04-01 10:49:14 +00001504}
1505
George Rimar5f857322016-04-27 09:16:28 +00001506// Adjusts the file alignment for a given output section and returns
1507// its new file offset. The file offset must be the same with its
1508// virtual address (modulo the page size) so that the loader can load
1509// executables without any address adjustment.
1510template <class ELFT, class uintX_t>
Rafael Espindola24e6f362017-02-24 15:07:30 +00001511static uintX_t getFileAlignment(uintX_t Off, OutputSection *Sec) {
1512 OutputSection *First = Sec->FirstInPtLoad;
Rafael Espindola8b8f74f2016-12-07 20:20:39 +00001513 // If the section is not in a PT_LOAD, we just have to align it.
Rafael Espindolac94678b2016-09-29 16:29:55 +00001514 if (!First)
Rafael Espindola37707632017-03-07 14:55:52 +00001515 return alignTo(Off, Sec->Alignment);
Eugene Leviant3d9abec2016-09-29 09:20:33 +00001516
Rafael Espindola8b8f74f2016-12-07 20:20:39 +00001517 // The first section in a PT_LOAD has to have congruent offset and address
1518 // module the page size.
Rafael Espindolac94678b2016-09-29 16:29:55 +00001519 if (Sec == First)
Rafael Espindolaa86a9c62016-12-07 20:10:43 +00001520 return alignTo(Off, Config->MaxPageSize, Sec->Addr);
Rafael Espindola8b8f74f2016-12-07 20:20:39 +00001521
1522 // If two sections share the same PT_LOAD the file offset is calculated
1523 // using this formula: Off2 = Off1 + (VA2 - VA1).
Rafael Espindola04a2e342016-11-09 01:42:41 +00001524 return First->Offset + Sec->Addr - First->Addr;
George Rimar5f857322016-04-27 09:16:28 +00001525}
1526
George Rimar86ce2672016-08-25 09:05:47 +00001527template <class ELFT, class uintX_t>
Rafael Espindola24e6f362017-02-24 15:07:30 +00001528static uintX_t setOffset(OutputSection *Sec, uintX_t Off) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001529 if (Sec->Type == SHT_NOBITS) {
1530 Sec->Offset = Off;
Rui Ueyama35723f02017-02-14 23:35:42 +00001531 return Off;
George Rimar86ce2672016-08-25 09:05:47 +00001532 }
1533
1534 Off = getFileAlignment<ELFT>(Off, Sec);
Rafael Espindola04a2e342016-11-09 01:42:41 +00001535 Sec->Offset = Off;
Rui Ueyama35723f02017-02-14 23:35:42 +00001536 return Off + Sec->Size;
George Rimar86ce2672016-08-25 09:05:47 +00001537}
1538
1539template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
1540 uintX_t Off = 0;
Rafael Espindola24e6f362017-02-24 15:07:30 +00001541 for (OutputSection *Sec : OutputSections)
Rafael Espindola04a2e342016-11-09 01:42:41 +00001542 if (Sec->Flags & SHF_ALLOC)
Rui Ueyama35723f02017-02-14 23:35:42 +00001543 Off = setOffset<ELFT>(Sec, Off);
George Rimar86ce2672016-08-25 09:05:47 +00001544 FileSize = alignTo(Off, sizeof(uintX_t));
1545}
1546
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001547// Assign file offsets to output sections.
1548template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
Eugene Leviant467c4d52016-07-01 10:27:36 +00001549 uintX_t Off = 0;
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001550 Off = setOffset<ELFT>(Out::ElfHeader, Off);
1551 Off = setOffset<ELFT>(Out::ProgramHeaders, Off);
George Rimar7ca06272016-04-06 07:20:45 +00001552
Rafael Espindola24e6f362017-02-24 15:07:30 +00001553 for (OutputSection *Sec : OutputSections)
Rui Ueyama35723f02017-02-14 23:35:42 +00001554 Off = setOffset<ELFT>(Sec, Off);
Eugene Leviant467c4d52016-07-01 10:27:36 +00001555
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001556 SectionHeaderOff = alignTo(Off, sizeof(uintX_t));
George Rimar7ca06272016-04-06 07:20:45 +00001557 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
Rui Ueyamae044e9c2016-04-01 17:07:17 +00001558}
1559
1560// Finalize the program headers. We call this function after we assign
1561// file offsets and VAs to all sections.
1562template <class ELFT> void Writer<ELFT>::setPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001563 for (PhdrEntry &P : Phdrs) {
Rafael Espindola24e6f362017-02-24 15:07:30 +00001564 OutputSection *First = P.First;
1565 OutputSection *Last = P.Last;
Rui Ueyamae8a45e42016-04-01 22:42:04 +00001566 if (First) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001567 P.p_filesz = Last->Offset - First->Offset;
Rafael Espindola04a2e342016-11-09 01:42:41 +00001568 if (Last->Type != SHT_NOBITS)
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001569 P.p_filesz += Last->Size;
1570 P.p_memsz = Last->Addr + Last->Size - First->Addr;
1571 P.p_offset = First->Offset;
1572 P.p_vaddr = First->Addr;
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001573 if (!P.HasLMA)
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001574 P.p_paddr = First->getLMA();
Rafael Espindola4fc60442016-02-10 22:43:13 +00001575 }
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001576 if (P.p_type == PT_LOAD)
1577 P.p_align = Config->MaxPageSize;
Peter Collingbourne7b5088b2017-01-04 18:56:15 +00001578 else if (P.p_type == PT_GNU_RELRO) {
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001579 P.p_align = 1;
Peter Collingbourne7b5088b2017-01-04 18:56:15 +00001580 // The glibc dynamic loader rounds the size down, so we need to round up
1581 // to protect the last page. This is a no-op on FreeBSD which always
1582 // rounds up.
Peter Collingbourne4a72c382017-01-30 18:20:07 +00001583 P.p_memsz = alignTo(P.p_memsz, Target->PageSize);
Peter Collingbourne7b5088b2017-01-04 18:56:15 +00001584 }
George Rimar8ceadb32016-08-17 07:44:19 +00001585
Rafael Espindola4fc60442016-02-10 22:43:13 +00001586 // The TLS pointer goes after PT_TLS. At least glibc will align it,
1587 // so round up the size to make sure the offsets are correct.
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001588 if (P.p_type == PT_TLS) {
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001589 Out::TlsPhdr = &P;
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001590 if (P.p_memsz)
1591 P.p_memsz = alignTo(P.p_memsz, P.p_align);
Rui Ueyama803195e2015-10-23 21:45:59 +00001592 }
1593 }
Michael J. Spencer84487f12015-07-24 21:03:07 +00001594}
1595
Rui Ueyama2eda6d12016-11-23 22:41:00 +00001596// The entry point address is chosen in the following ways.
1597//
1598// 1. the '-e' entry command-line option;
1599// 2. the ENTRY(symbol) command in a linker control script;
1600// 3. the value of the symbol start, if present;
1601// 4. the address of the first byte of the .text section, if present;
1602// 5. the address 0.
1603template <class ELFT> typename ELFT::uint Writer<ELFT>::getEntryAddr() {
Rui Ueyamaa1407c42016-12-07 03:23:06 +00001604 // Case 1, 2 or 3. As a special case, if the symbol is actually
1605 // a number, we'll use that number as an address.
Rui Ueyama8da7aa02016-10-20 00:07:36 +00001606 if (SymbolBody *B = Symtab<ELFT>::X->find(Config->Entry))
George Rimarf64618a2017-03-17 11:56:54 +00001607 return B->getVA();
Rui Ueyamaa1407c42016-12-07 03:23:06 +00001608 uint64_t Addr;
1609 if (!Config->Entry.getAsInteger(0, Addr))
1610 return Addr;
Rui Ueyama2eda6d12016-11-23 22:41:00 +00001611
1612 // Case 4
Rafael Espindola24e6f362017-02-24 15:07:30 +00001613 if (OutputSection *Sec = findSection(".text")) {
Rui Ueyama9e5f5ef2016-12-07 04:06:21 +00001614 if (Config->WarnMissingEntry)
Petr Hosek2f50fef2016-12-07 02:26:16 +00001615 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
1616 utohexstr(Sec->Addr));
Rui Ueyama2eda6d12016-11-23 22:41:00 +00001617 return Sec->Addr;
1618 }
1619
1620 // Case 5
Rui Ueyama9e5f5ef2016-12-07 04:06:21 +00001621 if (Config->WarnMissingEntry)
Petr Hosek2f50fef2016-12-07 02:26:16 +00001622 warn("cannot find entry symbol " + Config->Entry +
1623 "; not setting start address");
Rui Ueyama8da7aa02016-10-20 00:07:36 +00001624 return 0;
Rui Ueyama3bfaba92015-12-24 08:37:34 +00001625}
1626
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001627template <class ELFT> static uint8_t getELFEncoding() {
1628 if (ELFT::TargetEndianness == llvm::support::little)
1629 return ELFDATA2LSB;
1630 return ELFDATA2MSB;
1631}
1632
1633static uint16_t getELFType() {
Rui Ueyamad57e74b72017-03-17 23:29:01 +00001634 if (Config->Pic)
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001635 return ET_DYN;
1636 if (Config->Relocatable)
1637 return ET_REL;
1638 return ET_EXEC;
1639}
1640
Rui Ueyama1a311f12015-12-26 10:52:26 +00001641// This function is called after we have assigned address and size
Rafael Espindola78493a22017-01-28 17:48:21 +00001642// to each section. This function fixes some predefined
Rui Ueyama1a311f12015-12-26 10:52:26 +00001643// symbol values that depend on section address and size.
Rafael Espindola78493a22017-01-28 17:48:21 +00001644template <class ELFT> void Writer<ELFT>::fixPredefinedSymbols() {
Rafael Espindola5616adf2017-03-08 22:36:28 +00001645 auto Set = [](DefinedRegular *S1, DefinedRegular *S2, OutputSection *Sec,
Rafael Espindola24e6f362017-02-24 15:07:30 +00001646 uint64_t Value) {
Rafael Espindola78493a22017-01-28 17:48:21 +00001647 if (S1) {
1648 S1->Section = Sec;
1649 S1->Value = Value;
1650 }
1651 if (S2) {
1652 S2->Section = Sec;
1653 S2->Value = Value;
1654 }
Rui Ueyama467dbdd2016-04-21 20:50:15 +00001655 };
1656
George Rimar2abc5872016-03-01 19:18:07 +00001657 // _etext is the first location after the last read-only loadable segment.
1658 // _edata is the first location after the last read-write loadable segment.
George Rimarefded312016-04-01 10:23:32 +00001659 // _end is the first location after the uninitialized data region.
Rafael Espindola78493a22017-01-28 17:48:21 +00001660 PhdrEntry *Last = nullptr;
1661 PhdrEntry *LastRO = nullptr;
1662 PhdrEntry *LastRW = nullptr;
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001663 for (PhdrEntry &P : Phdrs) {
1664 if (P.p_type != PT_LOAD)
George Rimar9e859392016-02-26 14:36:36 +00001665 continue;
Rafael Espindola78493a22017-01-28 17:48:21 +00001666 Last = &P;
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001667 if (P.p_flags & PF_W)
Rafael Espindola78493a22017-01-28 17:48:21 +00001668 LastRW = &P;
George Rimar8bbff7e2016-04-14 14:37:59 +00001669 else
Rafael Espindola78493a22017-01-28 17:48:21 +00001670 LastRO = &P;
George Rimar9e859392016-02-26 14:36:36 +00001671 }
Rafael Espindola78493a22017-01-28 17:48:21 +00001672 if (Last)
Rui Ueyama80474a22017-02-28 19:29:55 +00001673 Set(ElfSym::End, ElfSym::End2, Last->First, Last->p_memsz);
Rafael Espindola78493a22017-01-28 17:48:21 +00001674 if (LastRO)
Rui Ueyama80474a22017-02-28 19:29:55 +00001675 Set(ElfSym::Etext, ElfSym::Etext2, LastRO->First, LastRO->p_filesz);
Rafael Espindola78493a22017-01-28 17:48:21 +00001676 if (LastRW)
Rui Ueyama80474a22017-02-28 19:29:55 +00001677 Set(ElfSym::Edata, ElfSym::Edata2, LastRW->First, LastRW->p_filesz);
Simon Atanasyan8469b882016-11-23 22:22:16 +00001678
1679 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1680 // be equal to the _gp symbol's value.
1681 if (Config->EMachine == EM_MIPS) {
Rui Ueyama80474a22017-02-28 19:29:55 +00001682 if (!ElfSym::MipsGp->Value) {
Simon Atanasyan2903a8a2016-12-12 21:34:11 +00001683 // Find GP-relative section with the lowest address
1684 // and use this address to calculate default _gp value.
1685 uintX_t Gp = -1;
Rafael Espindola24e6f362017-02-24 15:07:30 +00001686 for (const OutputSection *OS : OutputSections)
Simon Atanasyan2903a8a2016-12-12 21:34:11 +00001687 if ((OS->Flags & SHF_MIPS_GPREL) && OS->Addr < Gp)
1688 Gp = OS->Addr;
1689 if (Gp != (uintX_t)-1)
Rui Ueyama80474a22017-02-28 19:29:55 +00001690 ElfSym::MipsGp->Value = Gp + 0x7ff0;
Simon Atanasyan2903a8a2016-12-12 21:34:11 +00001691 }
Simon Atanasyan8469b882016-11-23 22:22:16 +00001692 }
Rui Ueyama1a311f12015-12-26 10:52:26 +00001693}
1694
Michael J. Spencer84487f12015-07-24 21:03:07 +00001695template <class ELFT> void Writer<ELFT>::writeHeader() {
1696 uint8_t *Buf = Buffer->getBufferStart();
Rui Ueyamae08cd672015-10-23 22:44:39 +00001697 memcpy(Buf, "\177ELF", 4);
1698
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001699 // Write the ELF header.
Rafael Espindola18608a02015-09-08 21:57:31 +00001700 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
Rafael Espindola4b7c2fc2015-08-05 15:08:40 +00001701 EHdr->e_ident[EI_CLASS] = ELFT::Is64Bits ? ELFCLASS64 : ELFCLASS32;
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001702 EHdr->e_ident[EI_DATA] = getELFEncoding<ELFT>();
Michael J. Spencer84487f12015-07-24 21:03:07 +00001703 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
Rafael Espindola7cc713a2016-10-27 14:00:51 +00001704 EHdr->e_ident[EI_OSABI] = Config->OSABI;
Rui Ueyama4cea4e82016-02-25 19:28:37 +00001705 EHdr->e_type = getELFType();
Rafael Espindola7cc713a2016-10-27 14:00:51 +00001706 EHdr->e_machine = Config->EMachine;
Michael J. Spencer84487f12015-07-24 21:03:07 +00001707 EHdr->e_version = EV_CURRENT;
Rui Ueyama2eda6d12016-11-23 22:41:00 +00001708 EHdr->e_entry = getEntryAddr();
Michael J. Spencer8039dae22015-07-29 00:30:10 +00001709 EHdr->e_shoff = SectionHeaderOff;
Rafael Espindola18608a02015-09-08 21:57:31 +00001710 EHdr->e_ehsize = sizeof(Elf_Ehdr);
Rui Ueyama2f1b79f2015-10-10 22:34:30 +00001711 EHdr->e_phnum = Phdrs.size();
Rafael Espindola18608a02015-09-08 21:57:31 +00001712 EHdr->e_shentsize = sizeof(Elf_Shdr);
George Rimar7ca06272016-04-06 07:20:45 +00001713 EHdr->e_shnum = OutputSections.size() + 1;
Eugene Leviant22eb0262016-11-14 09:16:00 +00001714 EHdr->e_shstrndx = In<ELFT>::ShStrTab->OutSec->SectionIndex;
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001715
Rui Ueyama1e2e8ea2016-09-13 20:51:32 +00001716 if (Config->EMachine == EM_ARM)
1717 // We don't currently use any features incompatible with EF_ARM_EABI_VER5,
1718 // but we don't have any firm guarantees of conformance. Linux AArch64
1719 // kernels (as of 2016) require an EABI version to be set.
1720 EHdr->e_flags = EF_ARM_EABI_VER5;
1721 else if (Config->EMachine == EM_MIPS)
Simon Atanasyan4f90c2f2016-07-20 20:30:41 +00001722 EHdr->e_flags = getMipsEFlags<ELFT>();
Rui Ueyama22b5d1f2016-03-13 19:29:17 +00001723
George Rimar58941ee2016-02-25 08:23:37 +00001724 if (!Config->Relocatable) {
1725 EHdr->e_phoff = sizeof(Elf_Ehdr);
1726 EHdr->e_phentsize = sizeof(Elf_Phdr);
1727 }
1728
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001729 // Write the program header table.
Rafael Espindola4fc60442016-02-10 22:43:13 +00001730 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001731 for (PhdrEntry &P : Phdrs) {
1732 HBuf->p_type = P.p_type;
1733 HBuf->p_flags = P.p_flags;
1734 HBuf->p_offset = P.p_offset;
1735 HBuf->p_vaddr = P.p_vaddr;
1736 HBuf->p_paddr = P.p_paddr;
1737 HBuf->p_filesz = P.p_filesz;
1738 HBuf->p_memsz = P.p_memsz;
1739 HBuf->p_align = P.p_align;
1740 ++HBuf;
1741 }
Rafael Espindolae438e072015-09-08 22:55:28 +00001742
Rui Ueyama6621d8e2015-10-24 17:57:40 +00001743 // Write the section header table. Note that the first table entry is null.
Rui Ueyamaad59b652016-02-25 23:58:21 +00001744 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
Rafael Espindola24e6f362017-02-24 15:07:30 +00001745 for (OutputSection *Sec : OutputSections)
Rafael Espindolae08e78d2016-11-09 23:23:45 +00001746 Sec->writeHeaderTo<ELFT>(++SHdrs);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001747}
1748
Rui Ueyama6d12eae2016-12-05 17:40:37 +00001749// Open a result file.
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +00001750template <class ELFT> void Writer<ELFT>::openFile() {
Rui Ueyama6d12eae2016-12-05 17:40:37 +00001751 unlinkAsync(Config->OutputFile);
Rafael Espindolabdc8f2f2015-08-13 00:31:46 +00001752 ErrorOr<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
Rui Ueyamacbe39262016-02-02 22:48:04 +00001753 FileOutputBuffer::create(Config->OutputFile, FileSize,
1754 FileOutputBuffer::F_executable);
Rui Ueyama6d12eae2016-12-05 17:40:37 +00001755
Rui Ueyamaaa2db882016-07-15 01:38:54 +00001756 if (auto EC = BufferOrErr.getError())
Rui Ueyamac8d3a832017-01-12 22:18:04 +00001757 error("failed to open " + Config->OutputFile + ": " + EC.message());
Rui Ueyamaf7f52ef2016-04-01 17:24:19 +00001758 else
Rui Ueyamaaa2db882016-07-15 01:38:54 +00001759 Buffer = std::move(*BufferOrErr);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001760}
1761
George Rimar86ce2672016-08-25 09:05:47 +00001762template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
1763 uint8_t *Buf = Buffer->getBufferStart();
Rafael Espindola24e6f362017-02-24 15:07:30 +00001764 for (OutputSection *Sec : OutputSections)
Rafael Espindola04a2e342016-11-09 01:42:41 +00001765 if (Sec->Flags & SHF_ALLOC)
Rafael Espindola24e6f362017-02-24 15:07:30 +00001766 Sec->writeTo<ELFT>(Buf + Sec->Offset);
George Rimar86ce2672016-08-25 09:05:47 +00001767}
1768
Michael J. Spencer84487f12015-07-24 21:03:07 +00001769// Write section contents to a mmap'ed file.
1770template <class ELFT> void Writer<ELFT>::writeSections() {
1771 uint8_t *Buf = Buffer->getBufferStart();
Hal Finkeldaedc122015-10-12 23:16:53 +00001772
Rui Ueyama75118252016-08-09 01:35:37 +00001773 // PPC64 needs to process relocations in the .opd section
1774 // before processing relocations in code-containing sections.
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001775 Out::Opd = findSection(".opd");
1776 if (Out::Opd) {
1777 Out::OpdBuf = Buf + Out::Opd->Offset;
1778 Out::Opd->template writeTo<ELFT>(Buf + Out::Opd->Offset);
Rafael Espindola7a513052015-10-13 14:45:51 +00001779 }
Hal Finkeldaedc122015-10-12 23:16:53 +00001780
Rafael Espindola24e6f362017-02-24 15:07:30 +00001781 OutputSection *EhFrameHdr =
Eugene Leviant952eb4d2016-11-21 15:52:10 +00001782 In<ELFT>::EhFrameHdr ? In<ELFT>::EhFrameHdr->OutSec : nullptr;
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001783
1784 // In -r or -emit-relocs mode, write the relocation sections first as in
1785 // ELf_Rel targets we might find out that we need to modify the relocated
1786 // section while doing it.
Rafael Espindola24e6f362017-02-24 15:07:30 +00001787 for (OutputSection *Sec : OutputSections)
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001788 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola24e6f362017-02-24 15:07:30 +00001789 Sec->writeTo<ELFT>(Buf + Sec->Offset);
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001790
Rafael Espindola24e6f362017-02-24 15:07:30 +00001791 for (OutputSection *Sec : OutputSections)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001792 if (Sec != Out::Opd && Sec != EhFrameHdr && Sec->Type != SHT_REL &&
Rafael Espindola08d6a3f2017-02-11 01:40:49 +00001793 Sec->Type != SHT_RELA)
Rafael Espindola24e6f362017-02-24 15:07:30 +00001794 Sec->writeTo<ELFT>(Buf + Sec->Offset);
Eugene Leviante4f590f2016-08-31 07:43:50 +00001795
1796 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
1797 // it should be written after .eh_frame is written.
Rafael Espindola66b4e212017-02-23 22:06:28 +00001798 if (EhFrameHdr)
Rafael Espindola24e6f362017-02-24 15:07:30 +00001799 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
Michael J. Spencer84487f12015-07-24 21:03:07 +00001800}
Rui Ueyama3ce825e2015-10-09 21:07:25 +00001801
Rui Ueyama634ddf02016-03-11 20:51:53 +00001802template <class ELFT> void Writer<ELFT>::writeBuildId() {
Eugene Leviant282251a2016-11-01 09:49:24 +00001803 if (!In<ELFT>::BuildId || !In<ELFT>::BuildId->OutSec)
Rui Ueyama634ddf02016-03-11 20:51:53 +00001804 return;
1805
Petr Hosekfdfcb792016-09-01 22:43:03 +00001806 // Compute a hash of all sections of the output file.
Rui Ueyama634ddf02016-03-11 20:51:53 +00001807 uint8_t *Start = Buffer->getBufferStart();
Petr Hosekfdfcb792016-09-01 22:43:03 +00001808 uint8_t *End = Start + FileSize;
Eugene Leviant282251a2016-11-01 09:49:24 +00001809 In<ELFT>::BuildId->writeBuildId({Start, End});
Rui Ueyama634ddf02016-03-11 20:51:53 +00001810}
1811
Rui Ueyama84907c52016-08-09 03:38:23 +00001812template void elf::writeResult<ELF32LE>();
1813template void elf::writeResult<ELF32BE>();
1814template void elf::writeResult<ELF64LE>();
1815template void elf::writeResult<ELF64BE>();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001816
Rafael Espindola24e6f362017-02-24 15:07:30 +00001817template bool elf::isRelroSection<ELF32LE>(const OutputSection *);
1818template bool elf::isRelroSection<ELF32BE>(const OutputSection *);
1819template bool elf::isRelroSection<ELF64LE>(const OutputSection *);
1820template bool elf::isRelroSection<ELF64BE>(const OutputSection *);