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