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