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