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