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