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