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 // It parses a linker script and write the result to Config or ScriptConfig
12 // objects.
13 //
14 // If SECTIONS command is used, a ScriptConfig contains an AST
15 // of the command which will later be consumed by createSections() and
16 // assignAddresses().
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "LinkerScript.h"
21 #include "Config.h"
22 #include "Driver.h"
23 #include "InputSection.h"
24 #include "OutputSections.h"
25 #include "ScriptParser.h"
26 #include "Strings.h"
27 #include "Symbols.h"
28 #include "SymbolTable.h"
29 #include "Target.h"
30 #include "Writer.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/Support/ELF.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/StringSaver.h"
37 
38 using namespace llvm;
39 using namespace llvm::ELF;
40 using namespace llvm::object;
41 using namespace lld;
42 using namespace lld::elf;
43 
44 LinkerScriptBase *elf::ScriptBase;
45 ScriptConfiguration *elf::ScriptConfig;
46 
47 template <class ELFT> static void addRegular(SymbolAssignment *Cmd) {
48   Symbol *Sym = Symtab<ELFT>::X->addRegular(Cmd->Name, STB_GLOBAL, STV_DEFAULT);
49   Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
50   Cmd->Sym = Sym->body();
51 
52   // If we have no SECTIONS then we don't have '.' and don't call
53   // assignAddresses(). We calculate symbol value immediately in this case.
54   if (!ScriptConfig->HasSections)
55     cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(0);
56 }
57 
58 template <class ELFT> static void addSynthetic(SymbolAssignment *Cmd) {
59   Symbol *Sym = Symtab<ELFT>::X->addSynthetic(
60       Cmd->Name, nullptr, 0, Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
61   Cmd->Sym = Sym->body();
62 }
63 
64 template <class ELFT> static void addSymbol(SymbolAssignment *Cmd) {
65   if (Cmd->IsAbsolute)
66     addRegular<ELFT>(Cmd);
67   else
68     addSynthetic<ELFT>(Cmd);
69 }
70 // If a symbol was in PROVIDE(), we need to define it only when
71 // it is an undefined symbol.
72 template <class ELFT> static bool shouldDefine(SymbolAssignment *Cmd) {
73   if (Cmd->Name == ".")
74     return false;
75   if (!Cmd->Provide)
76     return true;
77   SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
78   return B && B->isUndefined();
79 }
80 
81 bool SymbolAssignment::classof(const BaseCommand *C) {
82   return C->Kind == AssignmentKind;
83 }
84 
85 bool OutputSectionCommand::classof(const BaseCommand *C) {
86   return C->Kind == OutputSectionKind;
87 }
88 
89 bool InputSectionDescription::classof(const BaseCommand *C) {
90   return C->Kind == InputSectionKind;
91 }
92 
93 bool AssertCommand::classof(const BaseCommand *C) {
94   return C->Kind == AssertKind;
95 }
96 
97 template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
98   return !S || !S->Live;
99 }
100 
101 template <class ELFT> LinkerScript<ELFT>::LinkerScript() {}
102 template <class ELFT> LinkerScript<ELFT>::~LinkerScript() {}
103 
104 template <class ELFT>
105 bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
106   for (Regex *Re : Opt.KeptSections)
107     if (Re->match(S->Name))
108       return true;
109   return false;
110 }
111 
112 static bool comparePriority(InputSectionData *A, InputSectionData *B) {
113   return getPriority(A->Name) < getPriority(B->Name);
114 }
115 
116 static bool compareName(InputSectionData *A, InputSectionData *B) {
117   return A->Name < B->Name;
118 }
119 
120 static bool compareAlignment(InputSectionData *A, InputSectionData *B) {
121   // ">" is not a mistake. Larger alignments are placed before smaller
122   // alignments in order to reduce the amount of padding necessary.
123   // This is compatible with GNU.
124   return A->Alignment > B->Alignment;
125 }
126 
127 static std::function<bool(InputSectionData *, InputSectionData *)>
128 getComparator(SortSectionPolicy K) {
129   switch (K) {
130   case SortSectionPolicy::Alignment:
131     return compareAlignment;
132   case SortSectionPolicy::Name:
133     return compareName;
134   case SortSectionPolicy::Priority:
135     return comparePriority;
136   default:
137     llvm_unreachable("unknown sort policy");
138   }
139 }
140 
141 template <class ELFT>
142 static bool matchConstraints(ArrayRef<InputSectionBase<ELFT> *> Sections,
143                              ConstraintKind Kind) {
144   if (Kind == ConstraintKind::NoConstraint)
145     return true;
146   bool IsRW = llvm::any_of(Sections, [=](InputSectionData *Sec2) {
147     auto *Sec = static_cast<InputSectionBase<ELFT> *>(Sec2);
148     return Sec->getSectionHdr()->sh_flags & SHF_WRITE;
149   });
150   return (IsRW && Kind == ConstraintKind::ReadWrite) ||
151          (!IsRW && Kind == ConstraintKind::ReadOnly);
152 }
153 
154 static void sortSections(InputSectionData **Begin, InputSectionData **End,
155                          SortSectionPolicy K) {
156   if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
157     std::stable_sort(Begin, End, getComparator(K));
158 }
159 
160 // Compute and remember which sections the InputSectionDescription matches.
161 template <class ELFT>
162 void LinkerScript<ELFT>::computeInputSections(InputSectionDescription *I) {
163   // Collects all sections that satisfy constraints of I
164   // and attach them to I.
165   for (SectionPattern &Pat : I->SectionPatterns) {
166     size_t SizeBefore = I->Sections.size();
167     for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles()) {
168       StringRef Filename = sys::path::filename(F->getName());
169       if (!I->FileRe.match(Filename) || Pat.ExcludedFileRe.match(Filename))
170         continue;
171 
172       for (InputSectionBase<ELFT> *S : F->getSections())
173         if (!isDiscarded(S) && !S->OutSec && Pat.SectionRe.match(S->Name))
174           I->Sections.push_back(S);
175       if (Pat.SectionRe.match("COMMON"))
176         I->Sections.push_back(CommonInputSection<ELFT>::X);
177     }
178 
179     // Sort sections as instructed by SORT-family commands and --sort-section
180     // option. Because SORT-family commands can be nested at most two depth
181     // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
182     // line option is respected even if a SORT command is given, the exact
183     // behavior we have here is a bit complicated. Here are the rules.
184     //
185     // 1. If two SORT commands are given, --sort-section is ignored.
186     // 2. If one SORT command is given, and if it is not SORT_NONE,
187     //    --sort-section is handled as an inner SORT command.
188     // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
189     // 4. If no SORT command is given, sort according to --sort-section.
190     InputSectionData **Begin = I->Sections.data() + SizeBefore;
191     InputSectionData **End = I->Sections.data() + I->Sections.size();
192     if (Pat.SortOuter != SortSectionPolicy::None) {
193       if (Pat.SortInner == SortSectionPolicy::Default)
194         sortSections(Begin, End, Config->SortSection);
195       else
196         sortSections(Begin, End, Pat.SortInner);
197       sortSections(Begin, End, Pat.SortOuter);
198     }
199   }
200 
201   // We do not add duplicate input sections, so mark them with a dummy output
202   // section for now.
203   for (InputSectionData *S : I->Sections) {
204     auto *S2 = static_cast<InputSectionBase<ELFT> *>(S);
205     S2->OutSec = (OutputSectionBase<ELFT> *)-1;
206   }
207 }
208 
209 template <class ELFT>
210 void LinkerScript<ELFT>::discard(ArrayRef<InputSectionBase<ELFT> *> V) {
211   for (InputSectionBase<ELFT> *S : V) {
212     S->Live = false;
213     reportDiscarded(S);
214   }
215 }
216 
217 template <class ELFT>
218 std::vector<InputSectionBase<ELFT> *>
219 LinkerScript<ELFT>::createInputSectionList(OutputSectionCommand &OutCmd) {
220   std::vector<InputSectionBase<ELFT> *> Ret;
221 
222   for (const std::unique_ptr<BaseCommand> &Base : OutCmd.Commands) {
223     auto *Cmd = dyn_cast<InputSectionDescription>(Base.get());
224     if (!Cmd)
225       continue;
226     computeInputSections(Cmd);
227     for (InputSectionData *S : Cmd->Sections)
228       Ret.push_back(static_cast<InputSectionBase<ELFT> *>(S));
229   }
230 
231   return Ret;
232 }
233 
234 template <class ELFT>
235 static SectionKey<ELFT::Is64Bits> createKey(InputSectionBase<ELFT> *C,
236                                             StringRef OutsecName) {
237   // When using linker script the merge rules are different.
238   // Unfortunately, linker scripts are name based. This means that expressions
239   // like *(.foo*) can refer to multiple input sections that would normally be
240   // placed in different output sections. We cannot put them in different
241   // output sections or we would produce wrong results for
242   // start = .; *(.foo.*) end = .; *(.bar)
243   // and a mapping of .foo1 and .bar1 to one section and .foo2 and .bar2 to
244   // another. The problem is that there is no way to layout those output
245   // sections such that the .foo sections are the only thing between the
246   // start and end symbols.
247 
248   // An extra annoyance is that we cannot simply disable merging of the contents
249   // of SHF_MERGE sections, but our implementation requires one output section
250   // per "kind" (string or not, which size/aligment).
251   // Fortunately, creating symbols in the middle of a merge section is not
252   // supported by bfd or gold, so we can just create multiple section in that
253   // case.
254   const typename ELFT::Shdr *H = C->getSectionHdr();
255   typedef typename ELFT::uint uintX_t;
256   uintX_t Flags = H->sh_flags & (SHF_MERGE | SHF_STRINGS);
257 
258   uintX_t Alignment = 0;
259   if (isa<MergeInputSection<ELFT>>(C))
260     Alignment = std::max(H->sh_addralign, H->sh_entsize);
261 
262   return SectionKey<ELFT::Is64Bits>{OutsecName, /*Type*/ 0, Flags, Alignment};
263 }
264 
265 template <class ELFT>
266 void LinkerScript<ELFT>::addSection(OutputSectionFactory<ELFT> &Factory,
267                                     InputSectionBase<ELFT> *Sec,
268                                     StringRef Name) {
269   OutputSectionBase<ELFT> *OutSec;
270   bool IsNew;
271   std::tie(OutSec, IsNew) = Factory.create(createKey(Sec, Name), Sec);
272   if (IsNew)
273     OutputSections->push_back(OutSec);
274   OutSec->addSection(Sec);
275 }
276 
277 template <class ELFT>
278 void LinkerScript<ELFT>::processCommands(OutputSectionFactory<ELFT> &Factory) {
279 
280   for (unsigned I = 0; I < Opt.Commands.size(); ++I) {
281     auto Iter = Opt.Commands.begin() + I;
282     const std::unique_ptr<BaseCommand> &Base1 = *Iter;
283     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base1.get())) {
284       if (shouldDefine<ELFT>(Cmd))
285         addRegular<ELFT>(Cmd);
286       continue;
287     }
288     if (auto *Cmd = dyn_cast<AssertCommand>(Base1.get())) {
289       // If we don't have SECTIONS then output sections have already been
290       // created by Writer<ELFT>. The LinkerScript<ELFT>::assignAddresses
291       // will not be called, so ASSERT should be evaluated now.
292       if (!Opt.HasSections)
293         Cmd->Expression(0);
294       continue;
295     }
296 
297     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base1.get())) {
298       std::vector<InputSectionBase<ELFT> *> V = createInputSectionList(*Cmd);
299 
300       if (Cmd->Name == "/DISCARD/") {
301         discard(V);
302         continue;
303       }
304 
305       if (!matchConstraints<ELFT>(V, Cmd->Constraint)) {
306         for (InputSectionBase<ELFT> *S : V)
307           S->OutSec = nullptr;
308         Opt.Commands.erase(Iter);
309         --I;
310         continue;
311       }
312 
313       for (const std::unique_ptr<BaseCommand> &Base : Cmd->Commands)
314         if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base.get()))
315           if (shouldDefine<ELFT>(OutCmd))
316             addSymbol<ELFT>(OutCmd);
317 
318       if (V.empty())
319         continue;
320 
321       for (InputSectionBase<ELFT> *Sec : V) {
322         addSection(Factory, Sec, Cmd->Name);
323         if (uint32_t Subalign = Cmd->SubalignExpr ? Cmd->SubalignExpr(0) : 0)
324           Sec->Alignment = Subalign;
325       }
326     }
327   }
328 }
329 
330 template <class ELFT>
331 void LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
332   processCommands(Factory);
333   // Add orphan sections.
334   for (ObjectFile<ELFT> *F : Symtab<ELFT>::X->getObjectFiles())
335     for (InputSectionBase<ELFT> *S : F->getSections())
336       if (!isDiscarded(S) && !S->OutSec)
337         addSection(Factory, S, getOutputSectionName(S));
338 }
339 
340 // Sets value of a section-defined symbol. Two kinds of
341 // symbols are processed: synthetic symbols, whose value
342 // is an offset from beginning of section and regular
343 // symbols whose value is absolute.
344 template <class ELFT>
345 static void assignSectionSymbol(SymbolAssignment *Cmd,
346                                 OutputSectionBase<ELFT> *Sec,
347                                 typename ELFT::uint Off) {
348   if (!Cmd->Sym)
349     return;
350 
351   if (auto *Body = dyn_cast<DefinedSynthetic<ELFT>>(Cmd->Sym)) {
352     Body->Section = Sec;
353     Body->Value = Cmd->Expression(Sec->getVA() + Off) - Sec->getVA();
354     return;
355   }
356   auto *Body = cast<DefinedRegular<ELFT>>(Cmd->Sym);
357   Body->Value = Cmd->Expression(Sec->getVA() + Off);
358 }
359 
360 template <class ELFT> void LinkerScript<ELFT>::output(InputSection<ELFT> *S) {
361   if (!AlreadyOutputIS.insert(S).second)
362     return;
363   bool IsTbss =
364       (CurOutSec->getFlags() & SHF_TLS) && CurOutSec->getType() == SHT_NOBITS;
365 
366   uintX_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
367   Pos = alignTo(Pos, S->Alignment);
368   S->OutSecOff = Pos - CurOutSec->getVA();
369   Pos += S->getSize();
370 
371   // Update output section size after adding each section. This is so that
372   // SIZEOF works correctly in the case below:
373   // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
374   CurOutSec->setSize(Pos - CurOutSec->getVA());
375 
376   if (!IsTbss)
377     Dot = Pos;
378 }
379 
380 template <class ELFT> void LinkerScript<ELFT>::flush() {
381   if (auto *OutSec = dyn_cast_or_null<OutputSection<ELFT>>(CurOutSec)) {
382     for (InputSection<ELFT> *I : OutSec->Sections)
383       output(I);
384     AlreadyOutputOS.insert(CurOutSec);
385   }
386 }
387 
388 template <class ELFT>
389 void LinkerScript<ELFT>::switchTo(OutputSectionBase<ELFT> *Sec) {
390   if (CurOutSec == Sec)
391     return;
392   if (AlreadyOutputOS.count(Sec))
393     return;
394 
395   flush();
396   CurOutSec = Sec;
397 
398   Dot = alignTo(Dot, CurOutSec->getAlignment());
399   CurOutSec->setVA(Dot);
400 }
401 
402 template <class ELFT> void LinkerScript<ELFT>::process(BaseCommand &Base) {
403   if (auto *AssignCmd = dyn_cast<SymbolAssignment>(&Base)) {
404     if (AssignCmd->Name == ".") {
405       // Update to location counter means update to section size.
406       Dot = AssignCmd->Expression(Dot);
407       CurOutSec->setSize(Dot - CurOutSec->getVA());
408       return;
409     }
410     assignSectionSymbol<ELFT>(AssignCmd, CurOutSec, Dot - CurOutSec->getVA());
411     return;
412   }
413   auto &ICmd = cast<InputSectionDescription>(Base);
414   for (InputSectionData *ID : ICmd.Sections) {
415     auto *IB = static_cast<InputSectionBase<ELFT> *>(ID);
416     switchTo(IB->OutSec);
417     if (auto *I = dyn_cast<InputSection<ELFT>>(IB))
418       output(I);
419     else if (AlreadyOutputOS.insert(CurOutSec).second)
420       Dot += CurOutSec->getSize();
421   }
422 }
423 
424 template <class ELFT>
425 static std::vector<OutputSectionBase<ELFT> *>
426 findSections(OutputSectionCommand &Cmd,
427              const std::vector<OutputSectionBase<ELFT> *> &Sections) {
428   std::vector<OutputSectionBase<ELFT> *> Ret;
429   for (OutputSectionBase<ELFT> *Sec : Sections)
430     if (Sec->getName() == Cmd.Name)
431       Ret.push_back(Sec);
432   return Ret;
433 }
434 
435 template <class ELFT>
436 void LinkerScript<ELFT>::assignOffsets(OutputSectionCommand *Cmd) {
437   std::vector<OutputSectionBase<ELFT> *> Sections =
438       findSections(*Cmd, *OutputSections);
439   if (Sections.empty())
440     return;
441   switchTo(Sections[0]);
442 
443   // Find the last section output location. We will output orphan sections
444   // there so that end symbols point to the correct location.
445   auto E = std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
446                         [](const std::unique_ptr<BaseCommand> &Cmd) {
447                           return !isa<SymbolAssignment>(*Cmd);
448                         })
449                .base();
450   for (auto I = Cmd->Commands.begin(); I != E; ++I)
451     process(**I);
452   flush();
453   for (OutputSectionBase<ELFT> *Base : Sections) {
454     if (AlreadyOutputOS.count(Base))
455       continue;
456     switchTo(Base);
457     Dot += CurOutSec->getSize();
458     flush();
459   }
460   std::for_each(E, Cmd->Commands.end(),
461                 [this](std::unique_ptr<BaseCommand> &B) { process(*B.get()); });
462 }
463 
464 template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
465   // It is common practice to use very generic linker scripts. So for any
466   // given run some of the output sections in the script will be empty.
467   // We could create corresponding empty output sections, but that would
468   // clutter the output.
469   // We instead remove trivially empty sections. The bfd linker seems even
470   // more aggressive at removing them.
471   auto Pos = std::remove_if(
472       Opt.Commands.begin(), Opt.Commands.end(),
473       [&](const std::unique_ptr<BaseCommand> &Base) {
474         auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
475         if (!Cmd)
476           return false;
477         std::vector<OutputSectionBase<ELFT> *> Secs =
478             findSections(*Cmd, *OutputSections);
479         if (!Secs.empty())
480           return false;
481         for (const std::unique_ptr<BaseCommand> &I : Cmd->Commands)
482           if (!isa<InputSectionDescription>(I.get()))
483             return false;
484         return true;
485       });
486   Opt.Commands.erase(Pos, Opt.Commands.end());
487 
488   // Orphan sections are sections present in the input files which
489   // are not explicitly placed into the output file by the linker script.
490   // We place orphan sections at end of file.
491   // Other linkers places them using some heuristics as described in
492   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
493 
494   // The OutputSections are already in the correct order.
495   // This loops creates or moves commands as needed so that they are in the
496   // correct order.
497   int CmdIndex = 0;
498   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
499     StringRef Name = Sec->getName();
500 
501     // Find the last spot where we can insert a command and still get the
502     // correct order.
503     auto CmdIter = Opt.Commands.begin() + CmdIndex;
504     auto E = Opt.Commands.end();
505     while (CmdIter != E && !isa<OutputSectionCommand>(**CmdIter)) {
506       ++CmdIter;
507       ++CmdIndex;
508     }
509 
510     auto Pos =
511         std::find_if(CmdIter, E, [&](const std::unique_ptr<BaseCommand> &Base) {
512           auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
513           return Cmd && Cmd->Name == Name;
514         });
515     if (Pos == E) {
516       Opt.Commands.insert(CmdIter,
517                           llvm::make_unique<OutputSectionCommand>(Name));
518     } else {
519       // If linker script lists alloc/non-alloc sections is the wrong order,
520       // this does a right rotate to bring the desired command in place.
521       auto RPos = llvm::make_reverse_iterator(Pos + 1);
522       std::rotate(RPos, RPos + 1, llvm::make_reverse_iterator(CmdIter));
523     }
524     ++CmdIndex;
525   }
526 
527   // Assign addresses as instructed by linker script SECTIONS sub-commands.
528   Dot = getHeaderSize();
529 
530   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
531     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
532       if (Cmd->Name == ".") {
533         Dot = Cmd->Expression(Dot);
534       } else if (Cmd->Sym) {
535         cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
536       }
537       continue;
538     }
539 
540     if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
541       Cmd->Expression(Dot);
542       continue;
543     }
544 
545     auto *Cmd = cast<OutputSectionCommand>(Base.get());
546 
547     if (Cmd->AddrExpr)
548       Dot = Cmd->AddrExpr(Dot);
549 
550     assignOffsets(Cmd);
551   }
552 
553   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
554   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
555     if (Sec->getFlags() & SHF_ALLOC)
556       MinVA = std::min(MinVA, Sec->getVA());
557     else
558       Sec->setVA(0);
559   }
560 
561   uintX_t HeaderSize =
562       Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
563   if (HeaderSize > MinVA)
564     fatal("Not enough space for ELF and program headers");
565 
566   // ELF and Program headers need to be right before the first section in
567   // memory. Set their addresses accordingly.
568   MinVA = alignDown(MinVA - HeaderSize, Target->PageSize);
569   Out<ELFT>::ElfHeader->setVA(MinVA);
570   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
571 }
572 
573 // Creates program headers as instructed by PHDRS linker script command.
574 template <class ELFT>
575 std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
576   std::vector<PhdrEntry<ELFT>> Ret;
577 
578   // Process PHDRS and FILEHDR keywords because they are not
579   // real output sections and cannot be added in the following loop.
580   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
581     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
582     PhdrEntry<ELFT> &Phdr = Ret.back();
583 
584     if (Cmd.HasFilehdr)
585       Phdr.add(Out<ELFT>::ElfHeader);
586     if (Cmd.HasPhdrs)
587       Phdr.add(Out<ELFT>::ProgramHeaders);
588 
589     if (Cmd.LMAExpr) {
590       Phdr.H.p_paddr = Cmd.LMAExpr(0);
591       Phdr.HasLMA = true;
592     }
593   }
594 
595   // Add output sections to program headers.
596   PhdrEntry<ELFT> *Load = nullptr;
597   uintX_t Flags = PF_R;
598   for (OutputSectionBase<ELFT> *Sec : *OutputSections) {
599     if (!(Sec->getFlags() & SHF_ALLOC))
600       break;
601 
602     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
603     if (!PhdrIds.empty()) {
604       // Assign headers specified by linker script
605       for (size_t Id : PhdrIds) {
606         Ret[Id].add(Sec);
607         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
608           Ret[Id].H.p_flags |= Sec->getPhdrFlags();
609       }
610     } else {
611       // If we have no load segment or flags've changed then we want new load
612       // segment.
613       uintX_t NewFlags = Sec->getPhdrFlags();
614       if (Load == nullptr || Flags != NewFlags) {
615         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
616         Flags = NewFlags;
617       }
618       Load->add(Sec);
619     }
620   }
621   return Ret;
622 }
623 
624 template <class ELFT> bool LinkerScript<ELFT>::ignoreInterpSection() {
625   // Ignore .interp section in case we have PHDRS specification
626   // and PT_INTERP isn't listed.
627   return !Opt.PhdrsCommands.empty() &&
628          llvm::find_if(Opt.PhdrsCommands, [](const PhdrsCommand &Cmd) {
629            return Cmd.Type == PT_INTERP;
630          }) == Opt.PhdrsCommands.end();
631 }
632 
633 template <class ELFT>
634 ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
635   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
636     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
637       if (Cmd->Name == Name)
638         return Cmd->Filler;
639   return {};
640 }
641 
642 template <class ELFT> Expr LinkerScript<ELFT>::getLma(StringRef Name) {
643   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
644     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
645       if (Cmd->LmaExpr && Cmd->Name == Name)
646         return Cmd->LmaExpr;
647   return {};
648 }
649 
650 // Returns the index of the given section name in linker script
651 // SECTIONS commands. Sections are laid out as the same order as they
652 // were in the script. If a given name did not appear in the script,
653 // it returns INT_MAX, so that it will be laid out at end of file.
654 template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
655   int I = 0;
656   for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
657     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
658       if (Cmd->Name == Name)
659         return I;
660     ++I;
661   }
662   return INT_MAX;
663 }
664 
665 template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
666   return !Opt.PhdrsCommands.empty();
667 }
668 
669 template <class ELFT>
670 uint64_t LinkerScript<ELFT>::getOutputSectionAddress(StringRef Name) {
671   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
672     if (Sec->getName() == Name)
673       return Sec->getVA();
674   error("undefined section " + Name);
675   return 0;
676 }
677 
678 template <class ELFT>
679 uint64_t LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
680   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
681     if (Sec->getName() == Name)
682       return Sec->getSize();
683   error("undefined section " + Name);
684   return 0;
685 }
686 
687 template <class ELFT>
688 uint64_t LinkerScript<ELFT>::getOutputSectionAlign(StringRef Name) {
689   for (OutputSectionBase<ELFT> *Sec : *OutputSections)
690     if (Sec->getName() == Name)
691       return Sec->getAlignment();
692   error("undefined section " + Name);
693   return 0;
694 }
695 
696 template <class ELFT> uint64_t LinkerScript<ELFT>::getHeaderSize() {
697   return Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
698 }
699 
700 template <class ELFT> uint64_t LinkerScript<ELFT>::getSymbolValue(StringRef S) {
701   if (SymbolBody *B = Symtab<ELFT>::X->find(S))
702     return B->getVA<ELFT>();
703   error("symbol not found: " + S);
704   return 0;
705 }
706 
707 // Returns indices of ELF headers containing specific section, identified
708 // by Name. Each index is a zero based number of ELF header listed within
709 // PHDRS {} script block.
710 template <class ELFT>
711 std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
712   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
713     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
714     if (!Cmd || Cmd->Name != SectionName)
715       continue;
716 
717     std::vector<size_t> Ret;
718     for (StringRef PhdrName : Cmd->Phdrs)
719       Ret.push_back(getPhdrIndex(PhdrName));
720     return Ret;
721   }
722   return {};
723 }
724 
725 template <class ELFT>
726 size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
727   size_t I = 0;
728   for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
729     if (Cmd.Name == PhdrName)
730       return I;
731     ++I;
732   }
733   error("section header '" + PhdrName + "' is not listed in PHDRS");
734   return 0;
735 }
736 
737 class elf::ScriptParser : public ScriptParserBase {
738   typedef void (ScriptParser::*Handler)();
739 
740 public:
741   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
742 
743   void readLinkerScript();
744   void readVersionScript();
745 
746 private:
747   void addFile(StringRef Path);
748 
749   void readAsNeeded();
750   void readEntry();
751   void readExtern();
752   void readGroup();
753   void readInclude();
754   void readOutput();
755   void readOutputArch();
756   void readOutputFormat();
757   void readPhdrs();
758   void readSearchDir();
759   void readSections();
760   void readVersion();
761   void readVersionScriptCommand();
762 
763   SymbolAssignment *readAssignment(StringRef Name);
764   std::vector<uint8_t> readFill();
765   OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
766   std::vector<uint8_t> readOutputSectionFiller(StringRef Tok);
767   std::vector<StringRef> readOutputSectionPhdrs();
768   InputSectionDescription *readInputSectionDescription(StringRef Tok);
769   Regex readFilePatterns();
770   std::vector<SectionPattern> readInputSectionsList();
771   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
772   unsigned readPhdrType();
773   SortSectionPolicy readSortKind();
774   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
775   SymbolAssignment *readProvideOrAssignment(StringRef Tok, bool MakeAbsolute);
776   void readSort();
777   Expr readAssert();
778 
779   Expr readExpr();
780   Expr readExpr1(Expr Lhs, int MinPrec);
781   Expr readPrimary();
782   Expr readTernary(Expr Cond);
783   Expr readParenExpr();
784 
785   // For parsing version script.
786   void readExtern(std::vector<SymbolVersion> *Globals);
787   void readVersionDeclaration(StringRef VerStr);
788   void readGlobal(StringRef VerStr);
789   void readLocal();
790 
791   ScriptConfiguration &Opt = *ScriptConfig;
792   StringSaver Saver = {ScriptConfig->Alloc};
793   bool IsUnderSysroot;
794 };
795 
796 void ScriptParser::readVersionScript() {
797   readVersionScriptCommand();
798   if (!atEOF())
799     setError("EOF expected, but got " + next());
800 }
801 
802 void ScriptParser::readVersionScriptCommand() {
803   if (skip("{")) {
804     readVersionDeclaration("");
805     return;
806   }
807 
808   while (!atEOF() && !Error && peek() != "}") {
809     StringRef VerStr = next();
810     if (VerStr == "{") {
811       setError("anonymous version definition is used in "
812                "combination with other version definitions");
813       return;
814     }
815     expect("{");
816     readVersionDeclaration(VerStr);
817   }
818 }
819 
820 void ScriptParser::readVersion() {
821   expect("{");
822   readVersionScriptCommand();
823   expect("}");
824 }
825 
826 void ScriptParser::readLinkerScript() {
827   while (!atEOF()) {
828     StringRef Tok = next();
829     if (Tok == ";")
830       continue;
831 
832     if (Tok == "ASSERT") {
833       Opt.Commands.emplace_back(new AssertCommand(readAssert()));
834     } else if (Tok == "ENTRY") {
835       readEntry();
836     } else if (Tok == "EXTERN") {
837       readExtern();
838     } else if (Tok == "GROUP" || Tok == "INPUT") {
839       readGroup();
840     } else if (Tok == "INCLUDE") {
841       readInclude();
842     } else if (Tok == "OUTPUT") {
843       readOutput();
844     } else if (Tok == "OUTPUT_ARCH") {
845       readOutputArch();
846     } else if (Tok == "OUTPUT_FORMAT") {
847       readOutputFormat();
848     } else if (Tok == "PHDRS") {
849       readPhdrs();
850     } else if (Tok == "SEARCH_DIR") {
851       readSearchDir();
852     } else if (Tok == "SECTIONS") {
853       readSections();
854     } else if (Tok == "VERSION") {
855       readVersion();
856     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok, true)) {
857       Opt.Commands.emplace_back(Cmd);
858     } else {
859       setError("unknown directive: " + Tok);
860     }
861   }
862 }
863 
864 void ScriptParser::addFile(StringRef S) {
865   if (IsUnderSysroot && S.startswith("/")) {
866     SmallString<128> Path;
867     (Config->Sysroot + S).toStringRef(Path);
868     if (sys::fs::exists(Path)) {
869       Driver->addFile(Saver.save(Path.str()));
870       return;
871     }
872   }
873 
874   if (sys::path::is_absolute(S)) {
875     Driver->addFile(S);
876   } else if (S.startswith("=")) {
877     if (Config->Sysroot.empty())
878       Driver->addFile(S.substr(1));
879     else
880       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
881   } else if (S.startswith("-l")) {
882     Driver->addLibrary(S.substr(2));
883   } else if (sys::fs::exists(S)) {
884     Driver->addFile(S);
885   } else {
886     std::string Path = findFromSearchPaths(S);
887     if (Path.empty())
888       setError("unable to find " + S);
889     else
890       Driver->addFile(Saver.save(Path));
891   }
892 }
893 
894 void ScriptParser::readAsNeeded() {
895   expect("(");
896   bool Orig = Config->AsNeeded;
897   Config->AsNeeded = true;
898   while (!Error && !skip(")"))
899     addFile(unquote(next()));
900   Config->AsNeeded = Orig;
901 }
902 
903 void ScriptParser::readEntry() {
904   // -e <symbol> takes predecence over ENTRY(<symbol>).
905   expect("(");
906   StringRef Tok = next();
907   if (Config->Entry.empty())
908     Config->Entry = Tok;
909   expect(")");
910 }
911 
912 void ScriptParser::readExtern() {
913   expect("(");
914   while (!Error && !skip(")"))
915     Config->Undefined.push_back(next());
916 }
917 
918 void ScriptParser::readGroup() {
919   expect("(");
920   while (!Error && !skip(")")) {
921     StringRef Tok = next();
922     if (Tok == "AS_NEEDED")
923       readAsNeeded();
924     else
925       addFile(unquote(Tok));
926   }
927 }
928 
929 void ScriptParser::readInclude() {
930   StringRef Tok = next();
931   auto MBOrErr = MemoryBuffer::getFile(unquote(Tok));
932   if (!MBOrErr) {
933     setError("cannot open " + Tok);
934     return;
935   }
936   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
937   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
938   std::vector<StringRef> V = tokenize(S);
939   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
940 }
941 
942 void ScriptParser::readOutput() {
943   // -o <file> takes predecence over OUTPUT(<file>).
944   expect("(");
945   StringRef Tok = next();
946   if (Config->OutputFile.empty())
947     Config->OutputFile = unquote(Tok);
948   expect(")");
949 }
950 
951 void ScriptParser::readOutputArch() {
952   // Error checking only for now.
953   expect("(");
954   next();
955   expect(")");
956 }
957 
958 void ScriptParser::readOutputFormat() {
959   // Error checking only for now.
960   expect("(");
961   next();
962   StringRef Tok = next();
963   if (Tok == ")")
964     return;
965   if (Tok != ",") {
966     setError("unexpected token: " + Tok);
967     return;
968   }
969   next();
970   expect(",");
971   next();
972   expect(")");
973 }
974 
975 void ScriptParser::readPhdrs() {
976   expect("{");
977   while (!Error && !skip("}")) {
978     StringRef Tok = next();
979     Opt.PhdrsCommands.push_back(
980         {Tok, PT_NULL, false, false, UINT_MAX, nullptr});
981     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
982 
983     PhdrCmd.Type = readPhdrType();
984     do {
985       Tok = next();
986       if (Tok == ";")
987         break;
988       if (Tok == "FILEHDR")
989         PhdrCmd.HasFilehdr = true;
990       else if (Tok == "PHDRS")
991         PhdrCmd.HasPhdrs = true;
992       else if (Tok == "AT")
993         PhdrCmd.LMAExpr = readParenExpr();
994       else if (Tok == "FLAGS") {
995         expect("(");
996         // Passing 0 for the value of dot is a bit of a hack. It means that
997         // we accept expressions like ".|1".
998         PhdrCmd.Flags = readExpr()(0);
999         expect(")");
1000       } else
1001         setError("unexpected header attribute: " + Tok);
1002     } while (!Error);
1003   }
1004 }
1005 
1006 void ScriptParser::readSearchDir() {
1007   expect("(");
1008   StringRef Tok = next();
1009   if (!Config->Nostdlib)
1010     Config->SearchPaths.push_back(unquote(Tok));
1011   expect(")");
1012 }
1013 
1014 void ScriptParser::readSections() {
1015   Opt.HasSections = true;
1016   expect("{");
1017   while (!Error && !skip("}")) {
1018     StringRef Tok = next();
1019     BaseCommand *Cmd = readProvideOrAssignment(Tok, true);
1020     if (!Cmd) {
1021       if (Tok == "ASSERT")
1022         Cmd = new AssertCommand(readAssert());
1023       else
1024         Cmd = readOutputSectionDescription(Tok);
1025     }
1026     Opt.Commands.emplace_back(Cmd);
1027   }
1028 }
1029 
1030 static int precedence(StringRef Op) {
1031   return StringSwitch<int>(Op)
1032       .Case("*", 4)
1033       .Case("/", 4)
1034       .Case("+", 3)
1035       .Case("-", 3)
1036       .Case("<", 2)
1037       .Case(">", 2)
1038       .Case(">=", 2)
1039       .Case("<=", 2)
1040       .Case("==", 2)
1041       .Case("!=", 2)
1042       .Case("&", 1)
1043       .Case("|", 1)
1044       .Default(-1);
1045 }
1046 
1047 Regex ScriptParser::readFilePatterns() {
1048   std::vector<StringRef> V;
1049   while (!Error && !skip(")"))
1050     V.push_back(next());
1051   return compileGlobPatterns(V);
1052 }
1053 
1054 SortSectionPolicy ScriptParser::readSortKind() {
1055   if (skip("SORT") || skip("SORT_BY_NAME"))
1056     return SortSectionPolicy::Name;
1057   if (skip("SORT_BY_ALIGNMENT"))
1058     return SortSectionPolicy::Alignment;
1059   if (skip("SORT_BY_INIT_PRIORITY"))
1060     return SortSectionPolicy::Priority;
1061   if (skip("SORT_NONE"))
1062     return SortSectionPolicy::None;
1063   return SortSectionPolicy::Default;
1064 }
1065 
1066 // Method reads a list of sequence of excluded files and section globs given in
1067 // a following form: ((EXCLUDE_FILE(file_pattern+))? section_pattern+)+
1068 // Example: *(.foo.1 EXCLUDE_FILE (*a.o) .foo.2 EXCLUDE_FILE (*b.o) .foo.3)
1069 // The semantics of that is next:
1070 // * Include .foo.1 from every file.
1071 // * Include .foo.2 from every file but a.o
1072 // * Include .foo.3 from every file but b.o
1073 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
1074   std::vector<SectionPattern> Ret;
1075   while (!Error && peek() != ")") {
1076     Regex ExcludeFileRe;
1077     if (skip("EXCLUDE_FILE")) {
1078       expect("(");
1079       ExcludeFileRe = readFilePatterns();
1080     }
1081 
1082     std::vector<StringRef> V;
1083     while (!Error && peek() != ")" && peek() != "EXCLUDE_FILE")
1084       V.push_back(next());
1085 
1086     if (!V.empty())
1087       Ret.push_back({std::move(ExcludeFileRe), compileGlobPatterns(V)});
1088     else
1089       setError("section pattern is expected");
1090   }
1091   return Ret;
1092 }
1093 
1094 // Section pattern grammar can have complex expressions, for example:
1095 // *(SORT(.foo.* EXCLUDE_FILE (*file1.o) .bar.*) .bar.* SORT(.zed.*))
1096 // Generally is a sequence of globs and excludes that may be wrapped in a SORT()
1097 // commands, like: SORT(glob0) glob1 glob2 SORT(glob4)
1098 // This methods handles wrapping sequences of excluded files and section globs
1099 // into SORT() if that needed and reads them all.
1100 InputSectionDescription *
1101 ScriptParser::readInputSectionRules(StringRef FilePattern) {
1102   auto *Cmd = new InputSectionDescription(FilePattern);
1103   expect("(");
1104   while (!HasError && !skip(")")) {
1105     SortSectionPolicy Outer = readSortKind();
1106     SortSectionPolicy Inner = SortSectionPolicy::Default;
1107     std::vector<SectionPattern> V;
1108     if (Outer != SortSectionPolicy::Default) {
1109       expect("(");
1110       Inner = readSortKind();
1111       if (Inner != SortSectionPolicy::Default) {
1112         expect("(");
1113         V = readInputSectionsList();
1114         expect(")");
1115       } else {
1116         V = readInputSectionsList();
1117       }
1118       expect(")");
1119     } else {
1120       V = readInputSectionsList();
1121     }
1122 
1123     for (SectionPattern &Pat : V) {
1124       Pat.SortInner = Inner;
1125       Pat.SortOuter = Outer;
1126     }
1127 
1128     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
1129   }
1130   return Cmd;
1131 }
1132 
1133 InputSectionDescription *
1134 ScriptParser::readInputSectionDescription(StringRef Tok) {
1135   // Input section wildcard can be surrounded by KEEP.
1136   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
1137   if (Tok == "KEEP") {
1138     expect("(");
1139     StringRef FilePattern = next();
1140     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
1141     expect(")");
1142     for (SectionPattern &Pat : Cmd->SectionPatterns)
1143       Opt.KeptSections.push_back(&Pat.SectionRe);
1144     return Cmd;
1145   }
1146   return readInputSectionRules(Tok);
1147 }
1148 
1149 void ScriptParser::readSort() {
1150   expect("(");
1151   expect("CONSTRUCTORS");
1152   expect(")");
1153 }
1154 
1155 Expr ScriptParser::readAssert() {
1156   expect("(");
1157   Expr E = readExpr();
1158   expect(",");
1159   StringRef Msg = unquote(next());
1160   expect(")");
1161   return [=](uint64_t Dot) {
1162     uint64_t V = E(Dot);
1163     if (!V)
1164       error(Msg);
1165     return V;
1166   };
1167 }
1168 
1169 // Reads a FILL(expr) command. We handle the FILL command as an
1170 // alias for =fillexp section attribute, which is different from
1171 // what GNU linkers do.
1172 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
1173 std::vector<uint8_t> ScriptParser::readFill() {
1174   expect("(");
1175   std::vector<uint8_t> V = readOutputSectionFiller(next());
1176   expect(")");
1177   expect(";");
1178   return V;
1179 }
1180 
1181 OutputSectionCommand *
1182 ScriptParser::readOutputSectionDescription(StringRef OutSec) {
1183   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
1184 
1185   // Read an address expression.
1186   // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
1187   if (peek() != ":")
1188     Cmd->AddrExpr = readExpr();
1189 
1190   expect(":");
1191 
1192   if (skip("AT"))
1193     Cmd->LmaExpr = readParenExpr();
1194   if (skip("ALIGN"))
1195     Cmd->AlignExpr = readParenExpr();
1196   if (skip("SUBALIGN"))
1197     Cmd->SubalignExpr = readParenExpr();
1198 
1199   // Parse constraints.
1200   if (skip("ONLY_IF_RO"))
1201     Cmd->Constraint = ConstraintKind::ReadOnly;
1202   if (skip("ONLY_IF_RW"))
1203     Cmd->Constraint = ConstraintKind::ReadWrite;
1204   expect("{");
1205 
1206   while (!Error && !skip("}")) {
1207     StringRef Tok = next();
1208     if (SymbolAssignment *Assignment = readProvideOrAssignment(Tok, false))
1209       Cmd->Commands.emplace_back(Assignment);
1210     else if (Tok == "FILL")
1211       Cmd->Filler = readFill();
1212     else if (Tok == "SORT")
1213       readSort();
1214     else if (peek() == "(")
1215       Cmd->Commands.emplace_back(readInputSectionDescription(Tok));
1216     else
1217       setError("unknown command " + Tok);
1218   }
1219   Cmd->Phdrs = readOutputSectionPhdrs();
1220   if (peek().startswith("="))
1221     Cmd->Filler = readOutputSectionFiller(next().drop_front());
1222   return Cmd;
1223 }
1224 
1225 // Read "=<number>" where <number> is an octal/decimal/hexadecimal number.
1226 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
1227 //
1228 // ld.gold is not fully compatible with ld.bfd. ld.bfd handles
1229 // hexstrings as blobs of arbitrary sizes, while ld.gold handles them
1230 // as 32-bit big-endian values. We will do the same as ld.gold does
1231 // because it's simpler than what ld.bfd does.
1232 std::vector<uint8_t> ScriptParser::readOutputSectionFiller(StringRef Tok) {
1233   uint32_t V;
1234   if (Tok.getAsInteger(0, V)) {
1235     setError("invalid filler expression: " + Tok);
1236     return {};
1237   }
1238   return {uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V)};
1239 }
1240 
1241 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
1242   expect("(");
1243   SymbolAssignment *Cmd = readAssignment(next());
1244   Cmd->Provide = Provide;
1245   Cmd->Hidden = Hidden;
1246   expect(")");
1247   expect(";");
1248   return Cmd;
1249 }
1250 
1251 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok,
1252                                                         bool MakeAbsolute) {
1253   SymbolAssignment *Cmd = nullptr;
1254   if (peek() == "=" || peek() == "+=") {
1255     Cmd = readAssignment(Tok);
1256     expect(";");
1257   } else if (Tok == "PROVIDE") {
1258     Cmd = readProvideHidden(true, false);
1259   } else if (Tok == "HIDDEN") {
1260     Cmd = readProvideHidden(false, true);
1261   } else if (Tok == "PROVIDE_HIDDEN") {
1262     Cmd = readProvideHidden(true, true);
1263   }
1264   if (Cmd && MakeAbsolute)
1265     Cmd->IsAbsolute = true;
1266   return Cmd;
1267 }
1268 
1269 static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
1270   if (S == ".")
1271     return Dot;
1272   return ScriptBase->getSymbolValue(S);
1273 }
1274 
1275 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
1276   StringRef Op = next();
1277   bool IsAbsolute = false;
1278   Expr E;
1279   assert(Op == "=" || Op == "+=");
1280   if (skip("ABSOLUTE")) {
1281     E = readParenExpr();
1282     IsAbsolute = true;
1283   } else {
1284     E = readExpr();
1285   }
1286   if (Op == "+=")
1287     E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
1288   return new SymbolAssignment(Name, E, IsAbsolute);
1289 }
1290 
1291 // This is an operator-precedence parser to parse a linker
1292 // script expression.
1293 Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
1294 
1295 static Expr combine(StringRef Op, Expr L, Expr R) {
1296   if (Op == "*")
1297     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1298   if (Op == "/") {
1299     return [=](uint64_t Dot) -> uint64_t {
1300       uint64_t RHS = R(Dot);
1301       if (RHS == 0) {
1302         error("division by zero");
1303         return 0;
1304       }
1305       return L(Dot) / RHS;
1306     };
1307   }
1308   if (Op == "+")
1309     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1310   if (Op == "-")
1311     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1312   if (Op == "<")
1313     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1314   if (Op == ">")
1315     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1316   if (Op == ">=")
1317     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1318   if (Op == "<=")
1319     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1320   if (Op == "==")
1321     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1322   if (Op == "!=")
1323     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1324   if (Op == "&")
1325     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1326   if (Op == "|")
1327     return [=](uint64_t Dot) { return L(Dot) | R(Dot); };
1328   llvm_unreachable("invalid operator");
1329 }
1330 
1331 // This is a part of the operator-precedence parser. This function
1332 // assumes that the remaining token stream starts with an operator.
1333 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
1334   while (!atEOF() && !Error) {
1335     // Read an operator and an expression.
1336     StringRef Op1 = peek();
1337     if (Op1 == "?")
1338       return readTernary(Lhs);
1339     if (precedence(Op1) < MinPrec)
1340       break;
1341     next();
1342     Expr Rhs = readPrimary();
1343 
1344     // Evaluate the remaining part of the expression first if the
1345     // next operator has greater precedence than the previous one.
1346     // For example, if we have read "+" and "3", and if the next
1347     // operator is "*", then we'll evaluate 3 * ... part first.
1348     while (!atEOF()) {
1349       StringRef Op2 = peek();
1350       if (precedence(Op2) <= precedence(Op1))
1351         break;
1352       Rhs = readExpr1(Rhs, precedence(Op2));
1353     }
1354 
1355     Lhs = combine(Op1, Lhs, Rhs);
1356   }
1357   return Lhs;
1358 }
1359 
1360 uint64_t static getConstant(StringRef S) {
1361   if (S == "COMMONPAGESIZE")
1362     return Target->PageSize;
1363   if (S == "MAXPAGESIZE")
1364     return Target->MaxPageSize;
1365   error("unknown constant: " + S);
1366   return 0;
1367 }
1368 
1369 // Parses Tok as an integer. Returns true if successful.
1370 // It recognizes hexadecimal (prefixed with "0x" or suffixed with "H")
1371 // and decimal numbers. Decimal numbers may have "K" (kilo) or
1372 // "M" (mega) prefixes.
1373 static bool readInteger(StringRef Tok, uint64_t &Result) {
1374   if (Tok.startswith("-")) {
1375     if (!readInteger(Tok.substr(1), Result))
1376       return false;
1377     Result = -Result;
1378     return true;
1379   }
1380   if (Tok.startswith_lower("0x"))
1381     return !Tok.substr(2).getAsInteger(16, Result);
1382   if (Tok.endswith_lower("H"))
1383     return !Tok.drop_back().getAsInteger(16, Result);
1384 
1385   int Suffix = 1;
1386   if (Tok.endswith_lower("K")) {
1387     Suffix = 1024;
1388     Tok = Tok.drop_back();
1389   } else if (Tok.endswith_lower("M")) {
1390     Suffix = 1024 * 1024;
1391     Tok = Tok.drop_back();
1392   }
1393   if (Tok.getAsInteger(10, Result))
1394     return false;
1395   Result *= Suffix;
1396   return true;
1397 }
1398 
1399 Expr ScriptParser::readPrimary() {
1400   if (peek() == "(")
1401     return readParenExpr();
1402 
1403   StringRef Tok = next();
1404 
1405   if (Tok == "~") {
1406     Expr E = readPrimary();
1407     return [=](uint64_t Dot) { return ~E(Dot); };
1408   }
1409   if (Tok == "-") {
1410     Expr E = readPrimary();
1411     return [=](uint64_t Dot) { return -E(Dot); };
1412   }
1413 
1414   // Built-in functions are parsed here.
1415   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
1416   if (Tok == "ADDR") {
1417     expect("(");
1418     StringRef Name = next();
1419     expect(")");
1420     return
1421         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAddress(Name); };
1422   }
1423   if (Tok == "ASSERT")
1424     return readAssert();
1425   if (Tok == "ALIGN") {
1426     Expr E = readParenExpr();
1427     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1428   }
1429   if (Tok == "CONSTANT") {
1430     expect("(");
1431     StringRef Tok = next();
1432     expect(")");
1433     return [=](uint64_t Dot) { return getConstant(Tok); };
1434   }
1435   if (Tok == "SEGMENT_START") {
1436     expect("(");
1437     next();
1438     expect(",");
1439     Expr E = readExpr();
1440     expect(")");
1441     return [=](uint64_t Dot) { return E(Dot); };
1442   }
1443   if (Tok == "DATA_SEGMENT_ALIGN") {
1444     expect("(");
1445     Expr E = readExpr();
1446     expect(",");
1447     readExpr();
1448     expect(")");
1449     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1450   }
1451   if (Tok == "DATA_SEGMENT_END") {
1452     expect("(");
1453     expect(".");
1454     expect(")");
1455     return [](uint64_t Dot) { return Dot; };
1456   }
1457   // GNU linkers implements more complicated logic to handle
1458   // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1459   // the next page boundary for simplicity.
1460   if (Tok == "DATA_SEGMENT_RELRO_END") {
1461     expect("(");
1462     readExpr();
1463     expect(",");
1464     readExpr();
1465     expect(")");
1466     return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1467   }
1468   if (Tok == "SIZEOF") {
1469     expect("(");
1470     StringRef Name = next();
1471     expect(")");
1472     return [=](uint64_t Dot) { return ScriptBase->getOutputSectionSize(Name); };
1473   }
1474   if (Tok == "ALIGNOF") {
1475     expect("(");
1476     StringRef Name = next();
1477     expect(")");
1478     return
1479         [=](uint64_t Dot) { return ScriptBase->getOutputSectionAlign(Name); };
1480   }
1481   if (Tok == "SIZEOF_HEADERS")
1482     return [=](uint64_t Dot) { return ScriptBase->getHeaderSize(); };
1483 
1484   // Tok is a literal number.
1485   uint64_t V;
1486   if (readInteger(Tok, V))
1487     return [=](uint64_t Dot) { return V; };
1488 
1489   // Tok is a symbol name.
1490   if (Tok != "." && !isValidCIdentifier(Tok))
1491     setError("malformed number: " + Tok);
1492   return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
1493 }
1494 
1495 Expr ScriptParser::readTernary(Expr Cond) {
1496   next();
1497   Expr L = readExpr();
1498   expect(":");
1499   Expr R = readExpr();
1500   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1501 }
1502 
1503 Expr ScriptParser::readParenExpr() {
1504   expect("(");
1505   Expr E = readExpr();
1506   expect(")");
1507   return E;
1508 }
1509 
1510 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1511   std::vector<StringRef> Phdrs;
1512   while (!Error && peek().startswith(":")) {
1513     StringRef Tok = next();
1514     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1515     if (Tok.empty()) {
1516       setError("section header name is empty");
1517       break;
1518     }
1519     Phdrs.push_back(Tok);
1520   }
1521   return Phdrs;
1522 }
1523 
1524 unsigned ScriptParser::readPhdrType() {
1525   StringRef Tok = next();
1526   unsigned Ret = StringSwitch<unsigned>(Tok)
1527                      .Case("PT_NULL", PT_NULL)
1528                      .Case("PT_LOAD", PT_LOAD)
1529                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1530                      .Case("PT_INTERP", PT_INTERP)
1531                      .Case("PT_NOTE", PT_NOTE)
1532                      .Case("PT_SHLIB", PT_SHLIB)
1533                      .Case("PT_PHDR", PT_PHDR)
1534                      .Case("PT_TLS", PT_TLS)
1535                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1536                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1537                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1538                      .Default(-1);
1539 
1540   if (Ret == (unsigned)-1) {
1541     setError("invalid program header type: " + Tok);
1542     return PT_NULL;
1543   }
1544   return Ret;
1545 }
1546 
1547 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1548   // Identifiers start at 2 because 0 and 1 are reserved
1549   // for VER_NDX_LOCAL and VER_NDX_GLOBAL constants.
1550   size_t VersionId = Config->VersionDefinitions.size() + 2;
1551   Config->VersionDefinitions.push_back({VerStr, VersionId});
1552 
1553   if (skip("global:") || peek() != "local:")
1554     readGlobal(VerStr);
1555   if (skip("local:"))
1556     readLocal();
1557   expect("}");
1558 
1559   // Each version may have a parent version. For example, "Ver2" defined as
1560   // "Ver2 { global: foo; local: *; } Ver1;" has "Ver1" as a parent. This
1561   // version hierarchy is, probably against your instinct, purely for human; the
1562   // runtime doesn't care about them at all. In LLD, we simply skip the token.
1563   if (!VerStr.empty() && peek() != ";")
1564     next();
1565   expect(";");
1566 }
1567 
1568 void ScriptParser::readLocal() {
1569   Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1570   expect("*");
1571   expect(";");
1572 }
1573 
1574 void ScriptParser::readExtern(std::vector<SymbolVersion> *Globals) {
1575   expect("\"C++\"");
1576   expect("{");
1577 
1578   for (;;) {
1579     if (peek() == "}" || Error)
1580       break;
1581     bool HasWildcard = !peek().startswith("\"") && hasWildcard(peek());
1582     Globals->push_back({unquote(next()), true, HasWildcard});
1583     expect(";");
1584   }
1585 
1586   expect("}");
1587   expect(";");
1588 }
1589 
1590 void ScriptParser::readGlobal(StringRef VerStr) {
1591   std::vector<SymbolVersion> *Globals;
1592   if (VerStr.empty())
1593     Globals = &Config->VersionScriptGlobals;
1594   else
1595     Globals = &Config->VersionDefinitions.back().Globals;
1596 
1597   for (;;) {
1598     if (skip("extern"))
1599       readExtern(Globals);
1600 
1601     StringRef Cur = peek();
1602     if (Cur == "}" || Cur == "local:" || Error)
1603       return;
1604     next();
1605     Globals->push_back({unquote(Cur), false, hasWildcard(Cur)});
1606     expect(";");
1607   }
1608 }
1609 
1610 static bool isUnderSysroot(StringRef Path) {
1611   if (Config->Sysroot == "")
1612     return false;
1613   for (; !Path.empty(); Path = sys::path::parent_path(Path))
1614     if (sys::fs::equivalent(Config->Sysroot, Path))
1615       return true;
1616   return false;
1617 }
1618 
1619 void elf::readLinkerScript(MemoryBufferRef MB) {
1620   StringRef Path = MB.getBufferIdentifier();
1621   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).readLinkerScript();
1622 }
1623 
1624 void elf::readVersionScript(MemoryBufferRef MB) {
1625   ScriptParser(MB.getBuffer(), false).readVersionScript();
1626 }
1627 
1628 template class elf::LinkerScript<ELF32LE>;
1629 template class elf::LinkerScript<ELF32BE>;
1630 template class elf::LinkerScript<ELF64LE>;
1631 template class elf::LinkerScript<ELF64BE>;
1632