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