1 //===- ScriptParser.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 a recursive-descendent parser for linker scripts.
11 // Parsed results are stored to Config and Script global objects.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "ScriptParser.h"
16 #include "Config.h"
17 #include "Driver.h"
18 #include "InputSection.h"
19 #include "LinkerScript.h"
20 #include "Memory.h"
21 #include "OutputSections.h"
22 #include "ScriptLexer.h"
23 #include "Symbols.h"
24 #include "Target.h"
25 #include "llvm/ADT/SmallString.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSet.h"
28 #include "llvm/ADT/StringSwitch.h"
29 #include "llvm/BinaryFormat/ELF.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Path.h"
34 #include <cassert>
35 #include <limits>
36 #include <vector>
37 
38 using namespace llvm;
39 using namespace llvm::ELF;
40 using namespace llvm::support::endian;
41 using namespace lld;
42 using namespace lld::elf;
43 
44 static bool isUnderSysroot(StringRef Path);
45 
46 namespace {
47 class ScriptParser final : ScriptLexer {
48 public:
49   ScriptParser(MemoryBufferRef MB)
50       : ScriptLexer(MB),
51         IsUnderSysroot(isUnderSysroot(MB.getBufferIdentifier())) {}
52 
53   void readLinkerScript();
54   void readVersionScript();
55   void readDynamicList();
56 
57 private:
58   void addFile(StringRef Path);
59   OutputSection *checkSection(OutputSection *Cmd, StringRef Loccation);
60 
61   void readAsNeeded();
62   void readEntry();
63   void readExtern();
64   void readGroup();
65   void readInclude();
66   void readMemory();
67   void readOutput();
68   void readOutputArch();
69   void readOutputFormat();
70   void readPhdrs();
71   void readRegionAlias();
72   void readSearchDir();
73   void readSections();
74   void readVersion();
75   void readVersionScriptCommand();
76 
77   SymbolAssignment *readAssignment(StringRef Name);
78   BytesDataCommand *readBytesDataCommand(StringRef Tok);
79   uint32_t readFill();
80   uint32_t parseFill(StringRef Tok);
81   void readSectionAddressType(OutputSection *Cmd);
82   OutputSection *readOutputSectionDescription(StringRef OutSec);
83   std::vector<StringRef> readOutputSectionPhdrs();
84   InputSectionDescription *readInputSectionDescription(StringRef Tok);
85   StringMatcher readFilePatterns();
86   std::vector<SectionPattern> readInputSectionsList();
87   InputSectionDescription *readInputSectionRules(StringRef FilePattern);
88   unsigned readPhdrType();
89   SortSectionPolicy readSortKind();
90   SymbolAssignment *readProvideHidden(bool Provide, bool Hidden);
91   SymbolAssignment *readProvideOrAssignment(StringRef Tok);
92   void readSort();
93   AssertCommand *readAssert();
94   Expr readAssertExpr();
95   Expr readConstant();
96   Expr getPageSize();
97 
98   uint64_t readMemoryAssignment(StringRef, StringRef, StringRef);
99   std::pair<uint32_t, uint32_t> readMemoryAttributes();
100 
101   Expr readExpr();
102   Expr readExpr1(Expr Lhs, int MinPrec);
103   StringRef readParenLiteral();
104   Expr readPrimary();
105   Expr readTernary(Expr Cond);
106   Expr readParenExpr();
107 
108   // For parsing version script.
109   std::vector<SymbolVersion> readVersionExtern();
110   void readAnonymousDeclaration();
111   void readVersionDeclaration(StringRef VerStr);
112 
113   std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
114   readSymbols();
115 
116   // True if a script being read is in a subdirectory specified by -sysroot.
117   bool IsUnderSysroot;
118 
119   // A set to detect an INCLUDE() cycle.
120   StringSet<> Seen;
121 };
122 } // namespace
123 
124 static StringRef unquote(StringRef S) {
125   if (S.startswith("\""))
126     return S.substr(1, S.size() - 2);
127   return S;
128 }
129 
130 static bool isUnderSysroot(StringRef Path) {
131   if (Config->Sysroot == "")
132     return false;
133   for (; !Path.empty(); Path = sys::path::parent_path(Path))
134     if (sys::fs::equivalent(Config->Sysroot, Path))
135       return true;
136   return false;
137 }
138 
139 // Some operations only support one non absolute value. Move the
140 // absolute one to the right hand side for convenience.
141 static void moveAbsRight(ExprValue &A, ExprValue &B) {
142   if (A.Sec == nullptr || (A.ForceAbsolute && !B.isAbsolute()))
143     std::swap(A, B);
144   if (!B.isAbsolute())
145     error(A.Loc + ": at least one side of the expression must be absolute");
146 }
147 
148 static ExprValue add(ExprValue A, ExprValue B) {
149   moveAbsRight(A, B);
150   return {A.Sec, A.ForceAbsolute, A.getSectionOffset() + B.getValue(), A.Loc};
151 }
152 
153 static ExprValue sub(ExprValue A, ExprValue B) {
154   return {A.Sec, A.getSectionOffset() - B.getValue(), A.Loc};
155 }
156 
157 static ExprValue mul(ExprValue A, ExprValue B) {
158   return A.getValue() * B.getValue();
159 }
160 
161 static ExprValue div(ExprValue A, ExprValue B) {
162   if (uint64_t BV = B.getValue())
163     return A.getValue() / BV;
164   error("division by zero");
165   return 0;
166 }
167 
168 static ExprValue bitAnd(ExprValue A, ExprValue B) {
169   moveAbsRight(A, B);
170   return {A.Sec, A.ForceAbsolute,
171           (A.getValue() & B.getValue()) - A.getSecAddr(), A.Loc};
172 }
173 
174 static ExprValue bitOr(ExprValue A, ExprValue B) {
175   moveAbsRight(A, B);
176   return {A.Sec, A.ForceAbsolute,
177           (A.getValue() | B.getValue()) - A.getSecAddr(), A.Loc};
178 }
179 
180 void ScriptParser::readDynamicList() {
181   Config->HasDynamicList = true;
182   expect("{");
183   std::vector<SymbolVersion> Locals;
184   std::vector<SymbolVersion> Globals;
185   std::tie(Locals, Globals) = readSymbols();
186   expect(";");
187 
188   if (!atEOF()) {
189     setError("EOF expected, but got " + next());
190     return;
191   }
192   if (!Locals.empty()) {
193     setError("\"local:\" scope not supported in --dynamic-list");
194     return;
195   }
196 
197   for (SymbolVersion V : Globals)
198     Config->DynamicList.push_back(V);
199 }
200 
201 void ScriptParser::readVersionScript() {
202   readVersionScriptCommand();
203   if (!atEOF())
204     setError("EOF expected, but got " + next());
205 }
206 
207 void ScriptParser::readVersionScriptCommand() {
208   if (consume("{")) {
209     readAnonymousDeclaration();
210     return;
211   }
212 
213   while (!atEOF() && !ErrorCount && peek() != "}") {
214     StringRef VerStr = next();
215     if (VerStr == "{") {
216       setError("anonymous version definition is used in "
217                "combination with other version definitions");
218       return;
219     }
220     expect("{");
221     readVersionDeclaration(VerStr);
222   }
223 }
224 
225 void ScriptParser::readVersion() {
226   expect("{");
227   readVersionScriptCommand();
228   expect("}");
229 }
230 
231 void ScriptParser::readLinkerScript() {
232   while (!atEOF()) {
233     StringRef Tok = next();
234     if (Tok == ";")
235       continue;
236 
237     if (Tok == "ASSERT") {
238       Script->Opt.Commands.push_back(readAssert());
239     } else if (Tok == "ENTRY") {
240       readEntry();
241     } else if (Tok == "EXTERN") {
242       readExtern();
243     } else if (Tok == "GROUP" || Tok == "INPUT") {
244       readGroup();
245     } else if (Tok == "INCLUDE") {
246       readInclude();
247     } else if (Tok == "MEMORY") {
248       readMemory();
249     } else if (Tok == "OUTPUT") {
250       readOutput();
251     } else if (Tok == "OUTPUT_ARCH") {
252       readOutputArch();
253     } else if (Tok == "OUTPUT_FORMAT") {
254       readOutputFormat();
255     } else if (Tok == "PHDRS") {
256       readPhdrs();
257     } else if (Tok == "REGION_ALIAS") {
258       readRegionAlias();
259     } else if (Tok == "SEARCH_DIR") {
260       readSearchDir();
261     } else if (Tok == "SECTIONS") {
262       readSections();
263     } else if (Tok == "VERSION") {
264       readVersion();
265     } else if (SymbolAssignment *Cmd = readProvideOrAssignment(Tok)) {
266       Script->Opt.Commands.push_back(Cmd);
267     } else {
268       setError("unknown directive: " + Tok);
269     }
270   }
271 }
272 
273 void ScriptParser::addFile(StringRef S) {
274   if (IsUnderSysroot && S.startswith("/")) {
275     SmallString<128> PathData;
276     StringRef Path = (Config->Sysroot + S).toStringRef(PathData);
277     if (sys::fs::exists(Path)) {
278       Driver->addFile(Saver.save(Path), /*WithLOption=*/false);
279       return;
280     }
281   }
282 
283   if (S.startswith("/")) {
284     Driver->addFile(S, /*WithLOption=*/false);
285   } else if (S.startswith("=")) {
286     if (Config->Sysroot.empty())
287       Driver->addFile(S.substr(1), /*WithLOption=*/false);
288     else
289       Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)),
290                       /*WithLOption=*/false);
291   } else if (S.startswith("-l")) {
292     Driver->addLibrary(S.substr(2));
293   } else if (sys::fs::exists(S)) {
294     Driver->addFile(S, /*WithLOption=*/false);
295   } else {
296     if (Optional<std::string> Path = findFromSearchPaths(S))
297       Driver->addFile(Saver.save(*Path), /*WithLOption=*/true);
298     else
299       setError("unable to find " + S);
300   }
301 }
302 
303 void ScriptParser::readAsNeeded() {
304   expect("(");
305   bool Orig = Config->AsNeeded;
306   Config->AsNeeded = true;
307   while (!ErrorCount && !consume(")"))
308     addFile(unquote(next()));
309   Config->AsNeeded = Orig;
310 }
311 
312 void ScriptParser::readEntry() {
313   // -e <symbol> takes predecence over ENTRY(<symbol>).
314   expect("(");
315   StringRef Tok = next();
316   if (Config->Entry.empty())
317     Config->Entry = Tok;
318   expect(")");
319 }
320 
321 void ScriptParser::readExtern() {
322   expect("(");
323   while (!ErrorCount && !consume(")"))
324     Config->Undefined.push_back(next());
325 }
326 
327 void ScriptParser::readGroup() {
328   expect("(");
329   while (!ErrorCount && !consume(")")) {
330     if (consume("AS_NEEDED"))
331       readAsNeeded();
332     else
333       addFile(unquote(next()));
334   }
335 }
336 
337 void ScriptParser::readInclude() {
338   StringRef Tok = unquote(next());
339 
340   if (!Seen.insert(Tok).second) {
341     setError("there is a cycle in linker script INCLUDEs");
342     return;
343   }
344 
345   // https://sourceware.org/binutils/docs/ld/File-Commands.html:
346   // The file will be searched for in the current directory, and in any
347   // directory specified with the -L option.
348   if (sys::fs::exists(Tok)) {
349     if (Optional<MemoryBufferRef> MB = readFile(Tok))
350       tokenize(*MB);
351     return;
352   }
353   if (Optional<std::string> Path = findFromSearchPaths(Tok)) {
354     if (Optional<MemoryBufferRef> MB = readFile(*Path))
355       tokenize(*MB);
356     return;
357   }
358   setError("cannot open " + Tok);
359 }
360 
361 void ScriptParser::readOutput() {
362   // -o <file> takes predecence over OUTPUT(<file>).
363   expect("(");
364   StringRef Tok = next();
365   if (Config->OutputFile.empty())
366     Config->OutputFile = unquote(Tok);
367   expect(")");
368 }
369 
370 void ScriptParser::readOutputArch() {
371   // OUTPUT_ARCH is ignored for now.
372   expect("(");
373   while (!ErrorCount && !consume(")"))
374     skip();
375 }
376 
377 void ScriptParser::readOutputFormat() {
378   // Error checking only for now.
379   expect("(");
380   skip();
381   if (consume(")"))
382     return;
383   expect(",");
384   skip();
385   expect(",");
386   skip();
387   expect(")");
388 }
389 
390 void ScriptParser::readPhdrs() {
391   expect("{");
392   while (!ErrorCount && !consume("}")) {
393     Script->Opt.PhdrsCommands.push_back(
394         {next(), PT_NULL, false, false, UINT_MAX, nullptr});
395 
396     PhdrsCommand &PhdrCmd = Script->Opt.PhdrsCommands.back();
397     PhdrCmd.Type = readPhdrType();
398 
399     while (!ErrorCount && !consume(";")) {
400       if (consume("FILEHDR"))
401         PhdrCmd.HasFilehdr = true;
402       else if (consume("PHDRS"))
403         PhdrCmd.HasPhdrs = true;
404       else if (consume("AT"))
405         PhdrCmd.LMAExpr = readParenExpr();
406       else if (consume("FLAGS"))
407         PhdrCmd.Flags = readParenExpr()().getValue();
408       else
409         setError("unexpected header attribute: " + next());
410     }
411   }
412 }
413 
414 void ScriptParser::readRegionAlias() {
415   expect("(");
416   StringRef Alias = unquote(next());
417   expect(",");
418   StringRef Name = next();
419   expect(")");
420 
421   if (Script->Opt.MemoryRegions.count(Alias))
422     setError("redefinition of memory region '" + Alias + "'");
423   if (!Script->Opt.MemoryRegions.count(Name))
424     setError("memory region '" + Name + "' is not defined");
425   Script->Opt.MemoryRegions[Alias] = Script->Opt.MemoryRegions[Name];
426 }
427 
428 void ScriptParser::readSearchDir() {
429   expect("(");
430   StringRef Tok = next();
431   if (!Config->Nostdlib)
432     Config->SearchPaths.push_back(unquote(Tok));
433   expect(")");
434 }
435 
436 void ScriptParser::readSections() {
437   Script->Opt.HasSections = true;
438 
439   // -no-rosegment is used to avoid placing read only non-executable sections in
440   // their own segment. We do the same if SECTIONS command is present in linker
441   // script. See comment for computeFlags().
442   Config->SingleRoRx = true;
443 
444   expect("{");
445   while (!ErrorCount && !consume("}")) {
446     StringRef Tok = next();
447     BaseCommand *Cmd = readProvideOrAssignment(Tok);
448     if (!Cmd) {
449       if (Tok == "ASSERT")
450         Cmd = readAssert();
451       else
452         Cmd = readOutputSectionDescription(Tok);
453     }
454     Script->Opt.Commands.push_back(Cmd);
455   }
456 }
457 
458 static int precedence(StringRef Op) {
459   return StringSwitch<int>(Op)
460       .Cases("*", "/", 5)
461       .Cases("+", "-", 4)
462       .Cases("<<", ">>", 3)
463       .Cases("<", "<=", ">", ">=", "==", "!=", 2)
464       .Cases("&", "|", 1)
465       .Default(-1);
466 }
467 
468 StringMatcher ScriptParser::readFilePatterns() {
469   std::vector<StringRef> V;
470   while (!ErrorCount && !consume(")"))
471     V.push_back(next());
472   return StringMatcher(V);
473 }
474 
475 SortSectionPolicy ScriptParser::readSortKind() {
476   if (consume("SORT") || consume("SORT_BY_NAME"))
477     return SortSectionPolicy::Name;
478   if (consume("SORT_BY_ALIGNMENT"))
479     return SortSectionPolicy::Alignment;
480   if (consume("SORT_BY_INIT_PRIORITY"))
481     return SortSectionPolicy::Priority;
482   if (consume("SORT_NONE"))
483     return SortSectionPolicy::None;
484   return SortSectionPolicy::Default;
485 }
486 
487 // Reads SECTIONS command contents in the following form:
488 //
489 // <contents> ::= <elem>*
490 // <elem>     ::= <exclude>? <glob-pattern>
491 // <exclude>  ::= "EXCLUDE_FILE" "(" <glob-pattern>+ ")"
492 //
493 // For example,
494 //
495 // *(.foo EXCLUDE_FILE (a.o) .bar EXCLUDE_FILE (b.o) .baz)
496 //
497 // is parsed as ".foo", ".bar" with "a.o", and ".baz" with "b.o".
498 // The semantics of that is section .foo in any file, section .bar in
499 // any file but a.o, and section .baz in any file but b.o.
500 std::vector<SectionPattern> ScriptParser::readInputSectionsList() {
501   std::vector<SectionPattern> Ret;
502   while (!ErrorCount && peek() != ")") {
503     StringMatcher ExcludeFilePat;
504     if (consume("EXCLUDE_FILE")) {
505       expect("(");
506       ExcludeFilePat = readFilePatterns();
507     }
508 
509     std::vector<StringRef> V;
510     while (!ErrorCount && peek() != ")" && peek() != "EXCLUDE_FILE")
511       V.push_back(next());
512 
513     if (!V.empty())
514       Ret.push_back({std::move(ExcludeFilePat), StringMatcher(V)});
515     else
516       setError("section pattern is expected");
517   }
518   return Ret;
519 }
520 
521 // Reads contents of "SECTIONS" directive. That directive contains a
522 // list of glob patterns for input sections. The grammar is as follows.
523 //
524 // <patterns> ::= <section-list>
525 //              | <sort> "(" <section-list> ")"
526 //              | <sort> "(" <sort> "(" <section-list> ")" ")"
527 //
528 // <sort>     ::= "SORT" | "SORT_BY_NAME" | "SORT_BY_ALIGNMENT"
529 //              | "SORT_BY_INIT_PRIORITY" | "SORT_NONE"
530 //
531 // <section-list> is parsed by readInputSectionsList().
532 InputSectionDescription *
533 ScriptParser::readInputSectionRules(StringRef FilePattern) {
534   auto *Cmd = make<InputSectionDescription>(FilePattern);
535   expect("(");
536 
537   while (!ErrorCount && !consume(")")) {
538     SortSectionPolicy Outer = readSortKind();
539     SortSectionPolicy Inner = SortSectionPolicy::Default;
540     std::vector<SectionPattern> V;
541     if (Outer != SortSectionPolicy::Default) {
542       expect("(");
543       Inner = readSortKind();
544       if (Inner != SortSectionPolicy::Default) {
545         expect("(");
546         V = readInputSectionsList();
547         expect(")");
548       } else {
549         V = readInputSectionsList();
550       }
551       expect(")");
552     } else {
553       V = readInputSectionsList();
554     }
555 
556     for (SectionPattern &Pat : V) {
557       Pat.SortInner = Inner;
558       Pat.SortOuter = Outer;
559     }
560 
561     std::move(V.begin(), V.end(), std::back_inserter(Cmd->SectionPatterns));
562   }
563   return Cmd;
564 }
565 
566 InputSectionDescription *
567 ScriptParser::readInputSectionDescription(StringRef Tok) {
568   // Input section wildcard can be surrounded by KEEP.
569   // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
570   if (Tok == "KEEP") {
571     expect("(");
572     StringRef FilePattern = next();
573     InputSectionDescription *Cmd = readInputSectionRules(FilePattern);
574     expect(")");
575     Script->Opt.KeptSections.push_back(Cmd);
576     return Cmd;
577   }
578   return readInputSectionRules(Tok);
579 }
580 
581 void ScriptParser::readSort() {
582   expect("(");
583   expect("CONSTRUCTORS");
584   expect(")");
585 }
586 
587 AssertCommand *ScriptParser::readAssert() {
588   return make<AssertCommand>(readAssertExpr());
589 }
590 
591 Expr ScriptParser::readAssertExpr() {
592   expect("(");
593   Expr E = readExpr();
594   expect(",");
595   StringRef Msg = unquote(next());
596   expect(")");
597 
598   return [=] {
599     if (!E().getValue())
600       error(Msg);
601     return Script->getDot();
602   };
603 }
604 
605 // Reads a FILL(expr) command. We handle the FILL command as an
606 // alias for =fillexp section attribute, which is different from
607 // what GNU linkers do.
608 // https://sourceware.org/binutils/docs/ld/Output-Section-Data.html
609 uint32_t ScriptParser::readFill() {
610   expect("(");
611   uint32_t V = parseFill(next());
612   expect(")");
613   return V;
614 }
615 
616 // Reads an expression and/or the special directive "(NOLOAD)" for an
617 // output section definition.
618 //
619 // An output section name can be followed by an address expression
620 // and/or by "(NOLOAD)". This grammar is not LL(1) because "(" can be
621 // interpreted as either the beginning of some expression or "(NOLOAD)".
622 //
623 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html
624 // https://sourceware.org/binutils/docs/ld/Output-Section-Type.html
625 void ScriptParser::readSectionAddressType(OutputSection *Cmd) {
626   if (consume("(")) {
627     if (consume("NOLOAD")) {
628       expect(")");
629       Cmd->Noload = true;
630       return;
631     }
632     Cmd->AddrExpr = readExpr();
633     expect(")");
634   } else {
635     Cmd->AddrExpr = readExpr();
636   }
637 
638   if (consume("(")) {
639     expect("NOLOAD");
640     expect(")");
641     Cmd->Noload = true;
642   }
643 }
644 
645 OutputSection *ScriptParser::readOutputSectionDescription(StringRef OutSec) {
646   OutputSection *Cmd =
647       Script->createOutputSection(OutSec, getCurrentLocation());
648 
649   if (peek() != ":")
650     readSectionAddressType(Cmd);
651   expect(":");
652 
653   if (consume("AT"))
654     Cmd->LMAExpr = readParenExpr();
655   if (consume("ALIGN"))
656     Cmd->AlignExpr = readParenExpr();
657   if (consume("SUBALIGN"))
658     Cmd->SubalignExpr = readParenExpr();
659 
660   // Parse constraints.
661   if (consume("ONLY_IF_RO"))
662     Cmd->Constraint = ConstraintKind::ReadOnly;
663   if (consume("ONLY_IF_RW"))
664     Cmd->Constraint = ConstraintKind::ReadWrite;
665   expect("{");
666 
667   while (!ErrorCount && !consume("}")) {
668     StringRef Tok = next();
669     if (Tok == ";") {
670       // Empty commands are allowed. Do nothing here.
671     } else if (SymbolAssignment *Assign = readProvideOrAssignment(Tok)) {
672       Cmd->Commands.push_back(Assign);
673     } else if (BytesDataCommand *Data = readBytesDataCommand(Tok)) {
674       Cmd->Commands.push_back(Data);
675     } else if (Tok == "ASSERT") {
676       Cmd->Commands.push_back(readAssert());
677       expect(";");
678     } else if (Tok == "CONSTRUCTORS") {
679       // CONSTRUCTORS is a keyword to make the linker recognize C++ ctors/dtors
680       // by name. This is for very old file formats such as ECOFF/XCOFF.
681       // For ELF, we should ignore.
682     } else if (Tok == "FILL") {
683       Cmd->Filler = readFill();
684     } else if (Tok == "SORT") {
685       readSort();
686     } else if (peek() == "(") {
687       Cmd->Commands.push_back(readInputSectionDescription(Tok));
688     } else {
689       setError("unknown command " + Tok);
690     }
691   }
692 
693   if (consume(">"))
694     Cmd->MemoryRegionName = next();
695   else if (peek().startswith(">"))
696     Cmd->MemoryRegionName = next().drop_front();
697 
698   Cmd->Phdrs = readOutputSectionPhdrs();
699 
700   if (consume("="))
701     Cmd->Filler = parseFill(next());
702   else if (peek().startswith("="))
703     Cmd->Filler = parseFill(next().drop_front());
704 
705   // Consume optional comma following output section command.
706   consume(",");
707 
708   return Cmd;
709 }
710 
711 // Parses a given string as a octal/decimal/hexadecimal number and
712 // returns it as a big-endian number. Used for `=<fillexp>`.
713 // https://sourceware.org/binutils/docs/ld/Output-Section-Fill.html
714 //
715 // When reading a hexstring, ld.bfd handles it as a blob of arbitrary
716 // size, while ld.gold always handles it as a 32-bit big-endian number.
717 // We are compatible with ld.gold because it's easier to implement.
718 uint32_t ScriptParser::parseFill(StringRef Tok) {
719   uint32_t V = 0;
720   if (!to_integer(Tok, V))
721     setError("invalid filler expression: " + Tok);
722 
723   uint32_t Buf;
724   write32be(&Buf, V);
725   return Buf;
726 }
727 
728 SymbolAssignment *ScriptParser::readProvideHidden(bool Provide, bool Hidden) {
729   expect("(");
730   SymbolAssignment *Cmd = readAssignment(next());
731   Cmd->Provide = Provide;
732   Cmd->Hidden = Hidden;
733   expect(")");
734   expect(";");
735   return Cmd;
736 }
737 
738 SymbolAssignment *ScriptParser::readProvideOrAssignment(StringRef Tok) {
739   SymbolAssignment *Cmd = nullptr;
740   if (peek() == "=" || peek() == "+=") {
741     Cmd = readAssignment(Tok);
742     expect(";");
743   } else if (Tok == "PROVIDE") {
744     Cmd = readProvideHidden(true, false);
745   } else if (Tok == "HIDDEN") {
746     Cmd = readProvideHidden(false, true);
747   } else if (Tok == "PROVIDE_HIDDEN") {
748     Cmd = readProvideHidden(true, true);
749   }
750   return Cmd;
751 }
752 
753 SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
754   StringRef Op = next();
755   assert(Op == "=" || Op == "+=");
756   Expr E = readExpr();
757   if (Op == "+=") {
758     std::string Loc = getCurrentLocation();
759     E = [=] { return add(Script->getSymbolValue(Loc, Name), E()); };
760   }
761   return make<SymbolAssignment>(Name, E, getCurrentLocation());
762 }
763 
764 // This is an operator-precedence parser to parse a linker
765 // script expression.
766 Expr ScriptParser::readExpr() {
767   // Our lexer is context-aware. Set the in-expression bit so that
768   // they apply different tokenization rules.
769   bool Orig = InExpr;
770   InExpr = true;
771   Expr E = readExpr1(readPrimary(), 0);
772   InExpr = Orig;
773   return E;
774 }
775 
776 static Expr combine(StringRef Op, Expr L, Expr R) {
777   if (Op == "+")
778     return [=] { return add(L(), R()); };
779   if (Op == "-")
780     return [=] { return sub(L(), R()); };
781   if (Op == "*")
782     return [=] { return mul(L(), R()); };
783   if (Op == "/")
784     return [=] { return div(L(), R()); };
785   if (Op == "<<")
786     return [=] { return L().getValue() << R().getValue(); };
787   if (Op == ">>")
788     return [=] { return L().getValue() >> R().getValue(); };
789   if (Op == "<")
790     return [=] { return L().getValue() < R().getValue(); };
791   if (Op == ">")
792     return [=] { return L().getValue() > R().getValue(); };
793   if (Op == ">=")
794     return [=] { return L().getValue() >= R().getValue(); };
795   if (Op == "<=")
796     return [=] { return L().getValue() <= R().getValue(); };
797   if (Op == "==")
798     return [=] { return L().getValue() == R().getValue(); };
799   if (Op == "!=")
800     return [=] { return L().getValue() != R().getValue(); };
801   if (Op == "&")
802     return [=] { return bitAnd(L(), R()); };
803   if (Op == "|")
804     return [=] { return bitOr(L(), R()); };
805   llvm_unreachable("invalid operator");
806 }
807 
808 // This is a part of the operator-precedence parser. This function
809 // assumes that the remaining token stream starts with an operator.
810 Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
811   while (!atEOF() && !ErrorCount) {
812     // Read an operator and an expression.
813     if (consume("?"))
814       return readTernary(Lhs);
815     StringRef Op1 = peek();
816     if (precedence(Op1) < MinPrec)
817       break;
818     skip();
819     Expr Rhs = readPrimary();
820 
821     // Evaluate the remaining part of the expression first if the
822     // next operator has greater precedence than the previous one.
823     // For example, if we have read "+" and "3", and if the next
824     // operator is "*", then we'll evaluate 3 * ... part first.
825     while (!atEOF()) {
826       StringRef Op2 = peek();
827       if (precedence(Op2) <= precedence(Op1))
828         break;
829       Rhs = readExpr1(Rhs, precedence(Op2));
830     }
831 
832     Lhs = combine(Op1, Lhs, Rhs);
833   }
834   return Lhs;
835 }
836 
837 Expr ScriptParser::getPageSize() {
838   std::string Location = getCurrentLocation();
839   return [=]() -> uint64_t {
840     if (Target)
841       return Target->PageSize;
842     error(Location + ": unable to calculate page size");
843     return 4096; // Return a dummy value.
844   };
845 }
846 
847 Expr ScriptParser::readConstant() {
848   StringRef S = readParenLiteral();
849   if (S == "COMMONPAGESIZE")
850     return getPageSize();
851   if (S == "MAXPAGESIZE")
852     return [] { return Config->MaxPageSize; };
853   setError("unknown constant: " + S);
854   return {};
855 }
856 
857 // Parses Tok as an integer. It recognizes hexadecimal (prefixed with
858 // "0x" or suffixed with "H") and decimal numbers. Decimal numbers may
859 // have "K" (Ki) or "M" (Mi) suffixes.
860 static Optional<uint64_t> parseInt(StringRef Tok) {
861   // Negative number
862   if (Tok.startswith("-")) {
863     if (Optional<uint64_t> Val = parseInt(Tok.substr(1)))
864       return -*Val;
865     return None;
866   }
867 
868   // Hexadecimal
869   uint64_t Val;
870   if (Tok.startswith_lower("0x") && to_integer(Tok.substr(2), Val, 16))
871     return Val;
872   if (Tok.endswith_lower("H") && to_integer(Tok.drop_back(), Val, 16))
873     return Val;
874 
875   // Decimal
876   if (Tok.endswith_lower("K")) {
877     if (!to_integer(Tok.drop_back(), Val, 10))
878       return None;
879     return Val * 1024;
880   }
881   if (Tok.endswith_lower("M")) {
882     if (!to_integer(Tok.drop_back(), Val, 10))
883       return None;
884     return Val * 1024 * 1024;
885   }
886   if (!to_integer(Tok, Val, 10))
887     return None;
888   return Val;
889 }
890 
891 BytesDataCommand *ScriptParser::readBytesDataCommand(StringRef Tok) {
892   int Size = StringSwitch<int>(Tok)
893                  .Case("BYTE", 1)
894                  .Case("SHORT", 2)
895                  .Case("LONG", 4)
896                  .Case("QUAD", 8)
897                  .Default(-1);
898   if (Size == -1)
899     return nullptr;
900 
901   return make<BytesDataCommand>(readParenExpr(), Size);
902 }
903 
904 StringRef ScriptParser::readParenLiteral() {
905   expect("(");
906   StringRef Tok = next();
907   expect(")");
908   return Tok;
909 }
910 
911 OutputSection *ScriptParser::checkSection(OutputSection *Cmd,
912                                           StringRef Location) {
913   if (Cmd->Location.empty() && Script->ErrorOnMissingSection)
914     error(Location + ": undefined section " + Cmd->Name);
915   return Cmd;
916 }
917 
918 Expr ScriptParser::readPrimary() {
919   if (peek() == "(")
920     return readParenExpr();
921 
922   if (consume("~")) {
923     Expr E = readPrimary();
924     return [=] { return ~E().getValue(); };
925   }
926   if (consume("!")) {
927     Expr E = readPrimary();
928     return [=] { return !E().getValue(); };
929   }
930   if (consume("-")) {
931     Expr E = readPrimary();
932     return [=] { return -E().getValue(); };
933   }
934 
935   StringRef Tok = next();
936   std::string Location = getCurrentLocation();
937 
938   // Built-in functions are parsed here.
939   // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
940   if (Tok == "ABSOLUTE") {
941     Expr Inner = readParenExpr();
942     return [=] {
943       ExprValue I = Inner();
944       I.ForceAbsolute = true;
945       return I;
946     };
947   }
948   if (Tok == "ADDR") {
949     StringRef Name = readParenLiteral();
950     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
951     return [=]() -> ExprValue {
952       return {checkSection(Cmd, Location), 0, Location};
953     };
954   }
955   if (Tok == "ALIGN") {
956     expect("(");
957     Expr E = readExpr();
958     if (consume(")"))
959       return [=] {
960         return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
961       };
962     expect(",");
963     Expr E2 = readExpr();
964     expect(")");
965     return [=] {
966       ExprValue V = E();
967       V.Alignment = std::max((uint64_t)1, E2().getValue());
968       return V;
969     };
970   }
971   if (Tok == "ALIGNOF") {
972     StringRef Name = readParenLiteral();
973     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
974     return [=] { return checkSection(Cmd, Location)->Alignment; };
975   }
976   if (Tok == "ASSERT")
977     return readAssertExpr();
978   if (Tok == "CONSTANT")
979     return readConstant();
980   if (Tok == "DATA_SEGMENT_ALIGN") {
981     expect("(");
982     Expr E = readExpr();
983     expect(",");
984     readExpr();
985     expect(")");
986     return [=] {
987       return alignTo(Script->getDot(), std::max((uint64_t)1, E().getValue()));
988     };
989   }
990   if (Tok == "DATA_SEGMENT_END") {
991     expect("(");
992     expect(".");
993     expect(")");
994     return [] { return Script->getDot(); };
995   }
996   if (Tok == "DATA_SEGMENT_RELRO_END") {
997     // GNU linkers implements more complicated logic to handle
998     // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and
999     // just align to the next page boundary for simplicity.
1000     expect("(");
1001     readExpr();
1002     expect(",");
1003     readExpr();
1004     expect(")");
1005     Expr E = getPageSize();
1006     return [=] { return alignTo(Script->getDot(), E().getValue()); };
1007   }
1008   if (Tok == "DEFINED") {
1009     StringRef Name = readParenLiteral();
1010     return [=] { return Script->isDefined(Name) ? 1 : 0; };
1011   }
1012   if (Tok == "LENGTH") {
1013     StringRef Name = readParenLiteral();
1014     if (Script->Opt.MemoryRegions.count(Name) == 0)
1015       setError("memory region not defined: " + Name);
1016     return [=] { return Script->Opt.MemoryRegions[Name]->Length; };
1017   }
1018   if (Tok == "LOADADDR") {
1019     StringRef Name = readParenLiteral();
1020     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1021     return [=] { return checkSection(Cmd, Location)->getLMA(); };
1022   }
1023   if (Tok == "ORIGIN") {
1024     StringRef Name = readParenLiteral();
1025     if (Script->Opt.MemoryRegions.count(Name) == 0)
1026       setError("memory region not defined: " + Name);
1027     return [=] { return Script->Opt.MemoryRegions[Name]->Origin; };
1028   }
1029   if (Tok == "SEGMENT_START") {
1030     expect("(");
1031     skip();
1032     expect(",");
1033     Expr E = readExpr();
1034     expect(")");
1035     return [=] { return E(); };
1036   }
1037   if (Tok == "SIZEOF") {
1038     StringRef Name = readParenLiteral();
1039     OutputSection *Cmd = Script->getOrCreateOutputSection(Name);
1040     // Linker script does not create an output section if its content is empty.
1041     // We want to allow SIZEOF(.foo) where .foo is a section which happened to
1042     // be empty.
1043     return [=] { return Cmd->Size; };
1044   }
1045   if (Tok == "SIZEOF_HEADERS")
1046     return [=] { return elf::getHeaderSize(); };
1047 
1048   // Tok is the dot.
1049   if (Tok == ".")
1050     return [=] { return Script->getSymbolValue(Location, Tok); };
1051 
1052   // Tok is a literal number.
1053   if (Optional<uint64_t> Val = parseInt(Tok))
1054     return [=] { return *Val; };
1055 
1056   // Tok is a symbol name.
1057   if (!isValidCIdentifier(Tok))
1058     setError("malformed number: " + Tok);
1059   Script->Opt.ReferencedSymbols.push_back(Tok);
1060   return [=] { return Script->getSymbolValue(Location, Tok); };
1061 }
1062 
1063 Expr ScriptParser::readTernary(Expr Cond) {
1064   Expr L = readExpr();
1065   expect(":");
1066   Expr R = readExpr();
1067   return [=] { return Cond().getValue() ? L() : R(); };
1068 }
1069 
1070 Expr ScriptParser::readParenExpr() {
1071   expect("(");
1072   Expr E = readExpr();
1073   expect(")");
1074   return E;
1075 }
1076 
1077 std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1078   std::vector<StringRef> Phdrs;
1079   while (!ErrorCount && peek().startswith(":")) {
1080     StringRef Tok = next();
1081     Phdrs.push_back((Tok.size() == 1) ? next() : Tok.substr(1));
1082   }
1083   return Phdrs;
1084 }
1085 
1086 // Read a program header type name. The next token must be a
1087 // name of a program header type or a constant (e.g. "0x3").
1088 unsigned ScriptParser::readPhdrType() {
1089   StringRef Tok = next();
1090   if (Optional<uint64_t> Val = parseInt(Tok))
1091     return *Val;
1092 
1093   unsigned Ret = StringSwitch<unsigned>(Tok)
1094                      .Case("PT_NULL", PT_NULL)
1095                      .Case("PT_LOAD", PT_LOAD)
1096                      .Case("PT_DYNAMIC", PT_DYNAMIC)
1097                      .Case("PT_INTERP", PT_INTERP)
1098                      .Case("PT_NOTE", PT_NOTE)
1099                      .Case("PT_SHLIB", PT_SHLIB)
1100                      .Case("PT_PHDR", PT_PHDR)
1101                      .Case("PT_TLS", PT_TLS)
1102                      .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1103                      .Case("PT_GNU_STACK", PT_GNU_STACK)
1104                      .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1105                      .Case("PT_OPENBSD_RANDOMIZE", PT_OPENBSD_RANDOMIZE)
1106                      .Case("PT_OPENBSD_WXNEEDED", PT_OPENBSD_WXNEEDED)
1107                      .Case("PT_OPENBSD_BOOTDATA", PT_OPENBSD_BOOTDATA)
1108                      .Default(-1);
1109 
1110   if (Ret == (unsigned)-1) {
1111     setError("invalid program header type: " + Tok);
1112     return PT_NULL;
1113   }
1114   return Ret;
1115 }
1116 
1117 // Reads an anonymous version declaration.
1118 void ScriptParser::readAnonymousDeclaration() {
1119   std::vector<SymbolVersion> Locals;
1120   std::vector<SymbolVersion> Globals;
1121   std::tie(Locals, Globals) = readSymbols();
1122 
1123   for (SymbolVersion V : Locals) {
1124     if (V.Name == "*")
1125       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1126     else
1127       Config->VersionScriptLocals.push_back(V);
1128   }
1129 
1130   for (SymbolVersion V : Globals)
1131     Config->VersionScriptGlobals.push_back(V);
1132 
1133   expect(";");
1134 }
1135 
1136 // Reads a non-anonymous version definition,
1137 // e.g. "VerStr { global: foo; bar; local: *; };".
1138 void ScriptParser::readVersionDeclaration(StringRef VerStr) {
1139   // Read a symbol list.
1140   std::vector<SymbolVersion> Locals;
1141   std::vector<SymbolVersion> Globals;
1142   std::tie(Locals, Globals) = readSymbols();
1143 
1144   for (SymbolVersion V : Locals) {
1145     if (V.Name == "*")
1146       Config->DefaultSymbolVersion = VER_NDX_LOCAL;
1147     else
1148       Config->VersionScriptLocals.push_back(V);
1149   }
1150 
1151   // Create a new version definition and add that to the global symbols.
1152   VersionDefinition Ver;
1153   Ver.Name = VerStr;
1154   Ver.Globals = Globals;
1155 
1156   // User-defined version number starts from 2 because 0 and 1 are
1157   // reserved for VER_NDX_LOCAL and VER_NDX_GLOBAL, respectively.
1158   Ver.Id = Config->VersionDefinitions.size() + 2;
1159   Config->VersionDefinitions.push_back(Ver);
1160 
1161   // Each version may have a parent version. For example, "Ver2"
1162   // defined as "Ver2 { global: foo; local: *; } Ver1;" has "Ver1"
1163   // as a parent. This version hierarchy is, probably against your
1164   // instinct, purely for hint; the runtime doesn't care about it
1165   // at all. In LLD, we simply ignore it.
1166   if (peek() != ";")
1167     skip();
1168   expect(";");
1169 }
1170 
1171 static bool hasWildcard(StringRef S) {
1172   return S.find_first_of("?*[") != StringRef::npos;
1173 }
1174 
1175 // Reads a list of symbols, e.g. "{ global: foo; bar; local: *; };".
1176 std::pair<std::vector<SymbolVersion>, std::vector<SymbolVersion>>
1177 ScriptParser::readSymbols() {
1178   std::vector<SymbolVersion> Locals;
1179   std::vector<SymbolVersion> Globals;
1180   std::vector<SymbolVersion> *V = &Globals;
1181 
1182   while (!ErrorCount) {
1183     if (consume("}"))
1184       break;
1185     if (consumeLabel("local")) {
1186       V = &Locals;
1187       continue;
1188     }
1189     if (consumeLabel("global")) {
1190       V = &Globals;
1191       continue;
1192     }
1193 
1194     if (consume("extern")) {
1195       std::vector<SymbolVersion> Ext = readVersionExtern();
1196       V->insert(V->end(), Ext.begin(), Ext.end());
1197     } else {
1198       StringRef Tok = next();
1199       V->push_back({unquote(Tok), false, hasWildcard(Tok)});
1200     }
1201     expect(";");
1202   }
1203   return {Locals, Globals};
1204 }
1205 
1206 // Reads an "extern C++" directive, e.g.,
1207 // "extern "C++" { ns::*; "f(int, double)"; };"
1208 std::vector<SymbolVersion> ScriptParser::readVersionExtern() {
1209   StringRef Tok = next();
1210   bool IsCXX = Tok == "\"C++\"";
1211   if (!IsCXX && Tok != "\"C\"")
1212     setError("Unknown language");
1213   expect("{");
1214 
1215   std::vector<SymbolVersion> Ret;
1216   while (!ErrorCount && peek() != "}") {
1217     StringRef Tok = next();
1218     bool HasWildcard = !Tok.startswith("\"") && hasWildcard(Tok);
1219     Ret.push_back({unquote(Tok), IsCXX, HasWildcard});
1220     expect(";");
1221   }
1222 
1223   expect("}");
1224   return Ret;
1225 }
1226 
1227 uint64_t ScriptParser::readMemoryAssignment(StringRef S1, StringRef S2,
1228                                             StringRef S3) {
1229   if (!consume(S1) && !consume(S2) && !consume(S3)) {
1230     setError("expected one of: " + S1 + ", " + S2 + ", or " + S3);
1231     return 0;
1232   }
1233   expect("=");
1234   return readExpr()().getValue();
1235 }
1236 
1237 // Parse the MEMORY command as specified in:
1238 // https://sourceware.org/binutils/docs/ld/MEMORY.html
1239 //
1240 // MEMORY { name [(attr)] : ORIGIN = origin, LENGTH = len ... }
1241 void ScriptParser::readMemory() {
1242   expect("{");
1243   while (!ErrorCount && !consume("}")) {
1244     StringRef Name = next();
1245 
1246     uint32_t Flags = 0;
1247     uint32_t NegFlags = 0;
1248     if (consume("(")) {
1249       std::tie(Flags, NegFlags) = readMemoryAttributes();
1250       expect(")");
1251     }
1252     expect(":");
1253 
1254     uint64_t Origin = readMemoryAssignment("ORIGIN", "org", "o");
1255     expect(",");
1256     uint64_t Length = readMemoryAssignment("LENGTH", "len", "l");
1257 
1258     // Add the memory region to the region map.
1259     if (Script->Opt.MemoryRegions.count(Name))
1260       setError("region '" + Name + "' already defined");
1261     MemoryRegion *MR = make<MemoryRegion>();
1262     *MR = {Name, Origin, Length, Flags, NegFlags};
1263     Script->Opt.MemoryRegions[Name] = MR;
1264   }
1265 }
1266 
1267 // This function parses the attributes used to match against section
1268 // flags when placing output sections in a memory region. These flags
1269 // are only used when an explicit memory region name is not used.
1270 std::pair<uint32_t, uint32_t> ScriptParser::readMemoryAttributes() {
1271   uint32_t Flags = 0;
1272   uint32_t NegFlags = 0;
1273   bool Invert = false;
1274 
1275   for (char C : next().lower()) {
1276     uint32_t Flag = 0;
1277     if (C == '!')
1278       Invert = !Invert;
1279     else if (C == 'w')
1280       Flag = SHF_WRITE;
1281     else if (C == 'x')
1282       Flag = SHF_EXECINSTR;
1283     else if (C == 'a')
1284       Flag = SHF_ALLOC;
1285     else if (C != 'r')
1286       setError("invalid memory region attribute");
1287 
1288     if (Invert)
1289       NegFlags |= Flag;
1290     else
1291       Flags |= Flag;
1292   }
1293   return {Flags, NegFlags};
1294 }
1295 
1296 void elf::readLinkerScript(MemoryBufferRef MB) {
1297   ScriptParser(MB).readLinkerScript();
1298 }
1299 
1300 void elf::readVersionScript(MemoryBufferRef MB) {
1301   ScriptParser(MB).readVersionScript();
1302 }
1303 
1304 void elf::readDynamicList(MemoryBufferRef MB) {
1305   ScriptParser(MB).readDynamicList();
1306 }
1307