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