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 "Driver.h"
17 #include "InputSection.h"
18 #include "Memory.h"
19 #include "OutputSections.h"
20 #include "ScriptLexer.h"
21 #include "Strings.h"
22 #include "SymbolTable.h"
23 #include "Symbols.h"
24 #include "SyntheticSections.h"
25 #include "Target.h"
26 #include "Writer.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/Endian.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/Path.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <cstddef>
41 #include <cstdint>
42 #include <iterator>
43 #include <limits>
44 #include <memory>
45 #include <string>
46 #include <tuple>
47 #include <vector>
48 
49 using namespace llvm;
50 using namespace llvm::ELF;
51 using namespace llvm::object;
52 using namespace llvm::support::endian;
53 using namespace lld;
54 using namespace lld::elf;
55 
56 uint64_t ExprValue::getValue() const {
57   if (Sec)
58     return Sec->getOffset(Val) + Sec->getOutputSection()->Addr;
59   return Val;
60 }
61 
62 uint64_t ExprValue::getSecAddr() const {
63   if (Sec)
64     return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
65   return 0;
66 }
67 
68 // Some operations only support one non absolute value. Move the
69 // absolute one to the right hand side for convenience.
70 static void moveAbsRight(ExprValue &A, ExprValue &B) {
71   if (A.isAbsolute())
72     std::swap(A, B);
73   if (!B.isAbsolute())
74     error("At least one side of the expression must be absolute");
75 }
76 
77 static ExprValue add(ExprValue A, ExprValue B) {
78   moveAbsRight(A, B);
79   return {A.Sec, A.ForceAbsolute, A.Val + B.getValue()};
80 }
81 static ExprValue sub(ExprValue A, ExprValue B) {
82   return {A.Sec, A.Val - B.getValue()};
83 }
84 static ExprValue mul(ExprValue A, ExprValue B) {
85   return A.getValue() * B.getValue();
86 }
87 static ExprValue div(ExprValue A, ExprValue B) {
88   if (uint64_t BV = B.getValue())
89     return A.getValue() / BV;
90   error("division by zero");
91   return 0;
92 }
93 static ExprValue leftShift(ExprValue A, ExprValue B) {
94   return A.getValue() << B.getValue();
95 }
96 static ExprValue rightShift(ExprValue A, ExprValue B) {
97   return A.getValue() >> B.getValue();
98 }
99 static ExprValue bitAnd(ExprValue A, ExprValue B) {
100   moveAbsRight(A, B);
101   return {A.Sec, A.ForceAbsolute,
102           (A.getValue() & B.getValue()) - A.getSecAddr()};
103 }
104 static ExprValue bitOr(ExprValue A, ExprValue B) {
105   moveAbsRight(A, B);
106   return {A.Sec, A.ForceAbsolute,
107           (A.getValue() | B.getValue()) - A.getSecAddr()};
108 }
109 static ExprValue bitNot(ExprValue A) { return ~A.getValue(); }
110 static ExprValue minus(ExprValue A) { return -A.getValue(); }
111 
112 LinkerScriptBase *elf::Script;
113 ScriptConfiguration *elf::ScriptConfig;
114 
115 template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
116   Symbol *Sym;
117   uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
118   std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
119       Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
120       /*File*/ nullptr);
121   Sym->Binding = STB_GLOBAL;
122   ExprValue Value = Cmd->Expression();
123   SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
124   replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
125                               STT_NOTYPE, 0, 0, Sec, nullptr);
126   return Sym->body();
127 }
128 
129 static bool isUnderSysroot(StringRef Path) {
130   if (Config->Sysroot == "")
131     return false;
132   for (; !Path.empty(); Path = sys::path::parent_path(Path))
133     if (sys::fs::equivalent(Config->Sysroot, Path))
134       return true;
135   return false;
136 }
137 
138 OutputSection *LinkerScriptBase::getOutputSection(const Twine &Loc,
139                                                   StringRef Name) {
140   static OutputSection FakeSec("", 0, 0);
141 
142   for (OutputSection *Sec : *OutputSections)
143     if (Sec->Name == Name)
144       return Sec;
145 
146   if (ErrorOnMissingSection)
147     error(Loc + ": undefined section " + Name);
148   return &FakeSec;
149 }
150 
151 // This function is essentially the same as getOutputSection(Name)->Size,
152 // but it won't print out an error message if a given section is not found.
153 //
154 // Linker script does not create an output section if its content is empty.
155 // We want to allow SIZEOF(.foo) where .foo is a section which happened to
156 // be empty. That is why this function is different from getOutputSection().
157 uint64_t LinkerScriptBase::getOutputSectionSize(StringRef Name) {
158   for (OutputSection *Sec : *OutputSections)
159     if (Sec->Name == Name)
160       return Sec->Size;
161   return 0;
162 }
163 
164 void LinkerScriptBase::setDot(Expr E, const Twine &Loc, bool InSec) {
165   uint64_t Val = E().getValue();
166   if (Val < Dot) {
167     if (InSec)
168       error(Loc + ": unable to move location counter backward for: " +
169             CurOutSec->Name);
170     else
171       error(Loc + ": unable to move location counter backward");
172   }
173   Dot = Val;
174   // Update to location counter means update to section size.
175   if (InSec)
176     CurOutSec->Size = Dot - CurOutSec->Addr;
177 }
178 
179 // Sets value of a symbol. Two kinds of symbols are processed: synthetic
180 // symbols, whose value is an offset from beginning of section and regular
181 // symbols whose value is absolute.
182 void LinkerScriptBase::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
183   if (Cmd->Name == ".") {
184     setDot(Cmd->Expression, Cmd->Location, InSec);
185     return;
186   }
187 
188   if (!Cmd->Sym)
189     return;
190 
191   auto *Sym = cast<DefinedRegular>(Cmd->Sym);
192   ExprValue V = Cmd->Expression();
193   if (V.isAbsolute()) {
194     Sym->Value = V.getValue();
195   } else {
196     Sym->Section = V.Sec;
197     if (Sym->Section->Flags & SHF_ALLOC)
198       Sym->Value = V.Val;
199     else
200       Sym->Value = V.getValue();
201   }
202 }
203 
204 static SymbolBody *findSymbol(StringRef S) {
205   switch (Config->EKind) {
206   case ELF32LEKind:
207     return Symtab<ELF32LE>::X->find(S);
208   case ELF32BEKind:
209     return Symtab<ELF32BE>::X->find(S);
210   case ELF64LEKind:
211     return Symtab<ELF64LE>::X->find(S);
212   case ELF64BEKind:
213     return Symtab<ELF64BE>::X->find(S);
214   default:
215     llvm_unreachable("unknown Config->EKind");
216   }
217 }
218 
219 static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
220   switch (Config->EKind) {
221   case ELF32LEKind:
222     return addRegular<ELF32LE>(Cmd);
223   case ELF32BEKind:
224     return addRegular<ELF32BE>(Cmd);
225   case ELF64LEKind:
226     return addRegular<ELF64LE>(Cmd);
227   case ELF64BEKind:
228     return addRegular<ELF64BE>(Cmd);
229   default:
230     llvm_unreachable("unknown Config->EKind");
231   }
232 }
233 
234 void LinkerScriptBase::addSymbol(SymbolAssignment *Cmd) {
235   if (Cmd->Name == ".")
236     return;
237 
238   // If a symbol was in PROVIDE(), we need to define it only when
239   // it is a referenced undefined symbol.
240   SymbolBody *B = findSymbol(Cmd->Name);
241   if (Cmd->Provide && (!B || B->isDefined()))
242     return;
243 
244   Cmd->Sym = addRegularSymbol(Cmd);
245 }
246 
247 bool SymbolAssignment::classof(const BaseCommand *C) {
248   return C->Kind == AssignmentKind;
249 }
250 
251 bool OutputSectionCommand::classof(const BaseCommand *C) {
252   return C->Kind == OutputSectionKind;
253 }
254 
255 bool InputSectionDescription::classof(const BaseCommand *C) {
256   return C->Kind == InputSectionKind;
257 }
258 
259 bool AssertCommand::classof(const BaseCommand *C) {
260   return C->Kind == AssertKind;
261 }
262 
263 bool BytesDataCommand::classof(const BaseCommand *C) {
264   return C->Kind == BytesDataKind;
265 }
266 
267 static StringRef basename(InputSectionBase *S) {
268   if (S->File)
269     return sys::path::filename(S->File->getName());
270   return "";
271 }
272 
273 bool LinkerScriptBase::shouldKeep(InputSectionBase *S) {
274   for (InputSectionDescription *ID : Opt.KeptSections)
275     if (ID->FilePat.match(basename(S)))
276       for (SectionPattern &P : ID->SectionPatterns)
277         if (P.SectionPat.match(S->Name))
278           return true;
279   return false;
280 }
281 
282 static bool comparePriority(InputSectionBase *A, InputSectionBase *B) {
283   return getPriority(A->Name) < getPriority(B->Name);
284 }
285 
286 static bool compareName(InputSectionBase *A, InputSectionBase *B) {
287   return A->Name < B->Name;
288 }
289 
290 static bool compareAlignment(InputSectionBase *A, InputSectionBase *B) {
291   // ">" is not a mistake. Larger alignments are placed before smaller
292   // alignments in order to reduce the amount of padding necessary.
293   // This is compatible with GNU.
294   return A->Alignment > B->Alignment;
295 }
296 
297 static std::function<bool(InputSectionBase *, InputSectionBase *)>
298 getComparator(SortSectionPolicy K) {
299   switch (K) {
300   case SortSectionPolicy::Alignment:
301     return compareAlignment;
302   case SortSectionPolicy::Name:
303     return compareName;
304   case SortSectionPolicy::Priority:
305     return comparePriority;
306   default:
307     llvm_unreachable("unknown sort policy");
308   }
309 }
310 
311 static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
312                              ConstraintKind Kind) {
313   if (Kind == ConstraintKind::NoConstraint)
314     return true;
315   bool IsRW = llvm::any_of(Sections, [=](InputSectionBase *Sec2) {
316     auto *Sec = static_cast<InputSectionBase *>(Sec2);
317     return Sec->Flags & SHF_WRITE;
318   });
319   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
320          (!IsRW && Kind == ConstraintKind::ReadOnly);
321 }
322 
323 static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
324                          SortSectionPolicy K) {
325   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
326     std::stable_sort(Begin, End, getComparator(K));
327 }
328 
329 // Compute and remember which sections the InputSectionDescription matches.
330 void LinkerScriptBase::computeInputSections(InputSectionDescription *I) {
331   // Collects all sections that satisfy constraints of I
332   // and attach them to I.
333   for (SectionPattern &Pat : I->SectionPatterns) {
334     size_t SizeBefore = I->Sections.size();
335 
336     for (InputSectionBase *S : InputSections) {
337       if (S->Assigned)
338         continue;
339       // For -emit-relocs we have to ignore entries like
340       //   .rela.dyn : { *(.rela.data) }
341       // which are common because they are in the default bfd script.
342       if (S->Type == SHT_REL || S->Type == SHT_RELA)
343         continue;
344 
345       StringRef Filename = basename(S);
346       if (!I->FilePat.match(Filename) || Pat.ExcludedFilePat.match(Filename))
347         continue;
348       if (!Pat.SectionPat.match(S->Name))
349         continue;
350       I->Sections.push_back(S);
351       S->Assigned = true;
352     }
353 
354     // Sort sections as instructed by SORT-family commands and --sort-section
355     // option. Because SORT-family commands can be nested at most two depth
356     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
357     // line option is respected even if a SORT command is given, the exact
358     // behavior we have here is a bit complicated. Here are the rules.
359     //
360     // 1. If two SORT commands are given, --sort-section is ignored.
361     // 2. If one SORT command is given, and if it is not SORT_NONE,
362     //    --sort-section is handled as an inner SORT command.
363     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
364     // 4. If no SORT command is given, sort according to --sort-section.
365     InputSectionBase **Begin = I->Sections.data() + SizeBefore;
366     InputSectionBase **End = I->Sections.data() + I->Sections.size();
367     if (Pat.SortOuter != SortSectionPolicy::None) {
368       if (Pat.SortInner == SortSectionPolicy::Default)
369         sortSections(Begin, End, Config->SortSection);
370       else
371         sortSections(Begin, End, Pat.SortInner);
372       sortSections(Begin, End, Pat.SortOuter);
373     }
374   }
375 }
376 
377 void LinkerScriptBase::discard(ArrayRef<InputSectionBase *> V) {
378   for (InputSectionBase *S : V) {
379     S->Live = false;
380     if (S == InX::ShStrTab)
381       error("discarding .shstrtab section is not allowed");
382     discard(S->DependentSections);
383   }
384 }
385 
386 std::vector<InputSectionBase *>
387 LinkerScriptBase::createInputSectionList(OutputSectionCommand &OutCmd) {
388   std::vector<InputSectionBase *> Ret;
389 
390   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
391     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
392     if (!Cmd)
393       continue;
394     computeInputSections(Cmd);
395     for (InputSectionBase *S : Cmd->Sections)
396       Ret.push_back(static_cast<InputSectionBase *>(S));
397   }
398 
399   return Ret;
400 }
401 
402 void LinkerScriptBase::processCommands(OutputSectionFactory &Factory) {
403   // A symbol can be assigned before any section is mentioned in the linker
404   // script. In an DSO, the symbol values are addresses, so the only important
405   // section values are:
406   // * SHN_UNDEF
407   // * SHN_ABS
408   // * Any value meaning a regular section.
409   // To handle that, create a dummy aether section that fills the void before
410   // the linker scripts switches to another section. It has an index of one
411   // which will map to whatever the first actual section is.
412   Aether = make<OutputSection>("", 0, SHF_ALLOC);
413   Aether->SectionIndex = 1;
414   CurOutSec = Aether;
415   Dot = 0;
416 
417   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
418     auto Iter = Opt.Commands.begin() + I;
419     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
420 
421     // Handle symbol assignments outside of any output section.
422     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
423       addSymbol(Cmd);
424       continue;
425     }
426 
427     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
428       std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
429 
430       // The output section name `/DISCARD/' is special.
431       // Any input section assigned to it is discarded.
432       if (Cmd->Name == "/DISCARD/") {
433         discard(V);
434         continue;
435       }
436 
437       // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
438       // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
439       // sections satisfy a given constraint. If not, a directive is handled
440       // as if it wasn't present from the beginning.
441       //
442       // Because we'll iterate over Commands many more times, the easiest
443       // way to "make it as if it wasn't present" is to just remove it.
444       if (!matchConstraints(V, Cmd->Constraint)) {
445         for (InputSectionBase *S : V)
446           S->Assigned = false;
447         Opt.Commands.erase(Iter);
448         --I;
449         continue;
450       }
451 
452       // A directive may contain symbol definitions like this:
453       // ".foo : { ...; bar = .; }". Handle them.
454       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
455         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
456           addSymbol(OutCmd);
457 
458       // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
459       // is given, input sections are aligned to that value, whether the
460       // given value is larger or smaller than the original section alignment.
461       if (Cmd->SubalignExpr) {
462         uint32_t Subalign = Cmd->SubalignExpr().getValue();
463         for (InputSectionBase *S : V)
464           S->Alignment = Subalign;
465       }
466 
467       // Add input sections to an output section.
468       for (InputSectionBase *S : V)
469         Factory.addInputSec(S, Cmd->Name);
470     }
471   }
472   CurOutSec = nullptr;
473 }
474 
475 // Add sections that didn't match any sections command.
476 void LinkerScriptBase::addOrphanSections(OutputSectionFactory &Factory) {
477   for (InputSectionBase *S : InputSections)
478     if (S->Live && !S->OutSec)
479       Factory.addInputSec(S, getOutputSectionName(S->Name));
480 }
481 
482 static bool isTbss(OutputSection *Sec) {
483   return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
484 }
485 
486 void LinkerScriptBase::output(InputSection *S) {
487   if (!AlreadyOutputIS.insert(S).second)
488     return;
489   bool IsTbss = isTbss(CurOutSec);
490 
491   uint64_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
492   Pos = alignTo(Pos, S->Alignment);
493   S->OutSecOff = Pos - CurOutSec->Addr;
494   Pos += S->getSize();
495 
496   // Update output section size after adding each section. This is so that
497   // SIZEOF works correctly in the case below:
498   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
499   CurOutSec->Size = Pos - CurOutSec->Addr;
500 
501   // If there is a memory region associated with this input section, then
502   // place the section in that region and update the region index.
503   if (CurMemRegion) {
504     CurMemRegion->Offset += CurOutSec->Size;
505     uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
506     if (CurSize > CurMemRegion->Length) {
507       uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
508       error("section '" + CurOutSec->Name + "' will not fit in region '" +
509             CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
510             " bytes");
511     }
512   }
513 
514   if (IsTbss)
515     ThreadBssOffset = Pos - Dot;
516   else
517     Dot = Pos;
518 }
519 
520 void LinkerScriptBase::flush() {
521   assert(CurOutSec);
522   if (!AlreadyOutputOS.insert(CurOutSec).second)
523     return;
524   for (InputSection *I : CurOutSec->Sections)
525     output(I);
526 }
527 
528 void LinkerScriptBase::switchTo(OutputSection *Sec) {
529   if (CurOutSec == Sec)
530     return;
531   if (AlreadyOutputOS.count(Sec))
532     return;
533 
534   CurOutSec = Sec;
535 
536   Dot = alignTo(Dot, CurOutSec->Alignment);
537   CurOutSec->Addr = isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot;
538 
539   // If neither AT nor AT> is specified for an allocatable section, the linker
540   // will set the LMA such that the difference between VMA and LMA for the
541   // section is the same as the preceding output section in the same region
542   // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
543   if (LMAOffset)
544     CurOutSec->LMAOffset = LMAOffset();
545 }
546 
547 void LinkerScriptBase::process(BaseCommand &Base) {
548   // This handles the assignments to symbol or to a location counter (.)
549   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
550     assignSymbol(AssignCmd, true);
551     return;
552   }
553 
554   // Handle BYTE(), SHORT(), LONG(), or QUAD().
555   if (auto *DataCmd = dyn_cast<BytesDataCommand>(&Base)) {
556     DataCmd->Offset = Dot - CurOutSec->Addr;
557     Dot += DataCmd->Size;
558     CurOutSec->Size = Dot - CurOutSec->Addr;
559     return;
560   }
561 
562   if (auto *AssertCmd = dyn_cast<AssertCommand>(&Base)) {
563     AssertCmd->Expression();
564     return;
565   }
566 
567   // It handles single input section description command,
568   // calculates and assigns the offsets for each section and also
569   // updates the output section size.
570   auto &ICmd = cast<InputSectionDescription>(Base);
571   for (InputSectionBase *IB : ICmd.Sections) {
572     // We tentatively added all synthetic sections at the beginning and removed
573     // empty ones afterwards (because there is no way to know whether they were
574     // going be empty or not other than actually running linker scripts.)
575     // We need to ignore remains of empty sections.
576     if (auto *Sec = dyn_cast<SyntheticSection>(IB))
577       if (Sec->empty())
578         continue;
579 
580     if (!IB->Live)
581       continue;
582     assert(CurOutSec == IB->OutSec || AlreadyOutputOS.count(IB->OutSec));
583     output(cast<InputSection>(IB));
584   }
585 }
586 
587 static OutputSection *
588 findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
589   auto End = Sections.end();
590   auto HasName = [=](OutputSection *Sec) { return Sec->Name == Name; };
591   auto I = std::find_if(Sections.begin(), End, HasName);
592   std::vector<OutputSection *> Ret;
593   if (I == End)
594     return nullptr;
595   assert(std::find_if(I + 1, End, HasName) == End);
596   return *I;
597 }
598 
599 // This function searches for a memory region to place the given output
600 // section in. If found, a pointer to the appropriate memory region is
601 // returned. Otherwise, a nullptr is returned.
602 MemoryRegion *LinkerScriptBase::findMemoryRegion(OutputSectionCommand *Cmd,
603                                                  OutputSection *Sec) {
604   // If a memory region name was specified in the output section command,
605   // then try to find that region first.
606   if (!Cmd->MemoryRegionName.empty()) {
607     auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
608     if (It != Opt.MemoryRegions.end())
609       return &It->second;
610     error("memory region '" + Cmd->MemoryRegionName + "' not declared");
611     return nullptr;
612   }
613 
614   // The memory region name is empty, thus a suitable region must be
615   // searched for in the region map. If the region map is empty, just
616   // return. Note that this check doesn't happen at the very beginning
617   // so that uses of undeclared regions can be caught.
618   if (!Opt.MemoryRegions.size())
619     return nullptr;
620 
621   // See if a region can be found by matching section flags.
622   for (auto &MRI : Opt.MemoryRegions) {
623     MemoryRegion &MR = MRI.second;
624     if ((MR.Flags & Sec->Flags) != 0 && (MR.NegFlags & Sec->Flags) == 0)
625       return &MR;
626   }
627 
628   // Otherwise, no suitable region was found.
629   if (Sec->Flags & SHF_ALLOC)
630     error("no memory region specified for section '" + Sec->Name + "'");
631   return nullptr;
632 }
633 
634 // This function assigns offsets to input sections and an output section
635 // for a single sections command (e.g. ".text { *(.text); }").
636 void LinkerScriptBase::assignOffsets(OutputSectionCommand *Cmd) {
637   OutputSection *Sec = findSection(Cmd->Name, *OutputSections);
638   if (!Sec)
639     return;
640 
641   if (Cmd->AddrExpr && Sec->Flags & SHF_ALLOC)
642     setDot(Cmd->AddrExpr, Cmd->Location);
643 
644   if (Cmd->LMAExpr) {
645     uint64_t D = Dot;
646     LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
647   }
648 
649   // Handle align (e.g. ".foo : ALIGN(16) { ... }").
650   if (Cmd->AlignExpr)
651     Sec->updateAlignment(Cmd->AlignExpr().getValue());
652 
653   // Try and find an appropriate memory region to assign offsets in.
654   CurMemRegion = findMemoryRegion(Cmd, Sec);
655   if (CurMemRegion)
656     Dot = CurMemRegion->Offset;
657   switchTo(Sec);
658 
659   // Find the last section output location. We will output orphan sections
660   // there so that end symbols point to the correct location.
661   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
662                         [](const std::unique_ptr<BaseCommand> &Cmd) {
663                           return !isa<SymbolAssignment>(*Cmd);
664                         })
665                .base();
666   for (auto I = Cmd->Commands.begin(); I != E; ++I)
667     process(**I);
668   flush();
669   std::for_each(E, Cmd->Commands.end(),
670                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
671 }
672 
673 void LinkerScriptBase::removeEmptyCommands() {
674   // It is common practice to use very generic linker scripts. So for any
675   // given run some of the output sections in the script will be empty.
676   // We could create corresponding empty output sections, but that would
677   // clutter the output.
678   // We instead remove trivially empty sections. The bfd linker seems even
679   // more aggressive at removing them.
680   auto Pos = std::remove_if(
681       Opt.Commands.begin(), Opt.Commands.end(),
682       [&](const std::unique_ptr<BaseCommand> &Base) {
683         if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
684           return !findSection(Cmd->Name, *OutputSections);
685         return false;
686       });
687   Opt.Commands.erase(Pos, Opt.Commands.end());
688 }
689 
690 static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
691   for (const std::unique_ptr<BaseCommand> &I : Cmd.Commands)
692     if (!isa<InputSectionDescription>(*I))
693       return false;
694   return true;
695 }
696 
697 void LinkerScriptBase::adjustSectionsBeforeSorting() {
698   // If the output section contains only symbol assignments, create a
699   // corresponding output section. The bfd linker seems to only create them if
700   // '.' is assigned to, but creating these section should not have any bad
701   // consequeces and gives us a section to put the symbol in.
702   uint64_t Flags = SHF_ALLOC;
703   uint32_t Type = SHT_NOBITS;
704   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
705     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
706     if (!Cmd)
707       continue;
708     if (OutputSection *Sec = findSection(Cmd->Name, *OutputSections)) {
709       Flags = Sec->Flags;
710       Type = Sec->Type;
711       continue;
712     }
713 
714     if (isAllSectionDescription(*Cmd))
715       continue;
716 
717     auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
718     OutputSections->push_back(OutSec);
719   }
720 }
721 
722 void LinkerScriptBase::adjustSectionsAfterSorting() {
723   placeOrphanSections();
724 
725   // If output section command doesn't specify any segments,
726   // and we haven't previously assigned any section to segment,
727   // then we simply assign section to the very first load segment.
728   // Below is an example of such linker script:
729   // PHDRS { seg PT_LOAD; }
730   // SECTIONS { .aaa : { *(.aaa) } }
731   std::vector<StringRef> DefPhdrs;
732   auto FirstPtLoad =
733       std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
734                    [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
735   if (FirstPtLoad != Opt.PhdrsCommands.end())
736     DefPhdrs.push_back(FirstPtLoad->Name);
737 
738   // Walk the commands and propagate the program headers to commands that don't
739   // explicitly specify them.
740   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
741     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
742     if (!Cmd)
743       continue;
744     if (Cmd->Phdrs.empty())
745       Cmd->Phdrs = DefPhdrs;
746     else
747       DefPhdrs = Cmd->Phdrs;
748   }
749 
750   removeEmptyCommands();
751 }
752 
753 // When placing orphan sections, we want to place them after symbol assignments
754 // so that an orphan after
755 //   begin_foo = .;
756 //   foo : { *(foo) }
757 //   end_foo = .;
758 // doesn't break the intended meaning of the begin/end symbols.
759 // We don't want to go over sections since Writer<ELFT>::sortSections is the
760 // one in charge of deciding the order of the sections.
761 // We don't want to go over alignments, since doing so in
762 //  rx_sec : { *(rx_sec) }
763 //  . = ALIGN(0x1000);
764 //  /* The RW PT_LOAD starts here*/
765 //  rw_sec : { *(rw_sec) }
766 // would mean that the RW PT_LOAD would become unaligned.
767 static bool shouldSkip(const BaseCommand &Cmd) {
768   if (isa<OutputSectionCommand>(Cmd))
769     return false;
770   const auto *Assign = dyn_cast<SymbolAssignment>(&Cmd);
771   if (!Assign)
772     return true;
773   return Assign->Name != ".";
774 }
775 
776 // Orphan sections are sections present in the input files which are
777 // not explicitly placed into the output file by the linker script.
778 //
779 // When the control reaches this function, Opt.Commands contains
780 // output section commands for non-orphan sections only. This function
781 // adds new elements for orphan sections to Opt.Commands so that all
782 // sections are explicitly handled by Opt.Commands.
783 //
784 // Writer<ELFT>::sortSections has already sorted output sections.
785 // What we need to do is to scan OutputSections vector and
786 // Opt.Commands in parallel to find orphan sections. If there is an
787 // output section that doesn't have a corresponding entry in
788 // Opt.Commands, we will insert a new entry to Opt.Commands.
789 //
790 // There is some ambiguity as to where exactly a new entry should be
791 // inserted, because Opt.Commands contains not only output section
792 // commands but other types of commands such as symbol assignment
793 // expressions. There's no correct answer here due to the lack of the
794 // formal specification of the linker script. We use heuristics to
795 // determine whether a new output command should be added before or
796 // after another commands. For the details, look at shouldSkip
797 // function.
798 void LinkerScriptBase::placeOrphanSections() {
799   // The OutputSections are already in the correct order.
800   // This loops creates or moves commands as needed so that they are in the
801   // correct order.
802   int CmdIndex = 0;
803 
804   // As a horrible special case, skip the first . assignment if it is before any
805   // section. We do this because it is common to set a load address by starting
806   // the script with ". = 0xabcd" and the expectation is that every section is
807   // after that.
808   auto FirstSectionOrDotAssignment =
809       std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
810                    [](const std::unique_ptr<BaseCommand> &Cmd) {
811                      if (isa<OutputSectionCommand>(*Cmd))
812                        return true;
813                      const auto *Assign = dyn_cast<SymbolAssignment>(Cmd.get());
814                      if (!Assign)
815                        return false;
816                      return Assign->Name == ".";
817                    });
818   if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
819     CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
820     if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
821       ++CmdIndex;
822   }
823 
824   for (OutputSection *Sec : *OutputSections) {
825     StringRef Name = Sec->Name;
826 
827     // Find the last spot where we can insert a command and still get the
828     // correct result.
829     auto CmdIter = Opt.Commands.begin() + CmdIndex;
830     auto E = Opt.Commands.end();
831     while (CmdIter != E && shouldSkip(**CmdIter)) {
832       ++CmdIter;
833       ++CmdIndex;
834     }
835 
836     auto Pos =
837         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
838           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
839           return Cmd && Cmd->Name == Name;
840         });
841     if (Pos == E) {
842       Opt.Commands.insert(CmdIter,
843                           llvm::make_unique<OutputSectionCommand>(Name));
844       ++CmdIndex;
845       continue;
846     }
847 
848     // Continue from where we found it.
849     CmdIndex = (Pos - Opt.Commands.begin()) + 1;
850   }
851 }
852 
853 void LinkerScriptBase::processNonSectionCommands() {
854   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
855     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get()))
856       assignSymbol(Cmd);
857     else if (auto *Cmd = dyn_cast<AssertCommand>(Base.get()))
858       Cmd->Expression();
859   }
860 }
861 
862 void LinkerScriptBase::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
863   // Assign addresses as instructed by linker script SECTIONS sub-commands.
864   Dot = 0;
865   ErrorOnMissingSection = true;
866   switchTo(Aether);
867 
868   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
869     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
870       assignSymbol(Cmd);
871       continue;
872     }
873 
874     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
875       Cmd->Expression();
876       continue;
877     }
878 
879     auto *Cmd = cast<OutputSectionCommand>(Base.get());
880     assignOffsets(Cmd);
881   }
882 
883   uint64_t MinVA = std::numeric_limits<uint64_t>::max();
884   for (OutputSection *Sec : *OutputSections) {
885     if (Sec->Flags & SHF_ALLOC)
886       MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
887     else
888       Sec->Addr = 0;
889   }
890 
891   allocateHeaders(Phdrs, *OutputSections, MinVA);
892 }
893 
894 // Creates program headers as instructed by PHDRS linker script command.
895 std::vector<PhdrEntry> LinkerScriptBase::createPhdrs() {
896   std::vector<PhdrEntry> Ret;
897 
898   // Process PHDRS and FILEHDR keywords because they are not
899   // real output sections and cannot be added in the following loop.
900   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
901     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
902     PhdrEntry &Phdr = Ret.back();
903 
904     if (Cmd.HasFilehdr)
905       Phdr.add(Out::ElfHeader);
906     if (Cmd.HasPhdrs)
907       Phdr.add(Out::ProgramHeaders);
908 
909     if (Cmd.LMAExpr) {
910       Phdr.p_paddr = Cmd.LMAExpr().getValue();
911       Phdr.HasLMA = true;
912     }
913   }
914 
915   // Add output sections to program headers.
916   for (OutputSection *Sec : *OutputSections) {
917     if (!(Sec->Flags & SHF_ALLOC))
918       break;
919 
920     // Assign headers specified by linker script
921     for (size_t Id : getPhdrIndices(Sec->Name)) {
922       Ret[Id].add(Sec);
923       if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
924         Ret[Id].p_flags |= Sec->getPhdrFlags();
925     }
926   }
927   return Ret;
928 }
929 
930 bool LinkerScriptBase::ignoreInterpSection() {
931   // Ignore .interp section in case we have PHDRS specification
932   // and PT_INTERP isn't listed.
933   return !Opt.PhdrsCommands.empty() &&
934          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
935            return Cmd.Type == PT_INTERP;
936          }) == Opt.PhdrsCommands.end();
937 }
938 
939 uint32_t LinkerScriptBase::getFiller(StringRef Name) {
940   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
941     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
942       if (Cmd->Name == Name)
943         return Cmd->Filler;
944   return 0;
945 }
946 
947 static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
948   const endianness E = Config->IsLE ? endianness::little : endianness::big;
949 
950   switch (Size) {
951   case 1:
952     *Buf = (uint8_t)Data;
953     break;
954   case 2:
955     write16(Buf, Data, E);
956     break;
957   case 4:
958     write32(Buf, Data, E);
959     break;
960   case 8:
961     write64(Buf, Data, E);
962     break;
963   default:
964     llvm_unreachable("unsupported Size argument");
965   }
966 }
967 
968 void LinkerScriptBase::writeDataBytes(StringRef Name, uint8_t *Buf) {
969   int I = getSectionIndex(Name);
970   if (I == INT_MAX)
971     return;
972 
973   auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get());
974   for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
975     if (auto *Data = dyn_cast<BytesDataCommand>(Base.get()))
976       writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
977 }
978 
979 bool LinkerScriptBase::hasLMA(StringRef Name) {
980   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
981     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
982       if (Cmd->LMAExpr && Cmd->Name == Name)
983         return true;
984   return false;
985 }
986 
987 // Returns the index of the given section name in linker script
988 // SECTIONS commands. Sections are laid out as the same order as they
989 // were in the script. If a given name did not appear in the script,
990 // it returns INT_MAX, so that it will be laid out at end of file.
991 int LinkerScriptBase::getSectionIndex(StringRef Name) {
992   for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
993     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I].get()))
994       if (Cmd->Name == Name)
995         return I;
996   return INT_MAX;
997 }
998 
999 ExprValue LinkerScriptBase::getSymbolValue(const Twine &Loc, StringRef S) {
1000   if (S == ".")
1001     return {CurOutSec, Dot - CurOutSec->Addr};
1002   if (SymbolBody *B = findSymbol(S)) {
1003     if (auto *D = dyn_cast<DefinedRegular>(B))
1004       return {D->Section, D->Value};
1005     auto *C = cast<DefinedCommon>(B);
1006     return {InX::Common, C->Offset};
1007   }
1008   error(Loc + ": symbol not found: " + S);
1009   return 0;
1010 }
1011 
1012 bool LinkerScriptBase::isDefined(StringRef S) {
1013   return findSymbol(S) != nullptr;
1014 }
1015 
1016 // Returns indices of ELF headers containing specific section, identified
1017 // by Name. Each index is a zero based number of ELF header listed within
1018 // PHDRS {} script block.
1019 std::vector<size_t> LinkerScriptBase::getPhdrIndices(StringRef SectionName) {
1020   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
1021     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
1022     if (!Cmd || Cmd->Name != SectionName)
1023       continue;
1024 
1025     std::vector<size_t> Ret;
1026     for (StringRef PhdrName : Cmd->Phdrs)
1027       Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
1028     return Ret;
1029   }
1030   return {};
1031 }
1032 
1033 size_t LinkerScriptBase::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
1034   size_t I = 0;
1035   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1036     if (Cmd.Name == PhdrName)
1037       return I;
1038     ++I;
1039   }
1040   error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
1041   return 0;
1042 }
1043 
1044 class elf::ScriptParser final : public ScriptLexer {
1045   typedef void (ScriptParser::*Handler)();
1046 
1047 public:
1048   ScriptParser(MemoryBufferRef MB)
1049       : ScriptLexer(MB),
1050         IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
1051 
1052   void readLinkerScript();
1053   void readVersionScript();
1054   void readDynamicList();
1055 
1056 private:
1057   void addFile(StringRef Path);
1058 
1059   void readAsNeeded();
1060   void readEntry();
1061   void readExtern();
1062   void readGroup();
1063   void readInclude();
1064   void readMemory();
1065   void readOutput();
1066   void readOutputArch();
1067   void readOutputFormat();
1068   void readPhdrs();
1069   void readSearchDir();
1070   void readSections();
1071   void readVersion();
1072   void readVersionScriptCommand();
1073 
1074   SymbolAssignment *readAssignment(StringRef Name);
1075   BytesDataCommand *readBytesDataCommand(StringRef Tok);
1076   uint32_t readFill();
1077   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
1078   uint32_t readOutputSectionFiller(StringRef Tok);
1079   std::vector<StringRef> readOutputSectionPhdrs();
1080   InputSectionDescription *readInputSectionDescription(StringRef Tok);
1081   StringMatcher readFilePatterns();
1082   std::vector<SectionPattern> readInputSectionsList();
1083   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
1084   unsigned readPhdrType();
1085   SortSectionPolicy readSortKind();
1086   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
1087   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
1088   void readSort();
1089   Expr readAssert();
1090 
1091   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
1092   std::pair<uint32_t, uint32_t> readMemoryAttributes();
1093 
1094   Expr readExpr();
1095   Expr readExpr1(Expr Lhs, int MinPrec);
1096   StringRef readParenLiteral();
1097   Expr readPrimary();
1098   Expr readTernary(Expr Cond);
1099   Expr readParenExpr();
1100 
1101   // For parsing version script.
1102   std::vector<SymbolVersion> readVersionExtern();
1103   void readAnonymousDeclaration();
1104   void readVersionDeclaration(StringRef VerStr);
1105 
1106   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1107   readSymbols();
1108 
1109   ScriptConfiguration &Opt = *ScriptConfig;
1110   bool IsUnderSysroot;
1111 };
1112 
1113 void ScriptParser::readDynamicList() {
1114   expect("{");
1115   readAnonymousDeclaration();
1116   if (!atEOF())
1117     setError("EOF expected, but got " + next());
1118 }
1119 
1120 void ScriptParser::readVersionScript() {
1121   readVersionScriptCommand();
1122   if (!atEOF())
1123     setError("EOF expected, but got " + next());
1124 }
1125 
1126 void ScriptParser::readVersionScriptCommand() {
1127   if (consume("{")) {
1128     readAnonymousDeclaration();
1129     return;
1130   }
1131 
1132   while (!atEOF() && !Error && peek() != "}") {
1133     StringRef VerStr = next();
1134     if (VerStr == "{") {
1135       setError("anonymous version definition is used in "
1136                "combination with other version definitions");
1137       return;
1138     }
1139     expect("{");
1140     readVersionDeclaration(VerStr);
1141   }
1142 }
1143 
1144 void ScriptParser::readVersion() {
1145   expect("{");
1146   readVersionScriptCommand();
1147   expect("}");
1148 }
1149 
1150 void ScriptParser::readLinkerScript() {
1151   while (!atEOF()) {
1152     StringRef Tok = next();
1153     if (Tok == ";")
1154       continue;
1155 
1156     if (Tok == "ASSERT") {
1157       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
1158     } else if (Tok == "ENTRY") {
1159       readEntry();
1160     } else if (Tok == "EXTERN") {
1161       readExtern();
1162     } else if (Tok == "GROUP" || Tok == "INPUT") {
1163       readGroup();
1164     } else if (Tok == "INCLUDE") {
1165       readInclude();
1166     } else if (Tok == "MEMORY") {
1167       readMemory();
1168     } else if (Tok == "OUTPUT") {
1169       readOutput();
1170     } else if (Tok == "OUTPUT_ARCH") {
1171       readOutputArch();
1172     } else if (Tok == "OUTPUT_FORMAT") {
1173       readOutputFormat();
1174     } else if (Tok == "PHDRS") {
1175       readPhdrs();
1176     } else if (Tok == "SEARCH_DIR") {
1177       readSearchDir();
1178     } else if (Tok == "SECTIONS") {
1179       readSections();
1180     } else if (Tok == "VERSION") {
1181       readVersion();
1182     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
1183       Opt.Commands.emplace_back(Cmd);
1184     } else {
1185       setError("unknown directive: " + Tok);
1186     }
1187   }
1188 }
1189 
1190 void ScriptParser::addFile(StringRef S) {
1191   if (IsUnderSysroot && S.startswith("/")) {
1192     SmallString<128> PathData;
1193     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
1194     if (sys::fs::exists(Path)) {
1195       Driver->addFile(Saver.save(Path));
1196       return;
1197     }
1198   }
1199 
1200   if (sys::path::is_absolute(S)) {
1201     Driver->addFile(S);
1202   } else if (S.startswith("=")) {
1203     if (Config->Sysroot.empty())
1204       Driver->addFile(S.substr(1));
1205     else
1206       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
1207   } else if (S.startswith("-l")) {
1208     Driver->addLibrary(S.substr(2));
1209   } else if (sys::fs::exists(S)) {
1210     Driver->addFile(S);
1211   } else {
1212     if (Optional<std::string> Path = findFromSearchPaths(S))
1213       Driver->addFile(Saver.save(*Path));
1214     else
1215       setError("unable to find " + S);
1216   }
1217 }
1218 
1219 void ScriptParser::readAsNeeded() {
1220   expect("(");
1221   bool Orig = Config->AsNeeded;
1222   Config->AsNeeded = true;
1223   while (!Error && !consume(")"))
1224     addFile(unquote(next()));
1225   Config->AsNeeded = Orig;
1226 }
1227 
1228 void ScriptParser::readEntry() {
1229   // -e <symbol> takes predecence over ENTRY(<symbol>).
1230   expect("(");
1231   StringRef Tok = next();
1232   if (Config->Entry.empty())
1233     Config->Entry = Tok;
1234   expect(")");
1235 }
1236 
1237 void ScriptParser::readExtern() {
1238   expect("(");
1239   while (!Error && !consume(")"))
1240     Config->Undefined.push_back(next());
1241 }
1242 
1243 void ScriptParser::readGroup() {
1244   expect("(");
1245   while (!Error && !consume(")")) {
1246     StringRef Tok = next();
1247     if (Tok == "AS_NEEDED")
1248       readAsNeeded();
1249     else
1250       addFile(unquote(Tok));
1251   }
1252 }
1253 
1254 void ScriptParser::readInclude() {
1255   StringRef Tok = unquote(next());
1256 
1257   // https://sourceware.org/binutils/docs/ld/File-Commands.html:
1258   // The file will be searched for in the current directory, and in any
1259   // directory specified with the -L option.
1260   if (sys::fs::exists(Tok)) {
1261     if (Optional<MemoryBufferRef> MB = readFile(Tok))
1262       tokenize(*MB);
1263     return;
1264   }
1265   if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
1266     if (Optional<MemoryBufferRef> MB = readFile(*Path))
1267       tokenize(*MB);
1268     return;
1269   }
1270   setError("cannot open " + Tok);
1271 }
1272 
1273 void ScriptParser::readOutput() {
1274   // -o <file> takes predecence over OUTPUT(<file>).
1275   expect("(");
1276   StringRef Tok = next();
1277   if (Config->OutputFile.empty())
1278     Config->OutputFile = unquote(Tok);
1279   expect(")");
1280 }
1281 
1282 void ScriptParser::readOutputArch() {
1283   // OUTPUT_ARCH is ignored for now.
1284   expect("(");
1285   while (!Error && !consume(")"))
1286     skip();
1287 }
1288 
1289 void ScriptParser::readOutputFormat() {
1290   // Error checking only for now.
1291   expect("(");
1292   skip();
1293   StringRef Tok = next();
1294   if (Tok == ")")
1295     return;
1296   if (Tok != ",") {
1297     setError("unexpected token: " + Tok);
1298     return;
1299   }
1300   skip();
1301   expect(",");
1302   skip();
1303   expect(")");
1304 }
1305 
1306 void ScriptParser::readPhdrs() {
1307   expect("{");
1308   while (!Error && !consume("}")) {
1309     StringRef Tok = next();
1310     Opt.PhdrsCommands.push_back(
1311         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
1312     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
1313 
1314     PhdrCmd.Type = readPhdrType();
1315     do {
1316       Tok = next();
1317       if (Tok == ";")
1318         break;
1319       if (Tok == "FILEHDR")
1320         PhdrCmd.HasFilehdr = true;
1321       else if (Tok == "PHDRS")
1322         PhdrCmd.HasPhdrs = true;
1323       else if (Tok == "AT")
1324         PhdrCmd.LMAExpr = readParenExpr();
1325       else if (Tok == "FLAGS") {
1326         expect("(");
1327         // Passing 0 for the value of dot is a bit of a hack. It means that
1328         // we accept expressions like ".|1".
1329         PhdrCmd.Flags = readExpr()().getValue();
1330         expect(")");
1331       } else
1332         setError("unexpected header attribute: " + Tok);
1333     } while (!Error);
1334   }
1335 }
1336 
1337 void ScriptParser::readSearchDir() {
1338   expect("(");
1339   StringRef Tok = next();
1340   if (!Config->Nostdlib)
1341     Config->SearchPaths.push_back(unquote(Tok));
1342   expect(")");
1343 }
1344 
1345 void ScriptParser::readSections() {
1346   Opt.HasSections = true;
1347   // -no-rosegment is used to avoid placing read only non-executable sections in
1348   // their own segment. We do the same if SECTIONS command is present in linker
1349   // script. See comment for computeFlags().
1350   Config->SingleRoRx = true;
1351 
1352   expect("{");
1353   while (!Error && !consume("}")) {
1354     StringRef Tok = next();
1355     BaseCommand *Cmd = readProvideOrAssignment(Tok);
1356     if (!Cmd) {
1357       if (Tok == "ASSERT")
1358         Cmd = new AssertCommand(readAssert());
1359       else
1360         Cmd = readOutputSectionDescription(Tok);
1361     }
1362     Opt.Commands.emplace_back(Cmd);
1363   }
1364 }
1365 
1366 static int precedence(StringRef Op) {
1367   return StringSwitch<int>(Op)
1368       .Cases("*", "/", 5)
1369       .Cases("+", "-", 4)
1370       .Cases("<<", ">>", 3)
1371       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
1372       .Cases("&", "|", 1)
1373       .Default(-1);
1374 }
1375 
1376 StringMatcher ScriptParser::readFilePatterns() {
1377   std::vector<StringRef> V;
1378   while (!Error && !consume(")"))
1379     V.push_back(next());
1380   return StringMatcher(V);
1381 }
1382 
1383 SortSectionPolicy ScriptParser::readSortKind() {
1384   if (consume("SORT") || consume("SORT_BY_NAME"))
1385     return SortSectionPolicy::Name;
1386   if (consume("SORT_BY_ALIGNMENT"))
1387     return SortSectionPolicy::Alignment;
1388   if (consume("SORT_BY_INIT_PRIORITY"))
1389     return SortSectionPolicy::Priority;
1390   if (consume("SORT_NONE"))
1391     return SortSectionPolicy::None;
1392   return SortSectionPolicy::Default;
1393 }
1394 
1395 // Method reads a list of sequence of excluded files and section globs given in
1396 // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1397 // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1398 // The semantics of that is next:
1399 // * Include .foo.1 from every file.
1400 // * Include .foo.2 from every file but a.o
1401 // * Include .foo.3 from every file but b.o
1402 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1403   std::vector<SectionPattern> Ret;
1404   while (!Error && peek() != ")") {
1405     StringMatcher ExcludeFilePat;
1406     if (consume("EXCLUDE_FILE")) {
1407       expect("(");
1408       ExcludeFilePat = readFilePatterns();
1409     }
1410 
1411     std::vector<StringRef> V;
1412     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1413       V.push_back(next());
1414 
1415     if (!V.empty())
1416       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
1417     else
1418       setError("section pattern is expected");
1419   }
1420   return Ret;
1421 }
1422 
1423 // Reads contents of "SECTIONS" directive. That directive contains a
1424 // list of glob patterns for input sections. The grammar is as follows.
1425 //
1426 // <patterns> ::= <section-list>
1427 //              | <sort> "(" <section-list> ")"
1428 //              | <sort> "(" <sort> "(" <section-list> ")" ")"
1429 //
1430 // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
1431 //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
1432 //
1433 // <section-list> is parsed by readInputSectionsList().
1434 InputSectionDescription *
1435 ScriptParser::readInputSectionRules(StringRef FilePattern) {
1436   auto *Cmd = new InputSectionDescription(FilePattern);
1437   expect("(");
1438   while (!Error && !consume(")")) {
1439     SortSectionPolicy Outer = readSortKind();
1440     SortSectionPolicy Inner = SortSectionPolicy::Default;
1441     std::vector<SectionPattern> V;
1442     if (Outer != SortSectionPolicy::Default) {
1443       expect("(");
1444       Inner = readSortKind();
1445       if (Inner != SortSectionPolicy::Default) {
1446         expect("(");
1447         V = readInputSectionsList();
1448         expect(")");
1449       } else {
1450         V = readInputSectionsList();
1451       }
1452       expect(")");
1453     } else {
1454       V = readInputSectionsList();
1455     }
1456 
1457     for (SectionPattern &Pat : V) {
1458       Pat.SortInner = Inner;
1459       Pat.SortOuter = Outer;
1460     }
1461 
1462     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1463   }
1464   return Cmd;
1465 }
1466 
1467 InputSectionDescription *
1468 ScriptParser::readInputSectionDescription(StringRef Tok) {
1469   // Input section wildcard can be surrounded by KEEP.
1470   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1471   if (Tok == "KEEP") {
1472     expect("(");
1473     StringRef FilePattern = next();
1474     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
1475     expect(")");
1476     Opt.KeptSections.push_back(Cmd);
1477     return Cmd;
1478   }
1479   return readInputSectionRules(Tok);
1480 }
1481 
1482 void ScriptParser::readSort() {
1483   expect("(");
1484   expect("CONSTRUCTORS");
1485   expect(")");
1486 }
1487 
1488 Expr ScriptParser::readAssert() {
1489   expect("(");
1490   Expr E = readExpr();
1491   expect(",");
1492   StringRef Msg = unquote(next());
1493   expect(")");
1494   return [=] {
1495     if (!E().getValue())
1496       error(Msg);
1497     return Script->getDot();
1498   };
1499 }
1500 
1501 // Reads a FILL(expr) command. We handle the FILL command as an
1502 // alias for =fillexp section attribute, which is different from
1503 // what GNU linkers do.
1504 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1505 uint32_t ScriptParser::readFill() {
1506   expect("(");
1507   uint32_t V = readOutputSectionFiller(next());
1508   expect(")");
1509   expect(";");
1510   return V;
1511 }
1512 
1513 OutputSectionCommand *
1514 ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1515   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
1516   Cmd->Location = getCurrentLocation();
1517 
1518   // Read an address expression.
1519   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1520   if (peek() != ":")
1521     Cmd->AddrExpr = readExpr();
1522 
1523   expect(":");
1524 
1525   if (consume("AT"))
1526     Cmd->LMAExpr = readParenExpr();
1527   if (consume("ALIGN"))
1528     Cmd->AlignExpr = readParenExpr();
1529   if (consume("SUBALIGN"))
1530     Cmd->SubalignExpr = readParenExpr();
1531 
1532   // Parse constraints.
1533   if (consume("ONLY_IF_RO"))
1534     Cmd->Constraint = ConstraintKind::ReadOnly;
1535   if (consume("ONLY_IF_RW"))
1536     Cmd->Constraint = ConstraintKind::ReadWrite;
1537   expect("{");
1538 
1539   while (!Error && !consume("}")) {
1540     StringRef Tok = next();
1541     if (Tok == ";") {
1542       // Empty commands are allowed. Do nothing here.
1543     } else if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok)) {
1544       Cmd->Commands.emplace_back(Assignment);
1545     } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
1546       Cmd->Commands.emplace_back(Data);
1547     } else if (Tok == "ASSERT") {
1548       Cmd->Commands.emplace_back(new AssertCommand(readAssert()));
1549       expect(";");
1550     } else if (Tok == "CONSTRUCTORS") {
1551       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
1552       // by name. This is for very old file formats such as ECOFF/XCOFF.
1553       // For ELF, we should ignore.
1554     } else if (Tok == "FILL") {
1555       Cmd->Filler = readFill();
1556     } else if (Tok == "SORT") {
1557       readSort();
1558     } else if (peek() == "(") {
1559       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1560     } else {
1561       setError("unknown command " + Tok);
1562     }
1563   }
1564 
1565   if (consume(">"))
1566     Cmd->MemoryRegionName = next();
1567 
1568   Cmd->Phdrs = readOutputSectionPhdrs();
1569 
1570   if (consume("="))
1571     Cmd->Filler = readOutputSectionFiller(next());
1572   else if (peek().startswith("="))
1573     Cmd->Filler = readOutputSectionFiller(next().drop_front());
1574 
1575   // Consume optional comma following output section command.
1576   consume(",");
1577 
1578   return Cmd;
1579 }
1580 
1581 // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1582 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1583 //
1584 // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1585 // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1586 // as 32-bit big-endian values. We will do the same as ld.gold does
1587 // because it's simpler than what ld.bfd does.
1588 uint32_t ScriptParser::readOutputSectionFiller(StringRef Tok) {
1589   uint32_t V;
1590   if (!Tok.getAsInteger(0, V))
1591     return V;
1592   setError("invalid filler expression: " + Tok);
1593   return 0;
1594 }
1595 
1596 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1597   expect("(");
1598   SymbolAssignment *Cmd = readAssignment(next());
1599   Cmd->Provide = Provide;
1600   Cmd->Hidden = Hidden;
1601   expect(")");
1602   expect(";");
1603   return Cmd;
1604 }
1605 
1606 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
1607   SymbolAssignment *Cmd = nullptr;
1608   if (peek() == "=" || peek() == "+=") {
1609     Cmd = readAssignment(Tok);
1610     expect(";");
1611   } else if (Tok == "PROVIDE") {
1612     Cmd = readProvideHidden(true, false);
1613   } else if (Tok == "HIDDEN") {
1614     Cmd = readProvideHidden(false, true);
1615   } else if (Tok == "PROVIDE_HIDDEN") {
1616     Cmd = readProvideHidden(true, true);
1617   }
1618   return Cmd;
1619 }
1620 
1621 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1622   StringRef Op = next();
1623   assert(Op == "=" || Op == "+=");
1624   Expr E = readExpr();
1625   if (Op == "+=") {
1626     std::string Loc = getCurrentLocation();
1627     E = [=] { return add(Script->getSymbolValue(Loc, Name), E()); };
1628   }
1629   return new SymbolAssignment(Name, E, getCurrentLocation());
1630 }
1631 
1632 // This is an operator-precedence parser to parse a linker
1633 // script expression.
1634 Expr ScriptParser::readExpr() {
1635   // Our lexer is context-aware. Set the in-expression bit so that
1636   // they apply different tokenization rules.
1637   bool Orig = InExpr;
1638   InExpr = true;
1639   Expr E = readExpr1(readPrimary(), 0);
1640   InExpr = Orig;
1641   return E;
1642 }
1643 
1644 static Expr combine(StringRef Op, Expr L, Expr R) {
1645   if (Op == "*")
1646     return [=] { return mul(L(), R()); };
1647   if (Op == "/") {
1648     return [=] { return div(L(), R()); };
1649   }
1650   if (Op == "+")
1651     return [=] { return add(L(), R()); };
1652   if (Op == "-")
1653     return [=] { return sub(L(), R()); };
1654   if (Op == "<<")
1655     return [=] { return leftShift(L(), R()); };
1656   if (Op == ">>")
1657     return [=] { return rightShift(L(), R()); };
1658   if (Op == "<")
1659     return [=] { return L().getValue() < R().getValue(); };
1660   if (Op == ">")
1661     return [=] { return L().getValue() > R().getValue(); };
1662   if (Op == ">=")
1663     return [=] { return L().getValue() >= R().getValue(); };
1664   if (Op == "<=")
1665     return [=] { return L().getValue() <= R().getValue(); };
1666   if (Op == "==")
1667     return [=] { return L().getValue() == R().getValue(); };
1668   if (Op == "!=")
1669     return [=] { return L().getValue() != R().getValue(); };
1670   if (Op == "&")
1671     return [=] { return bitAnd(L(), R()); };
1672   if (Op == "|")
1673     return [=] { return bitOr(L(), R()); };
1674   llvm_unreachable("invalid operator");
1675 }
1676 
1677 // This is a part of the operator-precedence parser. This function
1678 // assumes that the remaining token stream starts with an operator.
1679 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1680   while (!atEOF() && !Error) {
1681     // Read an operator and an expression.
1682     if (consume("?"))
1683       return readTernary(Lhs);
1684     StringRef Op1 = peek();
1685     if (precedence(Op1) < MinPrec)
1686       break;
1687     skip();
1688     Expr Rhs = readPrimary();
1689 
1690     // Evaluate the remaining part of the expression first if the
1691     // next operator has greater precedence than the previous one.
1692     // For example, if we have read "+" and "3", and if the next
1693     // operator is "*", then we'll evaluate 3 * ... part first.
1694     while (!atEOF()) {
1695       StringRef Op2 = peek();
1696       if (precedence(Op2) <= precedence(Op1))
1697         break;
1698       Rhs = readExpr1(Rhs, precedence(Op2));
1699     }
1700 
1701     Lhs = combine(Op1, Lhs, Rhs);
1702   }
1703   return Lhs;
1704 }
1705 
1706 uint64_t static getConstant(StringRef S) {
1707   if (S == "COMMONPAGESIZE")
1708     return Target->PageSize;
1709   if (S == "MAXPAGESIZE")
1710     return Config->MaxPageSize;
1711   error("unknown constant: " + S);
1712   return 0;
1713 }
1714 
1715 // Parses Tok as an integer. Returns true if successful.
1716 // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1717 // and decimal numbers. Decimal numbers may have "K" (kilo) or
1718 // "M" (mega) prefixes.
1719 static bool readInteger(StringRef Tok, uint64_t &Result) {
1720   // Negative number
1721   if (Tok.startswith("-")) {
1722     if (!readInteger(Tok.substr(1), Result))
1723       return false;
1724     Result = -Result;
1725     return true;
1726   }
1727 
1728   // Hexadecimal
1729   if (Tok.startswith_lower("0x"))
1730     return !Tok.substr(2).getAsInteger(16, Result);
1731   if (Tok.endswith_lower("H"))
1732     return !Tok.drop_back().getAsInteger(16, Result);
1733 
1734   // Decimal
1735   int Suffix = 1;
1736   if (Tok.endswith_lower("K")) {
1737     Suffix = 1024;
1738     Tok = Tok.drop_back();
1739   } else if (Tok.endswith_lower("M")) {
1740     Suffix = 1024 * 1024;
1741     Tok = Tok.drop_back();
1742   }
1743   if (Tok.getAsInteger(10, Result))
1744     return false;
1745   Result *= Suffix;
1746   return true;
1747 }
1748 
1749 BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
1750   int Size = StringSwitch<unsigned>(Tok)
1751                  .Case("BYTE", 1)
1752                  .Case("SHORT", 2)
1753                  .Case("LONG", 4)
1754                  .Case("QUAD", 8)
1755                  .Default(-1);
1756   if (Size == -1)
1757     return nullptr;
1758 
1759   return new BytesDataCommand(readParenExpr(), Size);
1760 }
1761 
1762 StringRef ScriptParser::readParenLiteral() {
1763   expect("(");
1764   StringRef Tok = next();
1765   expect(")");
1766   return Tok;
1767 }
1768 
1769 Expr ScriptParser::readPrimary() {
1770   if (peek() == "(")
1771     return readParenExpr();
1772 
1773   StringRef Tok = next();
1774   std::string Location = getCurrentLocation();
1775 
1776   if (Tok == "~") {
1777     Expr E = readPrimary();
1778     return [=] { return bitNot(E()); };
1779   }
1780   if (Tok == "-") {
1781     Expr E = readPrimary();
1782     return [=] { return minus(E()); };
1783   }
1784 
1785   // Built-in functions are parsed here.
1786   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1787   if (Tok == "ABSOLUTE") {
1788     Expr Inner = readParenExpr();
1789     return [=] {
1790       ExprValue I = Inner();
1791       I.ForceAbsolute = true;
1792       return I;
1793     };
1794   }
1795   if (Tok == "ADDR") {
1796     StringRef Name = readParenLiteral();
1797     return [=]() -> ExprValue {
1798       return {Script->getOutputSection(Location, Name), 0};
1799     };
1800   }
1801   if (Tok == "LOADADDR") {
1802     StringRef Name = readParenLiteral();
1803     return [=] { return Script->getOutputSection(Location, Name)->getLMA(); };
1804   }
1805   if (Tok == "ASSERT")
1806     return readAssert();
1807   if (Tok == "ALIGN") {
1808     expect("(");
1809     Expr E = readExpr();
1810     if (consume(",")) {
1811       Expr E2 = readExpr();
1812       expect(")");
1813       return [=] { return alignTo(E().getValue(), E2().getValue()); };
1814     }
1815     expect(")");
1816     return [=] { return alignTo(Script->getDot(), E().getValue()); };
1817   }
1818   if (Tok == "CONSTANT") {
1819     StringRef Name = readParenLiteral();
1820     return [=] { return getConstant(Name); };
1821   }
1822   if (Tok == "DEFINED") {
1823     StringRef Name = readParenLiteral();
1824     return [=] { return Script->isDefined(Name) ? 1 : 0; };
1825   }
1826   if (Tok == "SEGMENT_START") {
1827     expect("(");
1828     skip();
1829     expect(",");
1830     Expr E = readExpr();
1831     expect(")");
1832     return [=] { return E(); };
1833   }
1834   if (Tok == "DATA_SEGMENT_ALIGN") {
1835     expect("(");
1836     Expr E = readExpr();
1837     expect(",");
1838     readExpr();
1839     expect(")");
1840     return [=] { return alignTo(Script->getDot(), E().getValue()); };
1841   }
1842   if (Tok == "DATA_SEGMENT_END") {
1843     expect("(");
1844     expect(".");
1845     expect(")");
1846     return [] { return Script->getDot(); };
1847   }
1848   // GNU linkers implements more complicated logic to handle
1849   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1850   // the next page boundary for simplicity.
1851   if (Tok == "DATA_SEGMENT_RELRO_END") {
1852     expect("(");
1853     readExpr();
1854     expect(",");
1855     readExpr();
1856     expect(")");
1857     return [] { return alignTo(Script->getDot(), Target->PageSize); };
1858   }
1859   if (Tok == "SIZEOF") {
1860     StringRef Name = readParenLiteral();
1861     return [=] { return Script->getOutputSectionSize(Name); };
1862   }
1863   if (Tok == "ALIGNOF") {
1864     StringRef Name = readParenLiteral();
1865     return [=] { return Script->getOutputSection(Location, Name)->Alignment; };
1866   }
1867   if (Tok == "SIZEOF_HEADERS")
1868     return [=] { return elf::getHeaderSize(); };
1869 
1870   // Tok is a literal number.
1871   uint64_t V;
1872   if (readInteger(Tok, V))
1873     return [=] { return V; };
1874 
1875   // Tok is a symbol name.
1876   if (Tok != "." && !isValidCIdentifier(Tok))
1877     setError("malformed number: " + Tok);
1878   return [=] { return Script->getSymbolValue(Location, Tok); };
1879 }
1880 
1881 Expr ScriptParser::readTernary(Expr Cond) {
1882   Expr L = readExpr();
1883   expect(":");
1884   Expr R = readExpr();
1885   return [=] { return Cond().getValue() ? L() : R(); };
1886 }
1887 
1888 Expr ScriptParser::readParenExpr() {
1889   expect("(");
1890   Expr E = readExpr();
1891   expect(")");
1892   return E;
1893 }
1894 
1895 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1896   std::vector<StringRef> Phdrs;
1897   while (!Error && peek().startswith(":")) {
1898     StringRef Tok = next();
1899     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1900   }
1901   return Phdrs;
1902 }
1903 
1904 // Read a program header type name. The next token must be a
1905 // name of a program header type or a constant (e.g. "0x3").
1906 unsigned ScriptParser::readPhdrType() {
1907   StringRef Tok = next();
1908   uint64_t Val;
1909   if (readInteger(Tok, Val))
1910     return Val;
1911 
1912   unsigned Ret = StringSwitch<unsigned>(Tok)
1913                      .Case("PT_NULL", PT_NULL)
1914                      .Case("PT_LOAD", PT_LOAD)
1915                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1916                      .Case("PT_INTERP", PT_INTERP)
1917                      .Case("PT_NOTE", PT_NOTE)
1918                      .Case("PT_SHLIB", PT_SHLIB)
1919                      .Case("PT_PHDR", PT_PHDR)
1920                      .Case("PT_TLS", PT_TLS)
1921                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1922                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1923                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1924                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1925                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1926                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1927                      .Default(-1);
1928 
1929   if (Ret == (unsigned)-1) {
1930     setError("invalid program header type: " + Tok);
1931     return PT_NULL;
1932   }
1933   return Ret;
1934 }
1935 
1936 // Reads an anonymous version declaration.
1937 void ScriptParser::readAnonymousDeclaration() {
1938   std::vector<SymbolVersion> Locals;
1939   std::vector<SymbolVersion> Globals;
1940   std::tie(Locals, Globals) = readSymbols();
1941 
1942   for (SymbolVersion V : Locals) {
1943     if (V.Name == "*")
1944       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1945     else
1946       Config->VersionScriptLocals.push_back(V);
1947   }
1948 
1949   for (SymbolVersion V : Globals)
1950     Config->VersionScriptGlobals.push_back(V);
1951 
1952   expect(";");
1953 }
1954 
1955 // Reads a non-anonymous version definition,
1956 // e.g. "VerStr { global: foo; bar; local: *; };".
1957 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1958   // Read a symbol list.
1959   std::vector<SymbolVersion> Locals;
1960   std::vector<SymbolVersion> Globals;
1961   std::tie(Locals, Globals) = readSymbols();
1962 
1963   for (SymbolVersion V : Locals) {
1964     if (V.Name == "*")
1965       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1966     else
1967       Config->VersionScriptLocals.push_back(V);
1968   }
1969 
1970   // Create a new version definition and add that to the global symbols.
1971   VersionDefinition Ver;
1972   Ver.Name = VerStr;
1973   Ver.Globals = Globals;
1974 
1975   // User-defined version number starts from 2 because 0 and 1 are
1976   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1977   Ver.Id = Config->VersionDefinitions.size() + 2;
1978   Config->VersionDefinitions.push_back(Ver);
1979 
1980   // Each version may have a parent version. For example, "Ver2"
1981   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1982   // as a parent. This version hierarchy is, probably against your
1983   // instinct, purely for hint; the runtime doesn't care about it
1984   // at all. In LLD, we simply ignore it.
1985   if (peek() != ";")
1986     skip();
1987   expect(";");
1988 }
1989 
1990 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1991 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1992 ScriptParser::readSymbols() {
1993   std::vector<SymbolVersion> Locals;
1994   std::vector<SymbolVersion> Globals;
1995   std::vector<SymbolVersion> *V = &Globals;
1996 
1997   while (!Error) {
1998     if (consume("}"))
1999       break;
2000     if (consumeLabel("local")) {
2001       V = &Locals;
2002       continue;
2003     }
2004     if (consumeLabel("global")) {
2005       V = &Globals;
2006       continue;
2007     }
2008 
2009     if (consume("extern")) {
2010       std::vector<SymbolVersion> Ext = readVersionExtern();
2011       V->insert(V->end(), Ext.begin(), Ext.end());
2012     } else {
2013       StringRef Tok = next();
2014       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
2015     }
2016     expect(";");
2017   }
2018   return {Locals, Globals};
2019 }
2020 
2021 // Reads an "extern C++" directive, e.g.,
2022 // "extern "C++" { ns::*; "f(int, double)"; };"
2023 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
2024   StringRef Tok = next();
2025   bool IsCXX = Tok == "\"C++\"";
2026   if (!IsCXX && Tok != "\"C\"")
2027     setError("Unknown language");
2028   expect("{");
2029 
2030   std::vector<SymbolVersion> Ret;
2031   while (!Error && peek() != "}") {
2032     StringRef Tok = next();
2033     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
2034     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
2035     expect(";");
2036   }
2037 
2038   expect("}");
2039   return Ret;
2040 }
2041 
2042 uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
2043                                             StringRef S3) {
2044   if (!(consume(S1) || consume(S2) || consume(S3))) {
2045     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
2046     return 0;
2047   }
2048   expect("=");
2049 
2050   // TODO: Fully support constant expressions.
2051   uint64_t Val;
2052   if (!readInteger(next(), Val))
2053     setError("nonconstant expression for " + S1);
2054   return Val;
2055 }
2056 
2057 // Parse the MEMORY command as specified in:
2058 // https://sourceware.org/binutils/docs/ld/MEMORY.html
2059 //
2060 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
2061 void ScriptParser::readMemory() {
2062   expect("{");
2063   while (!Error && !consume("}")) {
2064     StringRef Name = next();
2065 
2066     uint32_t Flags = 0;
2067     uint32_t NegFlags = 0;
2068     if (consume("(")) {
2069       std::tie(Flags, NegFlags) = readMemoryAttributes();
2070       expect(")");
2071     }
2072     expect(":");
2073 
2074     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
2075     expect(",");
2076     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
2077 
2078     // Add the memory region to the region map (if it doesn't already exist).
2079     auto It = Opt.MemoryRegions.find(Name);
2080     if (It != Opt.MemoryRegions.end())
2081       setError("region '" + Name + "' already defined");
2082     else
2083       Opt.MemoryRegions[Name] = {Name, Origin, Length, Origin, Flags, NegFlags};
2084   }
2085 }
2086 
2087 // This function parses the attributes used to match against section
2088 // flags when placing output sections in a memory region. These flags
2089 // are only used when an explicit memory region name is not used.
2090 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
2091   uint32_t Flags = 0;
2092   uint32_t NegFlags = 0;
2093   bool Invert = false;
2094 
2095   for (char C : next().lower()) {
2096     uint32_t Flag = 0;
2097     if (C == '!')
2098       Invert = !Invert;
2099     else if (C == 'w')
2100       Flag = SHF_WRITE;
2101     else if (C == 'x')
2102       Flag = SHF_EXECINSTR;
2103     else if (C == 'a')
2104       Flag = SHF_ALLOC;
2105     else if (C != 'r')
2106       setError("invalid memory region attribute");
2107 
2108     if (Invert)
2109       NegFlags |= Flag;
2110     else
2111       Flags |= Flag;
2112   }
2113   return {Flags, NegFlags};
2114 }
2115 
2116 void elf::readLinkerScript(MemoryBufferRef MB) {
2117   ScriptParser(MB).readLinkerScript();
2118 }
2119 
2120 void elf::readVersionScript(MemoryBufferRef MB) {
2121   ScriptParser(MB).readVersionScript();
2122 }
2123 
2124 void elf::readDynamicList(MemoryBufferRef MB) {
2125   ScriptParser(MB).readDynamicList();
2126 }
2127