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