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