1 //===- 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
10 #include "Writer.h"
11 #include "AArch64ErrataFix.h"
12 #include "CallGraphSort.h"
13 #include "Config.h"
14 #include "Filesystem.h"
15 #include "LinkerScript.h"
16 #include "MapFile.h"
17 #include "OutputSections.h"
18 #include "Relocations.h"
19 #include "SymbolTable.h"
20 #include "Symbols.h"
21 #include "SyntheticSections.h"
22 #include "Target.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/Strings.h"
25 #include "lld/Common/Threads.h"
26 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include <climits>
29
30 using namespace llvm;
31 using namespace llvm::ELF;
32 using namespace llvm::object;
33 using namespace llvm::support;
34 using namespace llvm::support::endian;
35
36 using namespace lld;
37 using namespace lld::elf;
38
39 namespace {
40 // The writer writes a SymbolTable result to a file.
41 template <class ELFT> class Writer {
42 public:
Writer()43 Writer() : Buffer(errorHandler().OutputBuffer) {}
44 typedef typename ELFT::Shdr Elf_Shdr;
45 typedef typename ELFT::Ehdr Elf_Ehdr;
46 typedef typename ELFT::Phdr Elf_Phdr;
47
48 void run();
49
50 private:
51 void copyLocalSymbols();
52 void addSectionSymbols();
53 void forEachRelSec(llvm::function_ref<void(InputSectionBase &)> Fn);
54 void sortSections();
55 void resolveShfLinkOrder();
56 void maybeAddThunks();
57 void sortInputSections();
58 void finalizeSections();
59 void checkExecuteOnly();
60 void setReservedSymbolSections();
61
62 std::vector<PhdrEntry *> createPhdrs();
63 void removeEmptyPTLoad();
64 void addPtArmExid(std::vector<PhdrEntry *> &Phdrs);
65 void assignFileOffsets();
66 void assignFileOffsetsBinary();
67 void setPhdrs();
68 void checkSections();
69 void fixSectionAlignments();
70 void openFile();
71 void writeTrapInstr();
72 void writeHeader();
73 void writeSections();
74 void writeSectionsBinary();
75 void writeBuildId();
76
77 std::unique_ptr<FileOutputBuffer> &Buffer;
78
79 void addRelIpltSymbols();
80 void addStartEndSymbols();
81 void addStartStopSymbols(OutputSection *Sec);
82
83 std::vector<PhdrEntry *> Phdrs;
84
85 uint64_t FileSize;
86 uint64_t SectionHeaderOff;
87 };
88 } // anonymous namespace
89
isSectionPrefix(StringRef Prefix,StringRef Name)90 static bool isSectionPrefix(StringRef Prefix, StringRef Name) {
91 return Name.startswith(Prefix) || Name == Prefix.drop_back();
92 }
93
getOutputSectionName(const InputSectionBase * S)94 StringRef elf::getOutputSectionName(const InputSectionBase *S) {
95 if (Config->Relocatable)
96 return S->Name;
97
98 // This is for --emit-relocs. If .text.foo is emitted as .text.bar, we want
99 // to emit .rela.text.foo as .rela.text.bar for consistency (this is not
100 // technically required, but not doing it is odd). This code guarantees that.
101 if (auto *IS = dyn_cast<InputSection>(S)) {
102 if (InputSectionBase *Rel = IS->getRelocatedSection()) {
103 OutputSection *Out = Rel->getOutputSection();
104 if (S->Type == SHT_RELA)
105 return Saver.save(".rela" + Out->Name);
106 return Saver.save(".rel" + Out->Name);
107 }
108 }
109
110 // This check is for -z keep-text-section-prefix. This option separates text
111 // sections with prefix ".text.hot", ".text.unlikely", ".text.startup" or
112 // ".text.exit".
113 // When enabled, this allows identifying the hot code region (.text.hot) in
114 // the final binary which can be selectively mapped to huge pages or mlocked,
115 // for instance.
116 if (Config->ZKeepTextSectionPrefix)
117 for (StringRef V :
118 {".text.hot.", ".text.unlikely.", ".text.startup.", ".text.exit."})
119 if (isSectionPrefix(V, S->Name))
120 return V.drop_back();
121
122 for (StringRef V :
123 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
124 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
125 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."})
126 if (isSectionPrefix(V, S->Name))
127 return V.drop_back();
128
129 // CommonSection is identified as "COMMON" in linker scripts.
130 // By default, it should go to .bss section.
131 if (S->Name == "COMMON")
132 return ".bss";
133
134 return S->Name;
135 }
136
needsInterpSection()137 static bool needsInterpSection() {
138 return !SharedFiles.empty() && !Config->DynamicLinker.empty() &&
139 Script->needsInterpSection();
140 }
141
writeResult()142 template <class ELFT> void elf::writeResult() { Writer<ELFT>().run(); }
143
removeEmptyPTLoad()144 template <class ELFT> void Writer<ELFT>::removeEmptyPTLoad() {
145 llvm::erase_if(Phdrs, [&](const PhdrEntry *P) {
146 if (P->p_type != PT_LOAD)
147 return false;
148 if (!P->FirstSec)
149 return true;
150 uint64_t Size = P->LastSec->Addr + P->LastSec->Size - P->FirstSec->Addr;
151 return Size == 0;
152 });
153 }
154
combineEhFrameSections()155 template <class ELFT> static void combineEhFrameSections() {
156 for (InputSectionBase *&S : InputSections) {
157 EhInputSection *ES = dyn_cast<EhInputSection>(S);
158 if (!ES || !ES->Live)
159 continue;
160
161 In.EhFrame->addSection<ELFT>(ES);
162 S = nullptr;
163 }
164
165 std::vector<InputSectionBase *> &V = InputSections;
166 V.erase(std::remove(V.begin(), V.end(), nullptr), V.end());
167 }
168
addOptionalRegular(StringRef Name,SectionBase * Sec,uint64_t Val,uint8_t StOther=STV_HIDDEN,uint8_t Binding=STB_GLOBAL)169 static Defined *addOptionalRegular(StringRef Name, SectionBase *Sec,
170 uint64_t Val, uint8_t StOther = STV_HIDDEN,
171 uint8_t Binding = STB_GLOBAL) {
172 Symbol *S = Symtab->find(Name);
173 if (!S || S->isDefined())
174 return nullptr;
175 return Symtab->addDefined(Name, StOther, STT_NOTYPE, Val,
176 /*Size=*/0, Binding, Sec,
177 /*File=*/nullptr);
178 }
179
addAbsolute(StringRef Name)180 static Defined *addAbsolute(StringRef Name) {
181 return Symtab->addDefined(Name, STV_HIDDEN, STT_NOTYPE, 0, 0, STB_GLOBAL,
182 nullptr, nullptr);
183 }
184
185 // The linker is expected to define some symbols depending on
186 // the linking result. This function defines such symbols.
addReservedSymbols()187 void elf::addReservedSymbols() {
188 if (Config->EMachine == EM_MIPS) {
189 // Define _gp for MIPS. st_value of _gp symbol will be updated by Writer
190 // so that it points to an absolute address which by default is relative
191 // to GOT. Default offset is 0x7ff0.
192 // See "Global Data Symbols" in Chapter 6 in the following document:
193 // ftp://www.linux-mips.org/pub/linux/mips/doc/ABI/mipsabi.pdf
194 ElfSym::MipsGp = addAbsolute("_gp");
195
196 // On MIPS O32 ABI, _gp_disp is a magic symbol designates offset between
197 // start of function and 'gp' pointer into GOT.
198 if (Symtab->find("_gp_disp"))
199 ElfSym::MipsGpDisp = addAbsolute("_gp_disp");
200
201 // The __gnu_local_gp is a magic symbol equal to the current value of 'gp'
202 // pointer. This symbol is used in the code generated by .cpload pseudo-op
203 // in case of using -mno-shared option.
204 // https://sourceware.org/ml/binutils/2004-12/msg00094.html
205 if (Symtab->find("__gnu_local_gp"))
206 ElfSym::MipsLocalGp = addAbsolute("__gnu_local_gp");
207 }
208
209 // The Power Architecture 64-bit v2 ABI defines a TableOfContents (TOC) which
210 // combines the typical ELF GOT with the small data sections. It commonly
211 // includes .got .toc .sdata .sbss. The .TOC. symbol replaces both
212 // _GLOBAL_OFFSET_TABLE_ and _SDA_BASE_ from the 32-bit ABI. It is used to
213 // represent the TOC base which is offset by 0x8000 bytes from the start of
214 // the .got section.
215 // We do not allow _GLOBAL_OFFSET_TABLE_ to be defined by input objects as the
216 // correctness of some relocations depends on its value.
217 StringRef GotTableSymName =
218 (Config->EMachine == EM_PPC64) ? ".TOC." : "_GLOBAL_OFFSET_TABLE_";
219 if (Symbol *S = Symtab->find(GotTableSymName)) {
220 if (S->isDefined())
221 error(toString(S->File) + " cannot redefine linker defined symbol '" +
222 GotTableSymName + "'");
223 else
224 ElfSym::GlobalOffsetTable = Symtab->addDefined(
225 GotTableSymName, STV_HIDDEN, STT_NOTYPE, Target->GotBaseSymOff,
226 /*Size=*/0, STB_GLOBAL, Out::ElfHeader,
227 /*File=*/nullptr);
228 }
229
230 // __ehdr_start is the location of ELF file headers. Note that we define
231 // this symbol unconditionally even when using a linker script, which
232 // differs from the behavior implemented by GNU linker which only define
233 // this symbol if ELF headers are in the memory mapped segment.
234 addOptionalRegular("__ehdr_start", Out::ElfHeader, 0, STV_HIDDEN);
235
236 // __executable_start is not documented, but the expectation of at
237 // least the Android libc is that it points to the ELF header.
238 addOptionalRegular("__executable_start", Out::ElfHeader, 0, STV_HIDDEN);
239
240 // __dso_handle symbol is passed to cxa_finalize as a marker to identify
241 // each DSO. The address of the symbol doesn't matter as long as they are
242 // different in different DSOs, so we chose the start address of the DSO.
243 addOptionalRegular("__dso_handle", Out::ElfHeader, 0, STV_HIDDEN);
244
245 // If linker script do layout we do not need to create any standart symbols.
246 if (Script->HasSectionsCommand)
247 return;
248
249 auto Add = [](StringRef S, int64_t Pos) {
250 return addOptionalRegular(S, Out::ElfHeader, Pos, STV_DEFAULT);
251 };
252
253 ElfSym::Bss = Add("__bss_start", 0);
254 ElfSym::End1 = Add("end", -1);
255 ElfSym::End2 = Add("_end", -1);
256 ElfSym::Etext1 = Add("etext", -1);
257 ElfSym::Etext2 = Add("_etext", -1);
258 ElfSym::Edata1 = Add("edata", -1);
259 ElfSym::Edata2 = Add("_edata", -1);
260 }
261
findSection(StringRef Name)262 static OutputSection *findSection(StringRef Name) {
263 for (BaseCommand *Base : Script->SectionCommands)
264 if (auto *Sec = dyn_cast<OutputSection>(Base))
265 if (Sec->Name == Name)
266 return Sec;
267 return nullptr;
268 }
269
270 // Initialize Out members.
createSyntheticSections()271 template <class ELFT> static void createSyntheticSections() {
272 // Initialize all pointers with NULL. This is needed because
273 // you can call lld::elf::main more than once as a library.
274 memset(&Out::First, 0, sizeof(Out));
275
276 auto Add = [](InputSectionBase *Sec) { InputSections.push_back(Sec); };
277
278 In.DynStrTab = make<StringTableSection>(".dynstr", true);
279 In.Dynamic = make<DynamicSection<ELFT>>();
280 if (Config->AndroidPackDynRelocs) {
281 In.RelaDyn = make<AndroidPackedRelocationSection<ELFT>>(
282 Config->IsRela ? ".rela.dyn" : ".rel.dyn");
283 } else {
284 In.RelaDyn = make<RelocationSection<ELFT>>(
285 Config->IsRela ? ".rela.dyn" : ".rel.dyn", Config->ZCombreloc);
286 }
287 In.ShStrTab = make<StringTableSection>(".shstrtab", false);
288
289 Out::ProgramHeaders = make<OutputSection>("", 0, SHF_ALLOC);
290 Out::ProgramHeaders->Alignment = Config->Wordsize;
291
292 if (needsInterpSection()) {
293 In.Interp = createInterpSection();
294 Add(In.Interp);
295 }
296
297 if (Config->Strip != StripPolicy::All) {
298 In.StrTab = make<StringTableSection>(".strtab", false);
299 In.SymTab = make<SymbolTableSection<ELFT>>(*In.StrTab);
300 In.SymTabShndx = make<SymtabShndxSection>();
301 }
302
303 if (Config->BuildId != BuildIdKind::None) {
304 In.BuildId = make<BuildIdSection>();
305 Add(In.BuildId);
306 }
307
308 In.Bss = make<BssSection>(".bss", 0, 1);
309 Add(In.Bss);
310
311 // If there is a SECTIONS command and a .data.rel.ro section name use name
312 // .data.rel.ro.bss so that we match in the .data.rel.ro output section.
313 // This makes sure our relro is contiguous.
314 bool HasDataRelRo = Script->HasSectionsCommand && findSection(".data.rel.ro");
315 In.BssRelRo =
316 make<BssSection>(HasDataRelRo ? ".data.rel.ro.bss" : ".bss.rel.ro", 0, 1);
317 Add(In.BssRelRo);
318
319 // Add MIPS-specific sections.
320 if (Config->EMachine == EM_MIPS) {
321 if (!Config->Shared && Config->HasDynSymTab) {
322 In.MipsRldMap = make<MipsRldMapSection>();
323 Add(In.MipsRldMap);
324 }
325 if (auto *Sec = MipsAbiFlagsSection<ELFT>::create())
326 Add(Sec);
327 if (auto *Sec = MipsOptionsSection<ELFT>::create())
328 Add(Sec);
329 if (auto *Sec = MipsReginfoSection<ELFT>::create())
330 Add(Sec);
331 }
332
333 if (Config->HasDynSymTab) {
334 In.DynSymTab = make<SymbolTableSection<ELFT>>(*In.DynStrTab);
335 Add(In.DynSymTab);
336
337 InX<ELFT>::VerSym = make<VersionTableSection<ELFT>>();
338 Add(InX<ELFT>::VerSym);
339
340 if (!Config->VersionDefinitions.empty()) {
341 In.VerDef = make<VersionDefinitionSection>();
342 Add(In.VerDef);
343 }
344
345 InX<ELFT>::VerNeed = make<VersionNeedSection<ELFT>>();
346 Add(InX<ELFT>::VerNeed);
347
348 if (Config->GnuHash) {
349 In.GnuHashTab = make<GnuHashTableSection>();
350 Add(In.GnuHashTab);
351 }
352
353 if (Config->SysvHash) {
354 In.HashTab = make<HashTableSection>();
355 Add(In.HashTab);
356 }
357
358 Add(In.Dynamic);
359 Add(In.DynStrTab);
360 Add(In.RelaDyn);
361 }
362
363 if (Config->RelrPackDynRelocs) {
364 In.RelrDyn = make<RelrSection<ELFT>>();
365 Add(In.RelrDyn);
366 }
367
368 // Add .got. MIPS' .got is so different from the other archs,
369 // it has its own class.
370 if (Config->EMachine == EM_MIPS) {
371 In.MipsGot = make<MipsGotSection>();
372 Add(In.MipsGot);
373 } else {
374 In.Got = make<GotSection>();
375 Add(In.Got);
376 }
377
378 if (Config->EMachine == EM_PPC64) {
379 In.PPC64LongBranchTarget = make<PPC64LongBranchTargetSection>();
380 Add(In.PPC64LongBranchTarget);
381 }
382
383 In.GotPlt = make<GotPltSection>();
384 Add(In.GotPlt);
385 In.IgotPlt = make<IgotPltSection>();
386 Add(In.IgotPlt);
387
388 if (Config->GdbIndex) {
389 In.GdbIndex = GdbIndexSection::create<ELFT>();
390 Add(In.GdbIndex);
391 }
392
393 // We always need to add rel[a].plt to output if it has entries.
394 // Even for static linking it can contain R_[*]_IRELATIVE relocations.
395 In.RelaPlt = make<RelocationSection<ELFT>>(
396 Config->IsRela ? ".rela.plt" : ".rel.plt", false /*Sort*/);
397 Add(In.RelaPlt);
398
399 // The RelaIplt immediately follows .rel.plt (.rel.dyn for ARM) to ensure
400 // that the IRelative relocations are processed last by the dynamic loader.
401 // We cannot place the iplt section in .rel.dyn when Android relocation
402 // packing is enabled because that would cause a section type mismatch.
403 // However, because the Android dynamic loader reads .rel.plt after .rel.dyn,
404 // we can get the desired behaviour by placing the iplt section in .rel.plt.
405 In.RelaIplt = make<RelocationSection<ELFT>>(
406 (Config->EMachine == EM_ARM && !Config->AndroidPackDynRelocs)
407 ? ".rel.dyn"
408 : In.RelaPlt->Name,
409 false /*Sort*/);
410 Add(In.RelaIplt);
411
412 In.Plt = make<PltSection>(false);
413 Add(In.Plt);
414 In.Iplt = make<PltSection>(true);
415 Add(In.Iplt);
416
417 // .note.GNU-stack is always added when we are creating a re-linkable
418 // object file. Other linkers are using the presence of this marker
419 // section to control the executable-ness of the stack area, but that
420 // is irrelevant these days. Stack area should always be non-executable
421 // by default. So we emit this section unconditionally.
422 if (Config->Relocatable)
423 Add(make<GnuStackSection>());
424
425 if (!Config->Relocatable) {
426 if (Config->EhFrameHdr) {
427 In.EhFrameHdr = make<EhFrameHeader>();
428 Add(In.EhFrameHdr);
429 }
430 In.EhFrame = make<EhFrameSection>();
431 Add(In.EhFrame);
432 }
433
434 if (In.SymTab)
435 Add(In.SymTab);
436 if (In.SymTabShndx)
437 Add(In.SymTabShndx);
438 Add(In.ShStrTab);
439 if (In.StrTab)
440 Add(In.StrTab);
441
442 if (Config->EMachine == EM_ARM && !Config->Relocatable)
443 // Add a sentinel to terminate .ARM.exidx. It helps an unwinder
444 // to find the exact address range of the last entry.
445 Add(make<ARMExidxSentinelSection>());
446 }
447
448 // The main function of the writer.
run()449 template <class ELFT> void Writer<ELFT>::run() {
450 // Create linker-synthesized sections such as .got or .plt.
451 // Such sections are of type input section.
452 createSyntheticSections<ELFT>();
453
454 if (!Config->Relocatable)
455 combineEhFrameSections<ELFT>();
456
457 // We want to process linker script commands. When SECTIONS command
458 // is given we let it create sections.
459 Script->processSectionCommands();
460
461 // Linker scripts controls how input sections are assigned to output sections.
462 // Input sections that were not handled by scripts are called "orphans", and
463 // they are assigned to output sections by the default rule. Process that.
464 Script->addOrphanSections();
465
466 if (Config->Discard != DiscardPolicy::All)
467 copyLocalSymbols();
468
469 if (Config->CopyRelocs)
470 addSectionSymbols();
471
472 // Now that we have a complete set of output sections. This function
473 // completes section contents. For example, we need to add strings
474 // to the string table, and add entries to .got and .plt.
475 // finalizeSections does that.
476 finalizeSections();
477 checkExecuteOnly();
478 if (errorCount())
479 return;
480
481 Script->assignAddresses();
482
483 // If -compressed-debug-sections is specified, we need to compress
484 // .debug_* sections. Do it right now because it changes the size of
485 // output sections.
486 for (OutputSection *Sec : OutputSections)
487 Sec->maybeCompress<ELFT>();
488
489 Script->allocateHeaders(Phdrs);
490
491 // Remove empty PT_LOAD to avoid causing the dynamic linker to try to mmap a
492 // 0 sized region. This has to be done late since only after assignAddresses
493 // we know the size of the sections.
494 removeEmptyPTLoad();
495
496 if (!Config->OFormatBinary)
497 assignFileOffsets();
498 else
499 assignFileOffsetsBinary();
500
501 setPhdrs();
502
503 if (Config->Relocatable)
504 for (OutputSection *Sec : OutputSections)
505 Sec->Addr = 0;
506
507 if (Config->CheckSections)
508 checkSections();
509
510 // It does not make sense try to open the file if we have error already.
511 if (errorCount())
512 return;
513 // Write the result down to a file.
514 openFile();
515 if (errorCount())
516 return;
517
518 if (!Config->OFormatBinary) {
519 writeTrapInstr();
520 writeHeader();
521 writeSections();
522 } else {
523 writeSectionsBinary();
524 }
525
526 // Backfill .note.gnu.build-id section content. This is done at last
527 // because the content is usually a hash value of the entire output file.
528 writeBuildId();
529 if (errorCount())
530 return;
531
532 // Handle -Map and -cref options.
533 writeMapFile();
534 writeCrossReferenceTable();
535 if (errorCount())
536 return;
537
538 if (auto E = Buffer->commit())
539 error("failed to write to the output file: " + toString(std::move(E)));
540 }
541
shouldKeepInSymtab(SectionBase * Sec,StringRef SymName,const Symbol & B)542 static bool shouldKeepInSymtab(SectionBase *Sec, StringRef SymName,
543 const Symbol &B) {
544 if (B.isSection())
545 return false;
546
547 if (Config->Discard == DiscardPolicy::None)
548 return true;
549
550 // If -emit-reloc is given, all symbols including local ones need to be
551 // copied because they may be referenced by relocations.
552 if (Config->EmitRelocs)
553 return true;
554
555 // In ELF assembly .L symbols are normally discarded by the assembler.
556 // If the assembler fails to do so, the linker discards them if
557 // * --discard-locals is used.
558 // * The symbol is in a SHF_MERGE section, which is normally the reason for
559 // the assembler keeping the .L symbol.
560 if (!SymName.startswith(".L") && !SymName.empty())
561 return true;
562
563 if (Config->Discard == DiscardPolicy::Locals)
564 return false;
565
566 return !Sec || !(Sec->Flags & SHF_MERGE);
567 }
568
includeInSymtab(const Symbol & B)569 static bool includeInSymtab(const Symbol &B) {
570 if (!B.isLocal() && !B.IsUsedInRegularObj)
571 return false;
572
573 if (auto *D = dyn_cast<Defined>(&B)) {
574 // Always include absolute symbols.
575 SectionBase *Sec = D->Section;
576 if (!Sec)
577 return true;
578 Sec = Sec->Repl;
579
580 // Exclude symbols pointing to garbage-collected sections.
581 if (isa<InputSectionBase>(Sec) && !Sec->Live)
582 return false;
583
584 if (auto *S = dyn_cast<MergeInputSection>(Sec))
585 if (!S->getSectionPiece(D->Value)->Live)
586 return false;
587 return true;
588 }
589 return B.Used;
590 }
591
592 // Local symbols are not in the linker's symbol table. This function scans
593 // each object file's symbol table to copy local symbols to the output.
copyLocalSymbols()594 template <class ELFT> void Writer<ELFT>::copyLocalSymbols() {
595 if (!In.SymTab)
596 return;
597 for (InputFile *File : ObjectFiles) {
598 ObjFile<ELFT> *F = cast<ObjFile<ELFT>>(File);
599 for (Symbol *B : F->getLocalSymbols()) {
600 if (!B->isLocal())
601 fatal(toString(F) +
602 ": broken object: getLocalSymbols returns a non-local symbol");
603 auto *DR = dyn_cast<Defined>(B);
604
605 // No reason to keep local undefined symbol in symtab.
606 if (!DR)
607 continue;
608 if (!includeInSymtab(*B))
609 continue;
610
611 SectionBase *Sec = DR->Section;
612 if (!shouldKeepInSymtab(Sec, B->getName(), *B))
613 continue;
614 In.SymTab->addSymbol(B);
615 }
616 }
617 }
618
619 // Create a section symbol for each output section so that we can represent
620 // relocations that point to the section. If we know that no relocation is
621 // referring to a section (that happens if the section is a synthetic one), we
622 // don't create a section symbol for that section.
addSectionSymbols()623 template <class ELFT> void Writer<ELFT>::addSectionSymbols() {
624 for (BaseCommand *Base : Script->SectionCommands) {
625 auto *Sec = dyn_cast<OutputSection>(Base);
626 if (!Sec)
627 continue;
628 auto I = llvm::find_if(Sec->SectionCommands, [](BaseCommand *Base) {
629 if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
630 return !ISD->Sections.empty();
631 return false;
632 });
633 if (I == Sec->SectionCommands.end())
634 continue;
635 InputSection *IS = cast<InputSectionDescription>(*I)->Sections[0];
636
637 // Relocations are not using REL[A] section symbols.
638 if (IS->Type == SHT_REL || IS->Type == SHT_RELA)
639 continue;
640
641 // Unlike other synthetic sections, mergeable output sections contain data
642 // copied from input sections, and there may be a relocation pointing to its
643 // contents if -r or -emit-reloc are given.
644 if (isa<SyntheticSection>(IS) && !(IS->Flags & SHF_MERGE))
645 continue;
646
647 auto *Sym =
648 make<Defined>(IS->File, "", STB_LOCAL, /*StOther=*/0, STT_SECTION,
649 /*Value=*/0, /*Size=*/0, IS);
650 In.SymTab->addSymbol(Sym);
651 }
652 }
653
654 // Today's loaders have a feature to make segments read-only after
655 // processing dynamic relocations to enhance security. PT_GNU_RELRO
656 // is defined for that.
657 //
658 // This function returns true if a section needs to be put into a
659 // PT_GNU_RELRO segment.
isRelroSection(const OutputSection * Sec)660 static bool isRelroSection(const OutputSection *Sec) {
661 if (!Config->ZRelro)
662 return false;
663
664 uint64_t Flags = Sec->Flags;
665
666 // Non-allocatable or non-writable sections don't need RELRO because
667 // they are not writable or not even mapped to memory in the first place.
668 // RELRO is for sections that are essentially read-only but need to
669 // be writable only at process startup to allow dynamic linker to
670 // apply relocations.
671 if (!(Flags & SHF_ALLOC) || !(Flags & SHF_WRITE))
672 return false;
673
674 // Once initialized, TLS data segments are used as data templates
675 // for a thread-local storage. For each new thread, runtime
676 // allocates memory for a TLS and copy templates there. No thread
677 // are supposed to use templates directly. Thus, it can be in RELRO.
678 if (Flags & SHF_TLS)
679 return true;
680
681 // .init_array, .preinit_array and .fini_array contain pointers to
682 // functions that are executed on process startup or exit. These
683 // pointers are set by the static linker, and they are not expected
684 // to change at runtime. But if you are an attacker, you could do
685 // interesting things by manipulating pointers in .fini_array, for
686 // example. So they are put into RELRO.
687 uint32_t Type = Sec->Type;
688 if (Type == SHT_INIT_ARRAY || Type == SHT_FINI_ARRAY ||
689 Type == SHT_PREINIT_ARRAY)
690 return true;
691
692 // .got contains pointers to external symbols. They are resolved by
693 // the dynamic linker when a module is loaded into memory, and after
694 // that they are not expected to change. So, it can be in RELRO.
695 if (In.Got && Sec == In.Got->getParent())
696 return true;
697
698 // .toc is a GOT-ish section for PowerPC64. Their contents are accessed
699 // through r2 register, which is reserved for that purpose. Since r2 is used
700 // for accessing .got as well, .got and .toc need to be close enough in the
701 // virtual address space. Usually, .toc comes just after .got. Since we place
702 // .got into RELRO, .toc needs to be placed into RELRO too.
703 if (Sec->Name.equals(".toc"))
704 return true;
705
706 // .got.plt contains pointers to external function symbols. They are
707 // by default resolved lazily, so we usually cannot put it into RELRO.
708 // However, if "-z now" is given, the lazy symbol resolution is
709 // disabled, which enables us to put it into RELRO.
710 if (Sec == In.GotPlt->getParent())
711 return Config->ZNow;
712
713 // .dynamic section contains data for the dynamic linker, and
714 // there's no need to write to it at runtime, so it's better to put
715 // it into RELRO.
716 if (Sec == In.Dynamic->getParent())
717 return true;
718
719 // Sections with some special names are put into RELRO. This is a
720 // bit unfortunate because section names shouldn't be significant in
721 // ELF in spirit. But in reality many linker features depend on
722 // magic section names.
723 StringRef S = Sec->Name;
724 return S == ".data.rel.ro" || S == ".bss.rel.ro" || S == ".ctors" ||
725 S == ".dtors" || S == ".jcr" || S == ".eh_frame" ||
726 S == ".openbsd.randomdata";
727 }
728
729 // We compute a rank for each section. The rank indicates where the
730 // section should be placed in the file. Instead of using simple
731 // numbers (0,1,2...), we use a series of flags. One for each decision
732 // point when placing the section.
733 // Using flags has two key properties:
734 // * It is easy to check if a give branch was taken.
735 // * It is easy two see how similar two ranks are (see getRankProximity).
736 enum RankFlags {
737 RF_NOT_ADDR_SET = 1 << 18,
738 RF_NOT_ALLOC = 1 << 17,
739 RF_NOT_INTERP = 1 << 16,
740 RF_NOT_NOTE = 1 << 15,
741 RF_WRITE = 1 << 14,
742 RF_EXEC_WRITE = 1 << 13,
743 RF_EXEC = 1 << 12,
744 RF_RODATA = 1 << 11,
745 RF_NON_TLS_BSS = 1 << 10,
746 RF_NON_TLS_BSS_RO = 1 << 9,
747 RF_NOT_TLS = 1 << 8,
748 RF_BSS = 1 << 7,
749 RF_PPC_NOT_TOCBSS = 1 << 6,
750 RF_PPC_TOCL = 1 << 5,
751 RF_PPC_TOC = 1 << 4,
752 RF_PPC_GOT = 1 << 3,
753 RF_PPC_BRANCH_LT = 1 << 2,
754 RF_MIPS_GPREL = 1 << 1,
755 RF_MIPS_NOT_GOT = 1 << 0
756 };
757
getSectionRank(const OutputSection * Sec)758 static unsigned getSectionRank(const OutputSection *Sec) {
759 unsigned Rank = 0;
760
761 // We want to put section specified by -T option first, so we
762 // can start assigning VA starting from them later.
763 if (Config->SectionStartMap.count(Sec->Name))
764 return Rank;
765 Rank |= RF_NOT_ADDR_SET;
766
767 // Allocatable sections go first to reduce the total PT_LOAD size and
768 // so debug info doesn't change addresses in actual code.
769 if (!(Sec->Flags & SHF_ALLOC))
770 return Rank | RF_NOT_ALLOC;
771
772 // Put .interp first because some loaders want to see that section
773 // on the first page of the executable file when loaded into memory.
774 if (Sec->Name == ".interp")
775 return Rank;
776 Rank |= RF_NOT_INTERP;
777
778 // Put .note sections (which make up one PT_NOTE) at the beginning so that
779 // they are likely to be included in a core file even if core file size is
780 // limited. In particular, we want a .note.gnu.build-id and a .note.tag to be
781 // included in a core to match core files with executables.
782 if (Sec->Type == SHT_NOTE)
783 return Rank;
784 Rank |= RF_NOT_NOTE;
785
786 // Sort sections based on their access permission in the following
787 // order: R, RX, RWX, RW. This order is based on the following
788 // considerations:
789 // * Read-only sections come first such that they go in the
790 // PT_LOAD covering the program headers at the start of the file.
791 // * Read-only, executable sections come next.
792 // * Writable, executable sections follow such that .plt on
793 // architectures where it needs to be writable will be placed
794 // between .text and .data.
795 // * Writable sections come last, such that .bss lands at the very
796 // end of the last PT_LOAD.
797 bool IsExec = Sec->Flags & SHF_EXECINSTR;
798 bool IsWrite = Sec->Flags & SHF_WRITE;
799
800 if (IsExec) {
801 if (IsWrite)
802 Rank |= RF_EXEC_WRITE;
803 else
804 Rank |= RF_EXEC;
805 } else if (IsWrite) {
806 Rank |= RF_WRITE;
807 } else if (Sec->Type == SHT_PROGBITS) {
808 // Make non-executable and non-writable PROGBITS sections (e.g .rodata
809 // .eh_frame) closer to .text. They likely contain PC or GOT relative
810 // relocations and there could be relocation overflow if other huge sections
811 // (.dynstr .dynsym) were placed in between.
812 Rank |= RF_RODATA;
813 }
814
815 // If we got here we know that both A and B are in the same PT_LOAD.
816
817 bool IsTls = Sec->Flags & SHF_TLS;
818 bool IsNoBits = Sec->Type == SHT_NOBITS;
819
820 // The first requirement we have is to put (non-TLS) nobits sections last. The
821 // reason is that the only thing the dynamic linker will see about them is a
822 // p_memsz that is larger than p_filesz. Seeing that it zeros the end of the
823 // PT_LOAD, so that has to correspond to the nobits sections.
824 bool IsNonTlsNoBits = IsNoBits && !IsTls;
825 if (IsNonTlsNoBits)
826 Rank |= RF_NON_TLS_BSS;
827
828 // We place nobits RelRo sections before plain r/w ones, and non-nobits RelRo
829 // sections after r/w ones, so that the RelRo sections are contiguous.
830 bool IsRelRo = isRelroSection(Sec);
831 if (IsNonTlsNoBits && !IsRelRo)
832 Rank |= RF_NON_TLS_BSS_RO;
833 if (!IsNonTlsNoBits && IsRelRo)
834 Rank |= RF_NON_TLS_BSS_RO;
835
836 // The TLS initialization block needs to be a single contiguous block in a R/W
837 // PT_LOAD, so stick TLS sections directly before the other RelRo R/W
838 // sections. The TLS NOBITS sections are placed here as they don't take up
839 // virtual address space in the PT_LOAD.
840 if (!IsTls)
841 Rank |= RF_NOT_TLS;
842
843 // Within the TLS initialization block, the non-nobits sections need to appear
844 // first.
845 if (IsNoBits)
846 Rank |= RF_BSS;
847
848 // Some architectures have additional ordering restrictions for sections
849 // within the same PT_LOAD.
850 if (Config->EMachine == EM_PPC64) {
851 // PPC64 has a number of special SHT_PROGBITS+SHF_ALLOC+SHF_WRITE sections
852 // that we would like to make sure appear is a specific order to maximize
853 // their coverage by a single signed 16-bit offset from the TOC base
854 // pointer. Conversely, the special .tocbss section should be first among
855 // all SHT_NOBITS sections. This will put it next to the loaded special
856 // PPC64 sections (and, thus, within reach of the TOC base pointer).
857 StringRef Name = Sec->Name;
858 if (Name != ".tocbss")
859 Rank |= RF_PPC_NOT_TOCBSS;
860
861 if (Name == ".toc1")
862 Rank |= RF_PPC_TOCL;
863
864 if (Name == ".toc")
865 Rank |= RF_PPC_TOC;
866
867 if (Name == ".got")
868 Rank |= RF_PPC_GOT;
869
870 if (Name == ".branch_lt")
871 Rank |= RF_PPC_BRANCH_LT;
872 }
873
874 if (Config->EMachine == EM_MIPS) {
875 // All sections with SHF_MIPS_GPREL flag should be grouped together
876 // because data in these sections is addressable with a gp relative address.
877 if (Sec->Flags & SHF_MIPS_GPREL)
878 Rank |= RF_MIPS_GPREL;
879
880 if (Sec->Name != ".got")
881 Rank |= RF_MIPS_NOT_GOT;
882 }
883
884 return Rank;
885 }
886
compareSections(const BaseCommand * ACmd,const BaseCommand * BCmd)887 static bool compareSections(const BaseCommand *ACmd, const BaseCommand *BCmd) {
888 const OutputSection *A = cast<OutputSection>(ACmd);
889 const OutputSection *B = cast<OutputSection>(BCmd);
890
891 if (A->SortRank != B->SortRank)
892 return A->SortRank < B->SortRank;
893
894 if (!(A->SortRank & RF_NOT_ADDR_SET))
895 return Config->SectionStartMap.lookup(A->Name) <
896 Config->SectionStartMap.lookup(B->Name);
897 return false;
898 }
899
add(OutputSection * Sec)900 void PhdrEntry::add(OutputSection *Sec) {
901 LastSec = Sec;
902 if (!FirstSec)
903 FirstSec = Sec;
904 p_align = std::max(p_align, Sec->Alignment);
905 if (p_type == PT_LOAD)
906 Sec->PtLoad = this;
907 }
908
909 // The beginning and the ending of .rel[a].plt section are marked
910 // with __rel[a]_iplt_{start,end} symbols if it is a statically linked
911 // executable. The runtime needs these symbols in order to resolve
912 // all IRELATIVE relocs on startup. For dynamic executables, we don't
913 // need these symbols, since IRELATIVE relocs are resolved through GOT
914 // and PLT. For details, see http://www.airs.com/blog/archives/403.
addRelIpltSymbols()915 template <class ELFT> void Writer<ELFT>::addRelIpltSymbols() {
916 if (Config->Relocatable || needsInterpSection())
917 return;
918
919 // By default, __rela_iplt_{start,end} belong to a dummy section 0
920 // because .rela.plt might be empty and thus removed from output.
921 // We'll override Out::ElfHeader with In.RelaIplt later when we are
922 // sure that .rela.plt exists in output.
923 ElfSym::RelaIpltStart = addOptionalRegular(
924 Config->IsRela ? "__rela_iplt_start" : "__rel_iplt_start",
925 Out::ElfHeader, 0, STV_HIDDEN, STB_WEAK);
926
927 ElfSym::RelaIpltEnd = addOptionalRegular(
928 Config->IsRela ? "__rela_iplt_end" : "__rel_iplt_end",
929 Out::ElfHeader, 0, STV_HIDDEN, STB_WEAK);
930 }
931
932 template <class ELFT>
forEachRelSec(llvm::function_ref<void (InputSectionBase &)> Fn)933 void Writer<ELFT>::forEachRelSec(
934 llvm::function_ref<void(InputSectionBase &)> Fn) {
935 // Scan all relocations. Each relocation goes through a series
936 // of tests to determine if it needs special treatment, such as
937 // creating GOT, PLT, copy relocations, etc.
938 // Note that relocations for non-alloc sections are directly
939 // processed by InputSection::relocateNonAlloc.
940 for (InputSectionBase *IS : InputSections)
941 if (IS->Live && isa<InputSection>(IS) && (IS->Flags & SHF_ALLOC))
942 Fn(*IS);
943 for (EhInputSection *ES : In.EhFrame->Sections)
944 Fn(*ES);
945 }
946
947 // This function generates assignments for predefined symbols (e.g. _end or
948 // _etext) and inserts them into the commands sequence to be processed at the
949 // appropriate time. This ensures that the value is going to be correct by the
950 // time any references to these symbols are processed and is equivalent to
951 // defining these symbols explicitly in the linker script.
setReservedSymbolSections()952 template <class ELFT> void Writer<ELFT>::setReservedSymbolSections() {
953 if (ElfSym::GlobalOffsetTable) {
954 // The _GLOBAL_OFFSET_TABLE_ symbol is defined by target convention usually
955 // to the start of the .got or .got.plt section.
956 InputSection *GotSection = In.GotPlt;
957 if (!Target->GotBaseSymInGotPlt)
958 GotSection = In.MipsGot ? cast<InputSection>(In.MipsGot)
959 : cast<InputSection>(In.Got);
960 ElfSym::GlobalOffsetTable->Section = GotSection;
961 }
962
963 // .rela_iplt_{start,end} mark the start and the end of .rela.plt section.
964 if (ElfSym::RelaIpltStart && !In.RelaIplt->empty()) {
965 ElfSym::RelaIpltStart->Section = In.RelaIplt;
966 ElfSym::RelaIpltEnd->Section = In.RelaIplt;
967 ElfSym::RelaIpltEnd->Value = In.RelaIplt->getSize();
968 }
969
970 PhdrEntry *Last = nullptr;
971 PhdrEntry *LastRO = nullptr;
972
973 for (PhdrEntry *P : Phdrs) {
974 if (P->p_type != PT_LOAD)
975 continue;
976 Last = P;
977 if (!(P->p_flags & PF_W))
978 LastRO = P;
979 }
980
981 if (LastRO) {
982 // _etext is the first location after the last read-only loadable segment.
983 if (ElfSym::Etext1)
984 ElfSym::Etext1->Section = LastRO->LastSec;
985 if (ElfSym::Etext2)
986 ElfSym::Etext2->Section = LastRO->LastSec;
987 }
988
989 if (Last) {
990 // _edata points to the end of the last mapped initialized section.
991 OutputSection *Edata = nullptr;
992 for (OutputSection *OS : OutputSections) {
993 if (OS->Type != SHT_NOBITS)
994 Edata = OS;
995 if (OS == Last->LastSec)
996 break;
997 }
998
999 if (ElfSym::Edata1)
1000 ElfSym::Edata1->Section = Edata;
1001 if (ElfSym::Edata2)
1002 ElfSym::Edata2->Section = Edata;
1003
1004 // _end is the first location after the uninitialized data region.
1005 if (ElfSym::End1)
1006 ElfSym::End1->Section = Last->LastSec;
1007 if (ElfSym::End2)
1008 ElfSym::End2->Section = Last->LastSec;
1009 }
1010
1011 if (ElfSym::Bss)
1012 ElfSym::Bss->Section = findSection(".bss");
1013
1014 // Setup MIPS _gp_disp/__gnu_local_gp symbols which should
1015 // be equal to the _gp symbol's value.
1016 if (ElfSym::MipsGp) {
1017 // Find GP-relative section with the lowest address
1018 // and use this address to calculate default _gp value.
1019 for (OutputSection *OS : OutputSections) {
1020 if (OS->Flags & SHF_MIPS_GPREL) {
1021 ElfSym::MipsGp->Section = OS;
1022 ElfSym::MipsGp->Value = 0x7ff0;
1023 break;
1024 }
1025 }
1026 }
1027 }
1028
1029 // We want to find how similar two ranks are.
1030 // The more branches in getSectionRank that match, the more similar they are.
1031 // Since each branch corresponds to a bit flag, we can just use
1032 // countLeadingZeros.
getRankProximityAux(OutputSection * A,OutputSection * B)1033 static int getRankProximityAux(OutputSection *A, OutputSection *B) {
1034 return countLeadingZeros(A->SortRank ^ B->SortRank);
1035 }
1036
getRankProximity(OutputSection * A,BaseCommand * B)1037 static int getRankProximity(OutputSection *A, BaseCommand *B) {
1038 if (auto *Sec = dyn_cast<OutputSection>(B))
1039 return getRankProximityAux(A, Sec);
1040 return -1;
1041 }
1042
1043 // When placing orphan sections, we want to place them after symbol assignments
1044 // so that an orphan after
1045 // begin_foo = .;
1046 // foo : { *(foo) }
1047 // end_foo = .;
1048 // doesn't break the intended meaning of the begin/end symbols.
1049 // We don't want to go over sections since findOrphanPos is the
1050 // one in charge of deciding the order of the sections.
1051 // We don't want to go over changes to '.', since doing so in
1052 // rx_sec : { *(rx_sec) }
1053 // . = ALIGN(0x1000);
1054 // /* The RW PT_LOAD starts here*/
1055 // rw_sec : { *(rw_sec) }
1056 // would mean that the RW PT_LOAD would become unaligned.
shouldSkip(BaseCommand * Cmd)1057 static bool shouldSkip(BaseCommand *Cmd) {
1058 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
1059 return Assign->Name != ".";
1060 return false;
1061 }
1062
1063 // We want to place orphan sections so that they share as much
1064 // characteristics with their neighbors as possible. For example, if
1065 // both are rw, or both are tls.
1066 template <typename ELFT>
1067 static std::vector<BaseCommand *>::iterator
findOrphanPos(std::vector<BaseCommand * >::iterator B,std::vector<BaseCommand * >::iterator E)1068 findOrphanPos(std::vector<BaseCommand *>::iterator B,
1069 std::vector<BaseCommand *>::iterator E) {
1070 OutputSection *Sec = cast<OutputSection>(*E);
1071
1072 // Find the first element that has as close a rank as possible.
1073 auto I = std::max_element(B, E, [=](BaseCommand *A, BaseCommand *B) {
1074 return getRankProximity(Sec, A) < getRankProximity(Sec, B);
1075 });
1076 if (I == E)
1077 return E;
1078
1079 // Consider all existing sections with the same proximity.
1080 int Proximity = getRankProximity(Sec, *I);
1081 for (; I != E; ++I) {
1082 auto *CurSec = dyn_cast<OutputSection>(*I);
1083 if (!CurSec)
1084 continue;
1085 if (getRankProximity(Sec, CurSec) != Proximity ||
1086 Sec->SortRank < CurSec->SortRank)
1087 break;
1088 }
1089
1090 auto IsOutputSec = [](BaseCommand *Cmd) { return isa<OutputSection>(Cmd); };
1091 auto J = std::find_if(llvm::make_reverse_iterator(I),
1092 llvm::make_reverse_iterator(B), IsOutputSec);
1093 I = J.base();
1094
1095 // As a special case, if the orphan section is the last section, put
1096 // it at the very end, past any other commands.
1097 // This matches bfd's behavior and is convenient when the linker script fully
1098 // specifies the start of the file, but doesn't care about the end (the non
1099 // alloc sections for example).
1100 auto NextSec = std::find_if(I, E, IsOutputSec);
1101 if (NextSec == E)
1102 return E;
1103
1104 while (I != E && shouldSkip(*I))
1105 ++I;
1106 return I;
1107 }
1108
1109 // Builds section order for handling --symbol-ordering-file.
buildSectionOrder()1110 static DenseMap<const InputSectionBase *, int> buildSectionOrder() {
1111 DenseMap<const InputSectionBase *, int> SectionOrder;
1112 // Use the rarely used option -call-graph-ordering-file to sort sections.
1113 if (!Config->CallGraphProfile.empty())
1114 return computeCallGraphProfileOrder();
1115
1116 if (Config->SymbolOrderingFile.empty())
1117 return SectionOrder;
1118
1119 struct SymbolOrderEntry {
1120 int Priority;
1121 bool Present;
1122 };
1123
1124 // Build a map from symbols to their priorities. Symbols that didn't
1125 // appear in the symbol ordering file have the lowest priority 0.
1126 // All explicitly mentioned symbols have negative (higher) priorities.
1127 DenseMap<StringRef, SymbolOrderEntry> SymbolOrder;
1128 int Priority = -Config->SymbolOrderingFile.size();
1129 for (StringRef S : Config->SymbolOrderingFile)
1130 SymbolOrder.insert({S, {Priority++, false}});
1131
1132 // Build a map from sections to their priorities.
1133 auto AddSym = [&](Symbol &Sym) {
1134 auto It = SymbolOrder.find(Sym.getName());
1135 if (It == SymbolOrder.end())
1136 return;
1137 SymbolOrderEntry &Ent = It->second;
1138 Ent.Present = true;
1139
1140 maybeWarnUnorderableSymbol(&Sym);
1141
1142 if (auto *D = dyn_cast<Defined>(&Sym)) {
1143 if (auto *Sec = dyn_cast_or_null<InputSectionBase>(D->Section)) {
1144 int &Priority = SectionOrder[cast<InputSectionBase>(Sec->Repl)];
1145 Priority = std::min(Priority, Ent.Priority);
1146 }
1147 }
1148 };
1149
1150 // We want both global and local symbols. We get the global ones from the
1151 // symbol table and iterate the object files for the local ones.
1152 for (Symbol *Sym : Symtab->getSymbols())
1153 if (!Sym->isLazy())
1154 AddSym(*Sym);
1155 for (InputFile *File : ObjectFiles)
1156 for (Symbol *Sym : File->getSymbols())
1157 if (Sym->isLocal())
1158 AddSym(*Sym);
1159
1160 if (Config->WarnSymbolOrdering)
1161 for (auto OrderEntry : SymbolOrder)
1162 if (!OrderEntry.second.Present)
1163 warn("symbol ordering file: no such symbol: " + OrderEntry.first);
1164
1165 return SectionOrder;
1166 }
1167
1168 // Sorts the sections in ISD according to the provided section order.
1169 static void
sortISDBySectionOrder(InputSectionDescription * ISD,const DenseMap<const InputSectionBase *,int> & Order)1170 sortISDBySectionOrder(InputSectionDescription *ISD,
1171 const DenseMap<const InputSectionBase *, int> &Order) {
1172 std::vector<InputSection *> UnorderedSections;
1173 std::vector<std::pair<InputSection *, int>> OrderedSections;
1174 uint64_t UnorderedSize = 0;
1175
1176 for (InputSection *IS : ISD->Sections) {
1177 auto I = Order.find(IS);
1178 if (I == Order.end()) {
1179 UnorderedSections.push_back(IS);
1180 UnorderedSize += IS->getSize();
1181 continue;
1182 }
1183 OrderedSections.push_back({IS, I->second});
1184 }
1185 llvm::sort(OrderedSections, [&](std::pair<InputSection *, int> A,
1186 std::pair<InputSection *, int> B) {
1187 return A.second < B.second;
1188 });
1189
1190 // Find an insertion point for the ordered section list in the unordered
1191 // section list. On targets with limited-range branches, this is the mid-point
1192 // of the unordered section list. This decreases the likelihood that a range
1193 // extension thunk will be needed to enter or exit the ordered region. If the
1194 // ordered section list is a list of hot functions, we can generally expect
1195 // the ordered functions to be called more often than the unordered functions,
1196 // making it more likely that any particular call will be within range, and
1197 // therefore reducing the number of thunks required.
1198 //
1199 // For example, imagine that you have 8MB of hot code and 32MB of cold code.
1200 // If the layout is:
1201 //
1202 // 8MB hot
1203 // 32MB cold
1204 //
1205 // only the first 8-16MB of the cold code (depending on which hot function it
1206 // is actually calling) can call the hot code without a range extension thunk.
1207 // However, if we use this layout:
1208 //
1209 // 16MB cold
1210 // 8MB hot
1211 // 16MB cold
1212 //
1213 // both the last 8-16MB of the first block of cold code and the first 8-16MB
1214 // of the second block of cold code can call the hot code without a thunk. So
1215 // we effectively double the amount of code that could potentially call into
1216 // the hot code without a thunk.
1217 size_t InsPt = 0;
1218 if (Target->getThunkSectionSpacing() && !OrderedSections.empty()) {
1219 uint64_t UnorderedPos = 0;
1220 for (; InsPt != UnorderedSections.size(); ++InsPt) {
1221 UnorderedPos += UnorderedSections[InsPt]->getSize();
1222 if (UnorderedPos > UnorderedSize / 2)
1223 break;
1224 }
1225 }
1226
1227 ISD->Sections.clear();
1228 for (InputSection *IS : makeArrayRef(UnorderedSections).slice(0, InsPt))
1229 ISD->Sections.push_back(IS);
1230 for (std::pair<InputSection *, int> P : OrderedSections)
1231 ISD->Sections.push_back(P.first);
1232 for (InputSection *IS : makeArrayRef(UnorderedSections).slice(InsPt))
1233 ISD->Sections.push_back(IS);
1234 }
1235
sortSection(OutputSection * Sec,const DenseMap<const InputSectionBase *,int> & Order)1236 static void sortSection(OutputSection *Sec,
1237 const DenseMap<const InputSectionBase *, int> &Order) {
1238 StringRef Name = Sec->Name;
1239
1240 // Sort input sections by section name suffixes for
1241 // __attribute__((init_priority(N))).
1242 if (Name == ".init_array" || Name == ".fini_array") {
1243 if (!Script->HasSectionsCommand)
1244 Sec->sortInitFini();
1245 return;
1246 }
1247
1248 // Sort input sections by the special rule for .ctors and .dtors.
1249 if (Name == ".ctors" || Name == ".dtors") {
1250 if (!Script->HasSectionsCommand)
1251 Sec->sortCtorsDtors();
1252 return;
1253 }
1254
1255 // Never sort these.
1256 if (Name == ".init" || Name == ".fini")
1257 return;
1258
1259 // Sort input sections by priority using the list provided
1260 // by --symbol-ordering-file.
1261 if (!Order.empty())
1262 for (BaseCommand *B : Sec->SectionCommands)
1263 if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1264 sortISDBySectionOrder(ISD, Order);
1265 }
1266
1267 // If no layout was provided by linker script, we want to apply default
1268 // sorting for special input sections. This also handles --symbol-ordering-file.
sortInputSections()1269 template <class ELFT> void Writer<ELFT>::sortInputSections() {
1270 // Build the order once since it is expensive.
1271 DenseMap<const InputSectionBase *, int> Order = buildSectionOrder();
1272 for (BaseCommand *Base : Script->SectionCommands)
1273 if (auto *Sec = dyn_cast<OutputSection>(Base))
1274 sortSection(Sec, Order);
1275 }
1276
sortSections()1277 template <class ELFT> void Writer<ELFT>::sortSections() {
1278 Script->adjustSectionsBeforeSorting();
1279
1280 // Don't sort if using -r. It is not necessary and we want to preserve the
1281 // relative order for SHF_LINK_ORDER sections.
1282 if (Config->Relocatable)
1283 return;
1284
1285 sortInputSections();
1286
1287 for (BaseCommand *Base : Script->SectionCommands) {
1288 auto *OS = dyn_cast<OutputSection>(Base);
1289 if (!OS)
1290 continue;
1291 OS->SortRank = getSectionRank(OS);
1292
1293 // We want to assign rude approximation values to OutSecOff fields
1294 // to know the relative order of the input sections. We use it for
1295 // sorting SHF_LINK_ORDER sections. See resolveShfLinkOrder().
1296 uint64_t I = 0;
1297 for (InputSection *Sec : getInputSections(OS))
1298 Sec->OutSecOff = I++;
1299 }
1300
1301 if (!Script->HasSectionsCommand) {
1302 // We know that all the OutputSections are contiguous in this case.
1303 auto IsSection = [](BaseCommand *Base) { return isa<OutputSection>(Base); };
1304 std::stable_sort(
1305 llvm::find_if(Script->SectionCommands, IsSection),
1306 llvm::find_if(llvm::reverse(Script->SectionCommands), IsSection).base(),
1307 compareSections);
1308 return;
1309 }
1310
1311 // Orphan sections are sections present in the input files which are
1312 // not explicitly placed into the output file by the linker script.
1313 //
1314 // The sections in the linker script are already in the correct
1315 // order. We have to figuere out where to insert the orphan
1316 // sections.
1317 //
1318 // The order of the sections in the script is arbitrary and may not agree with
1319 // compareSections. This means that we cannot easily define a strict weak
1320 // ordering. To see why, consider a comparison of a section in the script and
1321 // one not in the script. We have a two simple options:
1322 // * Make them equivalent (a is not less than b, and b is not less than a).
1323 // The problem is then that equivalence has to be transitive and we can
1324 // have sections a, b and c with only b in a script and a less than c
1325 // which breaks this property.
1326 // * Use compareSectionsNonScript. Given that the script order doesn't have
1327 // to match, we can end up with sections a, b, c, d where b and c are in the
1328 // script and c is compareSectionsNonScript less than b. In which case d
1329 // can be equivalent to c, a to b and d < a. As a concrete example:
1330 // .a (rx) # not in script
1331 // .b (rx) # in script
1332 // .c (ro) # in script
1333 // .d (ro) # not in script
1334 //
1335 // The way we define an order then is:
1336 // * Sort only the orphan sections. They are in the end right now.
1337 // * Move each orphan section to its preferred position. We try
1338 // to put each section in the last position where it can share
1339 // a PT_LOAD.
1340 //
1341 // There is some ambiguity as to where exactly a new entry should be
1342 // inserted, because Commands contains not only output section
1343 // commands but also other types of commands such as symbol assignment
1344 // expressions. There's no correct answer here due to the lack of the
1345 // formal specification of the linker script. We use heuristics to
1346 // determine whether a new output command should be added before or
1347 // after another commands. For the details, look at shouldSkip
1348 // function.
1349
1350 auto I = Script->SectionCommands.begin();
1351 auto E = Script->SectionCommands.end();
1352 auto NonScriptI = std::find_if(I, E, [](BaseCommand *Base) {
1353 if (auto *Sec = dyn_cast<OutputSection>(Base))
1354 return Sec->SectionIndex == UINT32_MAX;
1355 return false;
1356 });
1357
1358 // Sort the orphan sections.
1359 std::stable_sort(NonScriptI, E, compareSections);
1360
1361 // As a horrible special case, skip the first . assignment if it is before any
1362 // section. We do this because it is common to set a load address by starting
1363 // the script with ". = 0xabcd" and the expectation is that every section is
1364 // after that.
1365 auto FirstSectionOrDotAssignment =
1366 std::find_if(I, E, [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
1367 if (FirstSectionOrDotAssignment != E &&
1368 isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
1369 ++FirstSectionOrDotAssignment;
1370 I = FirstSectionOrDotAssignment;
1371
1372 while (NonScriptI != E) {
1373 auto Pos = findOrphanPos<ELFT>(I, NonScriptI);
1374 OutputSection *Orphan = cast<OutputSection>(*NonScriptI);
1375
1376 // As an optimization, find all sections with the same sort rank
1377 // and insert them with one rotate.
1378 unsigned Rank = Orphan->SortRank;
1379 auto End = std::find_if(NonScriptI + 1, E, [=](BaseCommand *Cmd) {
1380 return cast<OutputSection>(Cmd)->SortRank != Rank;
1381 });
1382 std::rotate(Pos, NonScriptI, End);
1383 NonScriptI = End;
1384 }
1385
1386 Script->adjustSectionsAfterSorting();
1387 }
1388
compareByFilePosition(InputSection * A,InputSection * B)1389 static bool compareByFilePosition(InputSection *A, InputSection *B) {
1390 // Synthetic, i. e. a sentinel section, should go last.
1391 if (A->kind() == InputSectionBase::Synthetic ||
1392 B->kind() == InputSectionBase::Synthetic)
1393 return A->kind() != InputSectionBase::Synthetic;
1394
1395 InputSection *LA = A->getLinkOrderDep();
1396 InputSection *LB = B->getLinkOrderDep();
1397 OutputSection *AOut = LA->getParent();
1398 OutputSection *BOut = LB->getParent();
1399
1400 if (AOut != BOut)
1401 return AOut->SectionIndex < BOut->SectionIndex;
1402 return LA->OutSecOff < LB->OutSecOff;
1403 }
1404
1405 // This function is used by the --merge-exidx-entries to detect duplicate
1406 // .ARM.exidx sections. It is Arm only.
1407 //
1408 // The .ARM.exidx section is of the form:
1409 // | PREL31 offset to function | Unwind instructions for function |
1410 // where the unwind instructions are either a small number of unwind
1411 // instructions inlined into the table entry, the special CANT_UNWIND value of
1412 // 0x1 or a PREL31 offset into a .ARM.extab Section that contains unwind
1413 // instructions.
1414 //
1415 // We return true if all the unwind instructions in the .ARM.exidx entries of
1416 // Cur can be merged into the last entry of Prev.
isDuplicateArmExidxSec(InputSection * Prev,InputSection * Cur)1417 static bool isDuplicateArmExidxSec(InputSection *Prev, InputSection *Cur) {
1418
1419 // References to .ARM.Extab Sections have bit 31 clear and are not the
1420 // special EXIDX_CANTUNWIND bit-pattern.
1421 auto IsExtabRef = [](uint32_t Unwind) {
1422 return (Unwind & 0x80000000) == 0 && Unwind != 0x1;
1423 };
1424
1425 struct ExidxEntry {
1426 ulittle32_t Fn;
1427 ulittle32_t Unwind;
1428 };
1429
1430 // Get the last table Entry from the previous .ARM.exidx section.
1431 const ExidxEntry &PrevEntry = Prev->getDataAs<ExidxEntry>().back();
1432 if (IsExtabRef(PrevEntry.Unwind))
1433 return false;
1434
1435 // We consider the unwind instructions of an .ARM.exidx table entry
1436 // a duplicate if the previous unwind instructions if:
1437 // - Both are the special EXIDX_CANTUNWIND.
1438 // - Both are the same inline unwind instructions.
1439 // We do not attempt to follow and check links into .ARM.extab tables as
1440 // consecutive identical entries are rare and the effort to check that they
1441 // are identical is high.
1442
1443 for (const ExidxEntry Entry : Cur->getDataAs<ExidxEntry>())
1444 if (IsExtabRef(Entry.Unwind) || Entry.Unwind != PrevEntry.Unwind)
1445 return false;
1446
1447 // All table entries in this .ARM.exidx Section can be merged into the
1448 // previous Section.
1449 return true;
1450 }
1451
resolveShfLinkOrder()1452 template <class ELFT> void Writer<ELFT>::resolveShfLinkOrder() {
1453 for (OutputSection *Sec : OutputSections) {
1454 if (!(Sec->Flags & SHF_LINK_ORDER))
1455 continue;
1456
1457 // Link order may be distributed across several InputSectionDescriptions
1458 // but sort must consider them all at once.
1459 std::vector<InputSection **> ScriptSections;
1460 std::vector<InputSection *> Sections;
1461 for (BaseCommand *Base : Sec->SectionCommands) {
1462 if (auto *ISD = dyn_cast<InputSectionDescription>(Base)) {
1463 for (InputSection *&IS : ISD->Sections) {
1464 ScriptSections.push_back(&IS);
1465 Sections.push_back(IS);
1466 }
1467 }
1468 }
1469 std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
1470
1471 if (!Config->Relocatable && Config->EMachine == EM_ARM &&
1472 Sec->Type == SHT_ARM_EXIDX) {
1473
1474 if (auto *Sentinel = dyn_cast<ARMExidxSentinelSection>(Sections.back())) {
1475 assert(Sections.size() >= 2 &&
1476 "We should create a sentinel section only if there are "
1477 "alive regular exidx sections.");
1478
1479 // The last executable section is required to fill the sentinel.
1480 // Remember it here so that we don't have to find it again.
1481 Sentinel->Highest = Sections[Sections.size() - 2]->getLinkOrderDep();
1482 }
1483
1484 // The EHABI for the Arm Architecture permits consecutive identical
1485 // table entries to be merged. We use a simple implementation that
1486 // removes a .ARM.exidx Input Section if it can be merged into the
1487 // previous one. This does not require any rewriting of InputSection
1488 // contents but misses opportunities for fine grained deduplication
1489 // where only a subset of the InputSection contents can be merged.
1490 if (Config->MergeArmExidx) {
1491 size_t Prev = 0;
1492 // The last one is a sentinel entry which should not be removed.
1493 for (size_t I = 1; I < Sections.size() - 1; ++I) {
1494 if (isDuplicateArmExidxSec(Sections[Prev], Sections[I]))
1495 Sections[I] = nullptr;
1496 else
1497 Prev = I;
1498 }
1499 }
1500 }
1501
1502 for (int I = 0, N = Sections.size(); I < N; ++I)
1503 *ScriptSections[I] = Sections[I];
1504
1505 // Remove the Sections we marked as duplicate earlier.
1506 for (BaseCommand *Base : Sec->SectionCommands)
1507 if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1508 llvm::erase_if(ISD->Sections, [](InputSection *IS) { return !IS; });
1509 }
1510 }
1511
1512 // For most RISC ISAs, we need to generate content that depends on the address
1513 // of InputSections. For example some architectures such as AArch64 use small
1514 // displacements for jump instructions that is the linker's responsibility for
1515 // creating range extension thunks for. As the generation of the content may
1516 // also alter InputSection addresses we must converge to a fixed point.
maybeAddThunks()1517 template <class ELFT> void Writer<ELFT>::maybeAddThunks() {
1518 if (!Target->NeedsThunks && !Config->AndroidPackDynRelocs &&
1519 !Config->RelrPackDynRelocs)
1520 return;
1521
1522 ThunkCreator TC;
1523 AArch64Err843419Patcher A64P;
1524
1525 for (;;) {
1526 bool Changed = false;
1527
1528 Script->assignAddresses();
1529
1530 if (Target->NeedsThunks)
1531 Changed |= TC.createThunks(OutputSections);
1532
1533 if (Config->FixCortexA53Errata843419) {
1534 if (Changed)
1535 Script->assignAddresses();
1536 Changed |= A64P.createFixes();
1537 }
1538
1539 if (In.MipsGot)
1540 In.MipsGot->updateAllocSize();
1541
1542 Changed |= In.RelaDyn->updateAllocSize();
1543
1544 if (In.RelrDyn)
1545 Changed |= In.RelrDyn->updateAllocSize();
1546
1547 if (!Changed)
1548 return;
1549 }
1550 }
1551
finalizeSynthetic(SyntheticSection * Sec)1552 static void finalizeSynthetic(SyntheticSection *Sec) {
1553 if (Sec && !Sec->empty() && Sec->getParent())
1554 Sec->finalizeContents();
1555 }
1556
1557 // In order to allow users to manipulate linker-synthesized sections,
1558 // we had to add synthetic sections to the input section list early,
1559 // even before we make decisions whether they are needed. This allows
1560 // users to write scripts like this: ".mygot : { .got }".
1561 //
1562 // Doing it has an unintended side effects. If it turns out that we
1563 // don't need a .got (for example) at all because there's no
1564 // relocation that needs a .got, we don't want to emit .got.
1565 //
1566 // To deal with the above problem, this function is called after
1567 // scanRelocations is called to remove synthetic sections that turn
1568 // out to be empty.
removeUnusedSyntheticSections()1569 static void removeUnusedSyntheticSections() {
1570 // All input synthetic sections that can be empty are placed after
1571 // all regular ones. We iterate over them all and exit at first
1572 // non-synthetic.
1573 for (InputSectionBase *S : llvm::reverse(InputSections)) {
1574 SyntheticSection *SS = dyn_cast<SyntheticSection>(S);
1575 if (!SS)
1576 return;
1577 OutputSection *OS = SS->getParent();
1578 if (!OS || !SS->empty())
1579 continue;
1580
1581 // If we reach here, then SS is an unused synthetic section and we want to
1582 // remove it from corresponding input section description of output section.
1583 for (BaseCommand *B : OS->SectionCommands)
1584 if (auto *ISD = dyn_cast<InputSectionDescription>(B))
1585 llvm::erase_if(ISD->Sections,
1586 [=](InputSection *IS) { return IS == SS; });
1587 }
1588 }
1589
1590 // Returns true if a symbol can be replaced at load-time by a symbol
1591 // with the same name defined in other ELF executable or DSO.
computeIsPreemptible(const Symbol & B)1592 static bool computeIsPreemptible(const Symbol &B) {
1593 assert(!B.isLocal());
1594
1595 // Only symbols that appear in dynsym can be preempted.
1596 if (!B.includeInDynsym())
1597 return false;
1598
1599 // Only default visibility symbols can be preempted.
1600 if (B.Visibility != STV_DEFAULT)
1601 return false;
1602
1603 // At this point copy relocations have not been created yet, so any
1604 // symbol that is not defined locally is preemptible.
1605 if (!B.isDefined())
1606 return true;
1607
1608 // If we have a dynamic list it specifies which local symbols are preemptible.
1609 if (Config->HasDynamicList)
1610 return false;
1611
1612 if (!Config->Shared)
1613 return false;
1614
1615 // -Bsymbolic means that definitions are not preempted.
1616 if (Config->Bsymbolic || (Config->BsymbolicFunctions && B.isFunc()))
1617 return false;
1618 return true;
1619 }
1620
1621 // Create output section objects and add them to OutputSections.
finalizeSections()1622 template <class ELFT> void Writer<ELFT>::finalizeSections() {
1623 Out::PreinitArray = findSection(".preinit_array");
1624 Out::InitArray = findSection(".init_array");
1625 Out::FiniArray = findSection(".fini_array");
1626
1627 // The linker needs to define SECNAME_start, SECNAME_end and SECNAME_stop
1628 // symbols for sections, so that the runtime can get the start and end
1629 // addresses of each section by section name. Add such symbols.
1630 if (!Config->Relocatable) {
1631 addStartEndSymbols();
1632 for (BaseCommand *Base : Script->SectionCommands)
1633 if (auto *Sec = dyn_cast<OutputSection>(Base))
1634 addStartStopSymbols(Sec);
1635 }
1636
1637 // Add _DYNAMIC symbol. Unlike GNU gold, our _DYNAMIC symbol has no type.
1638 // It should be okay as no one seems to care about the type.
1639 // Even the author of gold doesn't remember why gold behaves that way.
1640 // https://sourceware.org/ml/binutils/2002-03/msg00360.html
1641 if (In.Dynamic->Parent)
1642 Symtab->addDefined("_DYNAMIC", STV_HIDDEN, STT_NOTYPE, 0 /*Value*/,
1643 /*Size=*/0, STB_WEAK, In.Dynamic,
1644 /*File=*/nullptr);
1645
1646 // Define __rel[a]_iplt_{start,end} symbols if needed.
1647 addRelIpltSymbols();
1648
1649 // RISC-V's gp can address +/- 2 KiB, set it to .sdata + 0x800 if not defined.
1650 if (Config->EMachine == EM_RISCV)
1651 if (!dyn_cast_or_null<Defined>(Symtab->find("__global_pointer$")))
1652 addOptionalRegular("__global_pointer$", findSection(".sdata"), 0x800);
1653
1654 // This responsible for splitting up .eh_frame section into
1655 // pieces. The relocation scan uses those pieces, so this has to be
1656 // earlier.
1657 finalizeSynthetic(In.EhFrame);
1658
1659 for (Symbol *S : Symtab->getSymbols()) {
1660 if (!S->IsPreemptible)
1661 S->IsPreemptible = computeIsPreemptible(*S);
1662 if (S->isGnuIFunc() && Config->ZIfuncnoplt)
1663 S->ExportDynamic = true;
1664 }
1665
1666 // Scan relocations. This must be done after every symbol is declared so that
1667 // we can correctly decide if a dynamic relocation is needed.
1668 if (!Config->Relocatable)
1669 forEachRelSec(scanRelocations<ELFT>);
1670
1671 if (In.Plt && !In.Plt->empty())
1672 In.Plt->addSymbols();
1673 if (In.Iplt && !In.Iplt->empty())
1674 In.Iplt->addSymbols();
1675
1676 // Now that we have defined all possible global symbols including linker-
1677 // synthesized ones. Visit all symbols to give the finishing touches.
1678 for (Symbol *Sym : Symtab->getSymbols()) {
1679 if (!includeInSymtab(*Sym))
1680 continue;
1681 if (In.SymTab)
1682 In.SymTab->addSymbol(Sym);
1683
1684 if (Sym->includeInDynsym()) {
1685 In.DynSymTab->addSymbol(Sym);
1686 if (auto *File = dyn_cast_or_null<SharedFile<ELFT>>(Sym->File))
1687 if (File->IsNeeded && !Sym->isUndefined())
1688 InX<ELFT>::VerNeed->addSymbol(Sym);
1689 }
1690 }
1691
1692 // Do not proceed if there was an undefined symbol.
1693 if (errorCount())
1694 return;
1695
1696 if (In.MipsGot)
1697 In.MipsGot->build<ELFT>();
1698
1699 removeUnusedSyntheticSections();
1700
1701 sortSections();
1702
1703 // Now that we have the final list, create a list of all the
1704 // OutputSections for convenience.
1705 for (BaseCommand *Base : Script->SectionCommands)
1706 if (auto *Sec = dyn_cast<OutputSection>(Base))
1707 OutputSections.push_back(Sec);
1708
1709 // Prefer command line supplied address over other constraints.
1710 for (OutputSection *Sec : OutputSections) {
1711 auto I = Config->SectionStartMap.find(Sec->Name);
1712 if (I != Config->SectionStartMap.end())
1713 Sec->AddrExpr = [=] { return I->second; };
1714 }
1715
1716 // This is a bit of a hack. A value of 0 means undef, so we set it
1717 // to 1 to make __ehdr_start defined. The section number is not
1718 // particularly relevant.
1719 Out::ElfHeader->SectionIndex = 1;
1720
1721 for (size_t I = 0, E = OutputSections.size(); I != E; ++I) {
1722 OutputSection *Sec = OutputSections[I];
1723 Sec->SectionIndex = I + 1;
1724 Sec->ShName = In.ShStrTab->addString(Sec->Name);
1725 }
1726
1727 // Binary and relocatable output does not have PHDRS.
1728 // The headers have to be created before finalize as that can influence the
1729 // image base and the dynamic section on mips includes the image base.
1730 if (!Config->Relocatable && !Config->OFormatBinary) {
1731 Phdrs = Script->hasPhdrsCommands() ? Script->createPhdrs() : createPhdrs();
1732 addPtArmExid(Phdrs);
1733 Out::ProgramHeaders->Size = sizeof(Elf_Phdr) * Phdrs.size();
1734
1735 // Find the TLS segment. This happens before the section layout loop so that
1736 // Android relocation packing can look up TLS symbol addresses.
1737 for (PhdrEntry *P : Phdrs)
1738 if (P->p_type == PT_TLS)
1739 Out::TlsPhdr = P;
1740 }
1741
1742 // Some symbols are defined in term of program headers. Now that we
1743 // have the headers, we can find out which sections they point to.
1744 setReservedSymbolSections();
1745
1746 // Dynamic section must be the last one in this list and dynamic
1747 // symbol table section (DynSymTab) must be the first one.
1748 finalizeSynthetic(In.DynSymTab);
1749 finalizeSynthetic(In.Bss);
1750 finalizeSynthetic(In.BssRelRo);
1751 finalizeSynthetic(In.GnuHashTab);
1752 finalizeSynthetic(In.HashTab);
1753 finalizeSynthetic(In.SymTabShndx);
1754 finalizeSynthetic(In.ShStrTab);
1755 finalizeSynthetic(In.StrTab);
1756 finalizeSynthetic(In.VerDef);
1757 finalizeSynthetic(In.DynStrTab);
1758 finalizeSynthetic(In.Got);
1759 finalizeSynthetic(In.MipsGot);
1760 finalizeSynthetic(In.IgotPlt);
1761 finalizeSynthetic(In.GotPlt);
1762 finalizeSynthetic(In.RelaDyn);
1763 finalizeSynthetic(In.RelrDyn);
1764 finalizeSynthetic(In.RelaIplt);
1765 finalizeSynthetic(In.RelaPlt);
1766 finalizeSynthetic(In.Plt);
1767 finalizeSynthetic(In.Iplt);
1768 finalizeSynthetic(In.EhFrameHdr);
1769 finalizeSynthetic(InX<ELFT>::VerSym);
1770 finalizeSynthetic(InX<ELFT>::VerNeed);
1771 finalizeSynthetic(In.Dynamic);
1772
1773 if (!Script->HasSectionsCommand && !Config->Relocatable)
1774 fixSectionAlignments();
1775
1776 // After link order processing .ARM.exidx sections can be deduplicated, which
1777 // needs to be resolved before any other address dependent operation.
1778 resolveShfLinkOrder();
1779
1780 // Jump instructions in many ISAs have small displacements, and therefore they
1781 // cannot jump to arbitrary addresses in memory. For example, RISC-V JAL
1782 // instruction can target only +-1 MiB from PC. It is a linker's
1783 // responsibility to create and insert small pieces of code between sections
1784 // to extend the ranges if jump targets are out of range. Such code pieces are
1785 // called "thunks".
1786 //
1787 // We add thunks at this stage. We couldn't do this before this point because
1788 // this is the earliest point where we know sizes of sections and their
1789 // layouts (that are needed to determine if jump targets are in range).
1790 maybeAddThunks();
1791
1792 // maybeAddThunks may have added local symbols to the static symbol table.
1793 finalizeSynthetic(In.SymTab);
1794 finalizeSynthetic(In.PPC64LongBranchTarget);
1795
1796 // Fill other section headers. The dynamic table is finalized
1797 // at the end because some tags like RELSZ depend on result
1798 // of finalizing other sections.
1799 for (OutputSection *Sec : OutputSections)
1800 Sec->finalize<ELFT>();
1801 }
1802
1803 // Ensure data sections are not mixed with executable sections when
1804 // -execute-only is used. -execute-only is a feature to make pages executable
1805 // but not readable, and the feature is currently supported only on AArch64.
checkExecuteOnly()1806 template <class ELFT> void Writer<ELFT>::checkExecuteOnly() {
1807 if (!Config->ExecuteOnly)
1808 return;
1809
1810 for (OutputSection *OS : OutputSections)
1811 if (OS->Flags & SHF_EXECINSTR)
1812 for (InputSection *IS : getInputSections(OS))
1813 if (!(IS->Flags & SHF_EXECINSTR))
1814 error("cannot place " + toString(IS) + " into " + toString(OS->Name) +
1815 ": -execute-only does not support intermingling data and code");
1816 }
1817
1818 // The linker is expected to define SECNAME_start and SECNAME_end
1819 // symbols for a few sections. This function defines them.
addStartEndSymbols()1820 template <class ELFT> void Writer<ELFT>::addStartEndSymbols() {
1821 // If a section does not exist, there's ambiguity as to how we
1822 // define _start and _end symbols for an init/fini section. Since
1823 // the loader assume that the symbols are always defined, we need to
1824 // always define them. But what value? The loader iterates over all
1825 // pointers between _start and _end to run global ctors/dtors, so if
1826 // the section is empty, their symbol values don't actually matter
1827 // as long as _start and _end point to the same location.
1828 //
1829 // That said, we don't want to set the symbols to 0 (which is
1830 // probably the simplest value) because that could cause some
1831 // program to fail to link due to relocation overflow, if their
1832 // program text is above 2 GiB. We use the address of the .text
1833 // section instead to prevent that failure.
1834 //
1835 // In a rare sitaution, .text section may not exist. If that's the
1836 // case, use the image base address as a last resort.
1837 OutputSection *Default = findSection(".text");
1838 if (!Default)
1839 Default = Out::ElfHeader;
1840
1841 auto Define = [=](StringRef Start, StringRef End, OutputSection *OS) {
1842 if (OS) {
1843 addOptionalRegular(Start, OS, 0);
1844 addOptionalRegular(End, OS, -1);
1845 } else {
1846 addOptionalRegular(Start, Default, 0);
1847 addOptionalRegular(End, Default, 0);
1848 }
1849 };
1850
1851 Define("__preinit_array_start", "__preinit_array_end", Out::PreinitArray);
1852 Define("__init_array_start", "__init_array_end", Out::InitArray);
1853 Define("__fini_array_start", "__fini_array_end", Out::FiniArray);
1854
1855 if (OutputSection *Sec = findSection(".ARM.exidx"))
1856 Define("__exidx_start", "__exidx_end", Sec);
1857 }
1858
1859 // If a section name is valid as a C identifier (which is rare because of
1860 // the leading '.'), linkers are expected to define __start_<secname> and
1861 // __stop_<secname> symbols. They are at beginning and end of the section,
1862 // respectively. This is not requested by the ELF standard, but GNU ld and
1863 // gold provide the feature, and used by many programs.
1864 template <class ELFT>
addStartStopSymbols(OutputSection * Sec)1865 void Writer<ELFT>::addStartStopSymbols(OutputSection *Sec) {
1866 StringRef S = Sec->Name;
1867 if (!isValidCIdentifier(S))
1868 return;
1869 addOptionalRegular(Saver.save("__start_" + S), Sec, 0, STV_PROTECTED);
1870 addOptionalRegular(Saver.save("__stop_" + S), Sec, -1, STV_PROTECTED);
1871 }
1872
needsPtLoad(OutputSection * Sec)1873 static bool needsPtLoad(OutputSection *Sec) {
1874 if (!(Sec->Flags & SHF_ALLOC) || Sec->Noload)
1875 return false;
1876
1877 // Don't allocate VA space for TLS NOBITS sections. The PT_TLS PHDR is
1878 // responsible for allocating space for them, not the PT_LOAD that
1879 // contains the TLS initialization image.
1880 if ((Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS)
1881 return false;
1882 return true;
1883 }
1884
1885 // Linker scripts are responsible for aligning addresses. Unfortunately, most
1886 // linker scripts are designed for creating two PT_LOADs only, one RX and one
1887 // RW. This means that there is no alignment in the RO to RX transition and we
1888 // cannot create a PT_LOAD there.
computeFlags(uint64_t Flags)1889 static uint64_t computeFlags(uint64_t Flags) {
1890 if (Config->Omagic)
1891 return PF_R | PF_W | PF_X;
1892 if (Config->ExecuteOnly && (Flags & PF_X))
1893 return Flags & ~PF_R;
1894 if (Config->SingleRoRx && !(Flags & PF_W))
1895 return Flags | PF_X;
1896 return Flags;
1897 }
1898
1899 // Decide which program headers to create and which sections to include in each
1900 // one.
createPhdrs()1901 template <class ELFT> std::vector<PhdrEntry *> Writer<ELFT>::createPhdrs() {
1902 std::vector<PhdrEntry *> Ret;
1903 auto AddHdr = [&](unsigned Type, unsigned Flags) -> PhdrEntry * {
1904 Ret.push_back(make<PhdrEntry>(Type, Flags));
1905 return Ret.back();
1906 };
1907
1908 // The first phdr entry is PT_PHDR which describes the program header itself.
1909 AddHdr(PT_PHDR, PF_R)->add(Out::ProgramHeaders);
1910
1911 // PT_INTERP must be the second entry if exists.
1912 if (OutputSection *Cmd = findSection(".interp"))
1913 AddHdr(PT_INTERP, Cmd->getPhdrFlags())->add(Cmd);
1914
1915 // Add the first PT_LOAD segment for regular output sections.
1916 uint64_t Flags = computeFlags(PF_R);
1917 PhdrEntry *Load = AddHdr(PT_LOAD, Flags);
1918
1919 // Add the headers. We will remove them if they don't fit.
1920 Load->add(Out::ElfHeader);
1921 Load->add(Out::ProgramHeaders);
1922
1923 for (OutputSection *Sec : OutputSections) {
1924 if (!(Sec->Flags & SHF_ALLOC))
1925 break;
1926 if (!needsPtLoad(Sec))
1927 continue;
1928
1929 // Segments are contiguous memory regions that has the same attributes
1930 // (e.g. executable or writable). There is one phdr for each segment.
1931 // Therefore, we need to create a new phdr when the next section has
1932 // different flags or is loaded at a discontiguous address or memory
1933 // region using AT or AT> linker script command, respectively. At the same
1934 // time, we don't want to create a separate load segment for the headers,
1935 // even if the first output section has an AT or AT> attribute.
1936 uint64_t NewFlags = computeFlags(Sec->getPhdrFlags());
1937 if (((Sec->LMAExpr ||
1938 (Sec->LMARegion && (Sec->LMARegion != Load->FirstSec->LMARegion))) &&
1939 Load->LastSec != Out::ProgramHeaders) ||
1940 Sec->MemRegion != Load->FirstSec->MemRegion || Flags != NewFlags) {
1941
1942 Load = AddHdr(PT_LOAD, NewFlags);
1943 Flags = NewFlags;
1944 }
1945
1946 Load->add(Sec);
1947 }
1948
1949 // Add a TLS segment if any.
1950 PhdrEntry *TlsHdr = make<PhdrEntry>(PT_TLS, PF_R);
1951 for (OutputSection *Sec : OutputSections)
1952 if (Sec->Flags & SHF_TLS)
1953 TlsHdr->add(Sec);
1954 if (TlsHdr->FirstSec)
1955 Ret.push_back(TlsHdr);
1956
1957 // Add an entry for .dynamic.
1958 if (OutputSection *Sec = In.Dynamic->getParent())
1959 AddHdr(PT_DYNAMIC, Sec->getPhdrFlags())->add(Sec);
1960
1961 // PT_GNU_RELRO includes all sections that should be marked as
1962 // read-only by dynamic linker after proccessing relocations.
1963 // Current dynamic loaders only support one PT_GNU_RELRO PHDR, give
1964 // an error message if more than one PT_GNU_RELRO PHDR is required.
1965 PhdrEntry *RelRo = make<PhdrEntry>(PT_GNU_RELRO, PF_R);
1966 bool InRelroPhdr = false;
1967 bool IsRelroFinished = false;
1968 for (OutputSection *Sec : OutputSections) {
1969 if (!needsPtLoad(Sec))
1970 continue;
1971 if (isRelroSection(Sec)) {
1972 InRelroPhdr = true;
1973 if (!IsRelroFinished)
1974 RelRo->add(Sec);
1975 else
1976 error("section: " + Sec->Name + " is not contiguous with other relro" +
1977 " sections");
1978 } else if (InRelroPhdr) {
1979 InRelroPhdr = false;
1980 IsRelroFinished = true;
1981 }
1982 }
1983 if (RelRo->FirstSec)
1984 Ret.push_back(RelRo);
1985
1986 // PT_GNU_EH_FRAME is a special section pointing on .eh_frame_hdr.
1987 if (!In.EhFrame->empty() && In.EhFrameHdr && In.EhFrame->getParent() &&
1988 In.EhFrameHdr->getParent())
1989 AddHdr(PT_GNU_EH_FRAME, In.EhFrameHdr->getParent()->getPhdrFlags())
1990 ->add(In.EhFrameHdr->getParent());
1991
1992 // PT_OPENBSD_RANDOMIZE is an OpenBSD-specific feature. That makes
1993 // the dynamic linker fill the segment with random data.
1994 if (OutputSection *Cmd = findSection(".openbsd.randomdata"))
1995 AddHdr(PT_OPENBSD_RANDOMIZE, Cmd->getPhdrFlags())->add(Cmd);
1996
1997 // PT_GNU_STACK is a special section to tell the loader to make the
1998 // pages for the stack non-executable. If you really want an executable
1999 // stack, you can pass -z execstack, but that's not recommended for
2000 // security reasons.
2001 unsigned Perm = PF_R | PF_W;
2002 if (Config->ZExecstack)
2003 Perm |= PF_X;
2004 AddHdr(PT_GNU_STACK, Perm)->p_memsz = Config->ZStackSize;
2005
2006 // PT_OPENBSD_WXNEEDED is a OpenBSD-specific header to mark the executable
2007 // is expected to perform W^X violations, such as calling mprotect(2) or
2008 // mmap(2) with PROT_WRITE | PROT_EXEC, which is prohibited by default on
2009 // OpenBSD.
2010 if (Config->ZWxneeded)
2011 AddHdr(PT_OPENBSD_WXNEEDED, PF_X);
2012
2013 // Create one PT_NOTE per a group of contiguous .note sections.
2014 PhdrEntry *Note = nullptr;
2015 for (OutputSection *Sec : OutputSections) {
2016 if (Sec->Type == SHT_NOTE && (Sec->Flags & SHF_ALLOC)) {
2017 if (!Note || Sec->LMAExpr)
2018 Note = AddHdr(PT_NOTE, PF_R);
2019 Note->add(Sec);
2020 } else {
2021 Note = nullptr;
2022 }
2023 }
2024 return Ret;
2025 }
2026
2027 template <class ELFT>
addPtArmExid(std::vector<PhdrEntry * > & Phdrs)2028 void Writer<ELFT>::addPtArmExid(std::vector<PhdrEntry *> &Phdrs) {
2029 if (Config->EMachine != EM_ARM)
2030 return;
2031 auto I = llvm::find_if(OutputSections, [](OutputSection *Cmd) {
2032 return Cmd->Type == SHT_ARM_EXIDX;
2033 });
2034 if (I == OutputSections.end())
2035 return;
2036
2037 // PT_ARM_EXIDX is the ARM EHABI equivalent of PT_GNU_EH_FRAME
2038 PhdrEntry *ARMExidx = make<PhdrEntry>(PT_ARM_EXIDX, PF_R);
2039 ARMExidx->add(*I);
2040 Phdrs.push_back(ARMExidx);
2041 }
2042
2043 // The first section of each PT_LOAD, the first section in PT_GNU_RELRO and the
2044 // first section after PT_GNU_RELRO have to be page aligned so that the dynamic
2045 // linker can set the permissions.
fixSectionAlignments()2046 template <class ELFT> void Writer<ELFT>::fixSectionAlignments() {
2047 auto PageAlign = [](OutputSection *Cmd) {
2048 if (Cmd && !Cmd->AddrExpr)
2049 Cmd->AddrExpr = [=] {
2050 return alignTo(Script->getDot(), Config->MaxPageSize);
2051 };
2052 };
2053
2054 for (const PhdrEntry *P : Phdrs)
2055 if (P->p_type == PT_LOAD && P->FirstSec)
2056 PageAlign(P->FirstSec);
2057
2058 for (const PhdrEntry *P : Phdrs) {
2059 if (P->p_type != PT_GNU_RELRO)
2060 continue;
2061
2062 if (P->FirstSec)
2063 PageAlign(P->FirstSec);
2064
2065 // Find the first section after PT_GNU_RELRO. If it is in a PT_LOAD we
2066 // have to align it to a page.
2067 auto End = OutputSections.end();
2068 auto I = std::find(OutputSections.begin(), End, P->LastSec);
2069 if (I == End || (I + 1) == End)
2070 continue;
2071
2072 OutputSection *Cmd = (*(I + 1));
2073 if (needsPtLoad(Cmd))
2074 PageAlign(Cmd);
2075 }
2076 }
2077
2078 // Compute an in-file position for a given section. The file offset must be the
2079 // same with its virtual address modulo the page size, so that the loader can
2080 // load executables without any address adjustment.
computeFileOffset(OutputSection * OS,uint64_t Off)2081 static uint64_t computeFileOffset(OutputSection *OS, uint64_t Off) {
2082 // File offsets are not significant for .bss sections. By convention, we keep
2083 // section offsets monotonically increasing rather than setting to zero.
2084 if (OS->Type == SHT_NOBITS)
2085 return Off;
2086
2087 // If the section is not in a PT_LOAD, we just have to align it.
2088 if (!OS->PtLoad)
2089 return alignTo(Off, OS->Alignment);
2090
2091 // The first section in a PT_LOAD has to have congruent offset and address
2092 // module the page size.
2093 OutputSection *First = OS->PtLoad->FirstSec;
2094 if (OS == First) {
2095 uint64_t Alignment = std::max<uint64_t>(OS->Alignment, Config->MaxPageSize);
2096 return alignTo(Off, Alignment, OS->Addr);
2097 }
2098
2099 // If two sections share the same PT_LOAD the file offset is calculated
2100 // using this formula: Off2 = Off1 + (VA2 - VA1).
2101 return First->Offset + OS->Addr - First->Addr;
2102 }
2103
2104 // Set an in-file position to a given section and returns the end position of
2105 // the section.
setFileOffset(OutputSection * OS,uint64_t Off)2106 static uint64_t setFileOffset(OutputSection *OS, uint64_t Off) {
2107 Off = computeFileOffset(OS, Off);
2108 OS->Offset = Off;
2109
2110 if (OS->Type == SHT_NOBITS)
2111 return Off;
2112 return Off + OS->Size;
2113 }
2114
assignFileOffsetsBinary()2115 template <class ELFT> void Writer<ELFT>::assignFileOffsetsBinary() {
2116 uint64_t Off = 0;
2117 for (OutputSection *Sec : OutputSections)
2118 if (Sec->Flags & SHF_ALLOC)
2119 Off = setFileOffset(Sec, Off);
2120 FileSize = alignTo(Off, Config->Wordsize);
2121 }
2122
rangeToString(uint64_t Addr,uint64_t Len)2123 static std::string rangeToString(uint64_t Addr, uint64_t Len) {
2124 return "[0x" + utohexstr(Addr) + ", 0x" + utohexstr(Addr + Len - 1) + "]";
2125 }
2126
2127 // Assign file offsets to output sections.
assignFileOffsets()2128 template <class ELFT> void Writer<ELFT>::assignFileOffsets() {
2129 uint64_t Off = 0;
2130 Off = setFileOffset(Out::ElfHeader, Off);
2131 Off = setFileOffset(Out::ProgramHeaders, Off);
2132
2133 PhdrEntry *LastRX = nullptr;
2134 for (PhdrEntry *P : Phdrs)
2135 if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2136 LastRX = P;
2137
2138 for (OutputSection *Sec : OutputSections) {
2139 Off = setFileOffset(Sec, Off);
2140 if (Script->HasSectionsCommand)
2141 continue;
2142
2143 // If this is a last section of the last executable segment and that
2144 // segment is the last loadable segment, align the offset of the
2145 // following section to avoid loading non-segments parts of the file.
2146 if (LastRX && LastRX->LastSec == Sec)
2147 Off = alignTo(Off, Target->PageSize);
2148 }
2149
2150 SectionHeaderOff = alignTo(Off, Config->Wordsize);
2151 FileSize = SectionHeaderOff + (OutputSections.size() + 1) * sizeof(Elf_Shdr);
2152
2153 // Our logic assumes that sections have rising VA within the same segment.
2154 // With use of linker scripts it is possible to violate this rule and get file
2155 // offset overlaps or overflows. That should never happen with a valid script
2156 // which does not move the location counter backwards and usually scripts do
2157 // not do that. Unfortunately, there are apps in the wild, for example, Linux
2158 // kernel, which control segment distribution explicitly and move the counter
2159 // backwards, so we have to allow doing that to support linking them. We
2160 // perform non-critical checks for overlaps in checkSectionOverlap(), but here
2161 // we want to prevent file size overflows because it would crash the linker.
2162 for (OutputSection *Sec : OutputSections) {
2163 if (Sec->Type == SHT_NOBITS)
2164 continue;
2165 if ((Sec->Offset > FileSize) || (Sec->Offset + Sec->Size > FileSize))
2166 error("unable to place section " + Sec->Name + " at file offset " +
2167 rangeToString(Sec->Offset, Sec->Size) +
2168 "; check your linker script for overflows");
2169 }
2170 }
2171
2172 // Finalize the program headers. We call this function after we assign
2173 // file offsets and VAs to all sections.
setPhdrs()2174 template <class ELFT> void Writer<ELFT>::setPhdrs() {
2175 for (PhdrEntry *P : Phdrs) {
2176 OutputSection *First = P->FirstSec;
2177 OutputSection *Last = P->LastSec;
2178
2179 if (First) {
2180 P->p_filesz = Last->Offset - First->Offset;
2181 if (Last->Type != SHT_NOBITS)
2182 P->p_filesz += Last->Size;
2183
2184 P->p_memsz = Last->Addr + Last->Size - First->Addr;
2185 P->p_offset = First->Offset;
2186 P->p_vaddr = First->Addr;
2187
2188 if (!P->HasLMA)
2189 P->p_paddr = First->getLMA();
2190 }
2191
2192 if (P->p_type == PT_LOAD) {
2193 P->p_align = std::max<uint64_t>(P->p_align, Config->MaxPageSize);
2194 } else if (P->p_type == PT_GNU_RELRO) {
2195 P->p_align = 1;
2196 // The glibc dynamic loader rounds the size down, so we need to round up
2197 // to protect the last page. This is a no-op on FreeBSD which always
2198 // rounds up.
2199 P->p_memsz = alignTo(P->p_memsz, Target->PageSize);
2200 }
2201
2202 if (P->p_type == PT_TLS && P->p_memsz) {
2203 // The TLS pointer goes after PT_TLS for variant 2 targets. At least glibc
2204 // will align it, so round up the size to make sure the offsets are
2205 // correct.
2206 P->p_memsz = alignTo(P->p_memsz, P->p_align);
2207 }
2208 }
2209 }
2210
2211 // A helper struct for checkSectionOverlap.
2212 namespace {
2213 struct SectionOffset {
2214 OutputSection *Sec;
2215 uint64_t Offset;
2216 };
2217 } // namespace
2218
2219 // Check whether sections overlap for a specific address range (file offsets,
2220 // load and virtual adresses).
checkOverlap(StringRef Name,std::vector<SectionOffset> & Sections,bool IsVirtualAddr)2221 static void checkOverlap(StringRef Name, std::vector<SectionOffset> &Sections,
2222 bool IsVirtualAddr) {
2223 llvm::sort(Sections, [=](const SectionOffset &A, const SectionOffset &B) {
2224 return A.Offset < B.Offset;
2225 });
2226
2227 // Finding overlap is easy given a vector is sorted by start position.
2228 // If an element starts before the end of the previous element, they overlap.
2229 for (size_t I = 1, End = Sections.size(); I < End; ++I) {
2230 SectionOffset A = Sections[I - 1];
2231 SectionOffset B = Sections[I];
2232 if (B.Offset >= A.Offset + A.Sec->Size)
2233 continue;
2234
2235 // If both sections are in OVERLAY we allow the overlapping of virtual
2236 // addresses, because it is what OVERLAY was designed for.
2237 if (IsVirtualAddr && A.Sec->InOverlay && B.Sec->InOverlay)
2238 continue;
2239
2240 errorOrWarn("section " + A.Sec->Name + " " + Name +
2241 " range overlaps with " + B.Sec->Name + "\n>>> " + A.Sec->Name +
2242 " range is " + rangeToString(A.Offset, A.Sec->Size) + "\n>>> " +
2243 B.Sec->Name + " range is " +
2244 rangeToString(B.Offset, B.Sec->Size));
2245 }
2246 }
2247
2248 // Check for overlapping sections and address overflows.
2249 //
2250 // In this function we check that none of the output sections have overlapping
2251 // file offsets. For SHF_ALLOC sections we also check that the load address
2252 // ranges and the virtual address ranges don't overlap
checkSections()2253 template <class ELFT> void Writer<ELFT>::checkSections() {
2254 // First, check that section's VAs fit in available address space for target.
2255 for (OutputSection *OS : OutputSections)
2256 if ((OS->Addr + OS->Size < OS->Addr) ||
2257 (!ELFT::Is64Bits && OS->Addr + OS->Size > UINT32_MAX))
2258 errorOrWarn("section " + OS->Name + " at 0x" + utohexstr(OS->Addr) +
2259 " of size 0x" + utohexstr(OS->Size) +
2260 " exceeds available address space");
2261
2262 // Check for overlapping file offsets. In this case we need to skip any
2263 // section marked as SHT_NOBITS. These sections don't actually occupy space in
2264 // the file so Sec->Offset + Sec->Size can overlap with others. If --oformat
2265 // binary is specified only add SHF_ALLOC sections are added to the output
2266 // file so we skip any non-allocated sections in that case.
2267 std::vector<SectionOffset> FileOffs;
2268 for (OutputSection *Sec : OutputSections)
2269 if (Sec->Size > 0 && Sec->Type != SHT_NOBITS &&
2270 (!Config->OFormatBinary || (Sec->Flags & SHF_ALLOC)))
2271 FileOffs.push_back({Sec, Sec->Offset});
2272 checkOverlap("file", FileOffs, false);
2273
2274 // When linking with -r there is no need to check for overlapping virtual/load
2275 // addresses since those addresses will only be assigned when the final
2276 // executable/shared object is created.
2277 if (Config->Relocatable)
2278 return;
2279
2280 // Checking for overlapping virtual and load addresses only needs to take
2281 // into account SHF_ALLOC sections since others will not be loaded.
2282 // Furthermore, we also need to skip SHF_TLS sections since these will be
2283 // mapped to other addresses at runtime and can therefore have overlapping
2284 // ranges in the file.
2285 std::vector<SectionOffset> VMAs;
2286 for (OutputSection *Sec : OutputSections)
2287 if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2288 VMAs.push_back({Sec, Sec->Addr});
2289 checkOverlap("virtual address", VMAs, true);
2290
2291 // Finally, check that the load addresses don't overlap. This will usually be
2292 // the same as the virtual addresses but can be different when using a linker
2293 // script with AT().
2294 std::vector<SectionOffset> LMAs;
2295 for (OutputSection *Sec : OutputSections)
2296 if (Sec->Size > 0 && (Sec->Flags & SHF_ALLOC) && !(Sec->Flags & SHF_TLS))
2297 LMAs.push_back({Sec, Sec->getLMA()});
2298 checkOverlap("load address", LMAs, false);
2299 }
2300
2301 // The entry point address is chosen in the following ways.
2302 //
2303 // 1. the '-e' entry command-line option;
2304 // 2. the ENTRY(symbol) command in a linker control script;
2305 // 3. the value of the symbol _start, if present;
2306 // 4. the number represented by the entry symbol, if it is a number;
2307 // 5. the address of the first byte of the .text section, if present;
2308 // 6. the address 0.
getEntryAddr()2309 static uint64_t getEntryAddr() {
2310 // Case 1, 2 or 3
2311 if (Symbol *B = Symtab->find(Config->Entry))
2312 return B->getVA();
2313
2314 // Case 4
2315 uint64_t Addr;
2316 if (to_integer(Config->Entry, Addr))
2317 return Addr;
2318
2319 // Case 5
2320 if (OutputSection *Sec = findSection(".text")) {
2321 if (Config->WarnMissingEntry)
2322 warn("cannot find entry symbol " + Config->Entry + "; defaulting to 0x" +
2323 utohexstr(Sec->Addr));
2324 return Sec->Addr;
2325 }
2326
2327 // Case 6
2328 if (Config->WarnMissingEntry)
2329 warn("cannot find entry symbol " + Config->Entry +
2330 "; not setting start address");
2331 return 0;
2332 }
2333
getELFType()2334 static uint16_t getELFType() {
2335 if (Config->Pic)
2336 return ET_DYN;
2337 if (Config->Relocatable)
2338 return ET_REL;
2339 return ET_EXEC;
2340 }
2341
getAbiVersion()2342 static uint8_t getAbiVersion() {
2343 // MIPS non-PIC executable gets ABI version 1.
2344 if (Config->EMachine == EM_MIPS && getELFType() == ET_EXEC &&
2345 (Config->EFlags & (EF_MIPS_PIC | EF_MIPS_CPIC)) == EF_MIPS_CPIC)
2346 return 1;
2347 return 0;
2348 }
2349
writeHeader()2350 template <class ELFT> void Writer<ELFT>::writeHeader() {
2351 uint8_t *Buf = Buffer->getBufferStart();
2352
2353 // For executable segments, the trap instructions are written before writing
2354 // the header. Setting Elf header bytes to zero ensures that any unused bytes
2355 // in header are zero-cleared, instead of having trap instructions.
2356 memset(Buf, 0, sizeof(Elf_Ehdr));
2357 memcpy(Buf, "\177ELF", 4);
2358
2359 // Write the ELF header.
2360 auto *EHdr = reinterpret_cast<Elf_Ehdr *>(Buf);
2361 EHdr->e_ident[EI_CLASS] = Config->Is64 ? ELFCLASS64 : ELFCLASS32;
2362 EHdr->e_ident[EI_DATA] = Config->IsLE ? ELFDATA2LSB : ELFDATA2MSB;
2363 EHdr->e_ident[EI_VERSION] = EV_CURRENT;
2364 EHdr->e_ident[EI_OSABI] = Config->OSABI;
2365 EHdr->e_ident[EI_ABIVERSION] = getAbiVersion();
2366 EHdr->e_type = getELFType();
2367 EHdr->e_machine = Config->EMachine;
2368 EHdr->e_version = EV_CURRENT;
2369 EHdr->e_entry = getEntryAddr();
2370 EHdr->e_shoff = SectionHeaderOff;
2371 EHdr->e_flags = Config->EFlags;
2372 EHdr->e_ehsize = sizeof(Elf_Ehdr);
2373 EHdr->e_phnum = Phdrs.size();
2374 EHdr->e_shentsize = sizeof(Elf_Shdr);
2375
2376 if (!Config->Relocatable) {
2377 EHdr->e_phoff = sizeof(Elf_Ehdr);
2378 EHdr->e_phentsize = sizeof(Elf_Phdr);
2379 }
2380
2381 // Write the program header table.
2382 auto *HBuf = reinterpret_cast<Elf_Phdr *>(Buf + EHdr->e_phoff);
2383 for (PhdrEntry *P : Phdrs) {
2384 HBuf->p_type = P->p_type;
2385 HBuf->p_flags = P->p_flags;
2386 HBuf->p_offset = P->p_offset;
2387 HBuf->p_vaddr = P->p_vaddr;
2388 HBuf->p_paddr = P->p_paddr;
2389 HBuf->p_filesz = P->p_filesz;
2390 HBuf->p_memsz = P->p_memsz;
2391 HBuf->p_align = P->p_align;
2392 ++HBuf;
2393 }
2394
2395 // Write the section header table.
2396 //
2397 // The ELF header can only store numbers up to SHN_LORESERVE in the e_shnum
2398 // and e_shstrndx fields. When the value of one of these fields exceeds
2399 // SHN_LORESERVE ELF requires us to put sentinel values in the ELF header and
2400 // use fields in the section header at index 0 to store
2401 // the value. The sentinel values and fields are:
2402 // e_shnum = 0, SHdrs[0].sh_size = number of sections.
2403 // e_shstrndx = SHN_XINDEX, SHdrs[0].sh_link = .shstrtab section index.
2404 auto *SHdrs = reinterpret_cast<Elf_Shdr *>(Buf + EHdr->e_shoff);
2405 size_t Num = OutputSections.size() + 1;
2406 if (Num >= SHN_LORESERVE)
2407 SHdrs->sh_size = Num;
2408 else
2409 EHdr->e_shnum = Num;
2410
2411 uint32_t StrTabIndex = In.ShStrTab->getParent()->SectionIndex;
2412 if (StrTabIndex >= SHN_LORESERVE) {
2413 SHdrs->sh_link = StrTabIndex;
2414 EHdr->e_shstrndx = SHN_XINDEX;
2415 } else {
2416 EHdr->e_shstrndx = StrTabIndex;
2417 }
2418
2419 for (OutputSection *Sec : OutputSections)
2420 Sec->writeHeaderTo<ELFT>(++SHdrs);
2421 }
2422
2423 // Open a result file.
openFile()2424 template <class ELFT> void Writer<ELFT>::openFile() {
2425 uint64_t MaxSize = Config->Is64 ? INT64_MAX : UINT32_MAX;
2426 if (MaxSize < FileSize) {
2427 error("output file too large: " + Twine(FileSize) + " bytes");
2428 return;
2429 }
2430
2431 unlinkAsync(Config->OutputFile);
2432 unsigned Flags = 0;
2433 if (!Config->Relocatable)
2434 Flags = FileOutputBuffer::F_executable;
2435 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
2436 FileOutputBuffer::create(Config->OutputFile, FileSize, Flags);
2437
2438 if (!BufferOrErr)
2439 error("failed to open " + Config->OutputFile + ": " +
2440 llvm::toString(BufferOrErr.takeError()));
2441 else
2442 Buffer = std::move(*BufferOrErr);
2443 }
2444
writeSectionsBinary()2445 template <class ELFT> void Writer<ELFT>::writeSectionsBinary() {
2446 uint8_t *Buf = Buffer->getBufferStart();
2447 for (OutputSection *Sec : OutputSections)
2448 if (Sec->Flags & SHF_ALLOC)
2449 Sec->writeTo<ELFT>(Buf + Sec->Offset);
2450 }
2451
fillTrap(uint8_t * I,uint8_t * End)2452 static void fillTrap(uint8_t *I, uint8_t *End) {
2453 for (; I + 4 <= End; I += 4)
2454 memcpy(I, &Target->TrapInstr, 4);
2455 }
2456
2457 // Fill the last page of executable segments with trap instructions
2458 // instead of leaving them as zero. Even though it is not required by any
2459 // standard, it is in general a good thing to do for security reasons.
2460 //
2461 // We'll leave other pages in segments as-is because the rest will be
2462 // overwritten by output sections.
writeTrapInstr()2463 template <class ELFT> void Writer<ELFT>::writeTrapInstr() {
2464 if (Script->HasSectionsCommand)
2465 return;
2466
2467 // Fill the last page.
2468 uint8_t *Buf = Buffer->getBufferStart();
2469 for (PhdrEntry *P : Phdrs)
2470 if (P->p_type == PT_LOAD && (P->p_flags & PF_X))
2471 fillTrap(Buf + alignDown(P->p_offset + P->p_filesz, Target->PageSize),
2472 Buf + alignTo(P->p_offset + P->p_filesz, Target->PageSize));
2473
2474 // Round up the file size of the last segment to the page boundary iff it is
2475 // an executable segment to ensure that other tools don't accidentally
2476 // trim the instruction padding (e.g. when stripping the file).
2477 PhdrEntry *Last = nullptr;
2478 for (PhdrEntry *P : Phdrs)
2479 if (P->p_type == PT_LOAD)
2480 Last = P;
2481
2482 if (Last && (Last->p_flags & PF_X))
2483 Last->p_memsz = Last->p_filesz = alignTo(Last->p_filesz, Target->PageSize);
2484 }
2485
2486 // Write section contents to a mmap'ed file.
writeSections()2487 template <class ELFT> void Writer<ELFT>::writeSections() {
2488 uint8_t *Buf = Buffer->getBufferStart();
2489
2490 OutputSection *EhFrameHdr = nullptr;
2491 if (In.EhFrameHdr && !In.EhFrameHdr->empty())
2492 EhFrameHdr = In.EhFrameHdr->getParent();
2493
2494 // In -r or -emit-relocs mode, write the relocation sections first as in
2495 // ELf_Rel targets we might find out that we need to modify the relocated
2496 // section while doing it.
2497 for (OutputSection *Sec : OutputSections)
2498 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
2499 Sec->writeTo<ELFT>(Buf + Sec->Offset);
2500
2501 for (OutputSection *Sec : OutputSections)
2502 if (Sec != EhFrameHdr && Sec->Type != SHT_REL && Sec->Type != SHT_RELA)
2503 Sec->writeTo<ELFT>(Buf + Sec->Offset);
2504
2505 // The .eh_frame_hdr depends on .eh_frame section contents, therefore
2506 // it should be written after .eh_frame is written.
2507 if (EhFrameHdr)
2508 EhFrameHdr->writeTo<ELFT>(Buf + EhFrameHdr->Offset);
2509 }
2510
writeBuildId()2511 template <class ELFT> void Writer<ELFT>::writeBuildId() {
2512 if (!In.BuildId || !In.BuildId->getParent())
2513 return;
2514
2515 // Compute a hash of all sections of the output file.
2516 uint8_t *Start = Buffer->getBufferStart();
2517 uint8_t *End = Start + FileSize;
2518 In.BuildId->writeBuildId({Start, End});
2519 }
2520
2521 template void elf::writeResult<ELF32LE>();
2522 template void elf::writeResult<ELF32BE>();
2523 template void elf::writeResult<ELF64LE>();
2524 template void elf::writeResult<ELF64BE>();
2525