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 "Threads.h"
25 #include "Writer.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   return getValue() - getSecAddr();
75 }
76 
77 static SymbolBody *addRegular(SymbolAssignment *Cmd) {
78   Symbol *Sym;
79   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
80   std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
81                                               /*CanOmitFromDynSym*/ false,
82                                               /*File*/ nullptr);
83   Sym->Binding = STB_GLOBAL;
84   ExprValue Value = Cmd->Expression();
85   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
86 
87   // We want to set symbol values early if we can. This allows us to use symbols
88   // as variables in linker scripts. Doing so allows us to write expressions
89   // like this: `alignment = 16; . = ALIGN(., alignment)`
90   uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
91   replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
92                               Visibility, STT_NOTYPE, SymValue, 0, Sec);
93   return Sym->body();
94 }
95 
96 OutputSection *LinkerScript::createOutputSection(StringRef Name,
97                                                  StringRef Location) {
98   OutputSection *&SecRef = NameToOutputSection[Name];
99   OutputSection *Sec;
100   if (SecRef && SecRef->Location.empty()) {
101     // There was a forward reference.
102     Sec = SecRef;
103   } else {
104     Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
105     if (!SecRef)
106       SecRef = Sec;
107   }
108   Sec->Location = Location;
109   return Sec;
110 }
111 
112 OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
113   OutputSection *&CmdRef = NameToOutputSection[Name];
114   if (!CmdRef)
115     CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
116   return CmdRef;
117 }
118 
119 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
120   uint64_t Val = E().getValue();
121   if (Val < Dot && InSec)
122     error(Loc + ": unable to move location counter backward for: " +
123           CurAddressState->OutSec->Name);
124   Dot = Val;
125   // Update to location counter means update to section size.
126   if (InSec)
127     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
128 }
129 
130 // Sets value of a symbol. Two kinds of symbols are processed: synthetic
131 // symbols, whose value is an offset from beginning of section and regular
132 // symbols whose value is absolute.
133 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
134   if (Cmd->Name == ".") {
135     setDot(Cmd->Expression, Cmd->Location, InSec);
136     return;
137   }
138 
139   if (!Cmd->Sym)
140     return;
141 
142   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
143   ExprValue V = Cmd->Expression();
144   if (V.isAbsolute()) {
145     Sym->Value = V.getValue();
146   } else {
147     Sym->Section = V.Sec;
148     Sym->Value = V.getSectionOffset();
149   }
150 }
151 
152 void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
153   if (Cmd->Name == ".")
154     return;
155 
156   // If a symbol was in PROVIDE(), we need to define it only when
157   // it is a referenced undefined symbol.
158   SymbolBody *B = Symtab->find(Cmd->Name);
159   if (Cmd->Provide && (!B || B->isDefined()))
160     return;
161 
162   Cmd->Sym = addRegular(Cmd);
163 }
164 
165 bool SymbolAssignment::classof(const BaseCommand *C) {
166   return C->Kind == AssignmentKind;
167 }
168 
169 bool InputSectionDescription::classof(const BaseCommand *C) {
170   return C->Kind == InputSectionKind;
171 }
172 
173 bool AssertCommand::classof(const BaseCommand *C) {
174   return C->Kind == AssertKind;
175 }
176 
177 bool BytesDataCommand::classof(const BaseCommand *C) {
178   return C->Kind == BytesDataKind;
179 }
180 
181 static std::string filename(InputFile *File) {
182   if (!File)
183     return "";
184   if (File->ArchiveName.empty())
185     return File->getName();
186   return (File->ArchiveName + "(" + File->getName() + ")").str();
187 }
188 
189 bool LinkerScript::shouldKeep(InputSectionBase *S) {
190   for (InputSectionDescription *ID : Opt.KeptSections) {
191     std::string Filename = filename(S->File);
192     if (ID->FilePat.match(Filename))
193       for (SectionPattern &P : ID->SectionPatterns)
194         if (P.SectionPat.match(S->Name))
195           return true;
196   }
197   return false;
198 }
199 
200 // A helper function for the SORT() command.
201 static std::function<bool(InputSectionBase *, InputSectionBase *)>
202 getComparator(SortSectionPolicy K) {
203   switch (K) {
204   case SortSectionPolicy::Alignment:
205     return [](InputSectionBase *A, InputSectionBase *B) {
206       // ">" is not a mistake. Sections with larger alignments are placed
207       // before sections with smaller alignments in order to reduce the
208       // amount of padding necessary. This is compatible with GNU.
209       return A->Alignment > B->Alignment;
210     };
211   case SortSectionPolicy::Name:
212     return [](InputSectionBase *A, InputSectionBase *B) {
213       return A->Name < B->Name;
214     };
215   case SortSectionPolicy::Priority:
216     return [](InputSectionBase *A, InputSectionBase *B) {
217       return getPriority(A->Name) < getPriority(B->Name);
218     };
219   default:
220     llvm_unreachable("unknown sort policy");
221   }
222 }
223 
224 // A helper function for the SORT() command.
225 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
226                              ConstraintKind Kind) {
227   if (Kind == ConstraintKind::NoConstraint)
228     return true;
229 
230   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
231     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
232   });
233 
234   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
235          (!IsRW && Kind == ConstraintKind::ReadOnly);
236 }
237 
238 static void sortSections(InputSection **Begin, InputSection **End,
239                          SortSectionPolicy K) {
240   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
241     std::stable_sort(Begin, End, getComparator(K));
242 }
243 
244 static llvm::DenseMap<SectionBase *, int> getSectionOrder() {
245   switch (Config->EKind) {
246   case ELF32LEKind:
247     return buildSectionOrder<ELF32LE>();
248   case ELF32BEKind:
249     return buildSectionOrder<ELF32BE>();
250   case ELF64LEKind:
251     return buildSectionOrder<ELF64LE>();
252   case ELF64BEKind:
253     return buildSectionOrder<ELF64BE>();
254   default:
255     llvm_unreachable("unknown ELF type");
256   }
257 }
258 
259 static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
260   if (Config->SymbolOrderingFile.empty())
261     return;
262   static llvm::DenseMap<SectionBase *, int> Order = getSectionOrder();
263   MutableArrayRef<InputSection *> In(Begin, End - Begin);
264   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
265 }
266 
267 // Compute and remember which sections the InputSectionDescription matches.
268 std::vector<InputSection *>
269 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
270   std::vector<InputSection *> Ret;
271 
272   // Collects all sections that satisfy constraints of Cmd.
273   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
274     size_t SizeBefore = Ret.size();
275 
276     for (InputSectionBase *Sec : InputSections) {
277       if (Sec->Assigned)
278         continue;
279 
280       if (!Sec->Live) {
281         reportDiscarded(Sec);
282         continue;
283       }
284 
285       // For -emit-relocs we have to ignore entries like
286       //   .rela.dyn : { *(.rela.data) }
287       // which are common because they are in the default bfd script.
288       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
289         continue;
290 
291       std::string Filename = filename(Sec->File);
292       if (!Cmd->FilePat.match(Filename) ||
293           Pat.ExcludedFilePat.match(Filename) ||
294           !Pat.SectionPat.match(Sec->Name))
295         continue;
296 
297       Ret.push_back(cast<InputSection>(Sec));
298       Sec->Assigned = true;
299     }
300 
301     // Sort sections as instructed by SORT-family commands and --sort-section
302     // option. Because SORT-family commands can be nested at most two depth
303     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
304     // line option is respected even if a SORT command is given, the exact
305     // behavior we have here is a bit complicated. Here are the rules.
306     //
307     // 1. If two SORT commands are given, --sort-section is ignored.
308     // 2. If one SORT command is given, and if it is not SORT_NONE,
309     //    --sort-section is handled as an inner SORT command.
310     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
311     // 4. If no SORT command is given, sort according to --sort-section.
312     // 5. If no SORT commands are given and --sort-section is not specified,
313     //    apply sorting provided by --symbol-ordering-file if any exist.
314     InputSection **Begin = Ret.data() + SizeBefore;
315     InputSection **End = Ret.data() + Ret.size();
316     if (Pat.SortOuter == SortSectionPolicy::Default &&
317         Config->SortSection == SortSectionPolicy::Default) {
318       sortBySymbolOrder(Begin, End);
319       continue;
320     }
321     if (Pat.SortOuter != SortSectionPolicy::None) {
322       if (Pat.SortInner == SortSectionPolicy::Default)
323         sortSections(Begin, End, Config->SortSection);
324       else
325         sortSections(Begin, End, Pat.SortInner);
326       sortSections(Begin, End, Pat.SortOuter);
327     }
328   }
329   return Ret;
330 }
331 
332 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
333   for (InputSectionBase *S : V) {
334     S->Live = false;
335     if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
336         S == InX::DynStrTab)
337       error("discarding " + S->Name + " section is not allowed");
338     discard(S->DependentSections);
339   }
340 }
341 
342 std::vector<InputSectionBase *>
343 LinkerScript::createInputSectionList(OutputSection &OutCmd) {
344   std::vector<InputSectionBase *> Ret;
345 
346   for (BaseCommand *Base : OutCmd.Commands) {
347     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
348     if (!Cmd)
349       continue;
350 
351     Cmd->Sections = computeInputSections(Cmd);
352     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
353   }
354 
355   return Ret;
356 }
357 
358 void LinkerScript::processCommands(OutputSectionFactory &Factory) {
359   // A symbol can be assigned before any section is mentioned in the linker
360   // script. In an DSO, the symbol values are addresses, so the only important
361   // section values are:
362   // * SHN_UNDEF
363   // * SHN_ABS
364   // * Any value meaning a regular section.
365   // To handle that, create a dummy aether section that fills the void before
366   // the linker scripts switches to another section. It has an index of one
367   // which will map to whatever the first actual section is.
368   Aether = make<OutputSection>("", 0, SHF_ALLOC);
369   Aether->SectionIndex = 1;
370   auto State = make_unique<AddressState>(Opt);
371   // CurAddressState captures the local AddressState and makes it accessible
372   // deliberately. This is needed as there are some cases where we cannot just
373   // thread the current state through to a lambda function created by the
374   // script parser.
375   CurAddressState = State.get();
376   CurAddressState->OutSec = Aether;
377   Dot = 0;
378 
379   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
380     // Handle symbol assignments outside of any output section.
381     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
382       addSymbol(Cmd);
383       continue;
384     }
385 
386     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
387       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
388 
389       // The output section name `/DISCARD/' is special.
390       // Any input section assigned to it is discarded.
391       if (Sec->Name == "/DISCARD/") {
392         discard(V);
393         continue;
394       }
395 
396       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
397       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
398       // sections satisfy a given constraint. If not, a directive is handled
399       // as if it wasn't present from the beginning.
400       //
401       // Because we'll iterate over Commands many more times, the easiest
402       // way to "make it as if it wasn't present" is to just remove it.
403       if (!matchConstraints(V, Sec->Constraint)) {
404         for (InputSectionBase *S : V)
405           S->Assigned = false;
406         Opt.Commands.erase(Opt.Commands.begin() + I);
407         --I;
408         continue;
409       }
410 
411       // A directive may contain symbol definitions like this:
412       // ".foo : { ...; bar = .; }". Handle them.
413       for (BaseCommand *Base : Sec->Commands)
414         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
415           addSymbol(OutCmd);
416 
417       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
418       // is given, input sections are aligned to that value, whether the
419       // given value is larger or smaller than the original section alignment.
420       if (Sec->SubalignExpr) {
421         uint32_t Subalign = Sec->SubalignExpr().getValue();
422         for (InputSectionBase *S : V)
423           S->Alignment = Subalign;
424       }
425 
426       // Add input sections to an output section.
427       for (InputSectionBase *S : V)
428         Factory.addInputSec(S, Sec->Name, Sec);
429       assert(Sec->SectionIndex == INT_MAX);
430       Sec->SectionIndex = I;
431       if (Sec->Noload)
432         Sec->Type = SHT_NOBITS;
433     }
434   }
435   CurAddressState = nullptr;
436 }
437 
438 void LinkerScript::fabricateDefaultCommands() {
439   // Define start address
440   uint64_t StartAddr = -1;
441 
442   // The Sections with -T<section> have been sorted in order of ascending
443   // address. We must lower StartAddr if the lowest -T<section address> as
444   // calls to setDot() must be monotonically increasing.
445   for (auto &KV : Config->SectionStartMap)
446     StartAddr = std::min(StartAddr, KV.second);
447 
448   Opt.Commands.insert(Opt.Commands.begin(),
449                       make<SymbolAssignment>(".",
450                                              [=] {
451                                                return std::min(
452                                                    StartAddr,
453                                                    Config->ImageBase +
454                                                        elf::getHeaderSize());
455                                              },
456                                              ""));
457 }
458 
459 // Add sections that didn't match any sections command.
460 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
461   unsigned NumCommands = Opt.Commands.size();
462   for (InputSectionBase *S : InputSections) {
463     if (!S->Live || S->Parent)
464       continue;
465     StringRef Name = getOutputSectionName(S->Name);
466     auto End = Opt.Commands.begin() + NumCommands;
467     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
468       if (auto *Sec = dyn_cast<OutputSection>(Base))
469         return Sec->Name == Name;
470       return false;
471     });
472     if (I == End) {
473       Factory.addInputSec(S, Name);
474       assert(S->getOutputSection()->SectionIndex == INT_MAX);
475     } else {
476       OutputSection *Sec = cast<OutputSection>(*I);
477       Factory.addInputSec(S, Name, Sec);
478       unsigned Index = std::distance(Opt.Commands.begin(), I);
479       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
480       Sec->SectionIndex = Index;
481     }
482   }
483 }
484 
485 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
486   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
487                 CurAddressState->OutSec->Type == SHT_NOBITS;
488   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
489   Start = alignTo(Start, Align);
490   uint64_t End = Start + Size;
491 
492   if (IsTbss)
493     CurAddressState->ThreadBssOffset = End - Dot;
494   else
495     Dot = End;
496   return End;
497 }
498 
499 void LinkerScript::output(InputSection *S) {
500   uint64_t Before = advance(0, 1);
501   uint64_t Pos = advance(S->getSize(), S->Alignment);
502   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
503 
504   // Update output section size after adding each section. This is so that
505   // SIZEOF works correctly in the case below:
506   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
507   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
508 
509   // If there is a memory region associated with this input section, then
510   // place the section in that region and update the region index.
511   if (CurAddressState->MemRegion) {
512     uint64_t &CurOffset =
513         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
514     CurOffset += Pos - Before;
515     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
516     if (CurSize > CurAddressState->MemRegion->Length) {
517       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
518       error("section '" + CurAddressState->OutSec->Name +
519             "' will not fit in region '" + CurAddressState->MemRegion->Name +
520             "': overflowed by " + Twine(OverflowAmt) + " bytes");
521     }
522   }
523 }
524 
525 void LinkerScript::switchTo(OutputSection *Sec) {
526   if (CurAddressState->OutSec == Sec)
527     return;
528 
529   CurAddressState->OutSec = Sec;
530   CurAddressState->OutSec->Addr =
531       advance(0, CurAddressState->OutSec->Alignment);
532 
533   // If neither AT nor AT> is specified for an allocatable section, the linker
534   // will set the LMA such that the difference between VMA and LMA for the
535   // section is the same as the preceding output section in the same region
536   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
537   if (CurAddressState->LMAOffset)
538     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
539 }
540 
541 void LinkerScript::process(BaseCommand &Base) {
542   // This handles the assignments to symbol or to the dot.
543   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
544     assignSymbol(Cmd, true);
545     return;
546   }
547 
548   // Handle BYTE(), SHORT(), LONG(), or QUAD().
549   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
550     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
551     Dot += Cmd->Size;
552     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
553     return;
554   }
555 
556   // Handle ASSERT().
557   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
558     Cmd->Expression();
559     return;
560   }
561 
562   // Handle a single input section description command.
563   // It calculates and assigns the offsets for each section and also
564   // updates the output section size.
565   auto &Cmd = cast<InputSectionDescription>(Base);
566   for (InputSection *Sec : Cmd.Sections) {
567     // We tentatively added all synthetic sections at the beginning and removed
568     // empty ones afterwards (because there is no way to know whether they were
569     // going be empty or not other than actually running linker scripts.)
570     // We need to ignore remains of empty sections.
571     if (auto *S = dyn_cast<SyntheticSection>(Sec))
572       if (S->empty())
573         continue;
574 
575     if (!Sec->Live)
576       continue;
577     assert(CurAddressState->OutSec == Sec->getParent());
578     output(Sec);
579   }
580 }
581 
582 // This function searches for a memory region to place the given output
583 // section in. If found, a pointer to the appropriate memory region is
584 // returned. Otherwise, a nullptr is returned.
585 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
586   // If a memory region name was specified in the output section command,
587   // then try to find that region first.
588   if (!Sec->MemoryRegionName.empty()) {
589     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
590     if (It != Opt.MemoryRegions.end())
591       return It->second;
592     error("memory region '" + Sec->MemoryRegionName + "' not declared");
593     return nullptr;
594   }
595 
596   // If at least one memory region is defined, all sections must
597   // belong to some memory region. Otherwise, we don't need to do
598   // anything for memory regions.
599   if (Opt.MemoryRegions.empty())
600     return nullptr;
601 
602   // See if a region can be found by matching section flags.
603   for (auto &Pair : Opt.MemoryRegions) {
604     MemoryRegion *M = Pair.second;
605     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
606       return M;
607   }
608 
609   // Otherwise, no suitable region was found.
610   if (Sec->Flags & SHF_ALLOC)
611     error("no memory region specified for section '" + Sec->Name + "'");
612   return nullptr;
613 }
614 
615 // This function assigns offsets to input sections and an output section
616 // for a single sections command (e.g. ".text { *(.text); }").
617 void LinkerScript::assignOffsets(OutputSection *Sec) {
618   if (!(Sec->Flags & SHF_ALLOC))
619     Dot = 0;
620   else if (Sec->AddrExpr)
621     setDot(Sec->AddrExpr, Sec->Location, false);
622 
623   CurAddressState->MemRegion = Sec->MemRegion;
624   if (CurAddressState->MemRegion)
625     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
626 
627   if (Sec->LMAExpr) {
628     uint64_t D = Dot;
629     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
630   }
631 
632   switchTo(Sec);
633 
634   // We do not support custom layout for compressed debug sectons.
635   // At this point we already know their size and have compressed content.
636   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
637     return;
638 
639   for (BaseCommand *C : Sec->Commands)
640     process(*C);
641 }
642 
643 void LinkerScript::removeEmptyCommands() {
644   // It is common practice to use very generic linker scripts. So for any
645   // given run some of the output sections in the script will be empty.
646   // We could create corresponding empty output sections, but that would
647   // clutter the output.
648   // We instead remove trivially empty sections. The bfd linker seems even
649   // more aggressive at removing them.
650   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
651     if (auto *Sec = dyn_cast<OutputSection>(Base))
652       return !Sec->Live;
653     return false;
654   });
655 }
656 
657 static bool isAllSectionDescription(const OutputSection &Cmd) {
658   for (BaseCommand *Base : Cmd.Commands)
659     if (!isa<InputSectionDescription>(*Base))
660       return false;
661   return true;
662 }
663 
664 void LinkerScript::adjustSectionsBeforeSorting() {
665   // If the output section contains only symbol assignments, create a
666   // corresponding output section. The bfd linker seems to only create them if
667   // '.' is assigned to, but creating these section should not have any bad
668   // consequeces and gives us a section to put the symbol in.
669   uint64_t Flags = SHF_ALLOC;
670 
671   for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
672     auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I]);
673     if (!Sec)
674       continue;
675     if (Sec->Live) {
676       Flags = Sec->Flags;
677       continue;
678     }
679 
680     if (isAllSectionDescription(*Sec))
681       continue;
682 
683     Sec->Live = true;
684     Sec->SectionIndex = I;
685     Sec->Flags = Flags;
686   }
687 }
688 
689 void LinkerScript::adjustSectionsAfterSorting() {
690   // Try and find an appropriate memory region to assign offsets in.
691   for (BaseCommand *Base : Opt.Commands) {
692     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
693       Sec->MemRegion = findMemoryRegion(Sec);
694       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
695       if (Sec->AlignExpr)
696         Sec->updateAlignment(Sec->AlignExpr().getValue());
697     }
698   }
699 
700   // If output section command doesn't specify any segments,
701   // and we haven't previously assigned any section to segment,
702   // then we simply assign section to the very first load segment.
703   // Below is an example of such linker script:
704   // PHDRS { seg PT_LOAD; }
705   // SECTIONS { .aaa : { *(.aaa) } }
706   std::vector<StringRef> DefPhdrs;
707   auto FirstPtLoad =
708       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
709                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
710   if (FirstPtLoad != Opt.PhdrsCommands.end())
711     DefPhdrs.push_back(FirstPtLoad->Name);
712 
713   // Walk the commands and propagate the program headers to commands that don't
714   // explicitly specify them.
715   for (BaseCommand *Base : Opt.Commands) {
716     auto *Sec = dyn_cast<OutputSection>(Base);
717     if (!Sec)
718       continue;
719 
720     if (Sec->Phdrs.empty()) {
721       // To match the bfd linker script behaviour, only propagate program
722       // headers to sections that are allocated.
723       if (Sec->Flags & SHF_ALLOC)
724         Sec->Phdrs = DefPhdrs;
725     } else {
726       DefPhdrs = Sec->Phdrs;
727     }
728   }
729 
730   removeEmptyCommands();
731 }
732 
733 static OutputSection *findFirstSection(PhdrEntry *Load) {
734   for (OutputSection *Sec : OutputSections)
735     if (Sec->PtLoad == Load)
736       return Sec;
737   return nullptr;
738 }
739 
740 // Try to find an address for the file and program headers output sections,
741 // which were unconditionally added to the first PT_LOAD segment earlier.
742 //
743 // When using the default layout, we check if the headers fit below the first
744 // allocated section. When using a linker script, we also check if the headers
745 // are covered by the output section. This allows omitting the headers by not
746 // leaving enough space for them in the linker script; this pattern is common
747 // in embedded systems.
748 //
749 // If there isn't enough space for these sections, we'll remove them from the
750 // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
751 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
752   uint64_t Min = std::numeric_limits<uint64_t>::max();
753   for (OutputSection *Sec : OutputSections)
754     if (Sec->Flags & SHF_ALLOC)
755       Min = std::min<uint64_t>(Min, Sec->Addr);
756 
757   auto It = llvm::find_if(
758       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
759   if (It == Phdrs.end())
760     return;
761   PhdrEntry *FirstPTLoad = *It;
762 
763   uint64_t HeaderSize = getHeaderSize();
764   // When linker script with SECTIONS is being used, don't output headers
765   // unless there's a space for them.
766   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
767   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
768     Min = Opt.HasSections ? Base
769                           : alignDown(Min - HeaderSize, Config->MaxPageSize);
770     Out::ElfHeader->Addr = Min;
771     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
772     return;
773   }
774 
775   Out::ElfHeader->PtLoad = nullptr;
776   Out::ProgramHeaders->PtLoad = nullptr;
777   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
778 
779   llvm::erase_if(Phdrs,
780                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
781 }
782 
783 LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
784   for (auto &MRI : Opt.MemoryRegions) {
785     const MemoryRegion *MR = MRI.second;
786     MemRegionOffset[MR] = MR->Origin;
787   }
788 }
789 
790 void LinkerScript::assignAddresses() {
791   // Assign addresses as instructed by linker script SECTIONS sub-commands.
792   Dot = 0;
793   auto State = make_unique<AddressState>(Opt);
794   // CurAddressState captures the local AddressState and makes it accessible
795   // deliberately. This is needed as there are some cases where we cannot just
796   // thread the current state through to a lambda function created by the
797   // script parser.
798   CurAddressState = State.get();
799   ErrorOnMissingSection = true;
800   switchTo(Aether);
801 
802   for (BaseCommand *Base : Opt.Commands) {
803     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
804       assignSymbol(Cmd, false);
805       continue;
806     }
807 
808     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
809       Cmd->Expression();
810       continue;
811     }
812 
813     assignOffsets(cast<OutputSection>(Base));
814   }
815   CurAddressState = nullptr;
816 }
817 
818 // Creates program headers as instructed by PHDRS linker script command.
819 std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
820   std::vector<PhdrEntry *> Ret;
821 
822   // Process PHDRS and FILEHDR keywords because they are not
823   // real output sections and cannot be added in the following loop.
824   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
825     PhdrEntry *Phdr =
826         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
827 
828     if (Cmd.HasFilehdr)
829       Phdr->add(Out::ElfHeader);
830     if (Cmd.HasPhdrs)
831       Phdr->add(Out::ProgramHeaders);
832 
833     if (Cmd.LMAExpr) {
834       Phdr->p_paddr = Cmd.LMAExpr().getValue();
835       Phdr->HasLMA = true;
836     }
837     Ret.push_back(Phdr);
838   }
839 
840   // Add output sections to program headers.
841   for (OutputSection *Sec : OutputSections) {
842     // Assign headers specified by linker script
843     for (size_t Id : getPhdrIndices(Sec)) {
844       Ret[Id]->add(Sec);
845       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
846         Ret[Id]->p_flags |= Sec->getPhdrFlags();
847     }
848   }
849   return Ret;
850 }
851 
852 bool LinkerScript::ignoreInterpSection() {
853   // Ignore .interp section in case we have PHDRS specification
854   // and PT_INTERP isn't listed.
855   if (Opt.PhdrsCommands.empty())
856     return false;
857   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
858     if (Cmd.Type == PT_INTERP)
859       return false;
860   return true;
861 }
862 
863 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
864   if (S == ".") {
865     if (CurAddressState)
866       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
867               Loc};
868     error(Loc + ": unable to get location counter value");
869     return 0;
870   }
871   if (SymbolBody *B = Symtab->find(S)) {
872     if (auto *D = dyn_cast<DefinedRegular>(B))
873       return {D->Section, D->Value, Loc};
874     if (auto *C = dyn_cast<DefinedCommon>(B))
875       return {C->Section, 0, Loc};
876   }
877   error(Loc + ": symbol not found: " + S);
878   return 0;
879 }
880 
881 bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
882 
883 static const size_t NoPhdr = -1;
884 
885 // Returns indices of ELF headers containing specific section. Each index is a
886 // zero based number of ELF header listed within PHDRS {} script block.
887 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
888   std::vector<size_t> Ret;
889   for (StringRef PhdrName : Cmd->Phdrs) {
890     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
891     if (Index != NoPhdr)
892       Ret.push_back(Index);
893   }
894   return Ret;
895 }
896 
897 // Returns the index of the segment named PhdrName if found otherwise
898 // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
899 // (which can be used to explicitly specify that a section isn't assigned to a
900 // segment) then error.
901 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
902   size_t I = 0;
903   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
904     if (Cmd.Name == PhdrName)
905       return I;
906     ++I;
907   }
908   if (PhdrName != "NONE")
909     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
910   return NoPhdr;
911 }
912