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 "Writer.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/Casting.h"
27 #include "llvm/Support/ELF.h"
28 #include "llvm/Support/Endian.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/FileSystem.h"
31 #include "llvm/Support/Path.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstddef>
35 #include <cstdint>
36 #include <iterator>
37 #include <limits>
38 #include <string>
39 #include <vector>
40 
41 using namespace llvm;
42 using namespace llvm::ELF;
43 using namespace llvm::object;
44 using namespace llvm::support::endian;
45 using namespace lld;
46 using namespace lld::elf;
47 
48 LinkerScript *elf::Script;
49 
50 uint64_t ExprValue::getValue() const {
51   if (Sec)
52     return Sec->getOffset(Val) + Sec->getOutputSection()->Addr;
53   return Val;
54 }
55 
56 uint64_t ExprValue::getSecAddr() const {
57   if (Sec)
58     return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
59   return 0;
60 }
61 
62 template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
63   Symbol *Sym;
64   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
65   std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
66       Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
67       /*File*/ nullptr);
68   Sym->Binding = STB_GLOBAL;
69   ExprValue Value = Cmd->Expression();
70   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
71 
72   // We want to set symbol values early if we can. This allows us to use symbols
73   // as variables in linker scripts. Doing so allows us to write expressions
74   // like this: `alignment = 16; . = ALIGN(., alignment)`
75   uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
76   replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
77                               STT_NOTYPE, SymValue, 0, Sec, nullptr);
78   return Sym->body();
79 }
80 
81 OutputSection *LinkerScript::getOutputSection(const Twine &Loc,
82                                               StringRef Name) {
83   for (OutputSection *Sec : *OutputSections)
84     if (Sec->Name == Name)
85       return Sec;
86 
87   static OutputSection Dummy("", 0, 0);
88   if (ErrorOnMissingSection)
89     error(Loc + ": undefined section " + Name);
90   return &Dummy;
91 }
92 
93 // This function is essentially the same as getOutputSection(Name)->Size,
94 // but it won't print out an error message if a given section is not found.
95 //
96 // Linker script does not create an output section if its content is empty.
97 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
98 // be empty. That is why this function is different from getOutputSection().
99 uint64_t LinkerScript::getOutputSectionSize(StringRef Name) {
100   for (OutputSection *Sec : *OutputSections)
101     if (Sec->Name == Name)
102       return Sec->Size;
103   return 0;
104 }
105 
106 void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
107   uint64_t Val = E().getValue();
108   if (Val < Dot) {
109     if (InSec)
110       error(Loc + ": unable to move location counter backward for: " +
111             CurOutSec->Name);
112     else
113       error(Loc + ": unable to move location counter backward");
114   }
115   Dot = Val;
116   // Update to location counter means update to section size.
117   if (InSec)
118     CurOutSec->Size = Dot - CurOutSec->Addr;
119 }
120 
121 // Sets value of a symbol. Two kinds of symbols are processed: synthetic
122 // symbols, whose value is an offset from beginning of section and regular
123 // symbols whose value is absolute.
124 void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
125   if (Cmd->Name == ".") {
126     setDot(Cmd->Expression, Cmd->Location, InSec);
127     return;
128   }
129 
130   if (!Cmd->Sym)
131     return;
132 
133   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
134   ExprValue V = Cmd->Expression();
135   if (V.isAbsolute()) {
136     Sym->Value = V.getValue();
137   } else {
138     Sym->Section = V.Sec;
139     if (Sym->Section->Flags & SHF_ALLOC)
140       Sym->Value = V.Val;
141     else
142       Sym->Value = V.getValue();
143   }
144 }
145 
146 static SymbolBody *findSymbol(StringRef S) {
147   switch (Config->EKind) {
148   case ELF32LEKind:
149     return Symtab<ELF32LE>::X->find(S);
150   case ELF32BEKind:
151     return Symtab<ELF32BE>::X->find(S);
152   case ELF64LEKind:
153     return Symtab<ELF64LE>::X->find(S);
154   case ELF64BEKind:
155     return Symtab<ELF64BE>::X->find(S);
156   default:
157     llvm_unreachable("unknown Config->EKind");
158   }
159 }
160 
161 static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
162   switch (Config->EKind) {
163   case ELF32LEKind:
164     return addRegular<ELF32LE>(Cmd);
165   case ELF32BEKind:
166     return addRegular<ELF32BE>(Cmd);
167   case ELF64LEKind:
168     return addRegular<ELF64LE>(Cmd);
169   case ELF64BEKind:
170     return addRegular<ELF64BE>(Cmd);
171   default:
172     llvm_unreachable("unknown Config->EKind");
173   }
174 }
175 
176 void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
177   if (Cmd->Name == ".")
178     return;
179 
180   // If a symbol was in PROVIDE(), we need to define it only when
181   // it is a referenced undefined symbol.
182   SymbolBody *B = findSymbol(Cmd->Name);
183   if (Cmd->Provide && (!B || B->isDefined()))
184     return;
185 
186   Cmd->Sym = addRegularSymbol(Cmd);
187 }
188 
189 bool SymbolAssignment::classof(const BaseCommand *C) {
190   return C->Kind == AssignmentKind;
191 }
192 
193 bool OutputSectionCommand::classof(const BaseCommand *C) {
194   return C->Kind == OutputSectionKind;
195 }
196 
197 bool InputSectionDescription::classof(const BaseCommand *C) {
198   return C->Kind == InputSectionKind;
199 }
200 
201 bool AssertCommand::classof(const BaseCommand *C) {
202   return C->Kind == AssertKind;
203 }
204 
205 bool BytesDataCommand::classof(const BaseCommand *C) {
206   return C->Kind == BytesDataKind;
207 }
208 
209 static StringRef basename(InputSectionBase *S) {
210   if (S->File)
211     return sys::path::filename(S->File->getName());
212   return "";
213 }
214 
215 bool LinkerScript::shouldKeep(InputSectionBase *S) {
216   for (InputSectionDescription *ID : Opt.KeptSections)
217     if (ID->FilePat.match(basename(S)))
218       for (SectionPattern &P : ID->SectionPatterns)
219         if (P.SectionPat.match(S->Name))
220           return true;
221   return false;
222 }
223 
224 // A helper function for the SORT() command.
225 static std::function<bool(InputSectionBase *, InputSectionBase *)>
226 getComparator(SortSectionPolicy K) {
227   switch (K) {
228   case SortSectionPolicy::Alignment:
229     return [](InputSectionBase *A, InputSectionBase *B) {
230       // ">" is not a mistake. Sections with larger alignments are placed
231       // before sections with smaller alignments in order to reduce the
232       // amount of padding necessary. This is compatible with GNU.
233       return A->Alignment > B->Alignment;
234     };
235   case SortSectionPolicy::Name:
236     return [](InputSectionBase *A, InputSectionBase *B) {
237       return A->Name < B->Name;
238     };
239   case SortSectionPolicy::Priority:
240     return [](InputSectionBase *A, InputSectionBase *B) {
241       return getPriority(A->Name) < getPriority(B->Name);
242     };
243   default:
244     llvm_unreachable("unknown sort policy");
245   }
246 }
247 
248 // A helper function for the SORT() command.
249 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
250                              ConstraintKind Kind) {
251   if (Kind == ConstraintKind::NoConstraint)
252     return true;
253 
254   bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
255     return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
256   });
257 
258   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
259          (!IsRW && Kind == ConstraintKind::ReadOnly);
260 }
261 
262 static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
263                          SortSectionPolicy K) {
264   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
265     std::stable_sort(Begin, End, getComparator(K));
266 }
267 
268 // Compute and remember which sections the InputSectionDescription matches.
269 std::vector<InputSectionBase *>
270 LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
271   std::vector<InputSectionBase *> Ret;
272 
273   // Collects all sections that satisfy constraints of Cmd.
274   for (const SectionPattern &Pat : Cmd->SectionPatterns) {
275     size_t SizeBefore = Ret.size();
276 
277     for (InputSectionBase *Sec : InputSections) {
278       if (Sec->Assigned)
279         continue;
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       StringRef Filename = basename(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(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     InputSectionBase **Begin = Ret.data() + SizeBefore;
309     InputSectionBase **End = Ret.data() + Ret.size();
310     if (Pat.SortOuter != SortSectionPolicy::None) {
311       if (Pat.SortInner == SortSectionPolicy::Default)
312         sortSections(Begin, End, Config->SortSection);
313       else
314         sortSections(Begin, End, Pat.SortInner);
315       sortSections(Begin, End, Pat.SortOuter);
316     }
317   }
318   return Ret;
319 }
320 
321 void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
322   for (InputSectionBase *S : V) {
323     S->Live = false;
324     if (S == InX::ShStrTab)
325       error("discarding .shstrtab section is not allowed");
326     discard(S->DependentSections);
327   }
328 }
329 
330 std::vector<InputSectionBase *>
331 LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
332   std::vector<InputSectionBase *> Ret;
333 
334   for (BaseCommand *Base : OutCmd.Commands) {
335     auto *Cmd = dyn_cast<InputSectionDescription>(Base);
336     if (!Cmd)
337       continue;
338 
339     Cmd->Sections = computeInputSections(Cmd);
340     Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
341   }
342 
343   return Ret;
344 }
345 
346 void LinkerScript::processCommands(OutputSectionFactory &Factory) {
347   // A symbol can be assigned before any section is mentioned in the linker
348   // script. In an DSO, the symbol values are addresses, so the only important
349   // section values are:
350   // * SHN_UNDEF
351   // * SHN_ABS
352   // * Any value meaning a regular section.
353   // To handle that, create a dummy aether section that fills the void before
354   // the linker scripts switches to another section. It has an index of one
355   // which will map to whatever the first actual section is.
356   Aether = make<OutputSection>("", 0, SHF_ALLOC);
357   Aether->SectionIndex = 1;
358   CurOutSec = Aether;
359   Dot = 0;
360 
361   for (size_t I = 0; I < Opt.Commands.size(); ++I) {
362     // Handle symbol assignments outside of any output section.
363     if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
364       addSymbol(Cmd);
365       continue;
366     }
367 
368     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
369       std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
370 
371       // The output section name `/DISCARD/' is special.
372       // Any input section assigned to it is discarded.
373       if (Cmd->Name == "/DISCARD/") {
374         discard(V);
375         continue;
376       }
377 
378       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
379       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
380       // sections satisfy a given constraint. If not, a directive is handled
381       // as if it wasn't present from the beginning.
382       //
383       // Because we'll iterate over Commands many more times, the easiest
384       // way to "make it as if it wasn't present" is to just remove it.
385       if (!matchConstraints(V, Cmd->Constraint)) {
386         for (InputSectionBase *S : V)
387           S->Assigned = false;
388         Opt.Commands.erase(Opt.Commands.begin() + I);
389         --I;
390         continue;
391       }
392 
393       // A directive may contain symbol definitions like this:
394       // ".foo : { ...; bar = .; }". Handle them.
395       for (BaseCommand *Base : Cmd->Commands)
396         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
397           addSymbol(OutCmd);
398 
399       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
400       // is given, input sections are aligned to that value, whether the
401       // given value is larger or smaller than the original section alignment.
402       if (Cmd->SubalignExpr) {
403         uint32_t Subalign = Cmd->SubalignExpr().getValue();
404         for (InputSectionBase *S : V)
405           S->Alignment = Subalign;
406       }
407 
408       // Add input sections to an output section.
409       for (InputSectionBase *S : V)
410         Factory.addInputSec(S, Cmd->Name, Cmd->Sec);
411       if (OutputSection *Sec = Cmd->Sec) {
412         assert(Sec->SectionIndex == INT_MAX);
413         Sec->SectionIndex = I;
414       }
415     }
416   }
417   CurOutSec = nullptr;
418 }
419 
420 void LinkerScript::fabricateDefaultCommands() {
421   std::vector<BaseCommand *> Commands;
422 
423   // Define start address
424   uint64_t StartAddr = Config->ImageBase + elf::getHeaderSize();
425 
426   // The Sections with -T<section> have been sorted in order of ascending
427   // address. We must lower StartAddr if the lowest -T<section address> as
428   // calls to setDot() must be monotonically increasing.
429   for (auto& KV : Config->SectionStartMap)
430     StartAddr = std::min(StartAddr, KV.second);
431 
432   Commands.push_back(
433       make<SymbolAssignment>(".", [=] { return StartAddr; }, ""));
434 
435   // For each OutputSection that needs a VA fabricate an OutputSectionCommand
436   // with an InputSectionDescription describing the InputSections
437   for (OutputSection *Sec : *OutputSections) {
438     if (!(Sec->Flags & SHF_ALLOC))
439       continue;
440 
441     auto *OSCmd = make<OutputSectionCommand>(Sec->Name);
442     OSCmd->Sec = Sec;
443 
444     // Prefer user supplied address over additional alignment constraint
445     auto I = Config->SectionStartMap.find(Sec->Name);
446     if (I != Config->SectionStartMap.end())
447       Commands.push_back(
448           make<SymbolAssignment>(".", [=] { return I->second; }, ""));
449     else if (Sec->PageAlign)
450       OSCmd->AddrExpr = [=] {
451         return alignTo(Script->getDot(), Config->MaxPageSize);
452       };
453 
454     Commands.push_back(OSCmd);
455     if (Sec->Sections.size()) {
456       auto *ISD = make<InputSectionDescription>("");
457       OSCmd->Commands.push_back(ISD);
458       for (InputSection *ISec : Sec->Sections) {
459         ISD->Sections.push_back(ISec);
460         ISec->Assigned = true;
461       }
462     }
463   }
464   // SECTIONS commands run before other non SECTIONS commands
465   Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end());
466   Opt.Commands = std::move(Commands);
467 }
468 
469 // Add sections that didn't match any sections command.
470 void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
471   for (InputSectionBase *S : InputSections) {
472     if (!S->Live || S->OutSec)
473       continue;
474     StringRef Name = getOutputSectionName(S->Name);
475     auto I = std::find_if(
476         Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
477           if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
478             return Cmd->Name == Name;
479           return false;
480         });
481     if (I == Opt.Commands.end()) {
482       Factory.addInputSec(S, Name);
483     } else {
484       auto *Cmd = cast<OutputSectionCommand>(*I);
485       Factory.addInputSec(S, Name, Cmd->Sec);
486       if (OutputSection *Sec = Cmd->Sec) {
487         unsigned Index = std::distance(Opt.Commands.begin(), I);
488         assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
489         Sec->SectionIndex = Index;
490       }
491       auto *ISD = make<InputSectionDescription>("");
492       ISD->Sections.push_back(S);
493       Cmd->Commands.push_back(ISD);
494     }
495   }
496 }
497 
498 uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
499   bool IsTbss = (CurOutSec->Flags & SHF_TLS) && CurOutSec->Type == SHT_NOBITS;
500   uint64_t Start = IsTbss ? Dot + ThreadBssOffset : Dot;
501   Start = alignTo(Start, Align);
502   uint64_t End = Start + Size;
503 
504   if (IsTbss)
505     ThreadBssOffset = End - Dot;
506   else
507     Dot = End;
508   return End;
509 }
510 
511 void LinkerScript::output(InputSection *S) {
512   uint64_t Pos = advance(S->getSize(), S->Alignment);
513   S->OutSecOff = Pos - S->getSize() - CurOutSec->Addr;
514 
515   // Update output section size after adding each section. This is so that
516   // SIZEOF works correctly in the case below:
517   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
518   CurOutSec->Size = Pos - CurOutSec->Addr;
519 
520   // If there is a memory region associated with this input section, then
521   // place the section in that region and update the region index.
522   if (CurMemRegion) {
523     CurMemRegion->Offset += CurOutSec->Size;
524     uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
525     if (CurSize > CurMemRegion->Length) {
526       uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
527       error("section '" + CurOutSec->Name + "' will not fit in region '" +
528             CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
529             " bytes");
530     }
531   }
532 }
533 
534 void LinkerScript::switchTo(OutputSection *Sec) {
535   if (CurOutSec == Sec)
536     return;
537 
538   CurOutSec = Sec;
539   CurOutSec->Addr = advance(0, CurOutSec->Alignment);
540 
541   // If neither AT nor AT> is specified for an allocatable section, the linker
542   // will set the LMA such that the difference between VMA and LMA for the
543   // section is the same as the preceding output section in the same region
544   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
545   if (LMAOffset)
546     CurOutSec->LMAOffset = LMAOffset();
547 }
548 
549 void LinkerScript::process(BaseCommand &Base) {
550   // This handles the assignments to symbol or to the dot.
551   if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
552     assignSymbol(Cmd, true);
553     return;
554   }
555 
556   // Handle BYTE(), SHORT(), LONG(), or QUAD().
557   if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
558     Cmd->Offset = Dot - CurOutSec->Addr;
559     Dot += Cmd->Size;
560     CurOutSec->Size = Dot - CurOutSec->Addr;
561     return;
562   }
563 
564   // Handle ASSERT().
565   if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
566     Cmd->Expression();
567     return;
568   }
569 
570   // Handle a single input section description command.
571   // It calculates and assigns the offsets for each section and also
572   // updates the output section size.
573   auto &Cmd = cast<InputSectionDescription>(Base);
574   for (InputSectionBase *Sec : Cmd.Sections) {
575     // We tentatively added all synthetic sections at the beginning and removed
576     // empty ones afterwards (because there is no way to know whether they were
577     // going be empty or not other than actually running linker scripts.)
578     // We need to ignore remains of empty sections.
579     if (auto *S = dyn_cast<SyntheticSection>(Sec))
580       if (S->empty())
581         continue;
582 
583     if (!Sec->Live)
584       continue;
585     assert(CurOutSec == Sec->OutSec);
586     output(cast<InputSection>(Sec));
587   }
588 }
589 
590 // This function searches for a memory region to place the given output
591 // section in. If found, a pointer to the appropriate memory region is
592 // returned. Otherwise, a nullptr is returned.
593 MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) {
594   // If a memory region name was specified in the output section command,
595   // then try to find that region first.
596   if (!Cmd->MemoryRegionName.empty()) {
597     auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
598     if (It != Opt.MemoryRegions.end())
599       return &It->second;
600     error("memory region '" + Cmd->MemoryRegionName + "' not declared");
601     return nullptr;
602   }
603 
604   // If at least one memory region is defined, all sections must
605   // belong to some memory region. Otherwise, we don't need to do
606   // anything for memory regions.
607   if (Opt.MemoryRegions.empty())
608     return nullptr;
609 
610   OutputSection *Sec = Cmd->Sec;
611   // See if a region can be found by matching section flags.
612   for (auto &Pair : Opt.MemoryRegions) {
613     MemoryRegion &M = Pair.second;
614     if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
615       return &M;
616   }
617 
618   // Otherwise, no suitable region was found.
619   if (Sec->Flags & SHF_ALLOC)
620     error("no memory region specified for section '" + Sec->Name + "'");
621   return nullptr;
622 }
623 
624 // This function assigns offsets to input sections and an output section
625 // for a single sections command (e.g. ".text { *(.text); }").
626 void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
627   OutputSection *Sec = Cmd->Sec;
628   if (!Sec)
629     return;
630 
631   if (Cmd->AddrExpr && (Sec->Flags & SHF_ALLOC))
632     setDot(Cmd->AddrExpr, Cmd->Location, false);
633 
634   if (Cmd->LMAExpr) {
635     uint64_t D = Dot;
636     LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
637   }
638 
639   CurMemRegion = Cmd->MemRegion;
640   if (CurMemRegion)
641     Dot = CurMemRegion->Offset;
642   switchTo(Sec);
643 
644   // We do not support custom layout for compressed debug sectons.
645   // At this point we already know their size and have compressed content.
646   if (CurOutSec->Flags & SHF_COMPRESSED)
647     return;
648 
649   for (BaseCommand *C : Cmd->Commands)
650     process(*C);
651 }
652 
653 void LinkerScript::removeEmptyCommands() {
654   // It is common practice to use very generic linker scripts. So for any
655   // given run some of the output sections in the script will be empty.
656   // We could create corresponding empty output sections, but that would
657   // clutter the output.
658   // We instead remove trivially empty sections. The bfd linker seems even
659   // more aggressive at removing them.
660   auto Pos = std::remove_if(
661       Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
662         if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
663           return std::find(OutputSections->begin(), OutputSections->end(),
664                            Cmd->Sec) == OutputSections->end();
665         return false;
666       });
667   Opt.Commands.erase(Pos, Opt.Commands.end());
668 }
669 
670 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
671   for (BaseCommand *Base : Cmd.Commands)
672     if (!isa<InputSectionDescription>(*Base))
673       return false;
674   return true;
675 }
676 
677 void LinkerScript::adjustSectionsBeforeSorting() {
678   // If the output section contains only symbol assignments, create a
679   // corresponding output section. The bfd linker seems to only create them if
680   // '.' is assigned to, but creating these section should not have any bad
681   // consequeces and gives us a section to put the symbol in.
682   uint64_t Flags = SHF_ALLOC;
683   uint32_t Type = SHT_PROGBITS;
684 
685   for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
686     auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
687     if (!Cmd)
688       continue;
689     if (OutputSection *Sec = Cmd->Sec) {
690       Flags = Sec->Flags;
691       Type = Sec->Type;
692       continue;
693     }
694 
695     if (isAllSectionDescription(*Cmd))
696       continue;
697 
698     auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
699     OutSec->SectionIndex = I;
700     OutputSections->push_back(OutSec);
701     Cmd->Sec = OutSec;
702   }
703 }
704 
705 void LinkerScript::adjustSectionsAfterSorting() {
706   placeOrphanSections();
707 
708   // Try and find an appropriate memory region to assign offsets in.
709   for (BaseCommand *Base : Opt.Commands) {
710     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) {
711       Cmd->MemRegion = findMemoryRegion(Cmd);
712       // Handle align (e.g. ".foo : ALIGN(16) { ... }").
713       if (Cmd->AlignExpr)
714 	Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue());
715     }
716   }
717 
718   // If output section command doesn't specify any segments,
719   // and we haven't previously assigned any section to segment,
720   // then we simply assign section to the very first load segment.
721   // Below is an example of such linker script:
722   // PHDRS { seg PT_LOAD; }
723   // SECTIONS { .aaa : { *(.aaa) } }
724   std::vector<StringRef> DefPhdrs;
725   auto FirstPtLoad =
726       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
727                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
728   if (FirstPtLoad != Opt.PhdrsCommands.end())
729     DefPhdrs.push_back(FirstPtLoad->Name);
730 
731   // Walk the commands and propagate the program headers to commands that don't
732   // explicitly specify them.
733   for (BaseCommand *Base : Opt.Commands) {
734     auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
735     if (!Cmd)
736       continue;
737 
738     if (Cmd->Phdrs.empty())
739       Cmd->Phdrs = DefPhdrs;
740     else
741       DefPhdrs = Cmd->Phdrs;
742   }
743 
744   removeEmptyCommands();
745 }
746 
747 // When placing orphan sections, we want to place them after symbol assignments
748 // so that an orphan after
749 //   begin_foo = .;
750 //   foo : { *(foo) }
751 //   end_foo = .;
752 // doesn't break the intended meaning of the begin/end symbols.
753 // We don't want to go over sections since Writer<ELFT>::sortSections is the
754 // one in charge of deciding the order of the sections.
755 // We don't want to go over alignments, since doing so in
756 //  rx_sec : { *(rx_sec) }
757 //  . = ALIGN(0x1000);
758 //  /* The RW PT_LOAD starts here*/
759 //  rw_sec : { *(rw_sec) }
760 // would mean that the RW PT_LOAD would become unaligned.
761 static bool shouldSkip(BaseCommand *Cmd) {
762   if (isa<OutputSectionCommand>(Cmd))
763     return false;
764   if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
765     return Assign->Name != ".";
766   return true;
767 }
768 
769 // Orphan sections are sections present in the input files which are
770 // not explicitly placed into the output file by the linker script.
771 //
772 // When the control reaches this function, Opt.Commands contains
773 // output section commands for non-orphan sections only. This function
774 // adds new elements for orphan sections so that all sections are
775 // explicitly handled by Opt.Commands.
776 //
777 // Writer<ELFT>::sortSections has already sorted output sections.
778 // What we need to do is to scan OutputSections vector and
779 // Opt.Commands in parallel to find orphan sections. If there is an
780 // output section that doesn't have a corresponding entry in
781 // Opt.Commands, we will insert a new entry to Opt.Commands.
782 //
783 // There is some ambiguity as to where exactly a new entry should be
784 // inserted, because Opt.Commands contains not only output section
785 // commands but also other types of commands such as symbol assignment
786 // expressions. There's no correct answer here due to the lack of the
787 // formal specification of the linker script. We use heuristics to
788 // determine whether a new output command should be added before or
789 // after another commands. For the details, look at shouldSkip
790 // function.
791 void LinkerScript::placeOrphanSections() {
792   // The OutputSections are already in the correct order.
793   // This loops creates or moves commands as needed so that they are in the
794   // correct order.
795   int CmdIndex = 0;
796 
797   // As a horrible special case, skip the first . assignment if it is before any
798   // section. We do this because it is common to set a load address by starting
799   // the script with ". = 0xabcd" and the expectation is that every section is
800   // after that.
801   auto FirstSectionOrDotAssignment =
802       std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
803                    [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
804   if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
805     CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
806     if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
807       ++CmdIndex;
808   }
809 
810   for (OutputSection *Sec : *OutputSections) {
811     StringRef Name = Sec->Name;
812 
813     // Find the last spot where we can insert a command and still get the
814     // correct result.
815     auto CmdIter = Opt.Commands.begin() + CmdIndex;
816     auto E = Opt.Commands.end();
817     while (CmdIter != E && shouldSkip(*CmdIter)) {
818       ++CmdIter;
819       ++CmdIndex;
820     }
821 
822     // If there is no command corresponding to this output section,
823     // create one and put a InputSectionDescription in it so that both
824     // representations agree on which input sections to use.
825     auto Pos = std::find_if(CmdIter, E, [&](BaseCommand *Base) {
826       auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
827       return Cmd && Cmd->Name == Name;
828     });
829     if (Pos == E) {
830       auto *Cmd = make<OutputSectionCommand>(Name);
831       Opt.Commands.insert(CmdIter, Cmd);
832       ++CmdIndex;
833 
834       Cmd->Sec = Sec;
835       auto *ISD = make<InputSectionDescription>("");
836       for (InputSection *IS : Sec->Sections)
837         ISD->Sections.push_back(IS);
838       Cmd->Commands.push_back(ISD);
839 
840       continue;
841     }
842 
843     // Continue from where we found it.
844     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
845   }
846 }
847 
848 void LinkerScript::processNonSectionCommands() {
849   for (BaseCommand *Base : Opt.Commands) {
850     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
851       assignSymbol(Cmd, false);
852     else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
853       Cmd->Expression();
854   }
855 }
856 
857 // Do a last effort at synchronizing the linker script "AST" and the section
858 // list. This is needed to account for last minute changes, like adding a
859 // .ARM.exidx terminator and sorting SHF_LINK_ORDER sections.
860 //
861 // FIXME: We should instead create the "AST" earlier and the above changes would
862 // be done directly in the "AST".
863 //
864 // This can only handle new sections being added and sections being reordered.
865 void LinkerScript::synchronize() {
866   for (BaseCommand *Base : Opt.Commands) {
867     auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
868     if (!Cmd)
869       continue;
870     ArrayRef<InputSection *> Sections = Cmd->Sec->Sections;
871     std::vector<InputSectionBase **> ScriptSections;
872     DenseSet<InputSectionBase *> ScriptSectionsSet;
873     for (BaseCommand *Base : Cmd->Commands) {
874       auto *ISD = dyn_cast<InputSectionDescription>(Base);
875       if (!ISD)
876         continue;
877       for (InputSectionBase *&IS : ISD->Sections) {
878         if (IS->Live) {
879           ScriptSections.push_back(&IS);
880           ScriptSectionsSet.insert(IS);
881         }
882       }
883     }
884     std::vector<InputSectionBase *> Missing;
885     for (InputSection *IS : Sections)
886       if (!ScriptSectionsSet.count(IS))
887         Missing.push_back(IS);
888     if (!Missing.empty()) {
889       auto ISD = make<InputSectionDescription>("");
890       ISD->Sections = Missing;
891       Cmd->Commands.push_back(ISD);
892       for (InputSectionBase *&IS : ISD->Sections)
893         if (IS->Live)
894           ScriptSections.push_back(&IS);
895     }
896     assert(ScriptSections.size() == Sections.size());
897     for (int I = 0, N = Sections.size(); I < N; ++I)
898       *ScriptSections[I] = Sections[I];
899   }
900 }
901 
902 static bool allocateHeaders(std::vector<PhdrEntry> &Phdrs,
903                             ArrayRef<OutputSection *> OutputSections,
904                             uint64_t Min) {
905   auto FirstPTLoad =
906       std::find_if(Phdrs.begin(), Phdrs.end(),
907                    [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
908   if (FirstPTLoad == Phdrs.end())
909     return false;
910 
911   uint64_t HeaderSize = getHeaderSize();
912   if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
913     Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
914     Out::ElfHeader->Addr = Min;
915     Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
916     return true;
917   }
918 
919   assert(FirstPTLoad->First == Out::ElfHeader);
920   OutputSection *ActualFirst = nullptr;
921   for (OutputSection *Sec : OutputSections) {
922     if (Sec->FirstInPtLoad == Out::ElfHeader) {
923       ActualFirst = Sec;
924       break;
925     }
926   }
927   if (ActualFirst) {
928     for (OutputSection *Sec : OutputSections)
929       if (Sec->FirstInPtLoad == Out::ElfHeader)
930         Sec->FirstInPtLoad = ActualFirst;
931     FirstPTLoad->First = ActualFirst;
932   } else {
933     Phdrs.erase(FirstPTLoad);
934   }
935 
936   auto PhdrI = std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry &E) {
937     return E.p_type == PT_PHDR;
938   });
939   if (PhdrI != Phdrs.end())
940     Phdrs.erase(PhdrI);
941   return false;
942 }
943 
944 void LinkerScript::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
945   // Assign addresses as instructed by linker script SECTIONS sub-commands.
946   Dot = 0;
947   ErrorOnMissingSection = true;
948   switchTo(Aether);
949 
950   for (BaseCommand *Base : Opt.Commands) {
951     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
952       assignSymbol(Cmd, false);
953       continue;
954     }
955 
956     if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
957       Cmd->Expression();
958       continue;
959     }
960 
961     auto *Cmd = cast<OutputSectionCommand>(Base);
962     assignOffsets(Cmd);
963   }
964 
965   uint64_t MinVA = std::numeric_limits<uint64_t>::max();
966   for (OutputSection *Sec : *OutputSections) {
967     if (Sec->Flags & SHF_ALLOC)
968       MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
969     else
970       Sec->Addr = 0;
971   }
972 
973   allocateHeaders(Phdrs, *OutputSections, MinVA);
974 }
975 
976 // Creates program headers as instructed by PHDRS linker script command.
977 std::vector<PhdrEntry> LinkerScript::createPhdrs() {
978   std::vector<PhdrEntry> Ret;
979 
980   // Process PHDRS and FILEHDR keywords because they are not
981   // real output sections and cannot be added in the following loop.
982   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
983     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
984     PhdrEntry &Phdr = Ret.back();
985 
986     if (Cmd.HasFilehdr)
987       Phdr.add(Out::ElfHeader);
988     if (Cmd.HasPhdrs)
989       Phdr.add(Out::ProgramHeaders);
990 
991     if (Cmd.LMAExpr) {
992       Phdr.p_paddr = Cmd.LMAExpr().getValue();
993       Phdr.HasLMA = true;
994     }
995   }
996 
997   // Add output sections to program headers.
998   for (OutputSection *Sec : *OutputSections) {
999     if (!(Sec->Flags & SHF_ALLOC))
1000       break;
1001 
1002     // Assign headers specified by linker script
1003     for (size_t Id : getPhdrIndices(Sec->Name)) {
1004       Ret[Id].add(Sec);
1005       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
1006         Ret[Id].p_flags |= Sec->getPhdrFlags();
1007     }
1008   }
1009   return Ret;
1010 }
1011 
1012 bool LinkerScript::ignoreInterpSection() {
1013   // Ignore .interp section in case we have PHDRS specification
1014   // and PT_INTERP isn't listed.
1015   if (Opt.PhdrsCommands.empty())
1016     return false;
1017   for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
1018     if (Cmd.Type == PT_INTERP)
1019       return false;
1020   return true;
1021 }
1022 
1023 Optional<uint32_t> LinkerScript::getFiller(StringRef Name) {
1024   for (BaseCommand *Base : Opt.Commands)
1025     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1026       if (Cmd->Name == Name)
1027         return Cmd->Filler;
1028   return None;
1029 }
1030 
1031 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
1032   if (Size == 1)
1033     *Buf = Data;
1034   else if (Size == 2)
1035     write16(Buf, Data, Config->Endianness);
1036   else if (Size == 4)
1037     write32(Buf, Data, Config->Endianness);
1038   else if (Size == 8)
1039     write64(Buf, Data, Config->Endianness);
1040   else
1041     llvm_unreachable("unsupported Size argument");
1042 }
1043 
1044 void LinkerScript::writeDataBytes(OutputSection *Sec, uint8_t *Buf) {
1045   auto I = std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
1046                         [=](BaseCommand *Base) {
1047                           if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1048                             if (Cmd->Sec == Sec)
1049                               return true;
1050                           return false;
1051                         });
1052   if (I == Opt.Commands.end())
1053     return;
1054   auto *Cmd = cast<OutputSectionCommand>(*I);
1055   for (BaseCommand *Base : Cmd->Commands)
1056     if (auto *Data = dyn_cast<BytesDataCommand>(Base))
1057       writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
1058 }
1059 
1060 bool LinkerScript::hasLMA(StringRef Name) {
1061   for (BaseCommand *Base : Opt.Commands)
1062     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
1063       if (Cmd->LMAExpr && Cmd->Name == Name)
1064         return true;
1065   return false;
1066 }
1067 
1068 ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
1069   if (S == ".")
1070     return {CurOutSec, Dot - CurOutSec->Addr};
1071   if (SymbolBody *B = findSymbol(S)) {
1072     if (auto *D = dyn_cast<DefinedRegular>(B))
1073       return {D->Section, D->Value};
1074     if (auto *C = dyn_cast<DefinedCommon>(B))
1075       return {InX::Common, C->Offset};
1076   }
1077   error(Loc + ": symbol not found: " + S);
1078   return 0;
1079 }
1080 
1081 bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
1082 
1083 // Returns indices of ELF headers containing specific section, identified
1084 // by Name. Each index is a zero based number of ELF header listed within
1085 // PHDRS {} script block.
1086 std::vector<size_t> LinkerScript::getPhdrIndices(StringRef SectionName) {
1087   for (BaseCommand *Base : Opt.Commands) {
1088     auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
1089     if (!Cmd || Cmd->Name != SectionName)
1090       continue;
1091 
1092     std::vector<size_t> Ret;
1093     for (StringRef PhdrName : Cmd->Phdrs)
1094       Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
1095     return Ret;
1096   }
1097   return {};
1098 }
1099 
1100 size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
1101   size_t I = 0;
1102   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1103     if (Cmd.Name == PhdrName)
1104       return I;
1105     ++I;
1106   }
1107   error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
1108   return 0;
1109 }
1110