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