1 //===- LinkerScript.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains the parser/evaluator of the linker script.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "LinkerScript.h"
14 #include "Config.h"
15 #include "InputSection.h"
16 #include "OutputSections.h"
17 #include "SymbolTable.h"
18 #include "Symbols.h"
19 #include "SyntheticSections.h"
20 #include "Target.h"
21 #include "Writer.h"
22 #include "lld/Common/Memory.h"
23 #include "lld/Common/Strings.h"
24 #include "lld/Common/Threads.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/BinaryFormat/ELF.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/Endian.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/FileSystem.h"
32 #include "llvm/Support/Path.h"
33 #include <algorithm>
34 #include <cassert>
35 #include <cstddef>
36 #include <cstdint>
37 #include <iterator>
38 #include <limits>
39 #include <string>
40 #include <vector>
41 
42 using namespace llvm;
43 using namespace llvm::ELF;
44 using namespace llvm::object;
45 using namespace llvm::support::endian;
46 using namespace lld;
47 using namespace lld::elf;
48 
49 LinkerScript *elf::Script;
50 
51 static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) {
52   if (OutputSection *OS = InputSec->getOutputSection())
53     return OS->Addr;
54   error(Loc + ": unable to evaluate expression: input section " +
55         InputSec->Name + " has no output section assigned");
56   return 0;
57 }
58 
59 uint64_t ExprValue::getValue() const {
60   if (Sec)
61     return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc),
62                    Alignment);
63   return alignTo(Val, Alignment);
64 }
65 
66 uint64_t ExprValue::getSecAddr() const {
67   if (Sec)
68     return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc);
69   return 0;
70 }
71 
72 uint64_t ExprValue::getSectionOffset() const {
73   // If the alignment is trivial, we don't have to compute the full
74   // value to know the offset. This allows this function to succeed in
75   // cases where the output section is not yet known.
76   if (Alignment == 1 && (!Sec || !Sec->getOutputSection()))
77     return Val;
78   return getValue() - getSecAddr();
79 }
80 
81 OutputSection *LinkerScript::createOutputSection(StringRef Name,
82                                                  StringRef Location) {
83   OutputSection *&SecRef = NameToOutputSection[Name];
84   OutputSection *Sec;
85   if (SecRef && SecRef->Location.empty()) {
86     // There was a forward reference.
87     Sec = SecRef;
88   } else {
89     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
90     if (!SecRef)
91       SecRef = Sec;
92   }
93   Sec->Location = Location;
94   return Sec;
95 }
96 
97 OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
98   OutputSection *&CmdRef = NameToOutputSection[Name];
99   if (!CmdRef)
100     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
101   return CmdRef;
102 }
103 
104 // Expands the memory region by the specified size.
105 static void expandMemoryRegion(MemoryRegion *MemRegion, uint64_t Size,
106                                StringRef RegionName, StringRef SecName) {
107   MemRegion->CurPos += Size;
108   uint64_t NewSize = MemRegion->CurPos - MemRegion->Origin;
109   if (NewSize > MemRegion->Length)
110     error("section '" + SecName + "' will not fit in region '" + RegionName +
111           "': overflowed by " + Twine(NewSize - MemRegion->Length) + " bytes");
112 }
113 
114 void LinkerScript::expandMemoryRegions(uint64_t Size) {
115   if (Ctx->MemRegion)
116     expandMemoryRegion(Ctx->MemRegion, Size, Ctx->MemRegion->Name,
117                        Ctx->OutSec->Name);
118   // Only expand the LMARegion if it is different from MemRegion.
119   if (Ctx->LMARegion && Ctx->MemRegion != Ctx->LMARegion)
120     expandMemoryRegion(Ctx->LMARegion, Size, Ctx->LMARegion->Name,
121                        Ctx->OutSec->Name);
122 }
123 
124 void LinkerScript::expandOutputSection(uint64_t Size) {
125   Ctx->OutSec->Size += Size;
126   expandMemoryRegions(Size);
127 }
128 
129 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
130   uint64_t Val = E().getValue();
131   if (Val < Dot && InSec)
132     error(Loc + ": unable to move location counter backward for: " +
133           Ctx->OutSec->Name);
134 
135   // Update to location counter means update to section size.
136   if (InSec)
137     expandOutputSection(Val - Dot);
138 
139   Dot = Val;
140 }
141 
142 // Used for handling linker symbol assignments, for both finalizing
143 // their values and doing early declarations. Returns true if symbol
144 // should be defined from linker script.
145 static bool shouldDefineSym(SymbolAssignment *Cmd) {
146   if (Cmd->Name == ".")
147     return false;
148 
149   if (!Cmd->Provide)
150     return true;
151 
152   // If a symbol was in PROVIDE(), we need to define it only
153   // when it is a referenced undefined symbol.
154   Symbol *B = Symtab->find(Cmd->Name);
155   if (B && !B->isDefined())
156     return true;
157   return false;
158 }
159 
160 // This function is called from processSectionCommands,
161 // while we are fixing the output section layout.
162 void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
163   if (!shouldDefineSym(Cmd))
164     return;
165 
166   // Define a symbol.
167   ExprValue Value = Cmd->Expression();
168   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
169   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
170 
171   // When this function is called, section addresses have not been
172   // fixed yet. So, we may or may not know the value of the RHS
173   // expression.
174   //
175   // For example, if an expression is `x = 42`, we know x is always 42.
176   // However, if an expression is `x = .`, there's no way to know its
177   // value at the moment.
178   //
179   // We want to set symbol values early if we can. This allows us to
180   // use symbols as variables in linker scripts. Doing so allows us to
181   // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
182   uint64_t SymValue = Value.Sec ? 0 : Value.getValue();
183 
184   Defined New(nullptr, Cmd->Name, STB_GLOBAL, Visibility, STT_NOTYPE, SymValue,
185               0, Sec);
186 
187   Symbol *Sym = Symtab->insert(Cmd->Name);
188   Sym->mergeProperties(New);
189   Sym->replace(New);
190   Cmd->Sym = cast<Defined>(Sym);
191 }
192 
193 // This function is called from LinkerScript::declareSymbols.
194 // It creates a placeholder symbol if needed.
195 static void declareSymbol(SymbolAssignment *Cmd) {
196   if (!shouldDefineSym(Cmd))
197     return;
198 
199   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
200   Defined New(nullptr, Cmd->Name, STB_GLOBAL, Visibility, STT_NOTYPE, 0, 0,
201               nullptr);
202 
203   // We can't calculate final value right now.
204   Symbol *Sym = Symtab->insert(Cmd->Name);
205   Sym->mergeProperties(New);
206   Sym->replace(New);
207 
208   Cmd->Sym = cast<Defined>(Sym);
209   Cmd->Provide = false;
210   Sym->ScriptDefined = true;
211 }
212 
213 // This method is used to handle INSERT AFTER statement. Here we rebuild
214 // the list of script commands to mix sections inserted into.
215 void LinkerScript::processInsertCommands() {
216   std::vector<BaseCommand *> V;
217   auto Insert = [&](std::vector<BaseCommand *> &From) {
218     V.insert(V.end(), From.begin(), From.end());
219     From.clear();
220   };
221 
222   for (BaseCommand *Base : SectionCommands) {
223     if (auto *OS = dyn_cast<OutputSection>(Base)) {
224       Insert(InsertBeforeCommands[OS->Name]);
225       V.push_back(Base);
226       Insert(InsertAfterCommands[OS->Name]);
227       continue;
228     }
229     V.push_back(Base);
230   }
231 
232   for (auto &Cmds : {InsertBeforeCommands, InsertAfterCommands})
233     for (const std::pair<StringRef, std::vector<BaseCommand *>> &P : Cmds)
234       if (!P.second.empty())
235         error("unable to INSERT AFTER/BEFORE " + P.first +
236               ": section not defined");
237 
238   SectionCommands = std::move(V);
239 }
240 
241 // Symbols defined in script should not be inlined by LTO. At the same time
242 // we don't know their final values until late stages of link. Here we scan
243 // over symbol assignment commands and create placeholder symbols if needed.
244 void LinkerScript::declareSymbols() {
245   assert(!Ctx);
246   for (BaseCommand *Base : SectionCommands) {
247     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
248       declareSymbol(Cmd);
249       continue;
250     }
251 
252     // If the output section directive has constraints,
253     // we can't say for sure if it is going to be included or not.
254     // Skip such sections for now. Improve the checks if we ever
255     // need symbols from that sections to be declared early.
256     auto *Sec = cast<OutputSection>(Base);
257     if (Sec->Constraint != ConstraintKind::NoConstraint)
258       continue;
259     for (BaseCommand *Base2 : Sec->SectionCommands)
260       if (auto *Cmd = dyn_cast<SymbolAssignment>(Base2))
261         declareSymbol(Cmd);
262   }
263 }
264 
265 // This function is called from assignAddresses, while we are
266 // fixing the output section addresses. This function is supposed
267 // to set the final value for a given symbol assignment.
268 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
269   if (Cmd->Name == ".") {
270     setDot(Cmd->Expression, Cmd->Location, InSec);
271     return;
272   }
273 
274   if (!Cmd->Sym)
275     return;
276 
277   ExprValue V = Cmd->Expression();
278   if (V.isAbsolute()) {
279     Cmd->Sym->Section = nullptr;
280     Cmd->Sym->Value = V.getValue();
281   } else {
282     Cmd->Sym->Section = V.Sec;
283     Cmd->Sym->Value = V.getSectionOffset();
284   }
285 }
286 
287 static std::string getFilename(InputFile *File) {
288   if (!File)
289     return "";
290   if (File->ArchiveName.empty())
291     return File->getName();
292   return (File->ArchiveName + "(" + File->getName() + ")").str();
293 }
294 
295 bool LinkerScript::shouldKeep(InputSectionBase *S) {
296   if (KeptSections.empty())
297     return false;
298   std::string Filename = getFilename(S->File);
299   for (InputSectionDescription *ID : KeptSections)
300     if (ID->FilePat.match(Filename))
301       for (SectionPattern &P : ID->SectionPatterns)
302         if (P.SectionPat.match(S->Name))
303           return true;
304   return false;
305 }
306 
307 // A helper function for the SORT() command.
308 static std::function<bool(InputSectionBase *, InputSectionBase *)>
309 getComparator(SortSectionPolicy K) {
310   switch (K) {
311   case SortSectionPolicy::Alignment:
312     return [](InputSectionBase *A, InputSectionBase *B) {
313       // ">" is not a mistake. Sections with larger alignments are placed
314       // before sections with smaller alignments in order to reduce the
315       // amount of padding necessary. This is compatible with GNU.
316       return A->Alignment > B->Alignment;
317     };
318   case SortSectionPolicy::Name:
319     return [](InputSectionBase *A, InputSectionBase *B) {
320       return A->Name < B->Name;
321     };
322   case SortSectionPolicy::Priority:
323     return [](InputSectionBase *A, InputSectionBase *B) {
324       return getPriority(A->Name) < getPriority(B->Name);
325     };
326   default:
327     llvm_unreachable("unknown sort policy");
328   }
329 }
330 
331 // A helper function for the SORT() command.
332 static bool matchConstraints(ArrayRef<InputSection *> Sections,
333                              ConstraintKind Kind) {
334   if (Kind == ConstraintKind::NoConstraint)
335     return true;
336 
337   bool IsRW = llvm::any_of(
338       Sections, [](InputSection *Sec) { return Sec->Flags & SHF_WRITE; });
339 
340   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
341          (!IsRW && Kind == ConstraintKind::ReadOnly);
342 }
343 
344 static void sortSections(MutableArrayRef<InputSection *> Vec,
345                          SortSectionPolicy K) {
346   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
347     llvm::stable_sort(Vec, getComparator(K));
348 }
349 
350 // Sort sections as instructed by SORT-family commands and --sort-section
351 // option. Because SORT-family commands can be nested at most two depth
352 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
353 // line option is respected even if a SORT command is given, the exact
354 // behavior we have here is a bit complicated. Here are the rules.
355 //
356 // 1. If two SORT commands are given, --sort-section is ignored.
357 // 2. If one SORT command is given, and if it is not SORT_NONE,
358 //    --sort-section is handled as an inner SORT command.
359 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
360 // 4. If no SORT command is given, sort according to --sort-section.
361 static void sortInputSections(MutableArrayRef<InputSection *> Vec,
362                               const SectionPattern &Pat) {
363   if (Pat.SortOuter == SortSectionPolicy::None)
364     return;
365 
366   if (Pat.SortInner == SortSectionPolicy::Default)
367     sortSections(Vec, Config->SortSection);
368   else
369     sortSections(Vec, Pat.SortInner);
370   sortSections(Vec, Pat.SortOuter);
371 }
372 
373 // Compute and remember which sections the InputSectionDescription matches.
374 std::vector<InputSection *>
375 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
376   std::vector<InputSection *> Ret;
377 
378   // Collects all sections that satisfy constraints of Cmd.
379   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
380     size_t SizeBefore = Ret.size();
381 
382     for (InputSectionBase *Sec : InputSections) {
383       if (!Sec->Live || Sec->Assigned)
384         continue;
385 
386       // For -emit-relocs we have to ignore entries like
387       //   .rela.dyn : { *(.rela.data) }
388       // which are common because they are in the default bfd script.
389       // We do not ignore SHT_REL[A] linker-synthesized sections here because
390       // want to support scripts that do custom layout for them.
391       if (auto *IS = dyn_cast<InputSection>(Sec))
392         if (IS->getRelocatedSection())
393           continue;
394 
395       std::string Filename = getFilename(Sec->File);
396       if (!Cmd->FilePat.match(Filename) ||
397           Pat.ExcludedFilePat.match(Filename) ||
398           !Pat.SectionPat.match(Sec->Name))
399         continue;
400 
401       // It is safe to assume that Sec is an InputSection
402       // because mergeable or EH input sections have already been
403       // handled and eliminated.
404       Ret.push_back(cast<InputSection>(Sec));
405       Sec->Assigned = true;
406     }
407 
408     sortInputSections(MutableArrayRef<InputSection *>(Ret).slice(SizeBefore),
409                       Pat);
410   }
411   return Ret;
412 }
413 
414 void LinkerScript::discard(ArrayRef<InputSection *> V) {
415   for (InputSection *S : V) {
416     if (S == In.ShStrTab || S == In.RelaDyn || S == In.RelrDyn)
417       error("discarding " + S->Name + " section is not allowed");
418 
419     // You can discard .hash and .gnu.hash sections by linker scripts. Since
420     // they are synthesized sections, we need to handle them differently than
421     // other regular sections.
422     if (S == In.GnuHashTab)
423       In.GnuHashTab = nullptr;
424     if (S == In.HashTab)
425       In.HashTab = nullptr;
426 
427     S->Assigned = false;
428     S->Live = false;
429     discard(S->DependentSections);
430   }
431 }
432 
433 std::vector<InputSection *>
434 LinkerScript::createInputSectionList(OutputSection &OutCmd) {
435   std::vector<InputSection *> Ret;
436 
437   for (BaseCommand *Base : OutCmd.SectionCommands) {
438     if (auto *Cmd = dyn_cast<InputSectionDescription>(Base)) {
439       Cmd->Sections = computeInputSections(Cmd);
440       Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
441     }
442   }
443   return Ret;
444 }
445 
446 void LinkerScript::processSectionCommands() {
447   // A symbol can be assigned before any section is mentioned in the linker
448   // script. In an DSO, the symbol values are addresses, so the only important
449   // section values are:
450   // * SHN_UNDEF
451   // * SHN_ABS
452   // * Any value meaning a regular section.
453   // To handle that, create a dummy aether section that fills the void before
454   // the linker scripts switches to another section. It has an index of one
455   // which will map to whatever the first actual section is.
456   Aether = make<OutputSection>("", 0, SHF_ALLOC);
457   Aether->SectionIndex = 1;
458 
459   // Ctx captures the local AddressState and makes it accessible deliberately.
460   // This is needed as there are some cases where we cannot just
461   // thread the current state through to a lambda function created by the
462   // script parser.
463   auto Deleter = make_unique<AddressState>();
464   Ctx = Deleter.get();
465   Ctx->OutSec = Aether;
466 
467   size_t I = 0;
468   // Add input sections to output sections.
469   for (BaseCommand *Base : SectionCommands) {
470     // Handle symbol assignments outside of any output section.
471     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
472       addSymbol(Cmd);
473       continue;
474     }
475 
476     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
477       std::vector<InputSection *> V = createInputSectionList(*Sec);
478 
479       // The output section name `/DISCARD/' is special.
480       // Any input section assigned to it is discarded.
481       if (Sec->Name == "/DISCARD/") {
482         discard(V);
483         Sec->SectionCommands.clear();
484         Sec->SectionIndex = 0; // Not an orphan.
485         continue;
486       }
487 
488       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
489       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
490       // sections satisfy a given constraint. If not, a directive is handled
491       // as if it wasn't present from the beginning.
492       //
493       // Because we'll iterate over SectionCommands many more times, the easy
494       // way to "make it as if it wasn't present" is to make it empty.
495       if (!matchConstraints(V, Sec->Constraint)) {
496         for (InputSectionBase *S : V)
497           S->Assigned = false;
498         Sec->SectionCommands.clear();
499         continue;
500       }
501 
502       // A directive may contain symbol definitions like this:
503       // ".foo : { ...; bar = .; }". Handle them.
504       for (BaseCommand *Base : Sec->SectionCommands)
505         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
506           addSymbol(OutCmd);
507 
508       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
509       // is given, input sections are aligned to that value, whether the
510       // given value is larger or smaller than the original section alignment.
511       if (Sec->SubalignExpr) {
512         uint32_t Subalign = Sec->SubalignExpr().getValue();
513         for (InputSectionBase *S : V)
514           S->Alignment = Subalign;
515       }
516 
517       // Add input sections to an output section.
518       for (InputSection *S : V)
519         Sec->addSection(S);
520 
521       Sec->SectionIndex = I++;
522       if (Sec->Noload)
523         Sec->Type = SHT_NOBITS;
524       if (Sec->NonAlloc)
525         Sec->Flags &= ~(uint64_t)SHF_ALLOC;
526     }
527   }
528   Ctx = nullptr;
529 }
530 
531 static OutputSection *findByName(ArrayRef<BaseCommand *> Vec,
532                                  StringRef Name) {
533   for (BaseCommand *Base : Vec)
534     if (auto *Sec = dyn_cast<OutputSection>(Base))
535       if (Sec->Name == Name)
536         return Sec;
537   return nullptr;
538 }
539 
540 static OutputSection *createSection(InputSectionBase *IS,
541                                     StringRef OutsecName) {
542   OutputSection *Sec = Script->createOutputSection(OutsecName, "<internal>");
543   Sec->addSection(cast<InputSection>(IS));
544   return Sec;
545 }
546 
547 static OutputSection *addInputSec(StringMap<OutputSection *> &Map,
548                                   InputSectionBase *IS, StringRef OutsecName) {
549   // Sections with SHT_GROUP or SHF_GROUP attributes reach here only when the -r
550   // option is given. A section with SHT_GROUP defines a "section group", and
551   // its members have SHF_GROUP attribute. Usually these flags have already been
552   // stripped by InputFiles.cpp as section groups are processed and uniquified.
553   // However, for the -r option, we want to pass through all section groups
554   // as-is because adding/removing members or merging them with other groups
555   // change their semantics.
556   if (IS->Type == SHT_GROUP || (IS->Flags & SHF_GROUP))
557     return createSection(IS, OutsecName);
558 
559   // Imagine .zed : { *(.foo) *(.bar) } script. Both foo and bar may have
560   // relocation sections .rela.foo and .rela.bar for example. Most tools do
561   // not allow multiple REL[A] sections for output section. Hence we
562   // should combine these relocation sections into single output.
563   // We skip synthetic sections because it can be .rela.dyn/.rela.plt or any
564   // other REL[A] sections created by linker itself.
565   if (!isa<SyntheticSection>(IS) &&
566       (IS->Type == SHT_REL || IS->Type == SHT_RELA)) {
567     auto *Sec = cast<InputSection>(IS);
568     OutputSection *Out = Sec->getRelocatedSection()->getOutputSection();
569 
570     if (Out->RelocationSection) {
571       Out->RelocationSection->addSection(Sec);
572       return nullptr;
573     }
574 
575     Out->RelocationSection = createSection(IS, OutsecName);
576     return Out->RelocationSection;
577   }
578 
579   // When control reaches here, mergeable sections have already been merged into
580   // synthetic sections. For relocatable case we want to create one output
581   // section per syntetic section so that they have a valid sh_entsize.
582   if (Config->Relocatable && (IS->Flags & SHF_MERGE))
583     return createSection(IS, OutsecName);
584 
585   //  The ELF spec just says
586   // ----------------------------------------------------------------
587   // In the first phase, input sections that match in name, type and
588   // attribute flags should be concatenated into single sections.
589   // ----------------------------------------------------------------
590   //
591   // However, it is clear that at least some flags have to be ignored for
592   // section merging. At the very least SHF_GROUP and SHF_COMPRESSED have to be
593   // ignored. We should not have two output .text sections just because one was
594   // in a group and another was not for example.
595   //
596   // It also seems that wording was a late addition and didn't get the
597   // necessary scrutiny.
598   //
599   // Merging sections with different flags is expected by some users. One
600   // reason is that if one file has
601   //
602   // int *const bar __attribute__((section(".foo"))) = (int *)0;
603   //
604   // gcc with -fPIC will produce a read only .foo section. But if another
605   // file has
606   //
607   // int zed;
608   // int *const bar __attribute__((section(".foo"))) = (int *)&zed;
609   //
610   // gcc with -fPIC will produce a read write section.
611   //
612   // Last but not least, when using linker script the merge rules are forced by
613   // the script. Unfortunately, linker scripts are name based. This means that
614   // expressions like *(.foo*) can refer to multiple input sections with
615   // different flags. We cannot put them in different output sections or we
616   // would produce wrong results for
617   //
618   // start = .; *(.foo.*) end = .; *(.bar)
619   //
620   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
621   // another. The problem is that there is no way to layout those output
622   // sections such that the .foo sections are the only thing between the start
623   // and end symbols.
624   //
625   // Given the above issues, we instead merge sections by name and error on
626   // incompatible types and flags.
627   OutputSection *&Sec = Map[OutsecName];
628   if (Sec) {
629     Sec->addSection(cast<InputSection>(IS));
630     return nullptr;
631   }
632 
633   Sec = createSection(IS, OutsecName);
634   return Sec;
635 }
636 
637 // Add sections that didn't match any sections command.
638 void LinkerScript::addOrphanSections() {
639   StringMap<OutputSection *> Map;
640   std::vector<OutputSection *> V;
641 
642   auto Add = [&](InputSectionBase *S) {
643     if (!S->Live || S->Parent)
644       return;
645 
646     StringRef Name = getOutputSectionName(S);
647 
648     if (Config->OrphanHandling == OrphanHandlingPolicy::Error)
649       error(toString(S) + " is being placed in '" + Name + "'");
650     else if (Config->OrphanHandling == OrphanHandlingPolicy::Warn)
651       warn(toString(S) + " is being placed in '" + Name + "'");
652 
653     if (OutputSection *Sec = findByName(SectionCommands, Name)) {
654       Sec->addSection(cast<InputSection>(S));
655       return;
656     }
657 
658     if (OutputSection *OS = addInputSec(Map, S, Name))
659       V.push_back(OS);
660     assert(S->getOutputSection()->SectionIndex == UINT32_MAX);
661   };
662 
663   // For futher --emit-reloc handling code we need target output section
664   // to be created before we create relocation output section, so we want
665   // to create target sections first. We do not want priority handling
666   // for synthetic sections because them are special.
667   for (InputSectionBase *IS : InputSections) {
668     if (auto *Sec = dyn_cast<InputSection>(IS))
669       if (InputSectionBase *Rel = Sec->getRelocatedSection())
670         if (auto *RelIS = dyn_cast_or_null<InputSectionBase>(Rel->Parent))
671           Add(RelIS);
672     Add(IS);
673   }
674 
675   // If no SECTIONS command was given, we should insert sections commands
676   // before others, so that we can handle scripts which refers them,
677   // for example: "foo = ABSOLUTE(ADDR(.text)));".
678   // When SECTIONS command is present we just add all orphans to the end.
679   if (HasSectionsCommand)
680     SectionCommands.insert(SectionCommands.end(), V.begin(), V.end());
681   else
682     SectionCommands.insert(SectionCommands.begin(), V.begin(), V.end());
683 }
684 
685 uint64_t LinkerScript::advance(uint64_t Size, unsigned Alignment) {
686   bool IsTbss =
687       (Ctx->OutSec->Flags & SHF_TLS) && Ctx->OutSec->Type == SHT_NOBITS;
688   uint64_t Start = IsTbss ? Dot + Ctx->ThreadBssOffset : Dot;
689   Start = alignTo(Start, Alignment);
690   uint64_t End = Start + Size;
691 
692   if (IsTbss)
693     Ctx->ThreadBssOffset = End - Dot;
694   else
695     Dot = End;
696   return End;
697 }
698 
699 void LinkerScript::output(InputSection *S) {
700   assert(Ctx->OutSec == S->getParent());
701   uint64_t Before = advance(0, 1);
702   uint64_t Pos = advance(S->getSize(), S->Alignment);
703   S->OutSecOff = Pos - S->getSize() - Ctx->OutSec->Addr;
704 
705   // Update output section size after adding each section. This is so that
706   // SIZEOF works correctly in the case below:
707   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
708   expandOutputSection(Pos - Before);
709 }
710 
711 void LinkerScript::switchTo(OutputSection *Sec) {
712   Ctx->OutSec = Sec;
713 
714   uint64_t Before = advance(0, 1);
715   Ctx->OutSec->Addr = advance(0, Ctx->OutSec->Alignment);
716   expandMemoryRegions(Ctx->OutSec->Addr - Before);
717 }
718 
719 // This function searches for a memory region to place the given output
720 // section in. If found, a pointer to the appropriate memory region is
721 // returned. Otherwise, a nullptr is returned.
722 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
723   // If a memory region name was specified in the output section command,
724   // then try to find that region first.
725   if (!Sec->MemoryRegionName.empty()) {
726     if (MemoryRegion *M = MemoryRegions.lookup(Sec->MemoryRegionName))
727       return M;
728     error("memory region '" + Sec->MemoryRegionName + "' not declared");
729     return nullptr;
730   }
731 
732   // If at least one memory region is defined, all sections must
733   // belong to some memory region. Otherwise, we don't need to do
734   // anything for memory regions.
735   if (MemoryRegions.empty())
736     return nullptr;
737 
738   // See if a region can be found by matching section flags.
739   for (auto &Pair : MemoryRegions) {
740     MemoryRegion *M = Pair.second;
741     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
742       return M;
743   }
744 
745   // Otherwise, no suitable region was found.
746   if (Sec->Flags & SHF_ALLOC)
747     error("no memory region specified for section '" + Sec->Name + "'");
748   return nullptr;
749 }
750 
751 static OutputSection *findFirstSection(PhdrEntry *Load) {
752   for (OutputSection *Sec : OutputSections)
753     if (Sec->PtLoad == Load)
754       return Sec;
755   return nullptr;
756 }
757 
758 // This function assigns offsets to input sections and an output section
759 // for a single sections command (e.g. ".text { *(.text); }").
760 void LinkerScript::assignOffsets(OutputSection *Sec) {
761   if (!(Sec->Flags & SHF_ALLOC))
762     Dot = 0;
763 
764   Ctx->MemRegion = Sec->MemRegion;
765   Ctx->LMARegion = Sec->LMARegion;
766   if (Ctx->MemRegion)
767     Dot = Ctx->MemRegion->CurPos;
768 
769   if ((Sec->Flags & SHF_ALLOC) && Sec->AddrExpr)
770     setDot(Sec->AddrExpr, Sec->Location, false);
771 
772   switchTo(Sec);
773 
774   if (Sec->LMAExpr)
775     Ctx->LMAOffset = Sec->LMAExpr().getValue() - Dot;
776 
777   if (MemoryRegion *MR = Sec->LMARegion)
778     Ctx->LMAOffset = MR->CurPos - Dot;
779 
780   // If neither AT nor AT> is specified for an allocatable section, the linker
781   // will set the LMA such that the difference between VMA and LMA for the
782   // section is the same as the preceding output section in the same region
783   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
784   // This, however, should only be done by the first "non-header" section
785   // in the segment.
786   if (PhdrEntry *L = Ctx->OutSec->PtLoad)
787     if (Sec == findFirstSection(L))
788       L->LMAOffset = Ctx->LMAOffset;
789 
790   // We can call this method multiple times during the creation of
791   // thunks and want to start over calculation each time.
792   Sec->Size = 0;
793 
794   // We visited SectionsCommands from processSectionCommands to
795   // layout sections. Now, we visit SectionsCommands again to fix
796   // section offsets.
797   for (BaseCommand *Base : Sec->SectionCommands) {
798     // This handles the assignments to symbol or to the dot.
799     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
800       Cmd->Addr = Dot;
801       assignSymbol(Cmd, true);
802       Cmd->Size = Dot - Cmd->Addr;
803       continue;
804     }
805 
806     // Handle BYTE(), SHORT(), LONG(), or QUAD().
807     if (auto *Cmd = dyn_cast<ByteCommand>(Base)) {
808       Cmd->Offset = Dot - Ctx->OutSec->Addr;
809       Dot += Cmd->Size;
810       expandOutputSection(Cmd->Size);
811       continue;
812     }
813 
814     // Handle a single input section description command.
815     // It calculates and assigns the offsets for each section and also
816     // updates the output section size.
817     for (InputSection *Sec : cast<InputSectionDescription>(Base)->Sections)
818       output(Sec);
819   }
820 }
821 
822 static bool isDiscardable(OutputSection &Sec) {
823   // We do not remove empty sections that are explicitly
824   // assigned to any segment.
825   if (!Sec.Phdrs.empty())
826     return false;
827 
828   // We do not want to remove OutputSections with expressions that reference
829   // symbols even if the OutputSection is empty. We want to ensure that the
830   // expressions can be evaluated and report an error if they cannot.
831   if (Sec.ExpressionsUseSymbols)
832     return false;
833 
834   // OutputSections may be referenced by name in ADDR and LOADADDR expressions,
835   // as an empty Section can has a valid VMA and LMA we keep the OutputSection
836   // to maintain the integrity of the other Expression.
837   if (Sec.UsedInExpression)
838     return false;
839 
840   for (BaseCommand *Base : Sec.SectionCommands) {
841     if (auto Cmd = dyn_cast<SymbolAssignment>(Base))
842       // Don't create empty output sections just for unreferenced PROVIDE
843       // symbols.
844       if (Cmd->Name != "." && !Cmd->Sym)
845         continue;
846 
847     if (!isa<InputSectionDescription>(*Base))
848       return false;
849   }
850   return true;
851 }
852 
853 void LinkerScript::adjustSectionsBeforeSorting() {
854   // If the output section contains only symbol assignments, create a
855   // corresponding output section. The issue is what to do with linker script
856   // like ".foo : { symbol = 42; }". One option would be to convert it to
857   // "symbol = 42;". That is, move the symbol out of the empty section
858   // description. That seems to be what bfd does for this simple case. The
859   // problem is that this is not completely general. bfd will give up and
860   // create a dummy section too if there is a ". = . + 1" inside the section
861   // for example.
862   // Given that we want to create the section, we have to worry what impact
863   // it will have on the link. For example, if we just create a section with
864   // 0 for flags, it would change which PT_LOADs are created.
865   // We could remember that particular section is dummy and ignore it in
866   // other parts of the linker, but unfortunately there are quite a few places
867   // that would need to change:
868   //   * The program header creation.
869   //   * The orphan section placement.
870   //   * The address assignment.
871   // The other option is to pick flags that minimize the impact the section
872   // will have on the rest of the linker. That is why we copy the flags from
873   // the previous sections. Only a few flags are needed to keep the impact low.
874   uint64_t Flags = SHF_ALLOC;
875 
876   for (BaseCommand *&Cmd : SectionCommands) {
877     auto *Sec = dyn_cast<OutputSection>(Cmd);
878     if (!Sec)
879       continue;
880 
881     // Handle align (e.g. ".foo : ALIGN(16) { ... }").
882     if (Sec->AlignExpr)
883       Sec->Alignment =
884           std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue());
885 
886     // A live output section means that some input section was added to it. It
887     // might have been removed (if it was empty synthetic section), but we at
888     // least know the flags.
889     if (Sec->Live)
890       Flags = Sec->Flags;
891 
892     // We do not want to keep any special flags for output section
893     // in case it is empty.
894     bool IsEmpty = getInputSections(Sec).empty();
895     if (IsEmpty)
896       Sec->Flags = Flags & ((Sec->NonAlloc ? 0 : (uint64_t)SHF_ALLOC) |
897                             SHF_WRITE | SHF_EXECINSTR);
898 
899     if (IsEmpty && isDiscardable(*Sec)) {
900       Sec->Live = false;
901       Cmd = nullptr;
902     }
903   }
904 
905   // It is common practice to use very generic linker scripts. So for any
906   // given run some of the output sections in the script will be empty.
907   // We could create corresponding empty output sections, but that would
908   // clutter the output.
909   // We instead remove trivially empty sections. The bfd linker seems even
910   // more aggressive at removing them.
911   llvm::erase_if(SectionCommands, [&](BaseCommand *Base) { return !Base; });
912 }
913 
914 void LinkerScript::adjustSectionsAfterSorting() {
915   // Try and find an appropriate memory region to assign offsets in.
916   for (BaseCommand *Base : SectionCommands) {
917     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
918       if (!Sec->LMARegionName.empty()) {
919         if (MemoryRegion *M = MemoryRegions.lookup(Sec->LMARegionName))
920           Sec->LMARegion = M;
921         else
922           error("memory region '" + Sec->LMARegionName + "' not declared");
923       }
924       Sec->MemRegion = findMemoryRegion(Sec);
925     }
926   }
927 
928   // If output section command doesn't specify any segments,
929   // and we haven't previously assigned any section to segment,
930   // then we simply assign section to the very first load segment.
931   // Below is an example of such linker script:
932   // PHDRS { seg PT_LOAD; }
933   // SECTIONS { .aaa : { *(.aaa) } }
934   std::vector<StringRef> DefPhdrs;
935   auto FirstPtLoad = llvm::find_if(PhdrsCommands, [](const PhdrsCommand &Cmd) {
936     return Cmd.Type == PT_LOAD;
937   });
938   if (FirstPtLoad != PhdrsCommands.end())
939     DefPhdrs.push_back(FirstPtLoad->Name);
940 
941   // Walk the commands and propagate the program headers to commands that don't
942   // explicitly specify them.
943   for (BaseCommand *Base : SectionCommands) {
944     auto *Sec = dyn_cast<OutputSection>(Base);
945     if (!Sec)
946       continue;
947 
948     if (Sec->Phdrs.empty()) {
949       // To match the bfd linker script behaviour, only propagate program
950       // headers to sections that are allocated.
951       if (Sec->Flags & SHF_ALLOC)
952         Sec->Phdrs = DefPhdrs;
953     } else {
954       DefPhdrs = Sec->Phdrs;
955     }
956   }
957 }
958 
959 static uint64_t computeBase(uint64_t Min, bool AllocateHeaders) {
960   // If there is no SECTIONS or if the linkerscript is explicit about program
961   // headers, do our best to allocate them.
962   if (!Script->HasSectionsCommand || AllocateHeaders)
963     return 0;
964   // Otherwise only allocate program headers if that would not add a page.
965   return alignDown(Min, Config->MaxPageSize);
966 }
967 
968 // Try to find an address for the file and program headers output sections,
969 // which were unconditionally added to the first PT_LOAD segment earlier.
970 //
971 // When using the default layout, we check if the headers fit below the first
972 // allocated section. When using a linker script, we also check if the headers
973 // are covered by the output section. This allows omitting the headers by not
974 // leaving enough space for them in the linker script; this pattern is common
975 // in embedded systems.
976 //
977 // If there isn't enough space for these sections, we'll remove them from the
978 // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
979 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
980   uint64_t Min = std::numeric_limits<uint64_t>::max();
981   for (OutputSection *Sec : OutputSections)
982     if (Sec->Flags & SHF_ALLOC)
983       Min = std::min<uint64_t>(Min, Sec->Addr);
984 
985   auto It = llvm::find_if(
986       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
987   if (It == Phdrs.end())
988     return;
989   PhdrEntry *FirstPTLoad = *It;
990 
991   bool HasExplicitHeaders =
992       llvm::any_of(PhdrsCommands, [](const PhdrsCommand &Cmd) {
993         return Cmd.HasPhdrs || Cmd.HasFilehdr;
994       });
995   bool Paged = !Config->Omagic && !Config->Nmagic;
996   uint64_t HeaderSize = getHeaderSize();
997   if ((Paged || HasExplicitHeaders) &&
998       HeaderSize <= Min - computeBase(Min, HasExplicitHeaders)) {
999     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
1000     Out::ElfHeader->Addr = Min;
1001     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
1002     return;
1003   }
1004 
1005   // Error if we were explicitly asked to allocate headers.
1006   if (HasExplicitHeaders)
1007     error("could not allocate headers");
1008 
1009   Out::ElfHeader->PtLoad = nullptr;
1010   Out::ProgramHeaders->PtLoad = nullptr;
1011   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
1012 
1013   llvm::erase_if(Phdrs,
1014                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
1015 }
1016 
1017 LinkerScript::AddressState::AddressState() {
1018   for (auto &MRI : Script->MemoryRegions) {
1019     MemoryRegion *MR = MRI.second;
1020     MR->CurPos = MR->Origin;
1021   }
1022 }
1023 
1024 static uint64_t getInitialDot() {
1025   // By default linker scripts use an initial value of 0 for '.',
1026   // but prefer -image-base if set.
1027   if (Script->HasSectionsCommand)
1028     return Config->ImageBase ? *Config->ImageBase : 0;
1029 
1030   uint64_t StartAddr = UINT64_MAX;
1031   // The Sections with -T<section> have been sorted in order of ascending
1032   // address. We must lower StartAddr if the lowest -T<section address> as
1033   // calls to setDot() must be monotonically increasing.
1034   for (auto &KV : Config->SectionStartMap)
1035     StartAddr = std::min(StartAddr, KV.second);
1036   return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize());
1037 }
1038 
1039 // Here we assign addresses as instructed by linker script SECTIONS
1040 // sub-commands. Doing that allows us to use final VA values, so here
1041 // we also handle rest commands like symbol assignments and ASSERTs.
1042 void LinkerScript::assignAddresses() {
1043   Dot = getInitialDot();
1044 
1045   auto Deleter = make_unique<AddressState>();
1046   Ctx = Deleter.get();
1047   ErrorOnMissingSection = true;
1048   switchTo(Aether);
1049 
1050   for (BaseCommand *Base : SectionCommands) {
1051     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
1052       Cmd->Addr = Dot;
1053       assignSymbol(Cmd, false);
1054       Cmd->Size = Dot - Cmd->Addr;
1055       continue;
1056     }
1057     assignOffsets(cast<OutputSection>(Base));
1058   }
1059   Ctx = nullptr;
1060 }
1061 
1062 // Creates program headers as instructed by PHDRS linker script command.
1063 std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
1064   std::vector<PhdrEntry *> Ret;
1065 
1066   // Process PHDRS and FILEHDR keywords because they are not
1067   // real output sections and cannot be added in the following loop.
1068   for (const PhdrsCommand &Cmd : PhdrsCommands) {
1069     PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R);
1070 
1071     if (Cmd.HasFilehdr)
1072       Phdr->add(Out::ElfHeader);
1073     if (Cmd.HasPhdrs)
1074       Phdr->add(Out::ProgramHeaders);
1075 
1076     if (Cmd.LMAExpr) {
1077       Phdr->p_paddr = Cmd.LMAExpr().getValue();
1078       Phdr->HasLMA = true;
1079     }
1080     Ret.push_back(Phdr);
1081   }
1082 
1083   // Add output sections to program headers.
1084   for (OutputSection *Sec : OutputSections) {
1085     // Assign headers specified by linker script
1086     for (size_t Id : getPhdrIndices(Sec)) {
1087       Ret[Id]->add(Sec);
1088       if (!PhdrsCommands[Id].Flags.hasValue())
1089         Ret[Id]->p_flags |= Sec->getPhdrFlags();
1090     }
1091   }
1092   return Ret;
1093 }
1094 
1095 // Returns true if we should emit an .interp section.
1096 //
1097 // We usually do. But if PHDRS commands are given, and
1098 // no PT_INTERP is there, there's no place to emit an
1099 // .interp, so we don't do that in that case.
1100 bool LinkerScript::needsInterpSection() {
1101   if (PhdrsCommands.empty())
1102     return true;
1103   for (PhdrsCommand &Cmd : PhdrsCommands)
1104     if (Cmd.Type == PT_INTERP)
1105       return true;
1106   return false;
1107 }
1108 
1109 ExprValue LinkerScript::getSymbolValue(StringRef Name, const Twine &Loc) {
1110   if (Name == ".") {
1111     if (Ctx)
1112       return {Ctx->OutSec, false, Dot - Ctx->OutSec->Addr, Loc};
1113     error(Loc + ": unable to get location counter value");
1114     return 0;
1115   }
1116 
1117   if (Symbol *Sym = Symtab->find(Name)) {
1118     if (auto *DS = dyn_cast<Defined>(Sym))
1119       return {DS->Section, false, DS->Value, Loc};
1120     if (isa<SharedSymbol>(Sym))
1121       if (!ErrorOnMissingSection)
1122         return {nullptr, false, 0, Loc};
1123   }
1124 
1125   error(Loc + ": symbol not found: " + Name);
1126   return 0;
1127 }
1128 
1129 // Returns the index of the segment named Name.
1130 static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec,
1131                                      StringRef Name) {
1132   for (size_t I = 0; I < Vec.size(); ++I)
1133     if (Vec[I].Name == Name)
1134       return I;
1135   return None;
1136 }
1137 
1138 // Returns indices of ELF headers containing specific section. Each index is a
1139 // zero based number of ELF header listed within PHDRS {} script block.
1140 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
1141   std::vector<size_t> Ret;
1142 
1143   for (StringRef S : Cmd->Phdrs) {
1144     if (Optional<size_t> Idx = getPhdrIndex(PhdrsCommands, S))
1145       Ret.push_back(*Idx);
1146     else if (S != "NONE")
1147       error(Cmd->Location + ": section header '" + S +
1148             "' is not listed in PHDRS");
1149   }
1150   return Ret;
1151 }
1152