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 std::string filename(InputSectionBase *S) {
178   if (!S->File)
179     return "";
180   if (S->File->ArchiveName.empty())
181     return S->File->getName();
182   return (S->File->ArchiveName + "(" + S->File->getName() + ")").str();
183 }
184 
185 bool LinkerScript::shouldKeep(InputSectionBase *S) {
186   for (InputSectionDescription *ID : Opt.KeptSections) {
187     std::string Filename = filename(S);
188     if (ID->FilePat.match(Filename))
189       for (SectionPattern &P : ID->SectionPatterns)
190         if (P.SectionPat.match(S->Name))
191           return true;
192   }
193   return false;
194 }
195 
196 // A helper function for the SORT() command.
197 static std::function<bool(InputSectionBase *, InputSectionBase *)>
198 getComparator(SortSectionPolicy K) {
199   switch (K) {
200   case SortSectionPolicy::Alignment:
201     return [](InputSectionBase *A, InputSectionBase *B) {
202       // ">" is not a mistake. Sections with larger alignments are placed
203       // before sections with smaller alignments in order to reduce the
204       // amount of padding necessary. This is compatible with GNU.
205       return A->Alignment > B->Alignment;
206     };
207   case SortSectionPolicy::Name:
208     return [](InputSectionBase *A, InputSectionBase *B) {
209       return A->Name < B->Name;
210     };
211   case SortSectionPolicy::Priority:
212     return [](InputSectionBase *A, InputSectionBase *B) {
213       return getPriority(A->Name) < getPriority(B->Name);
214     };
215   default:
216     llvm_unreachable("unknown sort policy");
217   }
218 }
219 
220 // A helper function for the SORT() command.
221 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
222                              ConstraintKind Kind) {
223   if (Kind == ConstraintKind::NoConstraint)
224     return true;
225 
226   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
227     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
228   });
229 
230   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
231          (!IsRW && Kind == ConstraintKind::ReadOnly);
232 }
233 
234 static void sortSections(InputSection **Begin, InputSection **End,
235                          SortSectionPolicy K) {
236   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
237     std::stable_sort(Begin, End, getComparator(K));
238 }
239 
240 static llvm::DenseMap<SectionBase *, int> getSectionOrder() {
241   switch (Config->EKind) {
242   case ELF32LEKind:
243     return buildSectionOrder<ELF32LE>();
244   case ELF32BEKind:
245     return buildSectionOrder<ELF32BE>();
246   case ELF64LEKind:
247     return buildSectionOrder<ELF64LE>();
248   case ELF64BEKind:
249     return buildSectionOrder<ELF64BE>();
250   default:
251     llvm_unreachable("unknown ELF type");
252   }
253 }
254 
255 static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
256   if (Config->SymbolOrderingFile.empty())
257     return;
258   static llvm::DenseMap<SectionBase *, int> Order = getSectionOrder();
259   MutableArrayRef<InputSection *> In(Begin, End - Begin);
260   sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
261 }
262 
263 // Compute and remember which sections the InputSectionDescription matches.
264 std::vector<InputSection *>
265 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
266   std::vector<InputSection *> Ret;
267 
268   // Collects all sections that satisfy constraints of Cmd.
269   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
270     size_t SizeBefore = Ret.size();
271 
272     for (InputSectionBase *Sec : InputSections) {
273       if (Sec->Assigned)
274         continue;
275 
276       if (!Sec->Live) {
277         reportDiscarded(Sec);
278         continue;
279       }
280 
281       // For -emit-relocs we have to ignore entries like
282       //   .rela.dyn : { *(.rela.data) }
283       // which are common because they are in the default bfd script.
284       if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
285         continue;
286 
287       std::string Filename = filename(Sec);
288       if (!Cmd->FilePat.match(Filename) ||
289           Pat.ExcludedFilePat.match(Filename) ||
290           !Pat.SectionPat.match(Sec->Name))
291         continue;
292 
293       Ret.push_back(cast<InputSection>(Sec));
294       Sec->Assigned = true;
295     }
296 
297     // Sort sections as instructed by SORT-family commands and --sort-section
298     // option. Because SORT-family commands can be nested at most two depth
299     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
300     // line option is respected even if a SORT command is given, the exact
301     // behavior we have here is a bit complicated. Here are the rules.
302     //
303     // 1. If two SORT commands are given, --sort-section is ignored.
304     // 2. If one SORT command is given, and if it is not SORT_NONE,
305     //    --sort-section is handled as an inner SORT command.
306     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
307     // 4. If no SORT command is given, sort according to --sort-section.
308     // 5. If no SORT commands are given and --sort-section is not specified,
309     //    apply sorting provided by --symbol-ordering-file if any exist.
310     InputSection **Begin = Ret.data() + SizeBefore;
311     InputSection **End = Ret.data() + Ret.size();
312     if (Pat.SortOuter == SortSectionPolicy::Default &&
313         Config->SortSection == SortSectionPolicy::Default) {
314       sortBySymbolOrder(Begin, End);
315       continue;
316     }
317     if (Pat.SortOuter != SortSectionPolicy::None) {
318       if (Pat.SortInner == SortSectionPolicy::Default)
319         sortSections(Begin, End, Config->SortSection);
320       else
321         sortSections(Begin, End, Pat.SortInner);
322       sortSections(Begin, End, Pat.SortOuter);
323     }
324   }
325   return Ret;
326 }
327 
328 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
329   for (InputSectionBase *S : V) {
330     S->Live = false;
331     if (S == InX::ShStrTab || S == InX::Common || S == InX::Dynamic ||
332         S == InX::DynSymTab || S == InX::DynStrTab)
333       error("discarding " + S->Name + " section is not allowed");
334     discard(S->DependentSections);
335   }
336 }
337 
338 std::vector<InputSectionBase *>
339 LinkerScript::createInputSectionList(OutputSection &OutCmd) {
340   std::vector<InputSectionBase *> Ret;
341 
342   for (BaseCommand *Base : OutCmd.Commands) {
343     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
344     if (!Cmd)
345       continue;
346 
347     Cmd->Sections = computeInputSections(Cmd);
348     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
349   }
350 
351   return Ret;
352 }
353 
354 void LinkerScript::processCommands(OutputSectionFactory &Factory) {
355   // A symbol can be assigned before any section is mentioned in the linker
356   // script. In an DSO, the symbol values are addresses, so the only important
357   // section values are:
358   // * SHN_UNDEF
359   // * SHN_ABS
360   // * Any value meaning a regular section.
361   // To handle that, create a dummy aether section that fills the void before
362   // the linker scripts switches to another section. It has an index of one
363   // which will map to whatever the first actual section is.
364   Aether = make<OutputSection>("", 0, SHF_ALLOC);
365   Aether->SectionIndex = 1;
366   auto State = make_unique<AddressState>(Opt);
367   // CurAddressState captures the local AddressState and makes it accessible
368   // deliberately. This is needed as there are some cases where we cannot just
369   // thread the current state through to a lambda function created by the
370   // script parser.
371   CurAddressState = State.get();
372   CurAddressState->OutSec = Aether;
373   Dot = 0;
374 
375   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
376     // Handle symbol assignments outside of any output section.
377     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
378       addSymbol(Cmd);
379       continue;
380     }
381 
382     if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
383       std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
384 
385       // The output section name `/DISCARD/' is special.
386       // Any input section assigned to it is discarded.
387       if (Sec->Name == "/DISCARD/") {
388         discard(V);
389         continue;
390       }
391 
392       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
393       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
394       // sections satisfy a given constraint. If not, a directive is handled
395       // as if it wasn't present from the beginning.
396       //
397       // Because we'll iterate over Commands many more times, the easiest
398       // way to "make it as if it wasn't present" is to just remove it.
399       if (!matchConstraints(V, Sec->Constraint)) {
400         for (InputSectionBase *S : V)
401           S->Assigned = false;
402         Opt.Commands.erase(Opt.Commands.begin() + I);
403         --I;
404         continue;
405       }
406 
407       // A directive may contain symbol definitions like this:
408       // ".foo : { ...; bar = .; }". Handle them.
409       for (BaseCommand *Base : Sec->Commands)
410         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
411           addSymbol(OutCmd);
412 
413       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
414       // is given, input sections are aligned to that value, whether the
415       // given value is larger or smaller than the original section alignment.
416       if (Sec->SubalignExpr) {
417         uint32_t Subalign = Sec->SubalignExpr().getValue();
418         for (InputSectionBase *S : V)
419           S->Alignment = Subalign;
420       }
421 
422       // Add input sections to an output section.
423       for (InputSectionBase *S : V)
424         Factory.addInputSec(S, Sec->Name, Sec);
425       assert(Sec->SectionIndex == INT_MAX);
426       Sec->SectionIndex = I;
427       if (Sec->Noload)
428         Sec->Type = SHT_NOBITS;
429     }
430   }
431   CurAddressState = nullptr;
432 }
433 
434 void LinkerScript::fabricateDefaultCommands() {
435   // Define start address
436   uint64_t StartAddr = -1;
437 
438   // The Sections with -T<section> have been sorted in order of ascending
439   // address. We must lower StartAddr if the lowest -T<section address> as
440   // calls to setDot() must be monotonically increasing.
441   for (auto &KV : Config->SectionStartMap)
442     StartAddr = std::min(StartAddr, KV.second);
443 
444   Opt.Commands.insert(Opt.Commands.begin(),
445                       make<SymbolAssignment>(".",
446                                              [=] {
447                                                return std::min(
448                                                    StartAddr,
449                                                    Config->ImageBase +
450                                                        elf::getHeaderSize());
451                                              },
452                                              ""));
453 }
454 
455 // Add sections that didn't match any sections command.
456 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
457   unsigned NumCommands = Opt.Commands.size();
458   for (InputSectionBase *S : InputSections) {
459     if (!S->Live || S->Parent)
460       continue;
461     StringRef Name = getOutputSectionName(S->Name);
462     auto End = Opt.Commands.begin() + NumCommands;
463     auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
464       if (auto *Sec = dyn_cast<OutputSection>(Base))
465         return Sec->Name == Name;
466       return false;
467     });
468     if (I == End) {
469       Factory.addInputSec(S, Name);
470       assert(S->getOutputSection()->SectionIndex == INT_MAX);
471     } else {
472       OutputSection *Sec = cast<OutputSection>(*I);
473       Factory.addInputSec(S, Name, Sec);
474       unsigned Index = std::distance(Opt.Commands.begin(), I);
475       assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
476       Sec->SectionIndex = Index;
477     }
478   }
479 }
480 
481 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
482   bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
483                 CurAddressState->OutSec->Type == SHT_NOBITS;
484   uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
485   Start = alignTo(Start, Align);
486   uint64_t End = Start + Size;
487 
488   if (IsTbss)
489     CurAddressState->ThreadBssOffset = End - Dot;
490   else
491     Dot = End;
492   return End;
493 }
494 
495 void LinkerScript::output(InputSection *S) {
496   uint64_t Before = advance(0, 1);
497   uint64_t Pos = advance(S->getSize(), S->Alignment);
498   S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
499 
500   // Update output section size after adding each section. This is so that
501   // SIZEOF works correctly in the case below:
502   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
503   CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
504 
505   // If there is a memory region associated with this input section, then
506   // place the section in that region and update the region index.
507   if (CurAddressState->MemRegion) {
508     uint64_t &CurOffset =
509         CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
510     CurOffset += Pos - Before;
511     uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
512     if (CurSize > CurAddressState->MemRegion->Length) {
513       uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
514       error("section '" + CurAddressState->OutSec->Name +
515             "' will not fit in region '" + CurAddressState->MemRegion->Name +
516             "': overflowed by " + Twine(OverflowAmt) + " bytes");
517     }
518   }
519 }
520 
521 void LinkerScript::switchTo(OutputSection *Sec) {
522   if (CurAddressState->OutSec == Sec)
523     return;
524 
525   CurAddressState->OutSec = Sec;
526   CurAddressState->OutSec->Addr =
527       advance(0, CurAddressState->OutSec->Alignment);
528 
529   // If neither AT nor AT> is specified for an allocatable section, the linker
530   // will set the LMA such that the difference between VMA and LMA for the
531   // section is the same as the preceding output section in the same region
532   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
533   if (CurAddressState->LMAOffset)
534     CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
535 }
536 
537 void LinkerScript::process(BaseCommand &Base) {
538   // This handles the assignments to symbol or to the dot.
539   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
540     assignSymbol(Cmd, true);
541     return;
542   }
543 
544   // Handle BYTE(), SHORT(), LONG(), or QUAD().
545   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
546     Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
547     Dot += Cmd->Size;
548     CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
549     return;
550   }
551 
552   // Handle ASSERT().
553   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
554     Cmd->Expression();
555     return;
556   }
557 
558   // Handle a single input section description command.
559   // It calculates and assigns the offsets for each section and also
560   // updates the output section size.
561   auto &Cmd = cast<InputSectionDescription>(Base);
562   for (InputSection *Sec : Cmd.Sections) {
563     // We tentatively added all synthetic sections at the beginning and removed
564     // empty ones afterwards (because there is no way to know whether they were
565     // going be empty or not other than actually running linker scripts.)
566     // We need to ignore remains of empty sections.
567     if (auto *S = dyn_cast<SyntheticSection>(Sec))
568       if (S->empty())
569         continue;
570 
571     if (!Sec->Live)
572       continue;
573     assert(CurAddressState->OutSec == Sec->getParent());
574     output(Sec);
575   }
576 }
577 
578 // This function searches for a memory region to place the given output
579 // section in. If found, a pointer to the appropriate memory region is
580 // returned. Otherwise, a nullptr is returned.
581 MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
582   // If a memory region name was specified in the output section command,
583   // then try to find that region first.
584   if (!Sec->MemoryRegionName.empty()) {
585     auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
586     if (It != Opt.MemoryRegions.end())
587       return &It->second;
588     error("memory region '" + Sec->MemoryRegionName + "' not declared");
589     return nullptr;
590   }
591 
592   // If at least one memory region is defined, all sections must
593   // belong to some memory region. Otherwise, we don't need to do
594   // anything for memory regions.
595   if (Opt.MemoryRegions.empty())
596     return nullptr;
597 
598   // See if a region can be found by matching section flags.
599   for (auto &Pair : Opt.MemoryRegions) {
600     MemoryRegion &M = Pair.second;
601     if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
602       return &M;
603   }
604 
605   // Otherwise, no suitable region was found.
606   if (Sec->Flags & SHF_ALLOC)
607     error("no memory region specified for section '" + Sec->Name + "'");
608   return nullptr;
609 }
610 
611 // This function assigns offsets to input sections and an output section
612 // for a single sections command (e.g. ".text { *(.text); }").
613 void LinkerScript::assignOffsets(OutputSection *Sec) {
614   if (!(Sec->Flags & SHF_ALLOC))
615     Dot = 0;
616   else if (Sec->AddrExpr)
617     setDot(Sec->AddrExpr, Sec->Location, false);
618 
619   CurAddressState->MemRegion = Sec->MemRegion;
620   if (CurAddressState->MemRegion)
621     Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
622 
623   if (Sec->LMAExpr) {
624     uint64_t D = Dot;
625     CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
626   }
627 
628   switchTo(Sec);
629 
630   // We do not support custom layout for compressed debug sectons.
631   // At this point we already know their size and have compressed content.
632   if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
633     return;
634 
635   for (BaseCommand *C : Sec->Commands)
636     process(*C);
637 }
638 
639 void LinkerScript::removeEmptyCommands() {
640   // It is common practice to use very generic linker scripts. So for any
641   // given run some of the output sections in the script will be empty.
642   // We could create corresponding empty output sections, but that would
643   // clutter the output.
644   // We instead remove trivially empty sections. The bfd linker seems even
645   // more aggressive at removing them.
646   llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
647     if (auto *Sec = dyn_cast<OutputSection>(Base))
648       return !Sec->Live;
649     return false;
650   });
651 }
652 
653 static bool isAllSectionDescription(const OutputSection &Cmd) {
654   for (BaseCommand *Base : Cmd.Commands)
655     if (!isa<InputSectionDescription>(*Base))
656       return false;
657   return true;
658 }
659 
660 void LinkerScript::adjustSectionsBeforeSorting() {
661   // If the output section contains only symbol assignments, create a
662   // corresponding output section. The bfd linker seems to only create them if
663   // '.' is assigned to, but creating these section should not have any bad
664   // consequeces and gives us a section to put the symbol in.
665   uint64_t Flags = SHF_ALLOC;
666 
667   for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
668     auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I]);
669     if (!Sec)
670       continue;
671     if (Sec->Live) {
672       Flags = Sec->Flags;
673       continue;
674     }
675 
676     if (isAllSectionDescription(*Sec))
677       continue;
678 
679     Sec->Live = true;
680     Sec->SectionIndex = I;
681     Sec->Flags = Flags;
682   }
683 }
684 
685 void LinkerScript::adjustSectionsAfterSorting() {
686   // Try and find an appropriate memory region to assign offsets in.
687   for (BaseCommand *Base : Opt.Commands) {
688     if (auto *Sec = dyn_cast<OutputSection>(Base)) {
689       Sec->MemRegion = findMemoryRegion(Sec);
690       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
691       if (Sec->AlignExpr)
692         Sec->updateAlignment(Sec->AlignExpr().getValue());
693     }
694   }
695 
696   // If output section command doesn't specify any segments,
697   // and we haven't previously assigned any section to segment,
698   // then we simply assign section to the very first load segment.
699   // Below is an example of such linker script:
700   // PHDRS { seg PT_LOAD; }
701   // SECTIONS { .aaa : { *(.aaa) } }
702   std::vector<StringRef> DefPhdrs;
703   auto FirstPtLoad =
704       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
705                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
706   if (FirstPtLoad != Opt.PhdrsCommands.end())
707     DefPhdrs.push_back(FirstPtLoad->Name);
708 
709   // Walk the commands and propagate the program headers to commands that don't
710   // explicitly specify them.
711   for (BaseCommand *Base : Opt.Commands) {
712     auto *Sec = dyn_cast<OutputSection>(Base);
713     if (!Sec)
714       continue;
715 
716     if (Sec->Phdrs.empty()) {
717       // To match the bfd linker script behaviour, only propagate program
718       // headers to sections that are allocated.
719       if (Sec->Flags & SHF_ALLOC)
720         Sec->Phdrs = DefPhdrs;
721     } else {
722       DefPhdrs = Sec->Phdrs;
723     }
724   }
725 
726   removeEmptyCommands();
727 }
728 
729 // Try to find an address for the file and program headers output sections,
730 // which were unconditionally added to the first PT_LOAD segment earlier.
731 //
732 // When using the default layout, we check if the headers fit below the first
733 // allocated section. When using a linker script, we also check if the headers
734 // are covered by the output section. This allows omitting the headers by not
735 // leaving enough space for them in the linker script; this pattern is common
736 // in embedded systems.
737 //
738 // If there isn't enough space for these sections, we'll remove them from the
739 // PT_LOAD segment, and we'll also remove the PT_PHDR segment.
740 void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
741   uint64_t Min = std::numeric_limits<uint64_t>::max();
742   for (OutputSection *Sec : OutputSections)
743     if (Sec->Flags & SHF_ALLOC)
744       Min = std::min<uint64_t>(Min, Sec->Addr);
745 
746   auto It = llvm::find_if(
747       Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
748   if (It == Phdrs.end())
749     return;
750   PhdrEntry *FirstPTLoad = *It;
751 
752   uint64_t HeaderSize = getHeaderSize();
753   // When linker script with SECTIONS is being used, don't output headers
754   // unless there's a space for them.
755   uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
756   if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
757     Min = Opt.HasSections ? Base
758                           : alignDown(Min - HeaderSize, Config->MaxPageSize);
759     Out::ElfHeader->Addr = Min;
760     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
761     return;
762   }
763 
764   OutputSection *ActualFirst = nullptr;
765   for (OutputSection *Sec : OutputSections) {
766     if (Sec->FirstInPtLoad == Out::ElfHeader) {
767       ActualFirst = Sec;
768       break;
769     }
770   }
771   if (ActualFirst) {
772     for (OutputSection *Sec : OutputSections)
773       if (Sec->FirstInPtLoad == Out::ElfHeader)
774         Sec->FirstInPtLoad = ActualFirst;
775     FirstPTLoad->First = ActualFirst;
776   } else {
777     Phdrs.erase(It);
778   }
779 
780   llvm::erase_if(Phdrs,
781                  [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
782 }
783 
784 LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
785   for (auto &MRI : Opt.MemoryRegions) {
786     const MemoryRegion *MR = &MRI.second;
787     MemRegionOffset[MR] = MR->Origin;
788   }
789 }
790 
791 void LinkerScript::assignAddresses() {
792   // Assign addresses as instructed by linker script SECTIONS sub-commands.
793   Dot = 0;
794   auto State = make_unique<AddressState>(Opt);
795   // CurAddressState captures the local AddressState and makes it accessible
796   // deliberately. This is needed as there are some cases where we cannot just
797   // thread the current state through to a lambda function created by the
798   // script parser.
799   CurAddressState = State.get();
800   ErrorOnMissingSection = true;
801   switchTo(Aether);
802 
803   for (BaseCommand *Base : Opt.Commands) {
804     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
805       assignSymbol(Cmd, false);
806       continue;
807     }
808 
809     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
810       Cmd->Expression();
811       continue;
812     }
813 
814     assignOffsets(cast<OutputSection>(Base));
815   }
816   CurAddressState = nullptr;
817 }
818 
819 // Creates program headers as instructed by PHDRS linker script command.
820 std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
821   std::vector<PhdrEntry *> Ret;
822 
823   // Process PHDRS and FILEHDR keywords because they are not
824   // real output sections and cannot be added in the following loop.
825   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
826     PhdrEntry *Phdr =
827         make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
828 
829     if (Cmd.HasFilehdr)
830       Phdr->add(Out::ElfHeader);
831     if (Cmd.HasPhdrs)
832       Phdr->add(Out::ProgramHeaders);
833 
834     if (Cmd.LMAExpr) {
835       Phdr->p_paddr = Cmd.LMAExpr().getValue();
836       Phdr->HasLMA = true;
837     }
838     Ret.push_back(Phdr);
839   }
840 
841   // Add output sections to program headers.
842   for (OutputSection *Sec : OutputSections) {
843     // Assign headers specified by linker script
844     for (size_t Id : getPhdrIndices(Sec)) {
845       Ret[Id]->add(Sec);
846       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
847         Ret[Id]->p_flags |= Sec->getPhdrFlags();
848     }
849   }
850   return Ret;
851 }
852 
853 bool LinkerScript::ignoreInterpSection() {
854   // Ignore .interp section in case we have PHDRS specification
855   // and PT_INTERP isn't listed.
856   if (Opt.PhdrsCommands.empty())
857     return false;
858   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
859     if (Cmd.Type == PT_INTERP)
860       return false;
861   return true;
862 }
863 
864 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
865   if (S == ".") {
866     if (CurAddressState)
867       return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
868               Loc};
869     error(Loc + ": unable to get location counter value");
870     return 0;
871   }
872   if (SymbolBody *B = Symtab->find(S)) {
873     if (auto *D = dyn_cast<DefinedRegular>(B))
874       return {D->Section, D->Value, Loc};
875     if (auto *C = dyn_cast<DefinedCommon>(B))
876       return {InX::Common, C->Offset, Loc};
877   }
878   error(Loc + ": symbol not found: " + S);
879   return 0;
880 }
881 
882 bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
883 
884 static const size_t NoPhdr = -1;
885 
886 // Returns indices of ELF headers containing specific section. Each index is a
887 // zero based number of ELF header listed within PHDRS {} script block.
888 std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
889   std::vector<size_t> Ret;
890   for (StringRef PhdrName : Cmd->Phdrs) {
891     size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
892     if (Index != NoPhdr)
893       Ret.push_back(Index);
894   }
895   return Ret;
896 }
897 
898 // Returns the index of the segment named PhdrName if found otherwise
899 // NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
900 // (which can be used to explicitly specify that a section isn't assigned to a
901 // segment) then error.
902 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
903   size_t I = 0;
904   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
905     if (Cmd.Name == PhdrName)
906       return I;
907     ++I;
908   }
909   if (PhdrName != "NONE")
910     error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
911   return NoPhdr;
912 }
913