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         Factory.addInputSec(S, Sec->Name, Sec);
420       assert(Sec->SectionIndex == INT_MAX);
421       Sec->SectionIndex = I;
422       if (Sec->Noload)
423         Sec->Type = SHT_NOBITS;
424     }
425   }
426   CurAddressState = nullptr;
427 }
428 
429 void LinkerScript::fabricateDefaultCommands() {
430   // Define start address
431   uint64_t StartAddr = UINT64_MAX;
432 
433   // The Sections with -T<section> have been sorted in order of ascending
434   // address. We must lower StartAddr if the lowest -T<section address> as
435   // calls to setDot() must be monotonically increasing.
436   for (auto &KV : Config->SectionStartMap)
437     StartAddr = std::min(StartAddr, KV.second);
438 
439   auto Expr = [=] {
440     return std::min(StartAddr, Config->ImageBase + elf::getHeaderSize());
441   };
442   Opt.Commands.insert(Opt.Commands.begin(),
443                       make<SymbolAssignment>(".", Expr, ""));
444 }
445 
446 // Add sections that didn't match any sections command.
447 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
448   unsigned NumCommands = Opt.Commands.size();
449   for (InputSectionBase *S : InputSections) {
450     if (!S->Live || S->Parent)
451       continue;
452     StringRef Name = getOutputSectionName(S->Name);
453     auto End = Opt.Commands.begin() + NumCommands;
454     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
455       if (auto *Sec = dyn_cast<OutputSection>(Base))
456         return Sec->Name == Name;
457       return false;
458     });
459     log(toString(S) + " is being placed in '" + Name + "'");
460     if (I == End) {
461       Factory.addInputSec(S, Name);
462       assert(S->getOutputSection()->SectionIndex == INT_MAX);
463     } else {
464       OutputSection *Sec = cast<OutputSection>(*I);
465       Factory.addInputSec(S, Name, Sec);
466       unsigned Index = std::distance(Opt.Commands.begin(), I);
467       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
468       Sec->SectionIndex = Index;
469     }
470   }
471 }
472 
473 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
474   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
475                 CurAddressState->OutSec->Type == SHT_NOBITS;
476   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
477   Start = alignTo(Start, Align);
478   uint64_t End = Start + Size;
479 
480   if (IsTbss)
481     CurAddressState->ThreadBssOffset = End - Dot;
482   else
483     Dot = End;
484   return End;
485 }
486 
487 void LinkerScript::output(InputSection *S) {
488   uint64_t Before = advance(0, 1);
489   uint64_t Pos = advance(S->getSize(), S->Alignment);
490   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
491 
492   // Update output section size after adding each section. This is so that
493   // SIZEOF works correctly in the case below:
494   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
495   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
496 
497   // If there is a memory region associated with this input section, then
498   // place the section in that region and update the region index.
499   if (CurAddressState->MemRegion) {
500     uint64_t &CurOffset =
501         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
502     CurOffset += Pos - Before;
503     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
504     if (CurSize > CurAddressState->MemRegion->Length) {
505       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
506       error("section '" + CurAddressState->OutSec->Name +
507             "' will not fit in region '" + CurAddressState->MemRegion->Name +
508             "': overflowed by " + Twine(OverflowAmt) + " bytes");
509     }
510   }
511 }
512 
513 void LinkerScript::switchTo(OutputSection *Sec) {
514   if (CurAddressState->OutSec == Sec)
515     return;
516 
517   CurAddressState->OutSec = Sec;
518   CurAddressState->OutSec->Addr =
519       advance(0, CurAddressState->OutSec->Alignment);
520 
521   // If neither AT nor AT> is specified for an allocatable section, the linker
522   // will set the LMA such that the difference between VMA and LMA for the
523   // section is the same as the preceding output section in the same region
524   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
525   if (CurAddressState->LMAOffset)
526     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
527 }
528 
529 void LinkerScript::process(BaseCommand &Base) {
530   // This handles the assignments to symbol or to the dot.
531   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
532     assignSymbol(Cmd, true);
533     return;
534   }
535 
536   // Handle BYTE(), SHORT(), LONG(), or QUAD().
537   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
538     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
539     Dot += Cmd->Size;
540     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
541     return;
542   }
543 
544   // Handle ASSERT().
545   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
546     Cmd->Expression();
547     return;
548   }
549 
550   // Handle a single input section description command.
551   // It calculates and assigns the offsets for each section and also
552   // updates the output section size.
553   auto &Cmd = cast<InputSectionDescription>(Base);
554   for (InputSection *Sec : Cmd.Sections) {
555     // We tentatively added all synthetic sections at the beginning and removed
556     // empty ones afterwards (because there is no way to know whether they were
557     // going be empty or not other than actually running linker scripts.)
558     // We need to ignore remains of empty sections.
559     if (auto *S = dyn_cast<SyntheticSection>(Sec))
560       if (S->empty())
561         continue;
562 
563     if (!Sec->Live)
564       continue;
565     assert(CurAddressState->OutSec == Sec->getParent());
566     output(Sec);
567   }
568 }
569 
570 // This function searches for a memory region to place the given output
571 // section in. If found, a pointer to the appropriate memory region is
572 // returned. Otherwise, a nullptr is returned.
573 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
574   // If a memory region name was specified in the output section command,
575   // then try to find that region first.
576   if (!Sec->MemoryRegionName.empty()) {
577     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
578     if (It != Opt.MemoryRegions.end())
579       return It->second;
580     error("memory region '" + Sec->MemoryRegionName + "' not declared");
581     return nullptr;
582   }
583 
584   // If at least one memory region is defined, all sections must
585   // belong to some memory region. Otherwise, we don't need to do
586   // anything for memory regions.
587   if (Opt.MemoryRegions.empty())
588     return nullptr;
589 
590   // See if a region can be found by matching section flags.
591   for (auto &Pair : Opt.MemoryRegions) {
592     MemoryRegion *M = Pair.second;
593     if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
594       return M;
595   }
596 
597   // Otherwise, no suitable region was found.
598   if (Sec->Flags & SHF_ALLOC)
599     error("no memory region specified for section '" + Sec->Name + "'");
600   return nullptr;
601 }
602 
603 // This function assigns offsets to input sections and an output section
604 // for a single sections command (e.g. ".text { *(.text); }").
605 void LinkerScript::assignOffsets(OutputSection *Sec) {
606   if (!(Sec->Flags & SHF_ALLOC))
607     Dot = 0;
608   else if (Sec->AddrExpr)
609     setDot(Sec->AddrExpr, Sec->Location, false);
610 
611   CurAddressState->MemRegion = Sec->MemRegion;
612   if (CurAddressState->MemRegion)
613     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
614 
615   if (Sec->LMAExpr) {
616     uint64_t D = Dot;
617     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
618   }
619 
620   switchTo(Sec);
621 
622   // We do not support custom layout for compressed debug sectons.
623   // At this point we already know their size and have compressed content.
624   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
625     return;
626 
627   for (BaseCommand *C : Sec->Commands)
628     process(*C);
629 }
630 
631 void LinkerScript::removeEmptyCommands() {
632   // It is common practice to use very generic linker scripts. So for any
633   // given run some of the output sections in the script will be empty.
634   // We could create corresponding empty output sections, but that would
635   // clutter the output.
636   // We instead remove trivially empty sections. The bfd linker seems even
637   // more aggressive at removing them.
638   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
639     if (auto *Sec = dyn_cast<OutputSection>(Base))
640       return !Sec->Live;
641     return false;
642   });
643 }
644 
645 static bool isAllSectionDescription(const OutputSection &Cmd) {
646   for (BaseCommand *Base : Cmd.Commands)
647     if (!isa<InputSectionDescription>(*Base))
648       return false;
649   return true;
650 }
651 
652 void LinkerScript::adjustSectionsBeforeSorting() {
653   // If the output section contains only symbol assignments, create a
654   // corresponding output section. The bfd linker seems to only create them if
655   // '.' is assigned to, but creating these section should not have any bad
656   // consequeces and gives us a section to put the symbol in.
657   uint64_t Flags = SHF_ALLOC;
658 
659   for (BaseCommand * Cmd : Opt.Commands) {
660     auto *Sec = dyn_cast<OutputSection>(Cmd);
661     if (!Sec)
662       continue;
663     if (Sec->Live) {
664       Flags = Sec->Flags;
665       continue;
666     }
667 
668     if (isAllSectionDescription(*Sec))
669       continue;
670 
671     Sec->Live = true;
672     Sec->Flags = Flags;
673   }
674 }
675 
676 void LinkerScript::adjustSectionsAfterSorting() {
677   // Try and find an appropriate memory region to assign offsets in.
678   for (BaseCommand *Base : Opt.Commands) {
679     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
680       Sec->MemRegion = findMemoryRegion(Sec);
681       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
682       if (Sec->AlignExpr)
683         Sec->updateAlignment(Sec->AlignExpr().getValue());
684     }
685   }
686 
687   // If output section command doesn't specify any segments,
688   // and we haven't previously assigned any section to segment,
689   // then we simply assign section to the very first load segment.
690   // Below is an example of such linker script:
691   // PHDRS { seg PT_LOAD; }
692   // SECTIONS { .aaa : { *(.aaa) } }
693   std::vector<StringRef> DefPhdrs;
694   auto FirstPtLoad =
695       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
696                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
697   if (FirstPtLoad != Opt.PhdrsCommands.end())
698     DefPhdrs.push_back(FirstPtLoad->Name);
699 
700   // Walk the commands and propagate the program headers to commands that don't
701   // explicitly specify them.
702   for (BaseCommand *Base : Opt.Commands) {
703     auto *Sec = dyn_cast<OutputSection>(Base);
704     if (!Sec)
705       continue;
706 
707     if (Sec->Phdrs.empty()) {
708       // To match the bfd linker script behaviour, only propagate program
709       // headers to sections that are allocated.
710       if (Sec->Flags & SHF_ALLOC)
711         Sec->Phdrs = DefPhdrs;
712     } else {
713       DefPhdrs = Sec->Phdrs;
714     }
715   }
716 
717   removeEmptyCommands();
718 }
719 
720 static OutputSection *findFirstSection(PhdrEntry *Load) {
721   for (OutputSection *Sec : OutputSections)
722     if (Sec->PtLoad == Load)
723       return Sec;
724   return nullptr;
725 }
726 
727 // Try to find an address for the file and program headers output sections,
728 // which were unconditionally added to the first PT_LOAD segment earlier.
729 //
730 // When using the default layout, we check if the headers fit below the first
731 // allocated section. When using a linker script, we also check if the headers
732 // are covered by the output section. This allows omitting the headers by not
733 // leaving enough space for them in the linker script; this pattern is common
734 // in embedded systems.
735 //
736 // If there isn't enough space for these sections, we'll remove them from the
737 // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
738 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
739   uint64_t Min = std::numeric_limits<uint64_t>::max();
740   for (OutputSection *Sec : OutputSections)
741     if (Sec->Flags & SHF_ALLOC)
742       Min = std::min<uint64_t>(Min, Sec->Addr);
743 
744   auto It = llvm::find_if(
745       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
746   if (It == Phdrs.end())
747     return;
748   PhdrEntry *FirstPTLoad = *It;
749 
750   uint64_t HeaderSize = getHeaderSize();
751   // When linker script with SECTIONS is being used, don't output headers
752   // unless there's a space for them.
753   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
754   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
755     Min = Opt.HasSections ? Base
756                           : alignDown(Min - HeaderSize, Config->MaxPageSize);
757     Out::ElfHeader->Addr = Min;
758     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
759     return;
760   }
761 
762   Out::ElfHeader->PtLoad = nullptr;
763   Out::ProgramHeaders->PtLoad = nullptr;
764   FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
765 
766   llvm::erase_if(Phdrs,
767                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
768 }
769 
770 LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
771   for (auto &MRI : Opt.MemoryRegions) {
772     const MemoryRegion *MR = MRI.second;
773     MemRegionOffset[MR] = MR->Origin;
774   }
775 }
776 
777 void LinkerScript::assignAddresses() {
778   // Assign addresses as instructed by linker script SECTIONS sub-commands.
779   Dot = 0;
780   auto State = make_unique<AddressState>(Opt);
781   // CurAddressState captures the local AddressState and makes it accessible
782   // deliberately. This is needed as there are some cases where we cannot just
783   // thread the current state through to a lambda function created by the
784   // script parser.
785   CurAddressState = State.get();
786   ErrorOnMissingSection = true;
787   switchTo(Aether);
788 
789   for (BaseCommand *Base : Opt.Commands) {
790     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
791       assignSymbol(Cmd, false);
792       continue;
793     }
794 
795     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
796       Cmd->Expression();
797       continue;
798     }
799 
800     assignOffsets(cast<OutputSection>(Base));
801   }
802   CurAddressState = nullptr;
803 }
804 
805 // Creates program headers as instructed by PHDRS linker script command.
806 std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
807   std::vector<PhdrEntry *> Ret;
808 
809   // Process PHDRS and FILEHDR keywords because they are not
810   // real output sections and cannot be added in the following loop.
811   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
812     PhdrEntry *Phdr =
813         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
814 
815     if (Cmd.HasFilehdr)
816       Phdr->add(Out::ElfHeader);
817     if (Cmd.HasPhdrs)
818       Phdr->add(Out::ProgramHeaders);
819 
820     if (Cmd.LMAExpr) {
821       Phdr->p_paddr = Cmd.LMAExpr().getValue();
822       Phdr->HasLMA = true;
823     }
824     Ret.push_back(Phdr);
825   }
826 
827   // Add output sections to program headers.
828   for (OutputSection *Sec : OutputSections) {
829     // Assign headers specified by linker script
830     for (size_t Id : getPhdrIndices(Sec)) {
831       Ret[Id]->add(Sec);
832       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
833         Ret[Id]->p_flags |= Sec->getPhdrFlags();
834     }
835   }
836   return Ret;
837 }
838 
839 bool LinkerScript::ignoreInterpSection() {
840   // Ignore .interp section in case we have PHDRS specification
841   // and PT_INTERP isn't listed.
842   if (Opt.PhdrsCommands.empty())
843     return false;
844   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
845     if (Cmd.Type == PT_INTERP)
846       return false;
847   return true;
848 }
849 
850 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
851   if (S == ".") {
852     if (CurAddressState)
853       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
854               Loc};
855     error(Loc + ": unable to get location counter value");
856     return 0;
857   }
858   if (SymbolBody *B = Symtab->find(S)) {
859     if (auto *D = dyn_cast<DefinedRegular>(B))
860       return {D->Section, D->Value, Loc};
861     if (auto *C = dyn_cast<DefinedCommon>(B))
862       return {C->Section, 0, Loc};
863   }
864   error(Loc + ": symbol not found: " + S);
865   return 0;
866 }
867 
868 bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
869 
870 static const size_t NoPhdr = -1;
871 
872 // Returns indices of ELF headers containing specific section. Each index is a
873 // zero based number of ELF header listed within PHDRS {} script block.
874 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
875   std::vector<size_t> Ret;
876   for (StringRef PhdrName : Cmd->Phdrs) {
877     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
878     if (Index != NoPhdr)
879       Ret.push_back(Index);
880   }
881   return Ret;
882 }
883 
884 // Returns the index of the segment named PhdrName if found otherwise
885 // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
886 // (which can be used to explicitly specify that a section isn't assigned to a
887 // segment) then error.
888 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
889   size_t I = 0;
890   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
891     if (Cmd.Name == PhdrName)
892       return I;
893     ++I;
894   }
895   if (PhdrName != "NONE")
896     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
897   return NoPhdr;
898 }
899