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 ScriptConfiguration *elf::ScriptConfig;
45 
46 bool SymbolAssignment::classof(const BaseCommand *C) {
47   return C->Kind == AssignmentKind;
48 }
49 
50 bool OutputSectionCommand::classof(const BaseCommand *C) {
51   return C->Kind == OutputSectionKind;
52 }
53 
54 bool InputSectionDescription::classof(const BaseCommand *C) {
55   return C->Kind == InputSectionKind;
56 }
57 
58 template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
59   return !S || !S->Live;
60 }
61 
62 template <class ELFT>
63 bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
64   for (StringRef Pat : Opt.KeptSections)
65     if (globMatch(Pat, S->getSectionName()))
66       return true;
67   return false;
68 }
69 
70 static bool match(StringRef Pattern, ArrayRef<StringRef> Arr) {
71   for (StringRef S : Arr)
72     if (globMatch(S, Pattern))
73       return true;
74   return false;
75 }
76 
77 template <class ELFT>
78 std::vector<OutputSectionBase<ELFT> *>
79 LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
80   typedef const std::unique_ptr<ObjectFile<ELFT>> ObjectFile;
81   std::vector<OutputSectionBase<ELFT> *> Result;
82   DenseSet<OutputSectionBase<ELFT> *> Removed;
83 
84   // Add input section to output section. If there is no output section yet,
85   // then create it and add to output section list.
86   auto AddInputSec = [&](InputSectionBase<ELFT> *C, StringRef Name,
87                          ConstraintKind Constraint) {
88     OutputSectionBase<ELFT> *Sec;
89     bool IsNew;
90     std::tie(Sec, IsNew) = Factory.create(C, Name);
91     if (IsNew)
92       Result.push_back(Sec);
93     if ((!(C->getSectionHdr()->sh_flags & SHF_WRITE)) &&
94         Constraint == ReadWrite) {
95       Removed.insert(Sec);
96       return;
97     }
98     if ((C->getSectionHdr()->sh_flags & SHF_WRITE) && Constraint == ReadOnly) {
99       Removed.insert(Sec);
100       return;
101     }
102     Sec->addSection(C);
103   };
104 
105   // Select input sections matching rule and add them to corresponding
106   // output section. Section rules are processed in order they're listed
107   // in script, so correct input section order is maintained by design.
108   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
109     auto *OutCmd = dyn_cast<OutputSectionCommand>(Base.get());
110     if (!OutCmd)
111       continue;
112 
113     for (const std::unique_ptr<BaseCommand> &Cmd : OutCmd->Commands) {
114       auto *InCmd = dyn_cast<InputSectionDescription>(Cmd.get());
115       if (!InCmd)
116         continue;
117 
118       for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles()) {
119         for (InputSectionBase<ELFT> *S : F->getSections()) {
120           if (isDiscarded(S) || S->OutSec)
121             continue;
122 
123           if (match(S->getSectionName(), InCmd->Patterns)) {
124             if (OutCmd->Name == "/DISCARD/")
125               S->Live = false;
126             else
127               AddInputSec(S, OutCmd->Name, OutCmd->Constraint);
128           }
129         }
130       }
131     }
132   }
133 
134   // Add all other input sections, which are not listed in script.
135   for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles())
136     for (InputSectionBase<ELFT> *S : F->getSections()) {
137       if (!isDiscarded(S)) {
138         if (!S->OutSec)
139           AddInputSec(S, getOutputSectionName(S), NoConstraint);
140       } else
141         reportDiscarded(S, F);
142     }
143 
144   // Remove from the output all the sections which did not met the constraints.
145   Result.erase(std::remove_if(Result.begin(), Result.end(),
146                               [&](OutputSectionBase<ELFT> *Sec) {
147                                 return Removed.count(Sec);
148                               }),
149                Result.end());
150   return Result;
151 }
152 
153 template <class ELFT>
154 void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
155   uint64_t Val = Cmd->Expression(Dot);
156   if (Cmd->Name == ".") {
157     Dot = Val;
158   } else if (!Cmd->Ignore) {
159     auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
160     D->Value = Val;
161   }
162 }
163 
164 template <class ELFT>
165 void LinkerScript<ELFT>::assignAddresses(
166     ArrayRef<OutputSectionBase<ELFT> *> Sections) {
167   // Orphan sections are sections present in the input files which
168   // are not explicitly placed into the output file by the linker script.
169   // We place orphan sections at end of file.
170   // Other linkers places them using some heuristics as described in
171   // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
172   for (OutputSectionBase<ELFT> *Sec : Sections) {
173     StringRef Name = Sec->getName();
174     if (getSectionIndex(Name) == INT_MAX)
175       Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
176   }
177 
178   // Assign addresses as instructed by linker script SECTIONS sub-commands.
179   Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
180   uintX_t MinVA = std::numeric_limits<uintX_t>::max();
181   uintX_t ThreadBssOffset = 0;
182 
183   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
184     if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
185       dispatchAssignment(Cmd);
186       continue;
187     }
188 
189     // Find all the sections with required name. There can be more than
190     // one section with such name, if the alignment, flags or type
191     // attribute differs.
192     auto *Cmd = cast<OutputSectionCommand>(Base.get());
193     for (OutputSectionBase<ELFT> *Sec : Sections) {
194       if (Sec->getName() != Cmd->Name)
195         continue;
196 
197       if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
198         uintX_t TVA = Dot + ThreadBssOffset;
199         TVA = alignTo(TVA, Sec->getAlignment());
200         Sec->setVA(TVA);
201         ThreadBssOffset = TVA - Dot + Sec->getSize();
202         continue;
203       }
204 
205       if (Sec->getFlags() & SHF_ALLOC) {
206         Dot = alignTo(Dot, Sec->getAlignment());
207         Sec->setVA(Dot);
208         MinVA = std::min(MinVA, Dot);
209         Dot += Sec->getSize();
210         continue;
211       }
212     }
213   }
214 
215   // ELF and Program headers need to be right before the first section in
216   // memory. Set their addresses accordingly.
217   MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
218                         Out<ELFT>::ProgramHeaders->getSize(),
219                     Target->PageSize);
220   Out<ELFT>::ElfHeader->setVA(MinVA);
221   Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
222 }
223 
224 template <class ELFT>
225 std::vector<PhdrEntry<ELFT>>
226 LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
227   std::vector<PhdrEntry<ELFT>> Ret;
228   PhdrEntry<ELFT> *TlsPhdr = nullptr;
229   PhdrEntry<ELFT> *NotePhdr = nullptr;
230   PhdrEntry<ELFT> *RelroPhdr = nullptr;
231 
232   for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
233     Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
234     PhdrEntry<ELFT> &Phdr = Ret.back();
235 
236     if (Cmd.HasFilehdr)
237       Phdr.add(Out<ELFT>::ElfHeader);
238     if (Cmd.HasPhdrs)
239       Phdr.add(Out<ELFT>::ProgramHeaders);
240 
241     switch (Cmd.Type) {
242     case PT_INTERP:
243       if (Out<ELFT>::Interp)
244         Phdr.add(Out<ELFT>::Interp);
245       break;
246     case PT_DYNAMIC:
247       if (isOutputDynamic<ELFT>()) {
248         Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
249         Phdr.add(Out<ELFT>::Dynamic);
250       }
251       break;
252     case PT_TLS:
253       TlsPhdr = &Phdr;
254       break;
255     case PT_NOTE:
256       NotePhdr = &Phdr;
257       break;
258     case PT_GNU_RELRO:
259       RelroPhdr = &Phdr;
260       break;
261     case PT_GNU_EH_FRAME:
262       if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
263         Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
264         Phdr.add(Out<ELFT>::EhFrameHdr);
265       }
266       break;
267     }
268   }
269 
270   PhdrEntry<ELFT> *Load = nullptr;
271   uintX_t Flags = PF_R;
272   for (OutputSectionBase<ELFT> *Sec : Sections) {
273     if (!(Sec->getFlags() & SHF_ALLOC))
274       break;
275 
276     if (TlsPhdr && (Sec->getFlags() & SHF_TLS))
277       TlsPhdr->add(Sec);
278 
279     if (!needsPtLoad<ELFT>(Sec))
280       continue;
281 
282     std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
283     if (!PhdrIds.empty()) {
284       // Assign headers specified by linker script
285       for (size_t Id : PhdrIds) {
286         Ret[Id].add(Sec);
287         if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
288           Ret[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
289       }
290     } else {
291       // If we have no load segment or flags've changed then we want new load
292       // segment.
293       uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
294       if (Load == nullptr || Flags != NewFlags) {
295         Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
296         Flags = NewFlags;
297       }
298       Load->add(Sec);
299     }
300 
301     if (RelroPhdr && isRelroSection(Sec))
302       RelroPhdr->add(Sec);
303     if (NotePhdr && Sec->getType() == SHT_NOTE)
304       NotePhdr->add(Sec);
305   }
306   return Ret;
307 }
308 
309 template <class ELFT>
310 ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
311   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
312     if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
313       if (Cmd->Name == Name)
314         return Cmd->Filler;
315   return {};
316 }
317 
318 // Returns the index of the given section name in linker script
319 // SECTIONS commands. Sections are laid out as the same order as they
320 // were in the script. If a given name did not appear in the script,
321 // it returns INT_MAX, so that it will be laid out at end of file.
322 template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
323   auto Begin = Opt.Commands.begin();
324   auto End = Opt.Commands.end();
325   auto I =
326       std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
327         if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
328           if (Cmd->Name == Name)
329             return true;
330         return false;
331       });
332   return I == End ? INT_MAX : (I - Begin);
333 }
334 
335 // A compartor to sort output sections. Returns -1 or 1 if
336 // A or B are mentioned in linker script. Otherwise, returns 0.
337 template <class ELFT>
338 int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
339   int I = getSectionIndex(A);
340   int J = getSectionIndex(B);
341   if (I == INT_MAX && J == INT_MAX)
342     return 0;
343   return I < J ? -1 : 1;
344 }
345 
346 template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
347   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
348     auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
349     if (!Cmd || Cmd->Name == ".")
350       continue;
351 
352     SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
353     if (!B || B->isUndefined())
354       Symtab<ELFT>::X->addAbsolute(Cmd->Name,
355                                    Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
356     else
357       // Symbol already exists in symbol table. If it is provided
358       // then we can't override its value.
359       Cmd->Ignore = Cmd->Provide;
360   }
361 }
362 
363 template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
364   return !Opt.PhdrsCommands.empty();
365 }
366 
367 // Returns indices of ELF headers containing specific section, identified
368 // by Name. Each index is a zero based number of ELF header listed within
369 // PHDRS {} script block.
370 template <class ELFT>
371 std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
372   for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
373     auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
374     if (!Cmd || Cmd->Name != SectionName)
375       continue;
376 
377     std::vector<size_t> Indices;
378     for (StringRef PhdrName : Cmd->Phdrs) {
379       auto ItPhdr =
380           std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
381                        [&](PhdrsCommand &P) { return P.Name == PhdrName; });
382       if (ItPhdr == Opt.PhdrsCommands.rend())
383         error("section header '" + PhdrName + "' is not listed in PHDRS");
384       else
385         Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
386     }
387     return Indices;
388   }
389   return {};
390 }
391 
392 class elf::ScriptParser : public ScriptParserBase {
393   typedef void (ScriptParser::*Handler)();
394 
395 public:
396   ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
397 
398   void run();
399 
400 private:
401   void addFile(StringRef Path);
402 
403   void readAsNeeded();
404   void readEntry();
405   void readExtern();
406   void readGroup();
407   void readInclude();
408   void readNothing() {}
409   void readOutput();
410   void readOutputArch();
411   void readOutputFormat();
412   void readPhdrs();
413   void readSearchDir();
414   void readSections();
415 
416   SymbolAssignment *readAssignment(StringRef Name);
417   void readOutputSectionDescription(StringRef OutSec);
418   std::vector<StringRef> readOutputSectionPhdrs();
419   unsigned readPhdrType();
420   void readProvide(bool Hidden);
421 
422   Expr readExpr();
423   Expr readExpr1(Expr Lhs, int MinPrec);
424   Expr readPrimary();
425   Expr readTernary(Expr Cond);
426   Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
427 
428   const static StringMap<Handler> Cmd;
429   ScriptConfiguration &Opt = *ScriptConfig;
430   StringSaver Saver = {ScriptConfig->Alloc};
431   bool IsUnderSysroot;
432 };
433 
434 const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
435     {"ENTRY", &ScriptParser::readEntry},
436     {"EXTERN", &ScriptParser::readExtern},
437     {"GROUP", &ScriptParser::readGroup},
438     {"INCLUDE", &ScriptParser::readInclude},
439     {"INPUT", &ScriptParser::readGroup},
440     {"OUTPUT", &ScriptParser::readOutput},
441     {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
442     {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
443     {"PHDRS", &ScriptParser::readPhdrs},
444     {"SEARCH_DIR", &ScriptParser::readSearchDir},
445     {"SECTIONS", &ScriptParser::readSections},
446     {";", &ScriptParser::readNothing}};
447 
448 void ScriptParser::run() {
449   while (!atEOF()) {
450     StringRef Tok = next();
451     if (Handler Fn = Cmd.lookup(Tok))
452       (this->*Fn)();
453     else
454       setError("unknown directive: " + Tok);
455   }
456 }
457 
458 void ScriptParser::addFile(StringRef S) {
459   if (IsUnderSysroot && S.startswith("/")) {
460     SmallString<128> Path;
461     (Config->Sysroot + S).toStringRef(Path);
462     if (sys::fs::exists(Path)) {
463       Driver->addFile(Saver.save(Path.str()));
464       return;
465     }
466   }
467 
468   if (sys::path::is_absolute(S)) {
469     Driver->addFile(S);
470   } else if (S.startswith("=")) {
471     if (Config->Sysroot.empty())
472       Driver->addFile(S.substr(1));
473     else
474       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
475   } else if (S.startswith("-l")) {
476     Driver->addLibrary(S.substr(2));
477   } else if (sys::fs::exists(S)) {
478     Driver->addFile(S);
479   } else {
480     std::string Path = findFromSearchPaths(S);
481     if (Path.empty())
482       setError("unable to find " + S);
483     else
484       Driver->addFile(Saver.save(Path));
485   }
486 }
487 
488 void ScriptParser::readAsNeeded() {
489   expect("(");
490   bool Orig = Config->AsNeeded;
491   Config->AsNeeded = true;
492   while (!Error) {
493     StringRef Tok = next();
494     if (Tok == ")")
495       break;
496     addFile(Tok);
497   }
498   Config->AsNeeded = Orig;
499 }
500 
501 void ScriptParser::readEntry() {
502   // -e <symbol> takes predecence over ENTRY(<symbol>).
503   expect("(");
504   StringRef Tok = next();
505   if (Config->Entry.empty())
506     Config->Entry = Tok;
507   expect(")");
508 }
509 
510 void ScriptParser::readExtern() {
511   expect("(");
512   while (!Error) {
513     StringRef Tok = next();
514     if (Tok == ")")
515       return;
516     Config->Undefined.push_back(Tok);
517   }
518 }
519 
520 void ScriptParser::readGroup() {
521   expect("(");
522   while (!Error) {
523     StringRef Tok = next();
524     if (Tok == ")")
525       return;
526     if (Tok == "AS_NEEDED") {
527       readAsNeeded();
528       continue;
529     }
530     addFile(Tok);
531   }
532 }
533 
534 void ScriptParser::readInclude() {
535   StringRef Tok = next();
536   auto MBOrErr = MemoryBuffer::getFile(Tok);
537   if (!MBOrErr) {
538     setError("cannot open " + Tok);
539     return;
540   }
541   std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
542   StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
543   std::vector<StringRef> V = tokenize(S);
544   Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
545 }
546 
547 void ScriptParser::readOutput() {
548   // -o <file> takes predecence over OUTPUT(<file>).
549   expect("(");
550   StringRef Tok = next();
551   if (Config->OutputFile.empty())
552     Config->OutputFile = Tok;
553   expect(")");
554 }
555 
556 void ScriptParser::readOutputArch() {
557   // Error checking only for now.
558   expect("(");
559   next();
560   expect(")");
561 }
562 
563 void ScriptParser::readOutputFormat() {
564   // Error checking only for now.
565   expect("(");
566   next();
567   StringRef Tok = next();
568   if (Tok == ")")
569    return;
570   if (Tok != ",") {
571     setError("unexpected token: " + Tok);
572     return;
573   }
574   next();
575   expect(",");
576   next();
577   expect(")");
578 }
579 
580 void ScriptParser::readPhdrs() {
581   expect("{");
582   while (!Error && !skip("}")) {
583     StringRef Tok = next();
584     Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
585     PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
586 
587     PhdrCmd.Type = readPhdrType();
588     do {
589       Tok = next();
590       if (Tok == ";")
591         break;
592       if (Tok == "FILEHDR")
593         PhdrCmd.HasFilehdr = true;
594       else if (Tok == "PHDRS")
595         PhdrCmd.HasPhdrs = true;
596       else if (Tok == "FLAGS") {
597         expect("(");
598         next().getAsInteger(0, PhdrCmd.Flags);
599         expect(")");
600       } else
601         setError("unexpected header attribute: " + Tok);
602     } while (!Error);
603   }
604 }
605 
606 void ScriptParser::readSearchDir() {
607   expect("(");
608   Config->SearchPaths.push_back(next());
609   expect(")");
610 }
611 
612 void ScriptParser::readSections() {
613   Opt.DoLayout = true;
614   expect("{");
615   while (!Error && !skip("}")) {
616     StringRef Tok = next();
617     if (peek() == "=") {
618       readAssignment(Tok);
619       expect(";");
620     } else if (Tok == "PROVIDE") {
621       readProvide(false);
622     } else if (Tok == "PROVIDE_HIDDEN") {
623       readProvide(true);
624     } else {
625       readOutputSectionDescription(Tok);
626     }
627   }
628 }
629 
630 static int precedence(StringRef Op) {
631   return StringSwitch<int>(Op)
632       .Case("*", 4)
633       .Case("/", 4)
634       .Case("+", 3)
635       .Case("-", 3)
636       .Case("<", 2)
637       .Case(">", 2)
638       .Case(">=", 2)
639       .Case("<=", 2)
640       .Case("==", 2)
641       .Case("!=", 2)
642       .Case("&", 1)
643       .Default(-1);
644 }
645 
646 void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
647   OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
648   Opt.Commands.emplace_back(Cmd);
649   expect(":");
650 
651   // Parse constraints.
652   if (skip("ONLY_IF_RO"))
653     Cmd->Constraint = ReadOnly;
654   if (skip("ONLY_IF_RW"))
655     Cmd->Constraint = ReadWrite;
656   expect("{");
657 
658   while (!Error && !skip("}")) {
659     StringRef Tok = next();
660     if (Tok == "*") {
661       auto *InCmd = new InputSectionDescription();
662       Cmd->Commands.emplace_back(InCmd);
663       expect("(");
664       while (!Error && !skip(")"))
665         InCmd->Patterns.push_back(next());
666     } else if (Tok == "KEEP") {
667       expect("(");
668       expect("*");
669       expect("(");
670       auto *InCmd = new InputSectionDescription();
671       Cmd->Commands.emplace_back(InCmd);
672       while (!Error && !skip(")")) {
673         Opt.KeptSections.push_back(peek());
674         InCmd->Patterns.push_back(next());
675       }
676       expect(")");
677     } else if (Tok == "PROVIDE") {
678       readProvide(false);
679     } else if (Tok == "PROVIDE_HIDDEN") {
680       readProvide(true);
681     } else {
682       setError("unknown command " + Tok);
683     }
684   }
685   Cmd->Phdrs = readOutputSectionPhdrs();
686 
687   StringRef Tok = peek();
688   if (Tok.startswith("=")) {
689     if (!Tok.startswith("=0x")) {
690       setError("filler should be a hexadecimal value");
691       return;
692     }
693     Tok = Tok.substr(3);
694     Cmd->Filler = parseHex(Tok);
695     next();
696   }
697 }
698 
699 void ScriptParser::readProvide(bool Hidden) {
700   expect("(");
701   if (SymbolAssignment *Assignment = readAssignment(next())) {
702     Assignment->Provide = true;
703     Assignment->Hidden = Hidden;
704   }
705   expect(")");
706   expect(";");
707 }
708 
709 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
710   expect("=");
711   Expr E = readExpr();
712   auto *Cmd = new SymbolAssignment(Name, E);
713   Opt.Commands.emplace_back(Cmd);
714   return Cmd;
715 }
716 
717 // This is an operator-precedence parser to parse a linker
718 // script expression.
719 Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
720 
721 // This is a part of the operator-precedence parser. This function
722 // assumes that the remaining token stream starts with an operator.
723 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
724   while (!atEOF() && !Error) {
725     // Read an operator and an expression.
726     StringRef Op1 = peek();
727     if (Op1 == "?")
728       return readTernary(Lhs);
729     if (precedence(Op1) < MinPrec)
730       break;
731     next();
732     Expr Rhs = readPrimary();
733 
734     // Evaluate the remaining part of the expression first if the
735     // next operator has greater precedence than the previous one.
736     // For example, if we have read "+" and "3", and if the next
737     // operator is "*", then we'll evaluate 3 * ... part first.
738     while (!atEOF()) {
739       StringRef Op2 = peek();
740       if (precedence(Op2) <= precedence(Op1))
741         break;
742       Rhs = readExpr1(Rhs, precedence(Op2));
743     }
744 
745     Lhs = combine(Op1, Lhs, Rhs);
746   }
747   return Lhs;
748 }
749 
750 uint64_t static getConstant(StringRef S) {
751   if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
752     return Target->PageSize;
753   error("unknown constant: " + S);
754   return 0;
755 }
756 
757 Expr ScriptParser::readPrimary() {
758   StringRef Tok = next();
759 
760   if (Tok == ".")
761     return [](uint64_t Dot) { return Dot; };
762 
763   if (Tok == "(") {
764     Expr E = readExpr();
765     expect(")");
766     return E;
767   }
768 
769   // Built-in functions are parsed here.
770   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
771   if (Tok == "ALIGN") {
772     expect("(");
773     Expr E = readExpr();
774     expect(")");
775     return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
776   }
777   if (Tok == "CONSTANT") {
778     expect("(");
779     StringRef Tok = next();
780     expect(")");
781     return [=](uint64_t Dot) { return getConstant(Tok); };
782   }
783   if (Tok == "DATA_SEGMENT_ALIGN") {
784     expect("(");
785     Expr E = readExpr();
786     expect(",");
787     readExpr();
788     expect(")");
789     return [=](uint64_t Dot) -> uint64_t {
790       uint64_t Val = E(Dot);
791       return alignTo(Dot, Val) + (Dot & (Val - 1));
792     };
793   }
794   if (Tok == "DATA_SEGMENT_END") {
795     expect("(");
796     expect(".");
797     expect(")");
798     return [](uint64_t Dot) { return Dot; };
799   }
800 
801   // Parse a number literal
802   uint64_t V = 0;
803   if (Tok.getAsInteger(0, V))
804     setError("malformed number: " + Tok);
805   return [=](uint64_t Dot) { return V; };
806 }
807 
808 Expr ScriptParser::readTernary(Expr Cond) {
809   next();
810   Expr L = readExpr();
811   expect(":");
812   Expr R = readExpr();
813   return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
814 }
815 
816 Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
817   if (Op == "*")
818     return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
819   if (Op == "/") {
820     return [=](uint64_t Dot) -> uint64_t {
821       uint64_t RHS = R(Dot);
822       if (RHS == 0) {
823         error("division by zero");
824         return 0;
825       }
826       return L(Dot) / RHS;
827     };
828   }
829   if (Op == "+")
830     return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
831   if (Op == "-")
832     return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
833   if (Op == "<")
834     return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
835   if (Op == ">")
836     return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
837   if (Op == ">=")
838     return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
839   if (Op == "<=")
840     return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
841   if (Op == "==")
842     return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
843   if (Op == "!=")
844     return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
845   if (Op == "&")
846     return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
847   llvm_unreachable("invalid operator");
848 }
849 
850 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
851   std::vector<StringRef> Phdrs;
852   while (!Error && peek().startswith(":")) {
853     StringRef Tok = next();
854     Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
855     if (Tok.empty()) {
856       setError("section header name is empty");
857       break;
858     }
859     Phdrs.push_back(Tok);
860   }
861   return Phdrs;
862 }
863 
864 unsigned ScriptParser::readPhdrType() {
865   StringRef Tok = next();
866   unsigned Ret = StringSwitch<unsigned>(Tok)
867       .Case("PT_NULL", PT_NULL)
868       .Case("PT_LOAD", PT_LOAD)
869       .Case("PT_DYNAMIC", PT_DYNAMIC)
870       .Case("PT_INTERP", PT_INTERP)
871       .Case("PT_NOTE", PT_NOTE)
872       .Case("PT_SHLIB", PT_SHLIB)
873       .Case("PT_PHDR", PT_PHDR)
874       .Case("PT_TLS", PT_TLS)
875       .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
876       .Case("PT_GNU_STACK", PT_GNU_STACK)
877       .Case("PT_GNU_RELRO", PT_GNU_RELRO)
878       .Default(-1);
879 
880   if (Ret == (unsigned)-1) {
881     setError("invalid program header type: " + Tok);
882     return PT_NULL;
883   }
884   return Ret;
885 }
886 
887 static bool isUnderSysroot(StringRef Path) {
888   if (Config->Sysroot == "")
889     return false;
890   for (; !Path.empty(); Path = sys::path::parent_path(Path))
891     if (sys::fs::equivalent(Config->Sysroot, Path))
892       return true;
893   return false;
894 }
895 
896 // Entry point.
897 void elf::readLinkerScript(MemoryBufferRef MB) {
898   StringRef Path = MB.getBufferIdentifier();
899   ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
900 }
901 
902 template class elf::LinkerScript<ELF32LE>;
903 template class elf::LinkerScript<ELF32BE>;
904 template class elf::LinkerScript<ELF64LE>;
905 template class elf::LinkerScript<ELF64BE>;
906