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