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