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